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

The following examples show how to use com.google.devtools.build.lib.syntax.EvalException. 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: CcCommon.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the feature configuration for a given rule.
 *
 * @return the feature configuration for the given {@code ruleContext}.
 */
public static FeatureConfiguration configureFeaturesOrReportRuleError(
    RuleContext ruleContext,
    ImmutableSet<String> requestedFeatures,
    ImmutableSet<String> unsupportedFeatures,
    CcToolchainProvider toolchain,
    CppSemantics cppSemantics) {
  cppSemantics.validateLayeringCheckFeatures(
      ruleContext, /* aspectDescriptor= */ null, toolchain, ImmutableSet.of());
  try {
    return configureFeaturesOrThrowEvalException(
        requestedFeatures,
        unsupportedFeatures,
        toolchain,
        ruleContext.getFragment(CppConfiguration.class));
  } catch (EvalException e) {
    ruleContext.ruleError(e.getMessage());
    return FeatureConfiguration.EMPTY;
  }
}
 
Example #2
Source File: ThreadHandler.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the Starlark statements code in the environment defined by the provided {@link
 * StarlarkThread}. If the last statement is an expression, doEvaluate returns its value,
 * otherwise it returns null.
 *
 * <p>The caller is responsible for ensuring that the associated Starlark thread isn't currently
 * running.
 */
private Object doEvaluate(StarlarkThread thread, String content)
    throws SyntaxError.Exception, EvalException, InterruptedException {
  try {
    servicingEvalRequest.set(true);

    // TODO(adonovan): opt: don't parse and resolve the expression every time we hit a breakpoint
    // (!).
    ParserInput input = ParserInput.create(content, "<debug eval>");
    // TODO(adonovan): the module or call frame should be a parameter.
    Module module = Module.ofInnermostEnclosingStarlarkFunction(thread);
    return EvalUtils.exec(input, FileOptions.DEFAULT, module, thread);
  } finally {
    servicingEvalRequest.set(false);
  }
}
 
Example #3
Source File: SkylarkBuildModule.java    From buck with Apache License 2.0 6 votes vote down vote up
@SkylarkCallable(
    name = "package_name",
    doc =
        "The name of the package being evaluated. "
            + "For example, in the build file <code>some/package/BUCK</code>, its value "
            + "will be <code>some/package</code>. "
            + "If the BUCK file calls a function defined in a .bzl file, "
            + "<code>package_name()</code> will match the caller BUCK file package. "
            + "This function is equivalent to the deprecated variable <code>PACKAGE_NAME</code>.",
    parameters = {},
    useAst = true,
    useEnvironment = true)
public String packageName(FuncallExpression ast, Environment env) throws EvalException {
  SkylarkUtils.checkLoadingPhase(env, "native.package_name", ast.getLocation());
  ParseContext parseContext = ParseContext.getParseContext(env, ast);
  return parseContext
      .getPackageContext()
      .getPackageIdentifier()
      .getPackageFragment()
      .getPathString();
}
 
Example #4
Source File: CoreGlobal.java    From copybara with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
@StarlarkMethod(
    name = "parse_message",
    doc = "Returns a ChangeMessage parsed from a well formed string.",
    parameters = {
      @Param(
          name = "message",
          named = true,
          type = String.class,
          doc = "The contents of the change message"),
    })
public ChangeMessage parseMessage(String changeMessage) throws EvalException {
  try {
    return ChangeMessage.parseMessage(changeMessage);
  } catch (RuntimeException e) {
    throw Starlark.errorf("Cannot parse change message '%s': %s", changeMessage, e.getMessage());
  }
}
 
Example #5
Source File: CcToolchainFeaturesTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorForNoMatchingArtifactPatternForCategory() throws Exception {
            CcToolchainFeatures toolchainFeatures =
                buildFeatures(
                    "artifact_name_pattern {",
                    "category_name: 'static_library'",
                    "prefix: 'foo'",
                    "extension: '.a'}");
  EvalException e =
      assertThrows(
          EvalException.class,
          () ->
              toolchainFeatures.getArtifactNameForCategory(
                  ArtifactCategory.DYNAMIC_LIBRARY, "output_name"));
  assertThat(e)
      .hasMessageThat()
      .contains(
          String.format(
              CcToolchainFeatures.MISSING_ARTIFACT_NAME_PATTERN_ERROR_TEMPLATE,
              ArtifactCategory.DYNAMIC_LIBRARY.toString().toLowerCase()));
}
 
