use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.
the class SkylarkAspectFactory method create.
@Override
public ConfiguredAspect create(ConfiguredTarget base, RuleContext ruleContext, AspectParameters parameters) throws InterruptedException {
try (Mutability mutability = Mutability.create("aspect")) {
AspectDescriptor aspectDescriptor = new AspectDescriptor(skylarkAspect.getAspectClass(), parameters);
SkylarkRuleContext skylarkRuleContext;
try {
skylarkRuleContext = new SkylarkRuleContext(ruleContext, aspectDescriptor);
} catch (EvalException e) {
ruleContext.ruleError(e.getMessage());
return null;
}
Environment env = Environment.builder(mutability).setGlobals(skylarkAspect.getFuncallEnv().getGlobals()).setEventHandler(ruleContext.getAnalysisEnvironment().getEventHandler()).build();
// so we do *not* setLoadingPhase().
Object aspectSkylarkObject;
try {
aspectSkylarkObject = skylarkAspect.getImplementation().call(ImmutableList.<Object>of(base, skylarkRuleContext), ImmutableMap.<String, Object>of(), /*ast=*/
null, env);
if (ruleContext.hasErrors()) {
return null;
} else if (!(aspectSkylarkObject instanceof SkylarkClassObject) && !(aspectSkylarkObject instanceof Iterable)) {
ruleContext.ruleError(String.format("Aspect implementation should return a struct or a list, but got %s", SkylarkType.typeOf(aspectSkylarkObject)));
return null;
}
return createAspect(aspectSkylarkObject, aspectDescriptor, ruleContext);
} catch (EvalException e) {
addAspectToStackTrace(base, e);
ruleContext.ruleError("\n" + e.print());
return null;
}
}
}
use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.
the class WorkspaceFactory method newBindFunction.
private static BuiltinFunction newBindFunction(final RuleFactory ruleFactory) {
return new BuiltinFunction("bind", FunctionSignature.namedOnly(1, "name", "actual"), BuiltinFunction.USE_AST_ENV) {
public Object invoke(String name, String actual, FuncallExpression ast, Environment env) throws EvalException, InterruptedException {
Label nameLabel;
try {
nameLabel = Label.parseAbsolute("//external:" + name);
try {
Package.Builder builder = PackageFactory.getContext(env, ast).pkgBuilder;
RuleClass ruleClass = ruleFactory.getRuleClass("bind");
builder.externalPackageData().addBindRule(builder, ruleClass, nameLabel, actual == null ? null : Label.parseAbsolute(actual), ast.getLocation(), ruleFactory.getAttributeContainer(ruleClass));
} catch (RuleFactory.InvalidRuleException | Package.NameConflictException | LabelSyntaxException e) {
throw new EvalException(ast.getLocation(), e.getMessage());
}
} catch (LabelSyntaxException e) {
throw new EvalException(ast.getLocation(), e.getMessage());
}
return NONE;
}
};
}
use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.
the class PackageFactory method prefetchGlobs.
/**
* Visit all targets and expand the globs in parallel.
*/
private void prefetchGlobs(PackageIdentifier packageId, BuildFileAST buildFileAST, boolean wasPreprocessed, Path buildFilePath, Globber globber, RuleVisibility defaultVisibility, MakeEnvironment.Builder pkgMakeEnv) throws InterruptedException {
if (wasPreprocessed && preprocessorFactory.considersGlobs()) {
// point in prefetching them again.
return;
}
// these can be executed and their impact on the resulting package can be saved.
try (Mutability mutability = Mutability.create("prefetchGlobs for %s", packageId)) {
Environment pkgEnv = Environment.builder(mutability).setGlobals(BazelLibrary.GLOBALS).setEventHandler(NullEventHandler.INSTANCE).setPhase(Phase.LOADING).build();
SkylarkUtils.setToolsRepository(pkgEnv, ruleClassProvider.getToolsRepository());
Package.Builder pkgBuilder = new Package.Builder(packageBuilderHelper.createFreshPackage(packageId, ruleClassProvider.getRunfilesPrefix()));
pkgBuilder.setFilename(buildFilePath).setMakeEnv(pkgMakeEnv).setDefaultVisibility(defaultVisibility).setDefaultVisibilitySet(false);
// Stuff that closes over the package context:
PackageContext context = new PackageContext(pkgBuilder, globber, NullEventHandler.INSTANCE, ruleFactory.getAttributeContainerFactory());
buildPkgEnv(pkgEnv, context, ruleFactory);
try {
pkgEnv.update("glob", newGlobFunction.apply(context, /*async=*/
true));
// The Fileset function is heavyweight in that it can run glob(). Avoid this during the
// preloading phase.
pkgEnv.update("FilesetEntry", Runtime.NONE);
} catch (EvalException e) {
throw new AssertionError(e);
}
buildFileAST.exec(pkgEnv, NullEventHandler.INSTANCE);
}
}
use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.
the class PackageFactory method evaluateBuildFile.
/**
* Constructs a Package instance, evaluates the BUILD-file AST inside the
* build environment, and populates the package with Rule instances as it
* goes. As with most programming languages, evaluation stops when an
* exception is encountered: no further rules after the point of failure will
* be constructed. We assume that rules constructed before the point of
* failure are valid; this assumption is not entirely correct, since a
* "vardef" after a rule declaration can affect the behavior of that rule.
*
* <p>Rule attribute checking is performed during evaluation. Each attribute
* must conform to the type specified for that <i>(rule class, attribute
* name)</i> pair. Errors reported at this stage include: missing value for
* mandatory attribute, value of wrong type. Such error cause Rule
* construction to be aborted, so the resulting package will have missing
* members.
*
* @see PackageFactory#PackageFactory
*/
// used by PackageFactoryApparatus
@VisibleForTesting
public Package.Builder evaluateBuildFile(String workspaceName, PackageIdentifier packageId, BuildFileAST buildFileAST, Path buildFilePath, Globber globber, Iterable<Event> pastEvents, RuleVisibility defaultVisibility, boolean containsError, MakeEnvironment.Builder pkgMakeEnv, Map<String, Extension> imports, ImmutableList<Label> skylarkFileDependencies) throws InterruptedException {
Package.Builder pkgBuilder = new Package.Builder(packageBuilderHelper.createFreshPackage(packageId, ruleClassProvider.getRunfilesPrefix()));
StoredEventHandler eventHandler = new StoredEventHandler();
try (Mutability mutability = Mutability.create("package %s", packageId)) {
Environment pkgEnv = Environment.builder(mutability).setGlobals(BazelLibrary.GLOBALS).setEventHandler(eventHandler).setImportedExtensions(imports).setPhase(Phase.LOADING).build();
SkylarkUtils.setToolsRepository(pkgEnv, ruleClassProvider.getToolsRepository());
pkgBuilder.setFilename(buildFilePath).setMakeEnv(pkgMakeEnv).setDefaultVisibility(defaultVisibility).setDefaultVisibilitySet(false).setSkylarkFileDependencies(skylarkFileDependencies).setWorkspaceName(workspaceName);
Event.replayEventsOn(eventHandler, pastEvents);
// Stuff that closes over the package context:
PackageContext context = new PackageContext(pkgBuilder, globber, eventHandler, ruleFactory.getAttributeContainerFactory());
buildPkgEnv(pkgEnv, context, ruleFactory);
pkgEnv.setupDynamic(PKG_CONTEXT, context);
pkgEnv.setupDynamic(Runtime.PKG_NAME, packageId.getPackageFragment().getPathString());
pkgEnv.setupDynamic(Runtime.REPOSITORY_NAME, packageId.getRepository().toString());
if (containsError) {
pkgBuilder.setContainsErrors();
}
if (!validatePackageIdentifier(packageId, buildFileAST.getLocation(), eventHandler)) {
pkgBuilder.setContainsErrors();
}
if (!validateAssignmentStatements(pkgEnv, buildFileAST, eventHandler)) {
pkgBuilder.setContainsErrors();
}
if (buildFileAST.containsErrors()) {
pkgBuilder.setContainsErrors();
}
// createPackage().
if (!buildFileAST.exec(pkgEnv, eventHandler)) {
pkgBuilder.setContainsErrors();
}
}
pkgBuilder.addEvents(eventHandler.getEvents());
return pkgBuilder;
}
use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.
the class SkylarkRuleConfiguredTargetBuilder method buildRule.
/**
* Create a Rule Configured Target from the ruleContext and the ruleImplementation. The
* registeredProviderTypes map indicates which keys in structs returned by skylark rules
* should be interpreted as native TransitiveInfoProvider instances of type (map value).
*/
public static ConfiguredTarget buildRule(RuleContext ruleContext, BaseFunction ruleImplementation, Map<String, Class<? extends TransitiveInfoProvider>> registeredProviderTypes) throws InterruptedException {
String expectFailure = ruleContext.attributes().get("expect_failure", Type.STRING);
try (Mutability mutability = Mutability.create("configured target")) {
SkylarkRuleContext skylarkRuleContext = new SkylarkRuleContext(ruleContext, null);
Environment env = Environment.builder(mutability).setCallerLabel(ruleContext.getLabel()).setGlobals(ruleContext.getRule().getRuleClassObject().getRuleDefinitionEnvironment().getGlobals()).setEventHandler(ruleContext.getAnalysisEnvironment().getEventHandler()).build();
// so we do *not* setLoadingPhase().
Object target = ruleImplementation.call(ImmutableList.<Object>of(skylarkRuleContext), ImmutableMap.<String, Object>of(), /*ast=*/
null, env);
if (ruleContext.hasErrors()) {
return null;
} else if (!(target instanceof SkylarkClassObject) && target != Runtime.NONE && !(target instanceof Iterable)) {
ruleContext.ruleError(String.format("Rule should return a struct or a list, but got %s", SkylarkType.typeOf(target)));
return null;
} else if (!expectFailure.isEmpty()) {
ruleContext.ruleError("Expected failure not found: " + expectFailure);
return null;
}
ConfiguredTarget configuredTarget = createTarget(ruleContext, target, registeredProviderTypes);
SkylarkProviderValidationUtil.checkOrphanArtifacts(ruleContext);
return configuredTarget;
} catch (EvalException e) {
addRuleToStackTrace(e, ruleContext.getRule(), ruleImplementation);
// If the error was expected, return an empty target.
if (!expectFailure.isEmpty() && getMessageWithoutStackTrace(e).matches(expectFailure)) {
return new com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder(ruleContext).add(RunfilesProvider.class, RunfilesProvider.EMPTY).build();
}
ruleContext.ruleError("\n" + e.print());
return null;
}
}
Aggregations