// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules; import static com.google.devtools.build.lib.analysis.BaseRuleClasses.RUN_UNDER; import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.DATA; import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST; import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; import static com.google.devtools.build.lib.packages.BuildType.LICENSE; import static com.google.devtools.build.lib.syntax.SkylarkType.castMap; import static com.google.devtools.build.lib.syntax.Type.BOOLEAN; import static com.google.devtools.build.lib.syntax.Type.INTEGER; import static com.google.devtools.build.lib.syntax.Type.STRING; import static com.google.devtools.build.lib.syntax.Type.STRING_LIST; import com.google.common.annotations.VisibleForTesting; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.ActionsProvider; import com.google.devtools.build.lib.analysis.BaseRuleClasses; import com.google.devtools.build.lib.analysis.DefaultProvider; import com.google.devtools.build.lib.analysis.OutputGroupProvider; import com.google.devtools.build.lib.analysis.PlatformSemantics; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.LabelSyntaxException; import com.google.devtools.build.lib.cmdline.LabelValidator; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.packages.Attribute; import com.google.devtools.build.lib.packages.AttributeMap; import com.google.devtools.build.lib.packages.AttributeValueSource; import com.google.devtools.build.lib.packages.ClassObjectConstructor; import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.SkylarkImplicitOutputsFunctionWithCallback; import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.SkylarkImplicitOutputsFunctionWithMap; import com.google.devtools.build.lib.packages.NativeClassObjectConstructor; import com.google.devtools.build.lib.packages.Package.NameConflictException; import com.google.devtools.build.lib.packages.PackageFactory; import com.google.devtools.build.lib.packages.PackageFactory.PackageContext; import com.google.devtools.build.lib.packages.PredicateWithMessage; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder; import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.packages.RuleFactory; import com.google.devtools.build.lib.packages.RuleFactory.BuildLangTypedAttributeValuesMap; import com.google.devtools.build.lib.packages.RuleFactory.InvalidRuleException; import com.google.devtools.build.lib.packages.SkylarkAspect; import com.google.devtools.build.lib.packages.SkylarkClassObject; import com.google.devtools.build.lib.packages.SkylarkClassObjectConstructor; import com.google.devtools.build.lib.packages.SkylarkExportable; import com.google.devtools.build.lib.packages.TargetUtils; import com.google.devtools.build.lib.packages.TestSize; import com.google.devtools.build.lib.rules.SkylarkAttr.Descriptor; import com.google.devtools.build.lib.skylarkinterface.Param; import com.google.devtools.build.lib.skylarkinterface.SkylarkPrinter; import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature; import com.google.devtools.build.lib.syntax.BaseFunction; import com.google.devtools.build.lib.syntax.BuiltinFunction; import com.google.devtools.build.lib.syntax.ClassObject; import com.google.devtools.build.lib.syntax.Environment; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.EvalUtils; import com.google.devtools.build.lib.syntax.FuncallExpression; import com.google.devtools.build.lib.syntax.FunctionSignature; import com.google.devtools.build.lib.syntax.Runtime; import com.google.devtools.build.lib.syntax.SkylarkCallbackFunction; import com.google.devtools.build.lib.syntax.SkylarkDict; import com.google.devtools.build.lib.syntax.SkylarkList; import com.google.devtools.build.lib.syntax.SkylarkNestedSet; import com.google.devtools.build.lib.syntax.SkylarkSignatureProcessor; import com.google.devtools.build.lib.syntax.SkylarkUtils; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.syntax.Type.ConversionException; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.util.Preconditions; import com.google.protobuf.TextFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; /** * A helper class to provide an easier API for Skylark rule definitions. */ public class SkylarkRuleClassFunctions { // TODO(bazel-team): Copied from ConfiguredRuleClassProvider for the transition from built-in // rules to skylark extensions. Using the same instance would require a large refactoring. // If we don't want to support old built-in rules and Skylark simultaneously // (except for transition phase) it's probably OK. private static final LoadingCache labelCache = CacheBuilder.newBuilder().build(new CacheLoader() { @Override public Label load(String from) throws Exception { try { return Label.parseAbsolute(from, false); } catch (LabelSyntaxException e) { throw new Exception(from); } } }); // TODO(bazel-team): Remove the code duplication (BaseRuleClasses and this class). /** Parent rule class for non-executable non-test Skylark rules. */ public static final RuleClass baseRule = BaseRuleClasses.commonCoreAndSkylarkAttributes( PlatformSemantics.platformAttributes( BaseRuleClasses.nameAttribute( new RuleClass.Builder("$base_rule", RuleClassType.ABSTRACT, true)) .add(attr("expect_failure", STRING)))) .build(); /** Parent rule class for executable non-test Skylark rules. */ public static final RuleClass binaryBaseRule = new RuleClass.Builder("$binary_base_rule", RuleClassType.ABSTRACT, true, baseRule) .add(attr("args", STRING_LIST)) .add(attr("output_licenses", LICENSE)) .build(); /** Parent rule class for test Skylark rules. */ public static final RuleClass getTestBaseRule(String toolsRepository) { return new RuleClass.Builder("$test_base_rule", RuleClassType.ABSTRACT, true, baseRule) .add(attr("size", STRING).value("medium").taggable() .nonconfigurable("used in loading phase rule validation logic")) .add(attr("timeout", STRING).taggable() .nonconfigurable("used in loading phase rule validation logic").value( new Attribute.ComputedDefault() { @Override public Object getDefault(AttributeMap rule) { TestSize size = TestSize.getTestSize(rule.get("size", Type.STRING)); if (size != null) { String timeout = size.getDefaultTimeout().toString(); if (timeout != null) { return timeout; } } return "illegal"; } })) .add(attr("flaky", BOOLEAN).value(false).taggable() .nonconfigurable("taggable - called in Rule.getRuleTags")) .add(attr("shard_count", INTEGER).value(-1)) .add(attr("local", BOOLEAN).value(false).taggable() .nonconfigurable("policy decision: this should be consistent across configurations")) .add(attr("args", STRING_LIST)) // Input files for every test action .add(attr("$test_runtime", LABEL_LIST).cfg(HOST).value(ImmutableList.of( labelCache.getUnchecked(toolsRepository + "//tools/test:runtime")))) // Input files for test actions collecting code coverage .add(attr("$coverage_support", LABEL) .cfg(HOST) .value(labelCache.getUnchecked("//tools/defaults:coverage_support"))) // Used in the one-per-build coverage report generation action. .add(attr("$coverage_report_generator", LABEL) .cfg(HOST) .value(labelCache.getUnchecked("//tools/defaults:coverage_report_generator")) .singleArtifact()) .add(attr(":run_under", LABEL).cfg(DATA).value(RUN_UNDER)) .build(); } @SkylarkSignature( name = "struct", returnType = SkylarkClassObject.class, doc = "Creates an immutable struct using the keyword arguments as attributes. It is used to " + "group multiple values together. Example:
" + "
s = struct(x = 2, y = 3)\n"
            + "return s.x + getattr(s, \"y\")  # returns 5
