|
| 1 | +// Copyright 2024 The Bazel Authors. All rights reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | +package com.google.devtools.build.lib.bazel.bzlmod; |
| 16 | + |
| 17 | +import com.google.common.annotations.VisibleForTesting; |
| 18 | +import com.google.common.collect.ImmutableList; |
| 19 | +import com.google.devtools.build.lib.events.Event; |
| 20 | +import com.google.devtools.build.lib.events.ExtendedEventHandler; |
| 21 | +import com.google.devtools.build.lib.packages.BazelStarlarkEnvironment; |
| 22 | +import com.google.devtools.build.lib.packages.DotBazelFileSyntaxChecker; |
| 23 | +import com.google.devtools.build.lib.server.FailureDetails.ExternalDeps.Code; |
| 24 | +import net.starlark.java.eval.EvalException; |
| 25 | +import net.starlark.java.eval.Module; |
| 26 | +import net.starlark.java.eval.Starlark; |
| 27 | +import net.starlark.java.eval.StarlarkSemantics; |
| 28 | +import net.starlark.java.eval.StarlarkThread; |
| 29 | +import net.starlark.java.syntax.Argument; |
| 30 | +import net.starlark.java.syntax.AssignmentStatement; |
| 31 | +import net.starlark.java.syntax.CallExpression; |
| 32 | +import net.starlark.java.syntax.DotExpression; |
| 33 | +import net.starlark.java.syntax.ExpressionStatement; |
| 34 | +import net.starlark.java.syntax.Identifier; |
| 35 | +import net.starlark.java.syntax.Location; |
| 36 | +import net.starlark.java.syntax.ParserInput; |
| 37 | +import net.starlark.java.syntax.Program; |
| 38 | +import net.starlark.java.syntax.StarlarkFile; |
| 39 | +import net.starlark.java.syntax.StringLiteral; |
| 40 | +import net.starlark.java.syntax.SyntaxError; |
| 41 | + |
| 42 | +/** |
| 43 | + * Represents a compiled MODULE.bazel file, ready to be executed on a {@link StarlarkThread}. It's |
| 44 | + * been successfully checked for syntax errors. |
| 45 | + * |
| 46 | + * <p>Use the {@link #parseAndCompile} factory method instead of directly instantiating this record. |
| 47 | + */ |
| 48 | +public record CompiledModuleFile( |
| 49 | + ModuleFile moduleFile, |
| 50 | + Program program, |
| 51 | + Module predeclaredEnv, |
| 52 | + ImmutableList<IncludeStatement> includeStatements) { |
| 53 | + public static final String INCLUDE_IDENTIFIER = "include"; |
| 54 | + |
| 55 | + record IncludeStatement(String includeLabel, Location location) {} |
| 56 | + |
| 57 | + /** Parses and compiles a given module file, checking it for syntax errors. */ |
| 58 | + public static CompiledModuleFile parseAndCompile( |
| 59 | + ModuleFile moduleFile, |
| 60 | + ModuleKey moduleKey, |
| 61 | + StarlarkSemantics starlarkSemantics, |
| 62 | + BazelStarlarkEnvironment starlarkEnv, |
| 63 | + ExtendedEventHandler eventHandler) |
| 64 | + throws ExternalDepsException { |
| 65 | + StarlarkFile starlarkFile = |
| 66 | + StarlarkFile.parse(ParserInput.fromUTF8(moduleFile.getContent(), moduleFile.getLocation())); |
| 67 | + if (!starlarkFile.ok()) { |
| 68 | + Event.replayEventsOn(eventHandler, starlarkFile.errors()); |
| 69 | + throw ExternalDepsException.withMessage( |
| 70 | + Code.BAD_MODULE, "error parsing MODULE.bazel file for %s", moduleKey); |
| 71 | + } |
| 72 | + try { |
| 73 | + ImmutableList<IncludeStatement> includeStatements = checkModuleFileSyntax(starlarkFile); |
| 74 | + Module predeclaredEnv = |
| 75 | + Module.withPredeclared(starlarkSemantics, starlarkEnv.getModuleBazelEnv()); |
| 76 | + Program program = Program.compileFile(starlarkFile, predeclaredEnv); |
| 77 | + return new CompiledModuleFile(moduleFile, program, predeclaredEnv, includeStatements); |
| 78 | + } catch (SyntaxError.Exception e) { |
| 79 | + Event.replayEventsOn(eventHandler, e.errors()); |
| 80 | + throw ExternalDepsException.withMessage( |
| 81 | + Code.BAD_MODULE, "syntax error in MODULE.bazel file for %s", moduleKey); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Checks the given `starlarkFile` for module file syntax, and returns the list of `include` |
| 87 | + * statements it contains. This is a somewhat crude sweep over the AST; we loudly complain about |
| 88 | + * any usage of `include` that is not in a top-level function call statement with one single |
| 89 | + * string literal positional argument, *except* that we don't do this check once `include` is |
| 90 | + * assigned to, due to backwards compatibility concerns. |
| 91 | + */ |
| 92 | + @VisibleForTesting |
| 93 | + static ImmutableList<IncludeStatement> checkModuleFileSyntax(StarlarkFile starlarkFile) |
| 94 | + throws SyntaxError.Exception { |
| 95 | + var includeStatements = ImmutableList.<IncludeStatement>builder(); |
| 96 | + new DotBazelFileSyntaxChecker("MODULE.bazel files", /* canLoadBzl= */ false) { |
| 97 | + // Once `include` the identifier is assigned to, we no longer care about its appearance |
| 98 | + // anywhere. This allows `include` to be used as a module extension proxy (and technically |
| 99 | + // any other variable binding). |
| 100 | + private boolean includeWasAssigned = false; |
| 101 | + |
| 102 | + @Override |
| 103 | + public void visit(ExpressionStatement node) { |
| 104 | + // We can assume this statement isn't nested in any block, since we don't allow |
| 105 | + // `if`/`def`/`for` in MODULE.bazel. |
| 106 | + if (!includeWasAssigned |
| 107 | + && node.getExpression() instanceof CallExpression call |
| 108 | + && call.getFunction() instanceof Identifier id |
| 109 | + && id.getName().equals(INCLUDE_IDENTIFIER)) { |
| 110 | + // Found a top-level call to `include`! |
| 111 | + if (call.getArguments().size() == 1 |
| 112 | + && call.getArguments().getFirst() instanceof Argument.Positional pos |
| 113 | + && pos.getValue() instanceof StringLiteral str) { |
| 114 | + includeStatements.add(new IncludeStatement(str.getValue(), call.getStartLocation())); |
| 115 | + // Nothing else to check, we can stop visiting sub-nodes now. |
| 116 | + return; |
| 117 | + } |
| 118 | + error( |
| 119 | + node.getStartLocation(), |
| 120 | + "the `include` directive MUST be called with exactly one positional argument that " |
| 121 | + + "is a string literal"); |
| 122 | + return; |
| 123 | + } |
| 124 | + super.visit(node); |
| 125 | + } |
| 126 | + |
| 127 | + @Override |
| 128 | + public void visit(AssignmentStatement node) { |
| 129 | + visit(node.getRHS()); |
| 130 | + if (!includeWasAssigned |
| 131 | + && node.getLHS() instanceof Identifier id |
| 132 | + && id.getName().equals(INCLUDE_IDENTIFIER)) { |
| 133 | + includeWasAssigned = true; |
| 134 | + // Technically someone could do something like |
| 135 | + // (include, myvar) = (print, 3) |
| 136 | + // and work around our check, but at that point IDGAF. |
| 137 | + } else { |
| 138 | + visit(node.getLHS()); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + @Override |
| 143 | + public void visit(DotExpression node) { |
| 144 | + visit(node.getObject()); |
| 145 | + if (includeWasAssigned || !node.getField().getName().equals(INCLUDE_IDENTIFIER)) { |
| 146 | + // This is fine: `whatever.include` |
| 147 | + // (so `include` can be used as a tag class name) |
| 148 | + visit(node.getField()); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + @Override |
| 153 | + public void visit(Identifier node) { |
| 154 | + if (!includeWasAssigned && node.getName().equals(INCLUDE_IDENTIFIER)) { |
| 155 | + // If we somehow reach the `include` identifier but NOT as the other allowed cases above, |
| 156 | + // cry foul. |
| 157 | + error( |
| 158 | + node.getStartLocation(), |
| 159 | + "the `include` directive MUST be called directly at the top-level"); |
| 160 | + } |
| 161 | + super.visit(node); |
| 162 | + } |
| 163 | + }.check(starlarkFile); |
| 164 | + return includeStatements.build(); |
| 165 | + } |
| 166 | + |
| 167 | + public void runOnThread(StarlarkThread thread) throws EvalException, InterruptedException { |
| 168 | + Starlark.execFileProgram(program, predeclaredEnv, thread); |
| 169 | + } |
| 170 | +} |
0 commit comments