java.lang.invoke.WrongMethodTypeException#com.google.devtools.build.lib.syntax.EvalException源码实例Demo

下面列出了java.lang.invoke.WrongMethodTypeException#com.google.devtools.build.lib.syntax.EvalException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: bazel   文件: CcCommon.java
/**
 * 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;
  }
}
 
源代码2 项目: buck   文件: RunActionTest.java
@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));
}
 
源代码3 项目: buck   文件: UserDefinedProviderTest.java
@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"));
  }
}
 
源代码4 项目: bazel   文件: StarlarkActionFactoryApi.java
@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;
 
源代码5 项目: copybara   文件: CheckoutPath.java
@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);
}
 
源代码6 项目: copybara   文件: CheckoutPath.java
@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);
}
 
源代码7 项目: bazel   文件: StarlarkRepositoryContext.java
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();
}
 
源代码8 项目: bazel   文件: CommandLineArgsApi.java
@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;
 
源代码9 项目: bazel   文件: AndroidStarlarkData.java
@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);
  }
}
 
源代码10 项目: bazel   文件: ObjcProvider.java
/**
 * 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());
      }
    }
  }
}
 
源代码11 项目: bazel   文件: AppleCommonApi.java
@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;
 
源代码12 项目: bazel   文件: StarlarkBuiltinsFunction.java
/**
 * 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);
  }
}
 
源代码13 项目: bazel   文件: ThreadHandler.java
/**
 * 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);
  }
}
 
源代码14 项目: buck   文件: SkylarkBuildModule.java
@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();
}
 
源代码15 项目: copybara   文件: CoreGlobal.java
@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());
  }
}
 
源代码16 项目: bazel   文件: CcToolchainFeaturesTest.java
@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()));
}
 
源代码17 项目: bazel   文件: StarlarkCallbackHelper.java
/**
 * 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();
}
 
源代码18 项目: buck   文件: SkylarkArtifactApi.java
@SkylarkCallable(
    name = "as_output",
    doc =
        "Get an instance of this artifact that signals it is intended to be used as an output. "
            + "This is normally only of use with `ctx.action.run()`, or `ctx.action.args()`",
    useLocation = true)
SkylarkOutputArtifactApi asSkylarkOutputArtifact(Location location) throws EvalException;
 
源代码19 项目: buck   文件: BuckSkylarkTypesTest.java
@Test
public void validateKwargNameHandlesValidNames() throws EvalException {
  Location location = Location.fromPathFragment(PathFragment.create("foo"));
  BuckSkylarkTypes.validateKwargName(location, "foo");
  BuckSkylarkTypes.validateKwargName(location, "foo_bar");
  BuckSkylarkTypes.validateKwargName(location, "foo_bar1");
  BuckSkylarkTypes.validateKwargName(location, "_foo");
  BuckSkylarkTypes.validateKwargName(location, "_foo_bar2");
}
 
源代码20 项目: buck   文件: ParseContext.java
/** Get the {@link ParseContext} by looking up in the environment. */
public static ParseContext getParseContext(Environment env, FuncallExpression ast)
    throws EvalException {
  @Nullable ParseContext value = (ParseContext) env.dynamicLookup(PARSE_CONTEXT);
  if (value == null) {
    // if PARSE_CONTEXT is missing, we're not called from a build file. This happens if someone
    // uses native.some_func() in the wrong place.
    throw new EvalException(
        ast.getLocation(),
        "Top-level invocations of "
            + ast.getFunction()
            + " are not allowed in .bzl files. Wrap it in a macro and call it from a BUCK file.");
  }
  return value;
}
 
源代码21 项目: buck   文件: SourceArtifactImplTest.java
@Test
public void cannotBeUsedAsSkylarkOutputArtifact() throws EvalException {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();

  SourceArtifactImpl artifact =
      ImmutableSourceArtifactImpl.of(PathSourcePath.of(filesystem, Paths.get("foo", "bar.cpp")));

  thrown.expect(EvalException.class);
  artifact.asSkylarkOutputArtifact(Location.BUILTIN);
}
 
源代码22 项目: bazel   文件: BuildViewForTesting.java
@VisibleForTesting
public Collection<ConfiguredTarget> getDirectPrerequisitesForTesting(
    ExtendedEventHandler eventHandler,
    ConfiguredTarget ct,
    BuildConfigurationCollection configurations)
    throws EvalException, InvalidConfigurationException, InterruptedException,
        InconsistentAspectOrderException, StarlarkTransition.TransitionException {
  return Collections2.transform(
      getConfiguredTargetAndDataDirectPrerequisitesForTesting(eventHandler, ct, configurations),
      ConfiguredTargetAndData::getConfiguredTarget);
}
 
源代码23 项目: copybara   文件: PatchModule.java
private ConfigFile resolve(String path) throws EvalException {
  try {
    return configFile.resolve(path);
  } catch (CannotResolveLabel e) {
    throw Starlark.errorf("Failed to resolve patch: %s", path);
  }
}
 
源代码24 项目: bazel   文件: SelectTest.java
private static Object eval(String expr)
    throws SyntaxError.Exception, EvalException, InterruptedException {
  ParserInput input = ParserInput.fromLines(expr);
  Module module =
      Module.withPredeclared(StarlarkSemantics.DEFAULT, /*predeclared=*/ StarlarkLibrary.COMMON);
  try (Mutability mu = Mutability.create()) {
    StarlarkThread thread = new StarlarkThread(mu, StarlarkSemantics.DEFAULT);
    return EvalUtils.eval(input, FileOptions.DEFAULT, module, thread);
  }
}
 
源代码25 项目: bazel   文件: JavaStarlarkCommon.java
@Override
public boolean isJavaToolchainResolutionEnabled(StarlarkRuleContext ruleContext)
    throws EvalException {
  return ruleContext
      .getConfiguration()
      .getOptions()
      .get(PlatformOptions.class)
      .useToolchainResolutionForJavaRules;
}
 
源代码26 项目: bazel   文件: DefaultPackageArguments.java
@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());
  }
}
 
源代码27 项目: bazel   文件: StarlarkRuleConfiguredTargetUtil.java
/**
 * 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();
}
 
源代码28 项目: copybara   文件: CopyOrMove.java
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());
  }
}
 
源代码29 项目: copybara   文件: RegexTemplateTokens.java
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());
}
 
源代码30 项目: bazel   文件: PyWrapCcHelperApi.java
@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;