diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java | 27 | ||||
-rw-r--r-- | src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java | 13 |
2 files changed, 40 insertions, 0 deletions
diff --git a/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java b/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java index 3cc778984b..dbbb46ff47 100644 --- a/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java +++ b/src/main/java/com/google/devtools/build/lib/syntax/MethodLibrary.java @@ -882,6 +882,33 @@ public class MethodLibrary { } }; + @SkylarkSignature( + name = "index", + objectType = MutableList.class, + returnType = Integer.class, + doc = + "Returns the index in the list of the first item whose value is x. " + + "It is an error if there is no such item.", + mandatoryPositionals = { + @Param(name = "self", type = MutableList.class, doc = "This string, a separator."), + @Param(name = "x", type = Object.class, doc = "The object to search.") + }, + useLocation = true + ) + private static BuiltinFunction listIndex = + new BuiltinFunction("index") { + public Integer invoke(MutableList self, Object x, Location loc) throws EvalException { + int i = 0; + for (Object obj : self) { + if (obj.equals(x)) { + return i; + } + i++; + } + throw new EvalException(loc, Printer.format("Item %r not found in list", x)); + } + }; + // dictionary access operator @SkylarkSignature(name = "$index", documented = false, objectType = Map.class, doc = "Looks up a value in a dictionary.", diff --git a/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java b/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java index c78fba035c..eee12f78df 100644 --- a/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java +++ b/src/test/java/com/google/devtools/build/lib/syntax/MethodLibraryTest.java @@ -858,6 +858,19 @@ public class MethodLibraryTest extends EvaluationTestCase { } @Test + public void testListIndexMethod() throws Exception { + new BothModesTest() + .testStatement("['a', 'b', 'c'].index('a')", 0) + .testStatement("['a', 'b', 'c'].index('b')", 1) + .testStatement("['a', 'b', 'c'].index('c')", 2) + .testStatement("[2, 4, 6].index(4)", 1) + .testStatement("[2, 4, 6].index(4)", 1) + .testStatement("[0, 1, [1]].index([1])", 2) + .testIfErrorContains("Item \"a\" not found in list", "[1, 2].index('a')") + .testIfErrorContains("Item 0 not found in list", "[].index(0)"); + } + + @Test public void testListIndex() throws Exception { new BothModesTest() .testStatement("['a', 'b', 'c', 'd'][0]", "a") |