Search in sources :

Example 61 with Rule

use of com.google.devtools.build.lib.packages.Rule 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 62 with Rule

use of com.google.devtools.build.lib.packages.Rule in project bazel by bazelbuild.

the class BlazeTargetAccessor method getLabelListAttr.

@Override
public List<Target> getLabelListAttr(QueryExpression caller, Target target, String attrName, String errorMsgPrefix) throws QueryException, InterruptedException {
    Preconditions.checkArgument(target instanceof Rule);
    List<Target> result = new ArrayList<>();
    Rule rule = (Rule) target;
    AggregatingAttributeMapper attrMap = AggregatingAttributeMapper.of(rule);
    Type<?> attrType = attrMap.getAttributeType(attrName);
    if (attrType == null) {
        // Return an empty list if the attribute isn't defined for this rule.
        return ImmutableList.of();
    }
    for (Label label : attrMap.getReachableLabels(attrName, false)) {
        try {
            result.add(queryEnvironment.getTarget(label));
        } catch (TargetNotFoundException e) {
            queryEnvironment.reportBuildFileError(caller, errorMsgPrefix + e.getMessage());
        }
    }
    return result;
}
Also used : Target(com.google.devtools.build.lib.packages.Target) TargetNotFoundException(com.google.devtools.build.lib.query2.engine.QueryEnvironment.TargetNotFoundException) ArrayList(java.util.ArrayList) Label(com.google.devtools.build.lib.cmdline.Label) Rule(com.google.devtools.build.lib.packages.Rule) AggregatingAttributeMapper(com.google.devtools.build.lib.packages.AggregatingAttributeMapper)

Example 63 with Rule

use of com.google.devtools.build.lib.packages.Rule in project bazel by bazelbuild.

the class BlazeTargetAccessor method getAttrAsString.

@Override
public Iterable<String> getAttrAsString(Target target, String attrName) {
    Preconditions.checkArgument(target instanceof Rule);
    // May hold null values.
    List<String> values = new ArrayList<>();
    Attribute attribute = ((Rule) target).getAttributeDefinition(attrName);
    if (attribute != null) {
        Type<?> attributeType = attribute.getType();
        for (Object attrValue : AggregatingAttributeMapper.of((Rule) target).visitAttribute(attribute.getName(), attributeType)) {
            // opposite of the code in BooleanType and TriStateType respectively.
            if (attributeType == BOOLEAN) {
                values.add(Type.BOOLEAN.cast(attrValue) ? "1" : "0");
            } else if (attributeType == TRISTATE) {
                switch(BuildType.TRISTATE.cast(attrValue)) {
                    case AUTO:
                        values.add("-1");
                        break;
                    case NO:
                        values.add("0");
                        break;
                    case YES:
                        values.add("1");
                        break;
                    default:
                        throw new AssertionError("This can't happen!");
                }
            } else {
                values.add(attrValue == null ? null : attrValue.toString());
            }
        }
    }
    return values;
}
Also used : Attribute(com.google.devtools.build.lib.packages.Attribute) ArrayList(java.util.ArrayList) Rule(com.google.devtools.build.lib.packages.Rule)

Example 64 with Rule

use of com.google.devtools.build.lib.packages.Rule in project bazel by bazelbuild.

the class ConservativeAspectResolver method computeAspectDependencies.

@Override
public ImmutableMultimap<Attribute, Label> computeAspectDependencies(Target target, DependencyFilter dependencyFilter) throws InterruptedException {
    if (!(target instanceof Rule)) {
        return ImmutableMultimap.of();
    }
    Rule rule = (Rule) target;
    Multimap<Attribute, Label> result = LinkedHashMultimap.create();
    for (Attribute attribute : rule.getAttributes()) {
        for (Aspect aspect : attribute.getAspects(rule)) {
            AspectDefinition.addAllAttributesOfAspect(rule, result, aspect, dependencyFilter);
        }
    }
    return ImmutableMultimap.copyOf(result);
}
Also used : Attribute(com.google.devtools.build.lib.packages.Attribute) Label(com.google.devtools.build.lib.cmdline.Label) Rule(com.google.devtools.build.lib.packages.Rule) Aspect(com.google.devtools.build.lib.packages.Aspect)

Example 65 with Rule

use of com.google.devtools.build.lib.packages.Rule in project bazel by bazelbuild.

the class JvmConfigurationLoader method createDefault.

@Nullable
private static Jvm createDefault(ConfigurationEnvironment lookup, String javaHome, String cpu) throws InvalidConfigurationException, LabelSyntaxException, InterruptedException {
    try {
        Label label = Label.parseAbsolute(javaHome);
        label = RedirectChaser.followRedirects(lookup, label, "jdk");
        if (label == null) {
            return null;
        }
        Target javaHomeTarget = lookup.getTarget(label);
        if (javaHomeTarget instanceof Rule) {
            if (!((Rule) javaHomeTarget).getRuleClass().equals("java_runtime_suite")) {
                throw new InvalidConfigurationException("Unexpected javabase rule kind '" + ((Rule) javaHomeTarget).getRuleClass() + "'");
            }
            return createFromRuntimeSuite(lookup, (Rule) javaHomeTarget, cpu);
        }
        throw new InvalidConfigurationException("No JVM target found under " + javaHome + " that would work for " + cpu);
    } catch (NoSuchThingException e) {
        lookup.getEventHandler().handle(Event.error(e.getMessage()));
        throw new InvalidConfigurationException(e.getMessage(), e);
    }
}
Also used : Target(com.google.devtools.build.lib.packages.Target) NoSuchThingException(com.google.devtools.build.lib.packages.NoSuchThingException) Label(com.google.devtools.build.lib.cmdline.Label) Rule(com.google.devtools.build.lib.packages.Rule) InvalidConfigurationException(com.google.devtools.build.lib.analysis.config.InvalidConfigurationException) Nullable(javax.annotation.Nullable)

Aggregations

Rule (com.google.devtools.build.lib.packages.Rule)79 Test (org.junit.Test)27 Label (com.google.devtools.build.lib.cmdline.Label)26 Attribute (com.google.devtools.build.lib.packages.Attribute)20 Target (com.google.devtools.build.lib.packages.Target)19 Nullable (javax.annotation.Nullable)10 RawAttributeMapper (com.google.devtools.build.lib.packages.RawAttributeMapper)9 PathFragment (com.google.devtools.build.lib.vfs.PathFragment)9 OutputFile (com.google.devtools.build.lib.packages.OutputFile)8 BuildConfiguration (com.google.devtools.build.lib.analysis.config.BuildConfiguration)7 NoSuchThingException (com.google.devtools.build.lib.packages.NoSuchThingException)7 SkyKey (com.google.devtools.build.skyframe.SkyKey)7 ImmutableList (com.google.common.collect.ImmutableList)6 InputFile (com.google.devtools.build.lib.packages.InputFile)6 IOException (java.io.IOException)6 LinkedHashSet (java.util.LinkedHashSet)6 AggregatingAttributeMapper (com.google.devtools.build.lib.packages.AggregatingAttributeMapper)5 Package (com.google.devtools.build.lib.packages.Package)5 Artifact (com.google.devtools.build.lib.actions.Artifact)4 ConfiguredTarget (com.google.devtools.build.lib.analysis.ConfiguredTarget)4