Search in sources :

Example 11 with Environment

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;
    }
}
Also used : SkylarkClassObject(com.google.devtools.build.lib.packages.SkylarkClassObject) Mutability(com.google.devtools.build.lib.syntax.Mutability) ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) EvalException(com.google.devtools.build.lib.syntax.EvalException) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) Environment(com.google.devtools.build.lib.syntax.Environment) SkylarkClassObject(com.google.devtools.build.lib.packages.SkylarkClassObject) ClassObject(com.google.devtools.build.lib.syntax.ClassObject)

Example 12 with Environment

use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.

the class ProtoOutputFormatter method toTargetProtoBuffer.

/** Converts a logical {@link Target} object into a {@link Build.Target} protobuffer. */
@VisibleForTesting
public Build.Target toTargetProtoBuffer(Target target) throws InterruptedException {
    Build.Target.Builder targetPb = Build.Target.newBuilder();
    String location = getLocation(target, relativeLocations);
    if (target instanceof Rule) {
        Rule rule = (Rule) target;
        Build.Rule.Builder rulePb = Build.Rule.newBuilder().setName(rule.getLabel().toString()).setRuleClass(rule.getRuleClass());
        if (includeLocation()) {
            rulePb.setLocation(location);
        }
        Map<Attribute, Build.Attribute> serializedAttributes = Maps.newHashMap();
        for (Attribute attr : rule.getAttributes()) {
            if ((!includeDefaultValues && !rule.isAttributeValueExplicitlySpecified(attr)) || !includeAttribute(rule, attr)) {
                continue;
            }
            Object flattenedAttributeValue = flattenAttributeValues(attr.getType(), getPossibleAttributeValues(rule, attr));
            Build.Attribute serializedAttribute = AttributeFormatter.getAttributeProto(attr, flattenedAttributeValue, rule.isAttributeValueExplicitlySpecified(attr), /*encodeBooleanAndTriStateAsIntegerAndString=*/
            true);
            rulePb.addAttribute(serializedAttribute);
            serializedAttributes.put(attr, serializedAttribute);
        }
        postProcess(rule, rulePb, serializedAttributes);
        Environment env = rule.getRuleClassObject().getRuleDefinitionEnvironment();
        if (env != null && includeRuleDefinitionEnvironment()) {
            // The RuleDefinitionEnvironment is always defined for Skylark rules and
            // always null for non Skylark rules.
            rulePb.addAttribute(Build.Attribute.newBuilder().setName(RULE_IMPLEMENTATION_HASH_ATTR_NAME).setType(ProtoUtils.getDiscriminatorFromType(Type.STRING)).setStringValue(env.getTransitiveContentHashCode()));
        }
        ImmutableMultimap<Attribute, Label> aspectsDependencies = aspectResolver.computeAspectDependencies(target, dependencyFilter);
        // Add information about additional attributes from aspects.
        for (Entry<Attribute, Collection<Label>> entry : aspectsDependencies.asMap().entrySet()) {
            Attribute attribute = entry.getKey();
            Collection<Label> labels = entry.getValue();
            if (!includeAspectAttribute(attribute, labels)) {
                continue;
            }
            Object attributeValue = getAspectAttributeValue(attribute, labels);
            Build.Attribute serializedAttribute = AttributeFormatter.getAttributeProto(attribute, attributeValue, /*explicitlySpecified=*/
            false, /*encodeBooleanAndTriStateAsIntegerAndString=*/
            true);
            rulePb.addAttribute(serializedAttribute);
        }
        if (includeRuleInputsAndOutputs()) {
            // Add all deps from aspects as rule inputs of current target.
            for (Label label : aspectsDependencies.values()) {
                rulePb.addRuleInput(label.toString());
            }
            // host-configuration outputs, and default values.
            for (Label label : rule.getLabels(dependencyFilter)) {
                rulePb.addRuleInput(label.toString());
            }
            for (OutputFile outputFile : rule.getOutputFiles()) {
                Label fileLabel = outputFile.getLabel();
                rulePb.addRuleOutput(fileLabel.toString());
            }
        }
        for (String feature : rule.getFeatures()) {
            rulePb.addDefaultSetting(feature);
        }
        targetPb.setType(RULE);
        targetPb.setRule(rulePb);
    } else if (target instanceof OutputFile) {
        OutputFile outputFile = (OutputFile) target;
        Label label = outputFile.getLabel();
        Rule generatingRule = outputFile.getGeneratingRule();
        GeneratedFile.Builder output = GeneratedFile.newBuilder().setGeneratingRule(generatingRule.getLabel().toString()).setName(label.toString());
        if (includeLocation()) {
            output.setLocation(location);
        }
        targetPb.setType(GENERATED_FILE);
        targetPb.setGeneratedFile(output.build());
    } else if (target instanceof InputFile) {
        InputFile inputFile = (InputFile) target;
        Label label = inputFile.getLabel();
        Build.SourceFile.Builder input = Build.SourceFile.newBuilder().setName(label.toString());
        if (includeLocation()) {
            input.setLocation(location);
        }
        if (inputFile.getName().equals("BUILD")) {
            Set<Label> subincludeLabels = new LinkedHashSet<>();
            subincludeLabels.addAll(aspectResolver == null ? inputFile.getPackage().getSubincludeLabels() : aspectResolver.computeBuildFileDependencies(inputFile.getPackage(), BuildFileDependencyMode.SUBINCLUDE));
            subincludeLabels.addAll(aspectResolver == null ? inputFile.getPackage().getSkylarkFileDependencies() : aspectResolver.computeBuildFileDependencies(inputFile.getPackage(), BuildFileDependencyMode.SKYLARK));
            for (Label skylarkFileDep : subincludeLabels) {
                input.addSubinclude(skylarkFileDep.toString());
            }
            for (String feature : inputFile.getPackage().getFeatures()) {
                input.addFeature(feature);
            }
            input.setPackageContainsErrors(inputFile.getPackage().containsErrors());
        }
        for (Label visibilityDependency : target.getVisibility().getDependencyLabels()) {
            input.addPackageGroup(visibilityDependency.toString());
        }
        for (Label visibilityDeclaration : target.getVisibility().getDeclaredLabels()) {
            input.addVisibilityLabel(visibilityDeclaration.toString());
        }
        targetPb.setType(SOURCE_FILE);
        targetPb.setSourceFile(input);
    } else if (target instanceof FakeSubincludeTarget) {
        Label label = target.getLabel();
        SourceFile.Builder input = SourceFile.newBuilder().setName(label.toString());
        if (includeLocation()) {
            input.setLocation(location);
        }
        targetPb.setType(SOURCE_FILE);
        targetPb.setSourceFile(input.build());
    } else if (target instanceof PackageGroup) {
        PackageGroup packageGroup = (PackageGroup) target;
        Build.PackageGroup.Builder packageGroupPb = Build.PackageGroup.newBuilder().setName(packageGroup.getLabel().toString());
        for (String containedPackage : packageGroup.getContainedPackages()) {
            packageGroupPb.addContainedPackage(containedPackage);
        }
        for (Label include : packageGroup.getIncludes()) {
            packageGroupPb.addIncludedPackageGroup(include.toString());
        }
        targetPb.setType(PACKAGE_GROUP);
        targetPb.setPackageGroup(packageGroupPb);
    } else if (target instanceof EnvironmentGroup) {
        EnvironmentGroup envGroup = (EnvironmentGroup) target;
        Build.EnvironmentGroup.Builder envGroupPb = Build.EnvironmentGroup.newBuilder().setName(envGroup.getLabel().toString());
        for (Label env : envGroup.getEnvironments()) {
            envGroupPb.addEnvironment(env.toString());
        }
        for (Label defaultEnv : envGroup.getDefaults()) {
            envGroupPb.addDefault(defaultEnv.toString());
        }
        targetPb.setType(ENVIRONMENT_GROUP);
        targetPb.setEnvironmentGroup(envGroupPb);
    } else {
        throw new IllegalArgumentException(target.toString());
    }
    return targetPb.build();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Attribute(com.google.devtools.build.lib.packages.Attribute) Builder(com.google.devtools.build.lib.query2.proto.proto2api.Build.QueryResult.Builder) Label(com.google.devtools.build.lib.cmdline.Label) EnvironmentGroup(com.google.devtools.build.lib.packages.EnvironmentGroup) FakeSubincludeTarget(com.google.devtools.build.lib.query2.FakeSubincludeTarget) Target(com.google.devtools.build.lib.packages.Target) FakeSubincludeTarget(com.google.devtools.build.lib.query2.FakeSubincludeTarget) Build(com.google.devtools.build.lib.query2.proto.proto2api.Build) SourceFile(com.google.devtools.build.lib.query2.proto.proto2api.Build.SourceFile) OutputFile(com.google.devtools.build.lib.packages.OutputFile) PackageGroup(com.google.devtools.build.lib.packages.PackageGroup) InputFile(com.google.devtools.build.lib.packages.InputFile) Environment(com.google.devtools.build.lib.syntax.Environment) QueryEnvironment(com.google.devtools.build.lib.query2.engine.QueryEnvironment) Collection(java.util.Collection) Rule(com.google.devtools.build.lib.packages.Rule) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 13 with Environment

use of com.google.devtools.build.lib.syntax.Environment in project bazel by bazelbuild.

the class SkylarkRuleImplementationFunctionsTest method setupSkylarkFunction.

private void setupSkylarkFunction(String line) throws Exception {
    mockFunc = new BuiltinFunction("mock") {

        @SuppressWarnings("unused")
        public Object invoke(Object mandatory, Object optional, Object mandatoryKey, Object optionalKey, Environment env) {
            return EvalUtils.optionMap(env, "mandatory", mandatory, "optional", optional, "mandatory_key", mandatoryKey, "optional_key", optionalKey);
        }
    };
    assertFalse(mockFunc.isConfigured());
    mockFunc.configure(SkylarkRuleImplementationFunctionsTest.class.getDeclaredField("mockFunc").getAnnotation(SkylarkSignature.class));
    update("mock", mockFunc);
    eval(line);
}
Also used : BuiltinFunction(com.google.devtools.build.lib.syntax.BuiltinFunction) Environment(com.google.devtools.build.lib.syntax.Environment) SkylarkClassObject(com.google.devtools.build.lib.packages.SkylarkClassObject) SkylarkSignature(com.google.devtools.build.lib.skylarkinterface.SkylarkSignature)

Aggregations

Environment (com.google.devtools.build.lib.syntax.Environment)13 EvalException (com.google.devtools.build.lib.syntax.EvalException)7 Mutability (com.google.devtools.build.lib.syntax.Mutability)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 SkylarkClassObject (com.google.devtools.build.lib.packages.SkylarkClassObject)3 BuiltinFunction (com.google.devtools.build.lib.syntax.BuiltinFunction)3 ClassObject (com.google.devtools.build.lib.syntax.ClassObject)3 FuncallExpression (com.google.devtools.build.lib.syntax.FuncallExpression)3 Map (java.util.Map)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)2 Label (com.google.devtools.build.lib.cmdline.Label)2 LabelSyntaxException (com.google.devtools.build.lib.cmdline.LabelSyntaxException)2 NameConflictException (com.google.devtools.build.lib.packages.Package.NameConflictException)2 InvalidRuleException (com.google.devtools.build.lib.packages.RuleFactory.InvalidRuleException)2 HashMap (java.util.HashMap)2 ConfiguredTarget (com.google.devtools.build.lib.analysis.ConfiguredTarget)1 RuleConfiguredTargetBuilder (com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder)1 StoredEventHandler (com.google.devtools.build.lib.events.StoredEventHandler)1 AspectDescriptor (com.google.devtools.build.lib.packages.AspectDescriptor)1