Example #6
Source File: StarlarkRepositoryContext.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<String> checkAllUrls(Iterable<?> urlList) throws EvalException {
  ImmutableList.Builder<String> result = ImmutableList.builder();

  for (Object o : urlList) {
    if (!(o instanceof String)) {
      throw new EvalException(
          null,
          String.format(
              "Expected a string or sequence of strings for 'url' argument, "
                  + "but got '%s' item in the sequence",
              Starlark.type(o)));
    }
    result.add((String) o);
  }

  return result.build();
}
 
Example #7
Source File: CheckoutPath.java    From copybara with Apache License 2.0 6 votes vote down vote up
@StarlarkMethod(
    name = "resolve_sibling",
    doc = "Resolve the given path against this path.",
    parameters = {
      @Param(
          name = "other",
          type = Object.class,
          doc =
              "Resolve the given path against this path. The parameter can be a string or"
                  + " a Path."),
    })
public CheckoutPath resolveSibling(Object other) throws EvalException {
  if (other instanceof String) {
    return create(path.resolveSibling((String) other));
  } else if (other instanceof CheckoutPath) {
    return create(path.resolveSibling(((CheckoutPath) other).path));
  }
  throw Starlark.errorf(
      "Cannot resolve sibling for type %s: %s", other.getClass().getSimpleName(), other);
}
 
Example #8
Source File: CheckoutPath.java    From copybara with Apache License 2.0 6 votes vote down vote up
@StarlarkMethod(
    name = "resolve",
    doc = "Resolve the given path against this path.",
    parameters = {
      @Param(
          name = "child",
          type = Object.class,
          doc =
              "Resolve the given path against this path. The parameter"
                  + " can be a string or a Path.")
    })
public CheckoutPath resolve(Object child) throws EvalException {
  if (child instanceof String) {
    return create(path.resolve((String) child));
  } else if (child instanceof CheckoutPath) {
    return create(path.resolve(((CheckoutPath) child).path));
  }
  throw Starlark.errorf(
      "Cannot resolve children for type %s: %s", child.getClass().getSimpleName(), child);
}
 
Example #9
Source File: CommandLineArgsApi.java    From bazel with Apache License 2.0 6 votes vote down vote up
@StarlarkMethod(
    name = "set_param_file_format",
    doc = "Sets the format of the param file when written to disk",
    parameters = {
      @Param(
          name = "format",
          type = String.class,
          named = true,
          doc =
              "The format of the param file. Must be one of:<ul><li>"
                  + "\"shell\": All arguments are shell quoted and separated by "
                  + "whitespace (space, tab, newline)</li><li>"
                  + "\"multiline\": All arguments are unquoted and separated by newline "
                  + "characters</li></ul>"
                  + "<p>The format defaults to \"shell\" if not called.")
    })
CommandLineArgsApi setParamFileFormat(String format) throws EvalException;
 
Example #10
Source File: ObjcProvider.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the given providers from Starlark. An error is thrown if toAdd is not an iterable of
 * ObjcProvider instances.
 */
@SuppressWarnings("unchecked")
void addProvidersFromStarlark(Object toAdd) throws EvalException {
  if (!(toAdd instanceof Iterable)) {
    throw new EvalException(
        null,
        String.format(AppleStarlarkCommon.BAD_PROVIDERS_ITER_ERROR, Starlark.type(toAdd)));
  } else {
    Iterable<Object> toAddIterable = (Iterable<Object>) toAdd;
    for (Object toAddObject : toAddIterable) {
      if (!(toAddObject instanceof ObjcProvider)) {
        throw new EvalException(
            null,
            String.format(
                AppleStarlarkCommon.BAD_PROVIDERS_ELEM_ERROR, Starlark.type(toAddObject)));
      } else {
        ObjcProvider objcProvider = (ObjcProvider) toAddObject;
        this.addTransitiveAndPropagate(objcProvider);
        ccCompilationContextBuilder.mergeDependentCcCompilationContext(
            objcProvider.getCcCompilationContext());
      }
    }
  }
}
 