", extraKeywords = @Param(name = "kwargs", doc = "the struct attributes."), useLocation = true ) private static final ClassObjectConstructor struct = NativeClassObjectConstructor.STRUCT; @SkylarkSignature( name = "DefaultInfo", returnType = ClassObjectConstructor.class, doc = "A provider that is provided by every rule, even if it is not returned explicitly. " + "A DefaultInfo accepts the following parameters:" + "" + "Each instance of the default provider contains the following standard " + "fields: " + "" ) private static final ClassObjectConstructor defaultInfo = DefaultProvider.SKYLARK_CONSTRUCTOR; @SkylarkSignature( name = "OutputGroupInfo", returnType = ClassObjectConstructor.class, doc = "Provides information about output groups the rule provides.
" + "Instantiate this provider with
" + "
"
            + "OutputGroupInfo(group1 = <files>, group2 = <files>...)
" + "See Output Groups for more information" ) private static final ClassObjectConstructor outputGroupInfo = OutputGroupProvider.SKYLARK_CONSTRUCTOR; // TODO(bazel-team): Move to a "testing" namespace module. Normally we'd pass an objectType // to @SkylarkSignature to do this, but that doesn't work here because we're exposing an already- // configured BaseFunction, rather than defining a new BuiltinFunction. This should wait for // better support from the Skylark/Java interface, or perhaps support for first-class modules. @SkylarkSignature(name = "Actions", returnType = SkylarkClassObjectConstructor.class, doc = "(Note: This is a provider type. Don't instantiate it yourself; use it to retrieve a " + "provider object from a Target.)" + "

" + "Provides access to the actions generated by a rule. There " + "is one field, by_file, which is a dictionary from an output of the rule " + "to its corresponding generating action. " + "

" + "This is designed for testing rules, and should not be accessed outside of test logic. " + "This provider is only available for targets generated by rules that have " + "_skylark_testable set to " + "True." ) private static final ClassObjectConstructor actions = ActionsProvider.SKYLARK_CONSTRUCTOR; @SkylarkSignature( name = "provider", returnType = ClassObjectConstructor.class, doc = "Creates a declared provider 'constructor'. The return value of this " + "function can be used to create \"struct-like\" values. Example:
" + "
data = provider()\n"
            + "d = data(x = 2, y = 3)\n"
            + "print(d.x + d.y) # prints 5
", parameters = { @Param( name = "doc", type = String.class, defaultValue = "''", doc = "A description of the provider that can be extracted by documentation generating tools." ) }, useLocation = true ) private static final BuiltinFunction provider = new BuiltinFunction("provider") { public ClassObjectConstructor invoke(String doc, Location location) { return new SkylarkClassObjectConstructor( "", // name is set on export. location); } }; // TODO(bazel-team): implement attribute copy and other rule properties @SkylarkSignature( name = "rule", doc = "Creates a new rule. Store it in a global value, so that it can be loaded and called " + "from BUILD files.", returnType = BaseFunction.class, parameters = { @Param( name = "implementation", type = BaseFunction.class, doc = "the function implementing this rule, must have exactly one parameter: " + "ctx. The function is called during the analysis " + "phase for each instance of the rule. It can access the attributes " + "provided by the user. It must create actions to generate all the declared " + "outputs." ), @Param( name = "test", type = Boolean.class, defaultValue = "False", doc = "Whether this rule is a test rule. " + "If True, the rule must end with _test (otherwise it must " + "not), and there must be an action that generates " + "ctx.outputs.executable." ), @Param( name = "attrs", type = SkylarkDict.class, noneable = true, defaultValue = "None", doc = "dictionary to declare all the attributes of the rule. It maps from an attribute " + "name to an attribute object (see attr module). " + "Attributes starting with _ are private, and can be used to " + "add an implicit dependency on a label. The attribute name is " + "implicitly added and must not be specified. Attributes " + "visibility, deprecation, tags, " + "testonly, and features are implicitly added and " + "cannot be overriden." ), // TODO(bazel-team): need to give the types of these builtin attributes @Param( name = "outputs", type = SkylarkDict.class, callbackEnabled = true, noneable = true, defaultValue = "None", doc = "outputs of this rule. " + "It is a dictionary mapping from string to a template name. " + "For example: {\"ext\": \"%{name}.ext\"}.
" + "The dictionary key becomes an attribute in ctx.outputs. " + "Similar to computed dependency rule attributes, you can also specify the " + "name of a function that returns the dictionary. This function can access " + "all rule attributes that are listed as parameters in its function " + "signature. For example, outputs = _my_func with " + "def _my_func(srcs, deps): has access to the attributes " + "'srcs' and 'deps' (if defined)." ), @Param( name = "executable", type = Boolean.class, defaultValue = "False", doc = "whether this rule is marked as executable or not. If True, " + "there must be an action that generates " + "ctx.outputs.executable." ), @Param( name = "output_to_genfiles", type = Boolean.class, defaultValue = "False", doc = "If true, the files will be generated in the genfiles directory instead of the " + "bin directory. Unless you need it for compatibility with existing rules " + "(e.g. when generating header files for C++), do not set this flag." ), @Param( name = "fragments", type = SkylarkList.class, generic1 = String.class, defaultValue = "[]", doc = "List of names of configuration fragments that the rule requires " + "in target configuration." ), @Param( name = "host_fragments", type = SkylarkList.class, generic1 = String.class, defaultValue = "[]", doc = "List of names of configuration fragments that the rule requires " + "in host configuration." ), @Param( name = "_skylark_testable", type = Boolean.class, defaultValue = "False", doc = "(Experimental)

" + "If true, this rule will expose its actions for inspection by rules that " + "depend on it via an Actions " + "provider. The provider is also available to the rule itself by calling " + "ctx.created_actions()." + "

" + "This should only be used for testing the analysis-time behavior of " + "Skylark rules. This flag may be removed in the future." ), @Param( name = "toolchains", type = SkylarkList.class, generic1 = String.class, defaultValue = "[]", doc = "(Experimental)

" + "If set, the set of toolchains this rule requires. Toolchains will be " + "found by checking the current platform, and provided to the rule " + "implementation via ctx.toolchain." ), @Param( name = "doc", type = String.class, defaultValue = "''", doc = "A description of the rule that can be extracted by documentation generating tools." ) }, useAst = true, useEnvironment = true ) private static final BuiltinFunction rule = new BuiltinFunction("rule") { @SuppressWarnings({"rawtypes", "unchecked"}) // castMap produces // an Attribute.Builder instead of a Attribute.Builder but it's OK. public BaseFunction invoke( BaseFunction implementation, Boolean test, Object attrs, Object implicitOutputs, Boolean executable, Boolean outputToGenfiles, SkylarkList fragments, SkylarkList hostFragments, Boolean skylarkTestable, SkylarkList toolchains, String doc, FuncallExpression ast, Environment funcallEnv) throws EvalException, ConversionException { funcallEnv.checkLoadingOrWorkspacePhase("rule", ast.getLocation()); RuleClassType type = test ? RuleClassType.TEST : RuleClassType.NORMAL; RuleClass parent = test ? getTestBaseRule(SkylarkUtils.getToolsRepository(funcallEnv)) : (executable ? binaryBaseRule : baseRule); // We'll set the name later, pass the empty string for now. RuleClass.Builder builder = new RuleClass.Builder("", type, true, parent); ImmutableList> attributes = attrObjectToAttributesList(attrs, ast); if (skylarkTestable) { builder.setSkylarkTestable(); } if (executable || test) { addAttribute( ast.getLocation(), builder, attr("$is_executable", BOOLEAN) .value(true) .nonconfigurable("Called from RunCommand.isExecutable, which takes a Target") .build()); builder.setOutputsDefaultExecutable(); } if (implicitOutputs != Runtime.NONE) { if (implicitOutputs instanceof BaseFunction) { BaseFunction func = (BaseFunction) implicitOutputs; SkylarkCallbackFunction callback = new SkylarkCallbackFunction(func, ast, funcallEnv); builder.setImplicitOutputsFunction( new SkylarkImplicitOutputsFunctionWithCallback(callback, ast.getLocation())); } else { builder.setImplicitOutputsFunction( new SkylarkImplicitOutputsFunctionWithMap( ImmutableMap.copyOf( castMap( implicitOutputs, String.class, String.class, "implicit outputs of the rule class")))); } } if (outputToGenfiles) { builder.setOutputToGenfiles(); } builder.requiresConfigurationFragmentsBySkylarkModuleName( fragments.getContents(String.class, "fragments")); builder.requiresHostConfigurationFragmentsBySkylarkModuleName( hostFragments.getContents(String.class, "host_fragments")); builder.setConfiguredTargetFunction(implementation); builder.setRuleDefinitionEnvironment(funcallEnv); builder.addRequiredToolchains(collectToolchainLabels(toolchains, ast)); return new RuleFunction(builder, type, attributes, ast.getLocation()); } }; protected static ImmutableList> attrObjectToAttributesList( Object attrs, FuncallExpression ast) throws EvalException { ImmutableList.Builder> attributes = ImmutableList.builder(); if (attrs != Runtime.NONE) { for (Map.Entry attr : castMap(attrs, String.class, Descriptor.class, "attrs").entrySet()) { Descriptor attrDescriptor = attr.getValue(); AttributeValueSource source = attrDescriptor.getValueSource(); String attrName = source.convertToNativeName(attr.getKey(), ast.getLocation()); attributes.add(Pair.of(attrName, attrDescriptor)); } } return attributes.build(); } private static void addAttribute( Location location, RuleClass.Builder builder, Attribute attribute) throws EvalException { try { builder.addOrOverrideAttribute(attribute); } catch (IllegalArgumentException ex) { throw new EvalException(location, ex); } } private static ImmutableList