下面列出了java.lang.invoke.WrongMethodTypeException#com.google.devtools.build.lib.syntax.EvalException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
}
@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));
}
@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"));
}
}
@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;
@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);
}
@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);
}
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();
}
@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;
@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);
}
}
/**
* 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());
}
}
}
}
@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;
/**
* 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);
}
}
/**
* 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);
}
}
@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();
}
@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());
}
}
@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()));
}
/**
* 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();
}
@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;
@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");
}
/** 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;
}
@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);
}
@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);
}
private ConfigFile resolve(String path) throws EvalException {
try {
return configFile.resolve(path);
} catch (CannotResolveLabel e) {
throw Starlark.errorf("Failed to resolve patch: %s", path);
}
}
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);
}
}
@Override
public boolean isJavaToolchainResolutionEnabled(StarlarkRuleContext ruleContext)
throws EvalException {
return ruleContext
.getConfiguration()
.getOptions()
.get(PlatformOptions.class)
.useToolchainResolutionForJavaRules;
}
@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());
}
}
/**
* 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();
}
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());
}
}
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());
}
@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;