Example #11
Source File: AppleCommonApi.java    From bazel with Apache License 2.0 6 votes vote down vote up
@StarlarkMethod(
    name = "new_objc_provider",
    doc = "Creates a new ObjcProvider instance.",
    parameters = {
      @Param(
          name = "uses_swift",
          type = Boolean.class,
          defaultValue = "False",
          named = true,
          positional = false,
          doc = "Whether this provider should enable Swift support.")
    },
    extraKeywords =
        @Param(
            name = "kwargs",
            type = Dict.class,
            defaultValue = "{}",
            doc = "Dictionary of arguments."),
    useStarlarkThread = true)
// This method is registered statically for Starlark, and never called directly.
ObjcProviderApi<?> newObjcProvider(Boolean usesSwift, Dict<?, ?> kwargs, StarlarkThread thread)
    throws EvalException;
 
Example #12
Source File: StarlarkActionFactoryApi.java    From bazel with Apache License 2.0 6 votes vote down vote up
@StarlarkMethod(
    name = "declare_directory",
    doc =
        "Declares that the rule or aspect creates a directory with the given name, in the "
            + "current package. You must create an action that generates the directory. "
            + "The contents of the directory are not directly accessible from Starlark, "
            + "but can be expanded in an action command with "
            + "<a href=\"Args.html#add_all\"><code>Args.add_all()</code></a>.",
    parameters = {
      @Param(
          name = "filename",
          type = String.class,
          doc =
              "If no 'sibling' provided, path of the new directory, relative "
                  + "to the current package. Otherwise a base name for a file "
                  + "('sibling' defines a directory)."),
      @Param(
          name = "sibling",
          doc = "A file that lives in the same directory as the newly declared directory.",
          type = FileApi.class,
          noneable = true,
          positional = false,
          named = true,
          defaultValue = "None")
    })
FileApi declareDirectory(String filename, Object sibling) throws EvalException;
 
Example #13
Source File: StarlarkBuiltinsFunction.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the declarations of exports.bzl to the native predeclared symbols to obtain the final
 * {@link StarlarkBuiltinsValue}.
 */
private static StarlarkBuiltinsValue computeWithExports(
    BzlLoadValue exportsValue, RuleClassProvider ruleClassProvider, PackageFactory packageFactory)
    throws BuiltinsFailedException {
  byte[] transitiveDigest = exportsValue.getTransitiveDigest();
  Module module = exportsValue.getModule();

  try {
    ImmutableMap<String, Object> exportedToplevels = getDict(module, "exported_toplevels");
    ImmutableMap<String, Object> exportedRules = getDict(module, "exported_rules");
    ImmutableMap<String, Object> exportedToJava = getDict(module, "exported_to_java");
    ImmutableMap<String, Object> predeclared =
        createPredeclaredForBuildBzlUsingInjection(
            ruleClassProvider, packageFactory, exportedToplevels, exportedRules);
    return new StarlarkBuiltinsValue(predeclared, exportedToJava, transitiveDigest);
  } catch (EvalException ex) {
    ex.ensureLocation(EXPORTS_ENTRYPOINT_LOC);
    throw BuiltinsFailedException.errorApplyingExports(ex);
  }
}
 
Example #14
Source File: UserDefinedProviderTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void callReturnsCorrectUserDefinedProviderInfo()
    throws LabelSyntaxException, InterruptedException, EvalException {
  UserDefinedProvider provider =
      new UserDefinedProvider(location, new String[] {"foo", "bar", "baz"});
  provider.export(Label.parseAbsolute("//package:file.bzl", ImmutableMap.of()), "FooInfo");

  try (TestMutableEnv env = new TestMutableEnv()) {
    Object rawInfo =
        provider.call(
            ImmutableList.of(),
            ImmutableMap.of("foo", "foo_value", "bar", "bar_value", "baz", "baz_value"),
            null,
            env.getEnv());

    assertTrue(rawInfo instanceof UserDefinedProviderInfo);

    UserDefinedProviderInfo info = (UserDefinedProviderInfo) rawInfo;
    assertEquals("foo_value", info.getValue("foo"));
    assertEquals("bar_value", info.getValue("bar"));
    assertEquals("baz_value", info.getValue("baz"));
  }
}
 
