aboutsummaryrefslogtreecommitdiffhomepage
path: root/src
diff options
context:
space:
mode:
authorGravatar Laurent Le Brun <laurentlb@google.com>2015-03-31 13:54:36 +0000
committerGravatar Laurent Le Brun <laurentlb@google.com>2015-03-31 15:23:58 +0000
commitf9148978dec82f7bebae812645cb28e3bb269226 (patch)
tree1ee003c8ae298e68cc97d8f356d368b72507fd12 /src
parent5f81fb88c9d68a0022365e581f94486029d16a3b (diff)
Skylark: Add dictionary.get
-- MOS_MIGRATED_REVID=89962232
Diffstat (limited to 'src')
-rw-r--r--src/main/java/com/google/devtools/build/lib/packages/MethodLibrary.java26
1 files changed, 26 insertions, 0 deletions
diff --git a/src/main/java/com/google/devtools/build/lib/packages/MethodLibrary.java b/src/main/java/com/google/devtools/build/lib/packages/MethodLibrary.java
index 54276d8019..267f9ff212 100644
--- a/src/main/java/com/google/devtools/build/lib/packages/MethodLibrary.java
+++ b/src/main/java/com/google/devtools/build/lib/packages/MethodLibrary.java
@@ -571,6 +571,31 @@ public class MethodLibrary {
}
};
+ @SkylarkBuiltin(name = "get", objectType = DictModule.class,
+ doc = "Return the value for <code>key</code> if <code>key</code> is in the dictionary, "
+ + "else <code>default</code>. If <code>default</code> is not given, it defaults to "
+ + "<code>None</code>, so that this method never throws an error.",
+ mandatoryParams = {
+ @Param(name = "key", doc = "The key to look for.")},
+ optionalParams = {
+ @Param(name = "default",
+ doc = "The default value to use (instead of None) if the key is not found.")})
+ private static Function get =
+ new MixedModeFunction("get", ImmutableList.of("this", "key", "default"), 2, false) {
+ @Override
+ public Object call(Object[] args, FuncallExpression ast) throws ConversionException {
+ Map<?, ?> dict = (Map<?, ?>) args[0];
+ Object key = args[1];
+ if (dict.containsKey(key)) {
+ return dict.get(key);
+ }
+ if (args[2] == null) {
+ return Environment.NONE;
+ }
+ return args[2];
+ }
+ };
+
// TODO(bazel-team): Use the same type for both Skylark and BUILD files.
@SuppressWarnings("unchecked")
private static Iterable<Object> convert(Collection<?> list, Environment env, Location loc)
@@ -1074,6 +1099,7 @@ public class MethodLibrary {
public static final Map<Function, SkylarkType> dictFunctions = ImmutableMap
.<Function, SkylarkType>builder()
.put(items, SkylarkType.of(List.class))
+ .put(get, SkylarkType.UNKNOWN)
.put(keys, SkylarkType.of(Set.class))
.put(values, SkylarkType.of(List.class))
.build();