com.google.devtools.build.lib.syntax.Statement Java Examples

The following examples show how to use com.google.devtools.build.lib.syntax.Statement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WorkspaceASTFunction.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Cut {@code ast} into a list of AST separated by load statements. We cut right before each load
 * statement series.
 */
private static ImmutableList<StarlarkFile> splitAST(StarlarkFile ast) {
  ImmutableList.Builder<StarlarkFile> asts = ImmutableList.builder();
  int prevIdx = 0;
  boolean lastIsLoad = true; // don't cut if the first statement is a load.
  List<Statement> statements = ast.getStatements();
  for (int idx = 0; idx < statements.size(); idx++) {
    Statement st = statements.get(idx);
    if (st instanceof LoadStatement) {
      if (!lastIsLoad) {
        asts.add(ast.subTree(prevIdx, idx));
        prevIdx = idx;
      }
      lastIsLoad = true;
    } else {
      lastIsLoad = false;
    }
  }
  if (!statements.isEmpty()) {
    asts.add(ast.subTree(prevIdx, statements.size()));
  }
  return asts.build();
}
 
Example #2
Source File: SkydocMain.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static String getModuleDoc(StarlarkFile buildFileAST) {
  ImmutableList<Statement> fileStatements = buildFileAST.getStatements();
  if (!fileStatements.isEmpty()) {
    Statement stmt = fileStatements.get(0);
    if (stmt instanceof ExpressionStatement) {
      Expression expr = ((ExpressionStatement) stmt).getExpression();
      if (expr instanceof StringLiteral) {
        return ((StringLiteral) expr).getValue();
      }
    }
  }
  return "";
}
 
Example #3
Source File: ASTFileLookupFunctionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static List<String> getLoads(StarlarkFile file) {
  List<String> loads = Lists.newArrayList();
  for (Statement stmt : file.getStatements()) {
    if (stmt instanceof LoadStatement) {
      loads.add(((LoadStatement) stmt).getImport().getValue());
    }
  }
  return loads;
}
 
Example #4
Source File: BzlLoadFunction.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of pairs mapping each load string in the BUILD or .bzl file to the Label it
 * resolves to. Labels are resolved relative to {@code base}, the file's package. If any load
 * statement is malformed, the function reports one or more errors to the handler and returns
 * null. Order matches the source.
 */
@Nullable
static List<Pair<String, Label>> getLoadLabels(
    EventHandler handler,
    StarlarkFile file,
    PackageIdentifier base,
    ImmutableMap<RepositoryName, RepositoryName> repoMapping) {
  Preconditions.checkArgument(!base.getRepository().isDefault());

  // It's redundant that getRelativeWithRemapping needs a Label;
  // a PackageIdentifier should suffice. Make one here.
  Label buildLabel = getBUILDLabel(base);

  boolean ok = true;
  List<Pair<String, Label>> loads = Lists.newArrayList();
  for (Statement stmt : file.getStatements()) {
    if (stmt instanceof LoadStatement) {
      LoadStatement load = (LoadStatement) stmt;
      String module = load.getImport().getValue();

      // Parse the load statement's module string as a label.
      // It must end in .bzl and not be in package "//external".
      try {
        Label label = buildLabel.getRelativeWithRemapping(module, repoMapping);
        if (!label.getName().endsWith(".bzl")) {
          throw new LabelSyntaxException("The label must reference a file with extension '.bzl'");
        }
        if (label.getPackageIdentifier().equals(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER)) {
          throw new LabelSyntaxException(
              "Starlark files may not be loaded from the //external package");
        }
        loads.add(Pair.of(module, label));
      } catch (LabelSyntaxException ex) {
        handler.handle(
            Event.error(
                load.getImport().getStartLocation(), "in load statement: " + ex.getMessage()));
        ok = false;
      }
    }
  }
  return ok ? loads : null;
}
 
Example #5
Source File: AbstractSkylarkFileParser.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Given fully loaded extension represented by {@link ExtensionLoadState}, evaluates extension and
 * returns {@link ExtensionData}
 *
 * @param load {@link ExtensionLoadState} representing loaded extension
 * @returns {@link ExtensionData} for this extions.
 */
@VisibleForTesting
protected ExtensionData buildExtensionData(ExtensionLoadState load) throws InterruptedException {
  ImmutableList<ExtensionData> dependencies =
      getDependenciesExtensionData(load.getLabel(), load.getDependencies());
  Extension loadedExtension = null;
  try (Mutability mutability = Mutability.create("importing extension")) {
    Environment.Builder envBuilder =
        Environment.builder(mutability)
            .setEventHandler(eventHandler)
            .setGlobals(buckGlobals.getBuckLoadContextGlobals().withLabel(load.getLabel()));
    envBuilder.setImportedExtensions(toImportMap(dependencies, null));

    // Create this extension.
    Environment extensionEnv =
        envBuilder.setSemantics(BuckStarlark.BUCK_STARLARK_SEMANTICS).build();
    SkylarkUtils.setPhase(extensionEnv, Phase.LOADING);

    BuildFileAST ast = load.getAST();
    buckGlobals.getKnownUserDefinedRuleTypes().invalidateExtension(load.getLabel());
    for (Statement stmt : ast.getStatements()) {
      if (!ast.execTopLevelStatement(stmt, extensionEnv, eventHandler)) {
        throw BuildFileParseException.createForUnknownParseError(
            "Cannot evaluate extension %s referenced from %s",
            load.getLabel(), load.getParentLabel());
      }
      if (stmt.kind() == Statement.Kind.ASSIGNMENT) {
        try {
          ensureExportedIfExportable(extensionEnv, (AssignmentStatement) stmt);
        } catch (EvalException e) {
          throw BuildFileParseException.createForUnknownParseError(
              "Could evaluate extension %s referenced from %s: %s",
              load.getLabel(), load.getParentLabel(), e.getMessage());
        }
      }
    }
    loadedExtension = new Extension(extensionEnv);
  }

  return ImmutableExtensionData.of(
      loadedExtension,
      load.getPath(),
      dependencies,
      load.getSkylarkImport().getImportString(),
      toLoadedPaths(load.getPath(), dependencies, null));
}