Example #15
Source File: AndroidStarlarkData.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public AndroidAssetsInfo mergeAssets(
    AndroidDataContext ctx,
    Object assets,
    Object assetsDir,
    Sequence<?> deps, // <AndroidAssetsInfo>
    boolean neverlink)
    throws EvalException, InterruptedException {
  StarlarkErrorReporter errorReporter = StarlarkErrorReporter.from(ctx.getRuleErrorConsumer());
  try {
    return AndroidAssets.from(
            errorReporter,
            isNone(assets) ? null : Sequence.cast(assets, ConfiguredTarget.class, "assets"),
            isNone(assetsDir) ? null : PathFragment.create((String) assetsDir))
        .process(
            ctx,
            AssetDependencies.fromProviders(
                Sequence.cast(deps, AndroidAssetsInfo.class, "deps"), neverlink))
        .toProvider();
  } catch (RuleErrorException e) {
    throw handleRuleException(errorReporter, e);
  }
}
 
Example #16
Source File: StarlarkCallbackHelper.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a list of actual arguments that contains the given arguments and all attribute values
 * required from the specified context.
 */
private ImmutableList<Object> buildArgumentList(ClassObject ctx, Object... arguments)
    throws EvalException {
  ImmutableList.Builder<Object> builder = ImmutableList.builder();
  ImmutableList<String> names = getParameterNames();
  int requiredParameters = names.size() - arguments.length;
  for (int pos = 0; pos < requiredParameters; ++pos) {
    String name = names.get(pos);
    Object value = ctx.getValue(name);
    if (value == null) {
        throw new IllegalArgumentException(ctx.getErrorMessageForUnknownField(name));
    }
    builder.add(value);
  }
  return builder.add(arguments).build();
}
 
Example #17
Source File: RunActionTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException, EvalException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "run_scripts", tmp);
  workspace.setUp();

  BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
  filesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot());
  runner = new TestActionExecutionRunner(filesystem, target);
  scriptPath = Platform.isWindows() ? Paths.get("script.bat") : Paths.get("script.sh");
  script = runner.declareArtifact(scriptPath);

  // Make sure we're testing w/ a BuildArtifact instead of a SourceArtifact
  runner.runAction(
      new WriteAction(
          runner.getRegistry(),
          ImmutableSortedSet.of(),
          ImmutableSortedSet.of(script.asOutputArtifact()),
          filesystem.readFileIfItExists(scriptPath).get(),
          true));
}
 
Example #18
Source File: CppHelper.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience function for finding the dynamic runtime inputs for the current toolchain. Useful
 * for Starlark-defined rules that link against the C++ runtime.
 *
 * <p>This uses the default feature configuration. Do *not* use this method in rules that use a
 * non-default feature configuration, or risk a mismatch.
 */
public static NestedSet<Artifact> getDefaultCcToolchainDynamicRuntimeInputsFromStarlark(
    RuleContext ruleContext, CppSemantics semantics) throws EvalException {
  CcToolchainProvider defaultToolchain =
      getToolchainUsingDefaultCcToolchainAttribute(ruleContext);
  if (defaultToolchain == null) {
    return NestedSetBuilder.emptySet(Order.STABLE_ORDER);
  }
  FeatureConfiguration featureConfiguration =
      CcCommon.configureFeaturesOrReportRuleError(ruleContext, defaultToolchain, semantics);

  return defaultToolchain.getDynamicRuntimeLinkInputs(featureConfiguration);
}
 
Example #19
Source File: RunInfoTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void errorOnInvalidEnvType() throws EvalException {

  try (Mutability mut = Mutability.create("test")) {
    Object env = SkylarkDict.of(getEnv(mut), "foo", 1, "bar", 2);
    thrown.expect(EvalException.class);
    // Broken cast, but this can apparently happen, so... verify :)
    RunInfo.instantiateFromSkylark((SkylarkDict<String, String>) env, ImmutableList.of("value"));
  }
}
 
Example #20
Source File: FakeCcModule.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public CcCompilationContextApi<FileApi> createCcCompilationContext(
    Object headers,
    Object systemIncludes,
    Object includes,
    Object quoteIncludes,
    Object frameworkIncludes,
    Object defines,
    Object localDefines)
    throws EvalException {
  return null;
}
 
Example #21
Source File: FakeCcModule.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public FeatureConfigurationApi configureFeatures(
    Object ruleContextOrNone,
    CcToolchainProviderApi<FeatureConfigurationApi> toolchain,
    Sequence<?> requestedFeatures,
    Sequence<?> unsupportedFeatures)
    throws EvalException {
  return null;
}
 
