aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib
diff options
context:
space:
mode:
authorGravatar Laurent Le Brun <laurentlb@google.com>2015-05-07 14:00:32 +0000
committerGravatar Lukacs Berki <lberki@google.com>2015-05-07 14:07:19 +0000
commitf4648de34c67d27931ab47cdecf1aff79c1faff5 (patch)
tree331276f18188c811614c7cc6174d657907be6643 /src/main/java/com/google/devtools/build/lib
parenta6b401839e44155909b79d4ef534a90bb7f2eac6 (diff)
Skylark: int() function accepts bools and ints too.
-- MOS_MIGRATED_REVID=93026026
Diffstat (limited to 'src/main/java/com/google/devtools/build/lib')
-rw-r--r--src/main/java/com/google/devtools/build/lib/packages/MethodLibrary.java28
1 files changed, 20 insertions, 8 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 55d5bb5758..07c7157fbc 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
@@ -666,19 +666,31 @@ public class MethodLibrary {
}
};
- @SkylarkSignature(name = "int", returnType = Integer.class, doc = "Converts a string to int, "
- + "using base 10. It raises an error if the conversion fails."
+ @SkylarkSignature(name = "int", returnType = Integer.class, doc = "Converts a value to int. "
+ + "If the argument is a string, it is converted using base 10 and raises an error if the "
+ + "conversion fails. If the argument is a bool, it returns 0 (False) or 1 (True). "
+ + "If the argument is an int, it is simply returned."
+ "<pre class=\"language-python\">int(\"123\") == 123</pre>",
mandatoryPositionals = {
- @Param(name = "x", type = String.class, doc = "The string to convert.")},
+ @Param(name = "x", type = Object.class, doc = "The string to convert.")},
useLocation = true)
private static BuiltinFunction int_ = new BuiltinFunction("int") {
- public Integer invoke(String x, Location loc) throws EvalException {
- try {
- return Integer.parseInt(x);
- } catch (NumberFormatException e) {
+ public Integer invoke(Object x, Location loc) throws EvalException {
+ if (x instanceof Boolean) {
+ return ((Boolean) x).booleanValue() ? 1 : 0;
+ } else if (x instanceof Integer) {
+ return (Integer) x;
+ } else if (x instanceof String) {
+ try {
+ return Integer.parseInt((String) x);
+ } catch (NumberFormatException e) {
+ throw new EvalException(loc,
+ "invalid literal for int(): " + EvalUtils.prettyPrintValue(x));
+ }
+ } else {
throw new EvalException(loc,
- "invalid literal for int(): " + EvalUtils.prettyPrintValue(x));
+ String.format("argument must be string, int, or bool, not '%s'",
+ EvalUtils.prettyPrintValue(x)));
}
}
};