| // Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| package bazel2gn | |
| import ( | |
| "errors" | |
| "fmt" | |
| "path" | |
| "strings" | |
| "go.starlark.net/syntax" | |
| ) | |
| // writeFileRule is the Skylib rule from @bazel_skylib//rules:write_file.bzl, | |
| // which is converted to a GN `generated_file()`. | |
| const writeFileRule = "write_file" | |
| // writeFileOutGNPath returns the GN path of the output of a `write_file()`, | |
| // i.e. its `out` under `$target_gen_dir`. | |
| func writeFileOutGNPath(call *syntax.CallExpr) (string, error) { | |
| for _, arg := range call.Args { | |
| attr, ok := attrName(arg) | |
| if !ok || attr != "out" { | |
| continue | |
| } | |
| out, err := stringLiteralValue(arg.(*syntax.BinaryExpr).Y) | |
| if err != nil { | |
| return "", fmt.Errorf("%s out: %v", writeFileRule, err) | |
| } | |
| out = path.Clean(out) | |
| if out == "." || out == ".." || path.IsAbs(out) || strings.HasPrefix(out, "../") { | |
| return "", fmt.Errorf("%s out %q must be a path in the package", writeFileRule, out) | |
| } | |
| return "$target_gen_dir/" + out, nil | |
| } | |
| return "", fmt.Errorf("missing `out` attribute in %s", writeFileRule) | |
| } | |
| // writeFileContentToGN converts the `content` of a `write_file()` to the | |
| // value of GN `contents`. | |
| // | |
| // Skylib joins the lines with newlines and adds no trailing newline. GN writes | |
| // a string value as-is, so the lines are joined into one string, with `$0x0A` | |
| // (the GN escape for a newline) between them. | |
| func writeFileContentToGN(expr syntax.Expr, varStmts map[string]*syntax.AssignStmt) (string, error) { | |
| list, ok := unwrapParenExpr(expr).(*syntax.ListExpr) | |
| if !ok { | |
| return "", fmt.Errorf("expected list literal, got %T", expr) | |
| } | |
| var lines []string | |
| for _, elem := range list.List { | |
| line, err := writeFileLineToGN(elem, varStmts) | |
| if err != nil { | |
| return "", err | |
| } | |
| lines = append(lines, line) | |
| } | |
| switch len(lines) { | |
| case 0: | |
| return `""`, nil | |
| case 1: | |
| return lines[0], nil | |
| default: | |
| return fmt.Sprintf(`string_join("$0x0A", [ %s ])`, strings.Join(lines, ", ")), nil | |
| } | |
| } | |
| // validateWriteFileVarExpr verifies that a top-level variable's RHS is safe to | |
| // reference by identifier in GN `contents` (only double-quoted single-line | |
| // string literals without `$` or `\n`, `+` concatenations, or other valid | |
| // top-level variables). Top-level assignments pass `v.Raw` verbatim to GN, so | |
| // `$`, `\n`, single quotes, or `load()`ed identifiers would break GN. | |
| func validateWriteFileVarExpr(expr syntax.Expr, varStmts map[string]*syntax.AssignStmt, visiting map[string]bool) error { | |
| switch v := unwrapParenExpr(expr).(type) { | |
| case *syntax.Literal: | |
| s, ok := v.Value.(string) | |
| if !ok { | |
| return fmt.Errorf("expected string literal, got %s", v.Raw) | |
| } | |
| if !strings.HasPrefix(v.Raw, `"`) || strings.HasPrefix(v.Raw, `"""`) { | |
| return fmt.Errorf("string literal %s must use double-quoted single-line syntax", v.Raw) | |
| } | |
| if strings.ContainsAny(s, "$\n") { | |
| return fmt.Errorf("string literal %s must not contain '$' or newlines", v.Raw) | |
| } | |
| return nil | |
| case *syntax.Ident: | |
| if visiting[v.Name] { | |
| return fmt.Errorf("cyclic reference to variable %q", v.Name) | |
| } | |
| assign, ok := varStmts[v.Name] | |
| if !ok { | |
| return fmt.Errorf("undefined or imported variable %q", v.Name) | |
| } | |
| if assign.Op != syntax.EQ { | |
| return fmt.Errorf("variable %q uses unsupported assignment operator %s", v.Name, assign.Op) | |
| } | |
| visiting[v.Name] = true | |
| defer delete(visiting, v.Name) | |
| return validateWriteFileVarExpr(assign.RHS, varStmts, visiting) | |
| case *syntax.BinaryExpr: | |
| if v.Op != syntax.PLUS { | |
| return fmt.Errorf("unsupported operator %s", v.Op) | |
| } | |
| if err := validateWriteFileVarExpr(v.X, varStmts, visiting); err != nil { | |
| return err | |
| } | |
| return validateWriteFileVarExpr(v.Y, varStmts, visiting) | |
| default: | |
| return fmt.Errorf("unsupported expression %T", expr) | |
| } | |
| } | |
| // writeFileLineToGN converts one line of `write_file()` content: a string | |
| // literal, a validated top-level variable, or a `+` concatenation of those. | |
| func writeFileLineToGN(expr syntax.Expr, varStmts map[string]*syntax.AssignStmt) (string, error) { | |
| switch v := unwrapParenExpr(expr).(type) { | |
| case *syntax.Literal: | |
| s, ok := v.Value.(string) | |
| if !ok { | |
| return "", fmt.Errorf("expected string literal, got %s", v.Raw) | |
| } | |
| // Bazel doesn't expand `$` in content, so escape it for GN. | |
| return strings.ReplaceAll(gnQuoteLiteral(s), "\n", "$0x0A"), nil | |
| case *syntax.Ident: | |
| if err := validateWriteFileVarExpr(v, varStmts, map[string]bool{}); err != nil { | |
| return "", err | |
| } | |
| return v.Name, nil | |
| case *syntax.BinaryExpr: | |
| if v.Op != syntax.PLUS { | |
| return "", fmt.Errorf("unsupported operator %s", v.Op) | |
| } | |
| x, err := writeFileLineToGN(v.X, varStmts) | |
| if err != nil { | |
| return "", err | |
| } | |
| y, err := writeFileLineToGN(v.Y, varStmts) | |
| if err != nil { | |
| return "", err | |
| } | |
| return x + " + " + y, nil | |
| default: | |
| return "", fmt.Errorf("unsupported expression %T", expr) | |
| } | |
| } | |
| // writeFileToGN converts a Skylib `write_file()` call to a GN | |
| // `generated_file()` that writes the same bytes to `$target_gen_dir/<out>`. | |
| // | |
| // Same-file `resource()` targets that use the output as their source are | |
| // pointed at the generated path by `resolveResourceTargets()`. | |
| func writeFileToGN(call *syntax.CallExpr, varStmts map[string]*syntax.AssignStmt) ([]string, error) { | |
| var name, contents string | |
| var testonly, visArg *syntax.BinaryExpr | |
| var wrappingConditions []string | |
| hasContent := false | |
| for _, arg := range call.Args { | |
| binaryExpr, ok := arg.(*syntax.BinaryExpr) | |
| if !ok || binaryExpr.Op != syntax.EQ { | |
| return nil, fmt.Errorf("%s only accepts keyword arguments, got %T", writeFileRule, arg) | |
| } | |
| shouldSkip, err := hasSkipAnnotation(binaryExpr) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to check skip annotation: %v", err) | |
| } | |
| if shouldSkip { | |
| continue | |
| } | |
| ident, ok := binaryExpr.X.(*syntax.Ident) | |
| if !ok { | |
| return nil, fmt.Errorf("expected identifier for argument name, got %T", binaryExpr.X) | |
| } | |
| switch ident.Name { | |
| case "name": | |
| name, err = stringLiteralValue(binaryExpr.Y) | |
| if err != nil { | |
| return nil, fmt.Errorf("%s name: %v", writeFileRule, err) | |
| } | |
| case "out": | |
| // Converted by `writeFileOutGNPath()` below. | |
| case "content": | |
| contents, err = writeFileContentToGN(binaryExpr.Y, varStmts) | |
| if err != nil { | |
| return nil, fmt.Errorf("%s content: %v; use # @bazel2gn:skip and write the GN copy by hand", writeFileRule, err) | |
| } | |
| hasContent = true | |
| case "newline": | |
| // GN always writes "\n", like Skylib on Linux hosts. | |
| newline, err := stringLiteralValue(binaryExpr.Y) | |
| if err != nil || (newline != "auto" && newline != "unix") { | |
| return nil, fmt.Errorf("%s newline must be \"auto\" or \"unix\"; use # @bazel2gn:skip and write the GN copy by hand", writeFileRule) | |
| } | |
| case "testonly": | |
| testonly = binaryExpr | |
| case "visibility": | |
| visArg = binaryExpr | |
| case "target_compatible_with": | |
| wrappingConditions, err = targetCompatibleWithToGNConditions(binaryExpr.Y) | |
| if err != nil { | |
| return nil, fmt.Errorf("converting Bazel target_compatible_with to GN conditions: %v", err) | |
| } | |
| case "tags": | |
| // Bazel tags have no GN meaning for generated files. | |
| default: | |
| return nil, fmt.Errorf("bazel2gn doesn't support attribute %q of %s; use # @bazel2gn:skip and write the GN copy by hand", ident.Name, writeFileRule) | |
| } | |
| } | |
| if name == "" { | |
| return nil, fmt.Errorf("missing `name` attribute in %s", writeFileRule) | |
| } | |
| out, err := writeFileOutGNPath(call) | |
| if err != nil { | |
| return nil, fmt.Errorf("%s %q: %v", writeFileRule, name, err) | |
| } | |
| if !hasContent { | |
| contents = `""` | |
| } | |
| var body []string | |
| if testonly != nil { | |
| lines, err := attrAssignmentToGN(testonly, writeFileRule, nil /*compiledActionOutputs*/, false /*appendDeps*/, false /*hasWithUnitTests*/) | |
| if err != nil { | |
| return nil, fmt.Errorf("converting %s testonly: %v", writeFileRule, err) | |
| } | |
| body = append(body, lines...) | |
| } | |
| body = append(body, | |
| fmt.Sprintf("outputs = [ %s ]", gnQuote(out)), | |
| "contents = "+contents, | |
| ) | |
| if visArg != nil { | |
| lines, err := attrAssignmentToGN(visArg, writeFileRule, nil /*compiledActionOutputs*/, false /*appendDeps*/, false /*hasWithUnitTests*/) | |
| if err != nil { | |
| return nil, fmt.Errorf("converting %s visibility: %v", writeFileRule, err) | |
| } | |
| body = append(body, lines...) | |
| } | |
| if len(body) == 0 { | |
| return nil, errors.New("unexpected empty generated_file body") | |
| } | |
| ret := []string{fmt.Sprintf("generated_file(%s) {", gnQuote(name))} | |
| ret = append(ret, indent(body, 1)...) | |
| ret = append(ret, "}") | |
| if len(wrappingConditions) > 0 { | |
| ret = append([]string{ | |
| fmt.Sprintf("if (%s) {", strings.Join(wrappingConditions, " && ")), | |
| }, indent(ret, 1)...) | |
| ret = append(ret, "}") | |
| } | |
| return ret, nil | |
| } |