Example #22
Source File: StarlarkRuleContextApi.java    From bazel with Apache License 2.0 5 votes vote down vote up
@StarlarkMethod(
    name = "tokenize",
    doc = "Splits a shell command into a list of tokens.",
    // TODO(cparsons): Look into flipping this to true.
    documented = false,
    parameters = {
      @Param(
          name = "option",
          positional = true,
          named = false,
          type = String.class,
          doc = "The string to split."),
    })
Sequence<String> tokenize(String optionString) throws EvalException;
 
Example #23
Source File: TransformWork.java    From copybara with Apache License 2.0 5 votes vote down vote up
@StarlarkMethod(
    name = "read_path",
    doc = "Read the content of path as UTF-8",
    parameters = {
        @Param(name = "path", type = CheckoutPath.class, doc = "The string representing the path"),
    })
public String readPath(CheckoutPath path) throws IOException, EvalException {
  return new String(Files.readAllBytes(asCheckoutPath(path)), UTF_8);
}
 
Example #24
Source File: DefaultPackageArguments.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(Package.Builder pkgBuilder, Location location,
    List<Label> value) throws EvalException {
  try {
    pkgBuilder.setDefaultVisibility(
        PackageUtils.getVisibility(pkgBuilder.getBuildFileLabel(), value));
  } catch (EvalException e) {
    throw new EvalException(location, e.getMessage());
  }
}
 
Example #25
Source File: SkylarkDescriptionArgTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void throwsWhenInvalidFieldIsRequested() throws EvalException, LabelSyntaxException {

  SkylarkDescriptionArg arg =
      new SkylarkDescriptionArg(FakeSkylarkUserDefinedRuleFactory.createSimpleRule());

  expected.expect(NullPointerException.class);
  arg.getPostCoercionValue("baz");
}
 
Example #26
Source File: StarlarkRuleContext.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public Sequence<String> tokenize(String optionString) throws EvalException {
  checkMutable("tokenize");
  List<String> options = new ArrayList<>();
  try {
    ShellUtils.tokenize(options, optionString);
  } catch (TokenizationException e) {
    throw new EvalException(null, e.getMessage() + " while tokenizing '" + optionString + "'");
  }
  return StarlarkList.immutableCopyOf(options);
}
 
Example #27
Source File: PyWrapCcHelperApi.java    From bazel with Apache License 2.0 5 votes vote down vote up
@StarlarkMethod(
    name = "get_transitive_python_sources",
    doc = "",
    documented = false,
    parameters = {
      @Param(name = "ctx", positional = false, named = true, type = StarlarkRuleContextApi.class),
      @Param(name = "py_file", positional = false, named = true, type = FileApi.class),
    })
// TODO(plf): Not written in Starlark because of PyCommon.
public Depset getTransitivePythonSources(StarlarkRuleContextT starlarkRuleContext, FileT pyFile)
    throws EvalException, InterruptedException;
 
Example #28
Source File: CopyOrMove.java    From copybara with Apache License 2.0 5 votes vote down vote up
private static String validatePath(String strPath) throws EvalException {
  try {
    return FileUtil.checkNormalizedRelative(strPath);
  } catch (IllegalArgumentException e) {
    throw Starlark.errorf("'%s' is not a valid path: %s", strPath, e.getMessage());
  }
}
 
Example #29
Source File: StarlarkRuleConfiguredTargetUtil.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the provider key from an info object.
 *
 * @throws EvalException if the provider for this info object has not been exported, which can
 *     occur if the provider was declared in a non-global scope (for example a rule implementation
 *     function)
 */
private static Provider.Key getProviderKey(Location loc, Info infoObject) throws EvalException {
  if (!infoObject.getProvider().isExported()) {
    throw new EvalException(
        loc,
        "cannot return a non-exported provider instance from a "
            + "rule implementation function. provider defined at "
            + infoObject.getProvider().getLocation()
            + " must be defined outside of a function scope.");
  }
  return infoObject.getProvider().getKey();
}
 
Example #30
Source File: RegexTemplateTokens.java    From copybara with Apache License 2.0 5 votes vote down vote up
public RegexTemplateTokens(Location location, String template, Map<String, Pattern> regexGroups,
    boolean repeatedGroups) throws EvalException {
  this.template = Preconditions.checkNotNull(template);

  this.tokens = ImmutableList.copyOf(new Parser().parse(template));
  this.before = buildBefore(regexGroups, repeatedGroups);

  this.unusedGroups = Sets.difference(regexGroups.keySet(), groupIndexes.keySet());
}