// 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.analysis.skylark;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.LocationExpander;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.configuredtargets.AbstractConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.skylarkinterface.Param;
import com.google.devtools.build.lib.skylarkinterface.ParamType;
import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature;
import com.google.devtools.build.lib.syntax.BuiltinFunction;
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.Printer;
import com.google.devtools.build.lib.syntax.Runtime;
import com.google.devtools.build.lib.syntax.SkylarkDict;
import com.google.devtools.build.lib.syntax.SkylarkList;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
import com.google.devtools.build.lib.syntax.SkylarkNestedSet;
import com.google.devtools.build.lib.syntax.SkylarkSemanticsOptions;
import com.google.devtools.build.lib.syntax.SkylarkSignatureProcessor;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.syntax.Type.ConversionException;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// TODO(bazel-team): function argument names are often duplicated,
// figure out a nicely readable way to get rid of the duplications.
/**
* A helper class to provide an easier API for Skylark rule implementations
* and hide the original Java API. This is experimental code.
*/
public class SkylarkRuleImplementationFunctions {
// TODO(bazel-team): add all the remaining parameters
// TODO(bazel-team): merge executable and arguments
/**
* A Skylark built-in function to create and register a SpawnAction using a dictionary of
* parameters: action( inputs = [input1, input2, ...], outputs = [output1, output2, ...],
* executable = executable, arguments = [argument1, argument2, ...], mnemonic = 'Mnemonic',
* command = 'command', )
*/
@SkylarkSignature(
name = "action",
doc =
"DEPRECATED. Use ctx.actions.run() or"
+ " ctx.actions.run_shell(). "
+ "Creates an action that runs an executable or a shell command."
+ " You must specify either command or executable.\n"
+ "Actions and genrules are very similar, but have different use cases. Actions are "
+ "used inside rules, and genrules are used inside macros. Genrules also have make "
+ "variable expansion.",
objectType = SkylarkRuleContext.class,
returnType = Runtime.NoneType.class,
parameters = {
@Param(name = "self", type = SkylarkRuleContext.class, doc = "This RuleContext."),
@Param(
name = "outputs",
type = SkylarkList.class,
generic1 = Artifact.class,
named = true,
positional = false,
doc = "list of the output files of the action."
),
@Param(
name = "inputs",
allowedTypes = {
@ParamType(type = SkylarkList.class),
@ParamType(type = SkylarkNestedSet.class),
},
generic1 = Artifact.class,
defaultValue = "[]",
named = true,
positional = false,
doc = "list of the input files of the action."
),
@Param(
name = "executable",
type = Object.class,
allowedTypes = {
@ParamType(type = Artifact.class),
@ParamType(type = String.class),
@ParamType(type = Runtime.NoneType.class),
},
defaultValue = "None",
named = true,
positional = false,
doc = "the executable file to be called by the action."
),
@Param(
name = "arguments",
allowedTypes = {
@ParamType(type = SkylarkList.class),
},
defaultValue = "[]",
named = true,
positional = false,
doc =
"command line arguments of the action."
+ "Must be a list of strings or actions.args() objects."
),
@Param(
name = "mnemonic",
type = String.class,
noneable = true,
defaultValue = "None",
named = true,
positional = false,
doc = "a one-word description of the action, e.g. CppCompile or GoLink."
),
@Param(
name = "command",
type = Object.class,
allowedTypes = {
@ParamType(type = String.class),
@ParamType(type = SkylarkList.class, generic1 = String.class),
@ParamType(type = Runtime.NoneType.class),
},
defaultValue = "None",
named = true,
positional = false,
doc =
"shell command to execute. It is usually preferable to "
+ "use executable instead. "
+ "Arguments are available with $1, $2, etc."
),
@Param(
name = "progress_message",
type = String.class,
noneable = true,
defaultValue = "None",
named = true,
positional = false,
doc =
"progress message to show to the user during the build, "
+ "e.g. \"Compiling foo.cc to create foo.o\"."
),
@Param(
name = "use_default_shell_env",
type = Boolean.class,
defaultValue = "False",
named = true,
positional = false,
doc = "whether the action should use the built in shell environment or not."
),
@Param(
name = "env",
type = SkylarkDict.class,
noneable = true,
defaultValue = "None",
named = true,
positional = false,
doc = "sets the dictionary of environment variables."
),
@Param(
name = "execution_requirements",
type = SkylarkDict.class,
noneable = true,
defaultValue = "None",
named = true,
positional = false,
doc =
"information for scheduling the action. See "
+ "tags "
+ "for useful keys."
),
@Param(
// TODO(bazel-team): The name here isn't accurate anymore. This is technically experimental,
// so folks shouldn't be too attached, but consider renaming to be more accurate/opaque.
name = "input_manifests",
type = SkylarkList.class,
noneable = true,
defaultValue = "None",
named = true,
positional = false,
doc =
"(Experimental) sets the input runfiles metadata; "
+ "they are typically generated by resolve_command."
)
},
useLocation = true,
useEnvironment = true
)
private static final BuiltinFunction createSpawnAction =
new BuiltinFunction("action") {
public Runtime.NoneType invoke(
SkylarkRuleContext ctx,
SkylarkList outputs,
Object inputs,
Object executableUnchecked,
Object arguments,
Object mnemonicUnchecked,
Object commandUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Location loc,
Environment env)
throws EvalException {
checkDeprecated(
"ctx.actions.run or ctx.actions.run_shell", "ctx.action", loc, env.getSemantics());
ctx.checkMutable("action");
if ((commandUnchecked == Runtime.NONE) == (executableUnchecked == Runtime.NONE)) {
throw new EvalException(
loc, "You must specify either 'command' or 'executable' argument");
}
boolean hasCommand = commandUnchecked != Runtime.NONE;
if (!hasCommand) {
ctx.actions()
.run(
outputs,
inputs,
executableUnchecked,
arguments,
mnemonicUnchecked,
progressMessage,
useDefaultShellEnv,
envUnchecked,
executionRequirementsUnchecked,
inputManifestsUnchecked);
} else {
ctx.actions()
.runShell(
outputs,
inputs,
arguments,
mnemonicUnchecked,
commandUnchecked,
progressMessage,
useDefaultShellEnv,
envUnchecked,
executionRequirementsUnchecked,
inputManifestsUnchecked);
}
return Runtime.NONE;
}
};
static void checkDeprecated(
String newApi, String oldApi, Location loc, SkylarkSemanticsOptions semantics)
throws EvalException {
if (semantics.incompatibleNewActionsApi) {
throw new EvalException(
loc,
"Use " + newApi + " instead of " + oldApi + ". \n"
+ "Use --incompatible_new_actions_api=false to temporarily disable this check.");
}
}
@SkylarkSignature(
name = "expand_location",
doc =
"Expands all $(location ...) templates in the given string by replacing "
+ "$(location //x) with the path of the output file of target //x. "
+ "Expansion only works for labels that point to direct dependencies of this rule or "
+ "that are explicitly listed in the optional argument targets. "
+ "
"
+ "$(location ...) will cause an error if the referenced target has "
+ "multiple outputs. In this case, please use $(locations ...) since it "
+ "produces a space-separated list of output paths. It can be safely used for a "
+ "single output file, too.",
objectType = SkylarkRuleContext.class,
returnType = String.class,
parameters = {
@Param(name = "self", type = SkylarkRuleContext.class, doc = "this context."),
@Param(name = "input", type = String.class, doc = "string to be expanded."),
@Param(
name = "targets",
type = SkylarkList.class,
generic1 = AbstractConfiguredTarget.class,
defaultValue = "[]",
doc = "list of targets for additional lookup information."
),
},
useLocation = true,
useEnvironment = true
)
private static final BuiltinFunction expandLocation =
new BuiltinFunction("expand_location") {
@SuppressWarnings("unused")
public String invoke(
SkylarkRuleContext ctx,
String input,
SkylarkList targets,
Location loc,
Environment env)
throws EvalException {
ctx.checkMutable("expand_location");
try {
return new LocationExpander(
ctx.getRuleContext(),
makeLabelMap(targets.getContents(TransitiveInfoCollection.class, "targets")),
LocationExpander.Options.EXEC_PATHS)
.expand(input);
} catch (IllegalStateException ise) {
throw new EvalException(loc, ise);
}
}
};
/**
* Builds a map: Label -> List of files from the given labels
*
* @param knownLabels List of known labels
* @return Immutable map with immutable collections as values
*/
private static ImmutableMap