Damien Martin-Guillerez | f88f4d8 | 2015-09-25 13:56:55 +0000 | [diff] [blame] | 1 | // Copyright 2014 The Bazel Authors. All rights reserved. |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
Francois-Rene Rideau | 3679556 | 2015-07-29 18:50:50 +0000 | [diff] [blame] | 15 | package com.google.devtools.build.lib.syntax; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 16 | |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 17 | import static java.util.stream.Collectors.joining; |
| 18 | |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 19 | import com.google.common.base.CharMatcher; |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 20 | import com.google.common.base.Joiner; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 21 | import com.google.common.collect.ImmutableList; |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 22 | import com.google.common.collect.ImmutableMap; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 23 | import com.google.common.collect.Lists; |
Francois-Rene Rideau | c673a82 | 2015-03-02 19:52:39 +0000 | [diff] [blame] | 24 | import com.google.common.collect.Ordering; |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 25 | import com.google.devtools.build.lib.collect.nestedset.NestedSet; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 26 | import com.google.devtools.build.lib.events.Event; |
| 27 | import com.google.devtools.build.lib.events.Location; |
Damien Martin-Guillerez | 2ca9b72 | 2016-06-09 17:43:55 +0000 | [diff] [blame] | 28 | import com.google.devtools.build.lib.skylarkinterface.Param; |
John Field | 585d1a0 | 2015-12-16 16:03:52 +0000 | [diff] [blame] | 29 | import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; |
Dmitry Lomov | 34cdae3 | 2016-06-28 16:13:35 +0000 | [diff] [blame] | 30 | import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; |
John Field | 585d1a0 | 2015-12-16 16:03:52 +0000 | [diff] [blame] | 31 | import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature; |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 32 | import com.google.devtools.build.lib.syntax.EvalUtils.ComparisonException; |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 33 | import com.google.devtools.build.lib.syntax.SkylarkList.MutableList; |
| 34 | import com.google.devtools.build.lib.syntax.SkylarkList.Tuple; |
Lukacs Berki | ffa73ad | 2015-09-18 11:40:12 +0000 | [diff] [blame] | 35 | import com.google.devtools.build.lib.syntax.Type.ConversionException; |
brandjon | dc2c550 | 2017-12-07 14:30:04 -0800 | [diff] [blame] | 36 | import java.util.ArrayDeque; |
Googler | c60ec8c | 2015-03-23 14:20:18 +0000 | [diff] [blame] | 37 | import java.util.ArrayList; |
Googler | c60ec8c | 2015-03-23 14:20:18 +0000 | [diff] [blame] | 38 | import java.util.Iterator; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 39 | import java.util.List; |
| 40 | import java.util.Map; |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 41 | import java.util.NoSuchElementException; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 42 | import java.util.Set; |
| 43 | import java.util.TreeSet; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 44 | import java.util.regex.Matcher; |
| 45 | import java.util.regex.Pattern; |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 46 | import javax.annotation.Nullable; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 47 | |
Laurent Le Brun | bd9576a | 2016-11-18 15:10:51 +0000 | [diff] [blame] | 48 | /** A helper class containing built in functions for the Skylark language. */ |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 49 | public class MethodLibrary { |
| 50 | |
| 51 | private MethodLibrary() {} |
| 52 | |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 53 | // Emulate Python substring function |
| 54 | // It converts out of range indices, and never fails |
Francois-Rene Rideau | 76023b9 | 2015-04-17 15:31:59 +0000 | [diff] [blame] | 55 | private static String pythonSubstring(String str, int start, Object end, String msg) |
| 56 | throws ConversionException { |
| 57 | if (start == 0 && EvalUtils.isNullOrNone(end)) { |
| 58 | return str; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 59 | } |
Jon Brandvein | fab8487 | 2016-11-11 16:27:01 +0000 | [diff] [blame] | 60 | start = EvalUtils.clampRangeEndpoint(start, str.length()); |
Francois-Rene Rideau | 76023b9 | 2015-04-17 15:31:59 +0000 | [diff] [blame] | 61 | int stop; |
| 62 | if (EvalUtils.isNullOrNone(end)) { |
| 63 | stop = str.length(); |
| 64 | } else { |
Jon Brandvein | fab8487 | 2016-11-11 16:27:01 +0000 | [diff] [blame] | 65 | stop = EvalUtils.clampRangeEndpoint(Type.INTEGER.convert(end, msg), str.length()); |
Francois-Rene Rideau | 76023b9 | 2015-04-17 15:31:59 +0000 | [diff] [blame] | 66 | } |
| 67 | if (start >= stop) { |
| 68 | return ""; |
| 69 | } |
| 70 | return str.substring(start, stop); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 71 | } |
| 72 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 73 | // supported string methods |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 74 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 75 | @SkylarkSignature(name = "join", objectType = StringModule.class, returnType = String.class, |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 76 | doc = "Returns a string in which the string elements of the argument have been " |
| 77 | + "joined by this string as a separator. Example:<br>" |
Laurent Le Brun | 9d27a01 | 2015-03-31 12:28:02 +0000 | [diff] [blame] | 78 | + "<pre class=\"language-python\">\"|\".join([\"a\", \"b\", \"c\"]) == \"a|b|c\"</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 79 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 80 | @Param(name = "self", type = String.class, doc = "This string, a separator."), |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 81 | @Param(name = "elements", type = SkylarkList.class, doc = "The objects to join.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 82 | private static final BuiltinFunction join = new BuiltinFunction("join") { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 83 | public String invoke(String self, SkylarkList<?> elements) throws ConversionException { |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 84 | return Joiner.on(self).join(elements); |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 85 | } |
| 86 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 87 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 88 | @SkylarkSignature(name = "lower", objectType = StringModule.class, returnType = String.class, |
| 89 | doc = "Returns the lower case version of this string.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 90 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 91 | @Param(name = "self", type = String.class, doc = "This string, to convert to lower case.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 92 | private static final BuiltinFunction lower = new BuiltinFunction("lower") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 93 | public String invoke(String self) { |
| 94 | return self.toLowerCase(); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 95 | } |
| 96 | }; |
| 97 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 98 | @SkylarkSignature(name = "upper", objectType = StringModule.class, returnType = String.class, |
| 99 | doc = "Returns the upper case version of this string.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 100 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 101 | @Param(name = "self", type = String.class, doc = "This string, to convert to upper case.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 102 | private static final BuiltinFunction upper = new BuiltinFunction("upper") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 103 | public String invoke(String self) { |
| 104 | return self.toUpperCase(); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 105 | } |
| 106 | }; |
| 107 | |
Jon Brandvein | 36ecf16 | 2017-01-02 18:43:42 +0000 | [diff] [blame] | 108 | /** |
| 109 | * For consistency with Python we recognize the same whitespace characters as they do over the |
| 110 | * range 0x00-0xFF. See https://hg.python.org/cpython/file/3.6/Objects/unicodetype_db.h#l5738 |
| 111 | * This list is a consequence of Unicode character information. |
| 112 | * |
| 113 | * Note that this differs from Python 2.7, which uses ctype.h#isspace(), and from |
| 114 | * java.lang.Character#isWhitespace(), which does not recognize U+00A0. |
| 115 | */ |
| 116 | private static final String LATIN1_WHITESPACE = ( |
| 117 | "\u0009" |
| 118 | + "\n" |
| 119 | + "\u000B" |
| 120 | + "\u000C" |
| 121 | + "\r" |
| 122 | + "\u001C" |
| 123 | + "\u001D" |
| 124 | + "\u001E" |
| 125 | + "\u001F" |
| 126 | + "\u0020" |
| 127 | + "\u0085" |
| 128 | + "\u00A0" |
| 129 | ); |
| 130 | |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 131 | private static String stringLStrip(String self, String chars) { |
| 132 | CharMatcher matcher = CharMatcher.anyOf(chars); |
| 133 | for (int i = 0; i < self.length(); i++) { |
| 134 | if (!matcher.matches(self.charAt(i))) { |
| 135 | return self.substring(i); |
| 136 | } |
| 137 | } |
| 138 | return ""; // All characters were stripped. |
| 139 | } |
| 140 | |
| 141 | private static String stringRStrip(String self, String chars) { |
| 142 | CharMatcher matcher = CharMatcher.anyOf(chars); |
| 143 | for (int i = self.length() - 1; i >= 0; i--) { |
| 144 | if (!matcher.matches(self.charAt(i))) { |
| 145 | return self.substring(0, i + 1); |
| 146 | } |
| 147 | } |
| 148 | return ""; // All characters were stripped. |
| 149 | } |
| 150 | |
| 151 | @SkylarkSignature( |
| 152 | name = "lstrip", |
| 153 | objectType = StringModule.class, |
| 154 | returnType = String.class, |
| 155 | doc = |
| 156 | "Returns a copy of the string where leading characters that appear in <code>chars</code>" |
| 157 | + "are removed." |
| 158 | + "<pre class=\"language-python\">" |
| 159 | + "\"abcba\".lstrip(\"ba\") == \"cba\"" |
David Chen | f8e18b7 | 2016-09-09 14:46:48 +0000 | [diff] [blame] | 160 | + "</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 161 | parameters = { |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 162 | @Param(name = "self", type = String.class, doc = "This string."), |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 163 | @Param( |
| 164 | name = "chars", |
| 165 | type = String.class, |
Jon Brandvein | 36ecf16 | 2017-01-02 18:43:42 +0000 | [diff] [blame] | 166 | noneable = true, |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 167 | doc = "The characters to remove, or all whitespace if None.", |
Jon Brandvein | 36ecf16 | 2017-01-02 18:43:42 +0000 | [diff] [blame] | 168 | defaultValue = "None" |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 169 | ) |
| 170 | } |
| 171 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 172 | private static final BuiltinFunction lstrip = |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 173 | new BuiltinFunction("lstrip") { |
Jon Brandvein | 36ecf16 | 2017-01-02 18:43:42 +0000 | [diff] [blame] | 174 | public String invoke(String self, Object charsOrNone) { |
| 175 | String chars = charsOrNone != Runtime.NONE ? (String) charsOrNone : LATIN1_WHITESPACE; |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 176 | return stringLStrip(self, chars); |
| 177 | } |
| 178 | }; |
| 179 | |
| 180 | @SkylarkSignature( |
| 181 | name = "rstrip", |
| 182 | objectType = StringModule.class, |
| 183 | returnType = String.class, |
| 184 | doc = |
| 185 | "Returns a copy of the string where trailing characters that appear in <code>chars</code>" |
| 186 | + "are removed." |
| 187 | + "<pre class=\"language-python\">" |
brandjon | e835a3f | 2017-04-10 14:55:13 +0000 | [diff] [blame] | 188 | + "\"abcbaa\".rstrip(\"ab\") == \"abc\"" |
David Chen | f8e18b7 | 2016-09-09 14:46:48 +0000 | [diff] [blame] | 189 | + "</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 190 | parameters = { |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 191 | @Param(name = "self", type = String.class, doc = "This string."), |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 192 | @Param( |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 193 | name = "chars", |
| 194 | type = String.class, |
| 195 | noneable = true, |
| 196 | doc = "The characters to remove, or all whitespace if None.", |
| 197 | defaultValue = "None" |
| 198 | ) |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 199 | } |
| 200 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 201 | private static final BuiltinFunction rstrip = |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 202 | new BuiltinFunction("rstrip") { |
Jon Brandvein | 36ecf16 | 2017-01-02 18:43:42 +0000 | [diff] [blame] | 203 | public String invoke(String self, Object charsOrNone) { |
| 204 | String chars = charsOrNone != Runtime.NONE ? (String) charsOrNone : LATIN1_WHITESPACE; |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 205 | return stringRStrip(self, chars); |
| 206 | } |
| 207 | }; |
| 208 | |
| 209 | @SkylarkSignature( |
| 210 | name = "strip", |
| 211 | objectType = StringModule.class, |
| 212 | returnType = String.class, |
| 213 | doc = |
Googler | d2c226c | 2018-03-01 03:00:53 -0800 | [diff] [blame] | 214 | "Returns a copy of the string where leading or trailing characters that appear in " |
| 215 | + "<code>chars</code> are removed." |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 216 | + "<pre class=\"language-python\">" |
brandjon | e835a3f | 2017-04-10 14:55:13 +0000 | [diff] [blame] | 217 | + "\"aabcbcbaa\".strip(\"ab\") == \"cbc\"" |
David Chen | f8e18b7 | 2016-09-09 14:46:48 +0000 | [diff] [blame] | 218 | + "</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 219 | parameters = { |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 220 | @Param(name = "self", type = String.class, doc = "This string."), |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 221 | @Param( |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 222 | name = "chars", |
| 223 | type = String.class, |
| 224 | noneable = true, |
| 225 | doc = "The characters to remove, or all whitespace if None.", |
| 226 | defaultValue = "None" |
| 227 | ) |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 228 | } |
| 229 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 230 | private static final BuiltinFunction strip = |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 231 | new BuiltinFunction("strip") { |
Jon Brandvein | 36ecf16 | 2017-01-02 18:43:42 +0000 | [diff] [blame] | 232 | public String invoke(String self, Object charsOrNone) { |
| 233 | String chars = charsOrNone != Runtime.NONE ? (String) charsOrNone : LATIN1_WHITESPACE; |
Laurent Le Brun | ad84974 | 2015-10-15 11:36:01 +0000 | [diff] [blame] | 234 | return stringLStrip(stringRStrip(self, chars), chars); |
| 235 | } |
| 236 | }; |
| 237 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 238 | @SkylarkSignature( |
| 239 | name = "replace", |
| 240 | objectType = StringModule.class, |
| 241 | returnType = String.class, |
| 242 | doc = |
| 243 | "Returns a copy of the string in which the occurrences " |
| 244 | + "of <code>old</code> have been replaced with <code>new</code>, optionally " |
| 245 | + "restricting the number of replacements to <code>maxsplit</code>.", |
| 246 | parameters = { |
| 247 | @Param(name = "self", type = String.class, doc = "This string."), |
| 248 | @Param(name = "old", type = String.class, doc = "The string to be replaced."), |
| 249 | @Param(name = "new", type = String.class, doc = "The string to replace with."), |
| 250 | @Param( |
| 251 | name = "maxsplit", |
| 252 | type = Integer.class, |
| 253 | noneable = true, |
| 254 | defaultValue = "None", |
| 255 | doc = "The maximum number of replacements." |
| 256 | ) |
| 257 | }, |
| 258 | useLocation = true |
| 259 | ) |
| 260 | private static final BuiltinFunction replace = |
| 261 | new BuiltinFunction("replace") { |
| 262 | public String invoke( |
| 263 | String self, String oldString, String newString, Object maxSplitO, Location loc) |
| 264 | throws EvalException { |
| 265 | StringBuffer sb = new StringBuffer(); |
| 266 | Integer maxSplit = |
| 267 | Type.INTEGER.convertOptional( |
| 268 | maxSplitO, "'maxsplit' argument of 'replace'", /*label*/ null, Integer.MAX_VALUE); |
| 269 | try { |
| 270 | Matcher m = Pattern.compile(oldString, Pattern.LITERAL).matcher(self); |
| 271 | for (int i = 0; i < maxSplit && m.find(); i++) { |
| 272 | m.appendReplacement(sb, Matcher.quoteReplacement(newString)); |
| 273 | } |
| 274 | m.appendTail(sb); |
| 275 | } catch (IllegalStateException e) { |
| 276 | throw new EvalException(loc, e.getMessage() + " in call to replace"); |
| 277 | } |
| 278 | return sb.toString(); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 279 | } |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 280 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 281 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 282 | @SkylarkSignature( |
| 283 | name = "split", |
| 284 | objectType = StringModule.class, |
| 285 | returnType = MutableList.class, |
| 286 | doc = |
| 287 | "Returns a list of all the words in the string, using <code>sep</code> as the separator, " |
| 288 | + "optionally limiting the number of splits to <code>maxsplit</code>.", |
| 289 | parameters = { |
| 290 | @Param(name = "self", type = String.class, doc = "This string."), |
| 291 | @Param(name = "sep", type = String.class, doc = "The string to split on."), |
| 292 | @Param( |
| 293 | name = "maxsplit", |
| 294 | type = Integer.class, |
| 295 | noneable = true, |
| 296 | defaultValue = "None", |
| 297 | doc = "The maximum number of splits." |
| 298 | ) |
| 299 | }, |
| 300 | useEnvironment = true, |
| 301 | useLocation = true |
| 302 | ) |
| 303 | private static final BuiltinFunction split = |
| 304 | new BuiltinFunction("split") { |
| 305 | public MutableList<String> invoke( |
| 306 | String self, String sep, Object maxSplitO, Location loc, Environment env) |
| 307 | throws EvalException { |
| 308 | int maxSplit = |
| 309 | Type.INTEGER.convertOptional( |
| 310 | maxSplitO, "'split' argument of 'split'", /*label*/ null, -2); |
| 311 | // + 1 because the last result is the remainder. The default is -2 so that after +1, |
| 312 | // it becomes -1. |
| 313 | String[] ss = Pattern.compile(sep, Pattern.LITERAL).split(self, maxSplit + 1); |
| 314 | return MutableList.of(env, ss); |
| 315 | } |
| 316 | }; |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 317 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 318 | @SkylarkSignature( |
| 319 | name = "rsplit", |
| 320 | objectType = StringModule.class, |
| 321 | returnType = MutableList.class, |
| 322 | doc = |
| 323 | "Returns a list of all the words in the string, using <code>sep</code> as the separator, " |
| 324 | + "optionally limiting the number of splits to <code>maxsplit</code>. " |
| 325 | + "Except for splitting from the right, this method behaves like split().", |
| 326 | parameters = { |
| 327 | @Param(name = "self", type = String.class, doc = "This string."), |
| 328 | @Param(name = "sep", type = String.class, doc = "The string to split on."), |
| 329 | @Param( |
| 330 | name = "maxsplit", |
| 331 | type = Integer.class, |
| 332 | noneable = true, |
| 333 | defaultValue = "None", |
| 334 | doc = "The maximum number of splits." |
| 335 | ) |
| 336 | }, |
| 337 | useEnvironment = true, |
| 338 | useLocation = true |
| 339 | ) |
| 340 | private static final BuiltinFunction rsplit = |
| 341 | new BuiltinFunction("rsplit") { |
| 342 | @SuppressWarnings("unused") |
| 343 | public MutableList<String> invoke( |
| 344 | String self, String sep, Object maxSplitO, Location loc, Environment env) |
| 345 | throws EvalException { |
| 346 | int maxSplit = |
| 347 | Type.INTEGER.convertOptional(maxSplitO, "'split' argument of 'split'", null, -1); |
| 348 | try { |
| 349 | return stringRSplit(self, sep, maxSplit, env); |
| 350 | } catch (IllegalArgumentException ex) { |
| 351 | throw new EvalException(loc, ex); |
| 352 | } |
| 353 | } |
| 354 | }; |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 355 | |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 356 | /** |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 357 | * Splits the given string into a list of words, using {@code separator} as a delimiter. |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 358 | * |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 359 | * <p>At most {@code maxSplits} will be performed, going from right to left. |
| 360 | * |
| 361 | * @param input The input string. |
| 362 | * @param separator The separator string. |
| 363 | * @param maxSplits The maximum number of splits. Negative values mean unlimited splits. |
| 364 | * @return A list of words |
| 365 | * @throws IllegalArgumentException |
| 366 | */ |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 367 | private static MutableList<String> stringRSplit( |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 368 | String input, String separator, int maxSplits, Environment env) { |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 369 | if (separator.isEmpty()) { |
| 370 | throw new IllegalArgumentException("Empty separator"); |
| 371 | } |
| 372 | |
| 373 | if (maxSplits <= 0) { |
| 374 | maxSplits = Integer.MAX_VALUE; |
| 375 | } |
| 376 | |
brandjon | dc2c550 | 2017-12-07 14:30:04 -0800 | [diff] [blame] | 377 | ArrayDeque<String> result = new ArrayDeque<>(); |
Florian Weikert | e741e8f | 2015-06-22 20:57:01 +0000 | [diff] [blame] | 378 | String[] parts = input.split(Pattern.quote(separator), -1); |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 379 | int sepLen = separator.length(); |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 380 | int remainingLength = input.length(); |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 381 | int splitsSoFar = 0; |
| 382 | |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 383 | // Copies parts from the array into the final list, starting at the end (because |
| 384 | // it's rsplit), as long as fewer than maxSplits splits are performed. The |
| 385 | // last spot in the list is reserved for the remaining string, whose length |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 386 | // has to be tracked throughout the loop. |
| 387 | for (int pos = parts.length - 1; (pos >= 0) && (splitsSoFar < maxSplits); --pos) { |
| 388 | String current = parts[pos]; |
| 389 | result.addFirst(current); |
| 390 | |
| 391 | ++splitsSoFar; |
| 392 | remainingLength -= sepLen + current.length(); |
| 393 | } |
| 394 | |
| 395 | if (splitsSoFar == maxSplits && remainingLength >= 0) { |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 396 | result.addFirst(input.substring(0, remainingLength)); |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 397 | } |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 398 | |
michajlo | ff50f28 | 2017-10-05 20:02:51 +0200 | [diff] [blame] | 399 | return MutableList.copyOf(env, result); |
Florian Weikert | 8e2e5fc | 2015-05-29 12:39:08 +0000 | [diff] [blame] | 400 | } |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 401 | |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 402 | @SkylarkSignature(name = "partition", objectType = StringModule.class, |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 403 | returnType = Tuple.class, |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 404 | doc = "Splits the input string at the first occurrence of the separator " |
| 405 | + "<code>sep</code> and returns the resulting partition as a three-element " |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 406 | + "tuple of the form (substring_before, separator, substring_after).", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 407 | parameters = { |
| 408 | @Param(name = "self", type = String.class, doc = "This string."), |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 409 | @Param(name = "sep", type = String.class, |
laurentlb | d1e564b | 2017-07-19 21:18:24 +0200 | [diff] [blame] | 410 | defaultValue = "\" \"", doc = "The string to split on, default is space (\" \").")}, |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 411 | useEnvironment = true, |
| 412 | useLocation = true) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 413 | private static final BuiltinFunction partition = new BuiltinFunction("partition") { |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 414 | @SuppressWarnings("unused") |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 415 | public Tuple<String> invoke(String self, String sep, Location loc, Environment env) |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 416 | throws EvalException { |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 417 | return partitionWrapper(self, sep, true, loc); |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 418 | } |
| 419 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 420 | |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 421 | @SkylarkSignature(name = "rpartition", objectType = StringModule.class, |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 422 | returnType = Tuple.class, |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 423 | doc = "Splits the input string at the last occurrence of the separator " |
| 424 | + "<code>sep</code> and returns the resulting partition as a three-element " |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 425 | + "tuple of the form (substring_before, separator, substring_after).", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 426 | parameters = { |
| 427 | @Param(name = "self", type = String.class, doc = "This string."), |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 428 | @Param(name = "sep", type = String.class, |
laurentlb | d1e564b | 2017-07-19 21:18:24 +0200 | [diff] [blame] | 429 | defaultValue = "\" \"", doc = "The string to split on, default is space (\" \").")}, |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 430 | useEnvironment = true, |
| 431 | useLocation = true) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 432 | private static final BuiltinFunction rpartition = new BuiltinFunction("rpartition") { |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 433 | @SuppressWarnings("unused") |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 434 | public Tuple<String> invoke(String self, String sep, Location loc, Environment env) |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 435 | throws EvalException { |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 436 | return partitionWrapper(self, sep, false, loc); |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 437 | } |
| 438 | }; |
| 439 | |
| 440 | /** |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 441 | * Wraps the stringPartition() method and converts its results and exceptions |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 442 | * to the expected types. |
| 443 | * |
| 444 | * @param self The input string |
| 445 | * @param separator The string to split on |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 446 | * @param forward A flag that controls whether the input string is split around |
| 447 | * the first ({@code true}) or last ({@code false}) occurrence of the separator. |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 448 | * @param loc The location that is used for potential exceptions |
| 449 | * @return A list with three elements |
| 450 | */ |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 451 | private static Tuple<String> partitionWrapper( |
| 452 | String self, String separator, boolean forward, Location loc) throws EvalException { |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 453 | try { |
Vladimir Moskva | f2eacf0 | 2017-02-22 23:57:49 +0000 | [diff] [blame] | 454 | return Tuple.copyOf(stringPartition(self, separator, forward)); |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 455 | } catch (IllegalArgumentException ex) { |
| 456 | throw new EvalException(loc, ex); |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | /** |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 461 | * Splits the input string at the {first|last} occurrence of the given separator and returns the |
| 462 | * resulting partition as a three-tuple of Strings, contained in a {@code MutableList}. |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 463 | * |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 464 | * <p>If the input string does not contain the separator, the tuple will consist of the original |
| 465 | * input string and two empty strings. |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 466 | * |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 467 | * <p>This method emulates the behavior of Python's str.partition() and str.rpartition(), |
| 468 | * depending on the value of the {@code forward} flag. |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 469 | * |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 470 | * @param input The input string |
| 471 | * @param separator The string to split on |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 472 | * @param forward A flag that controls whether the input string is split around the first ({@code |
| 473 | * true}) or last ({@code false}) occurrence of the separator. |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 474 | * @return A three-tuple (List) of the form [part_before_separator, separator, |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 475 | * part_after_separator]. |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 476 | */ |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 477 | private static List<String> stringPartition(String input, String separator, boolean forward) { |
Googler | 7ad2f09 | 2015-05-28 11:04:47 +0000 | [diff] [blame] | 478 | if (separator.isEmpty()) { |
| 479 | throw new IllegalArgumentException("Empty separator"); |
| 480 | } |
| 481 | |
| 482 | int partitionSize = 3; |
| 483 | ArrayList<String> result = new ArrayList<>(partitionSize); |
| 484 | int pos = forward ? input.indexOf(separator) : input.lastIndexOf(separator); |
| 485 | |
| 486 | if (pos < 0) { |
| 487 | for (int i = 0; i < partitionSize; ++i) { |
| 488 | result.add(""); |
| 489 | } |
| 490 | |
| 491 | // Following Python's implementation of str.partition() and str.rpartition(), |
| 492 | // the input string is copied to either the first or the last position in the |
| 493 | // list, depending on the value of the forward flag. |
| 494 | result.set(forward ? 0 : partitionSize - 1, input); |
| 495 | } else { |
| 496 | result.add(input.substring(0, pos)); |
| 497 | result.add(separator); |
| 498 | |
| 499 | // pos + sep.length() is at most equal to input.length(). This worst-case |
| 500 | // happens when the separator is at the end of the input string. However, |
| 501 | // substring() will return an empty string in this scenario, thus making |
| 502 | // any additional safety checks obsolete. |
| 503 | result.add(input.substring(pos + separator.length())); |
| 504 | } |
| 505 | |
| 506 | return result; |
| 507 | } |
Laurent Le Brun | 5482074 | 2015-07-30 16:43:52 +0000 | [diff] [blame] | 508 | |
Laurent Le Brun | b4114cc | 2015-08-26 14:53:37 +0000 | [diff] [blame] | 509 | @SkylarkSignature( |
| 510 | name = "capitalize", |
| 511 | objectType = StringModule.class, |
| 512 | returnType = String.class, |
| 513 | doc = |
Mark Schaller | 86eeb8c | 2015-09-14 14:36:37 +0000 | [diff] [blame] | 514 | "Returns a copy of the string with its first character capitalized and the rest " |
Laurent Le Brun | b4114cc | 2015-08-26 14:53:37 +0000 | [diff] [blame] | 515 | + "lowercased. This method does not support non-ascii characters.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 516 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")} |
Laurent Le Brun | b4114cc | 2015-08-26 14:53:37 +0000 | [diff] [blame] | 517 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 518 | private static final BuiltinFunction capitalize = |
Laurent Le Brun | b4114cc | 2015-08-26 14:53:37 +0000 | [diff] [blame] | 519 | new BuiltinFunction("capitalize") { |
| 520 | @SuppressWarnings("unused") |
| 521 | public String invoke(String self) throws EvalException { |
| 522 | if (self.isEmpty()) { |
| 523 | return self; |
| 524 | } |
| 525 | return Character.toUpperCase(self.charAt(0)) + self.substring(1).toLowerCase(); |
| 526 | } |
| 527 | }; |
| 528 | |
Florian Weikert | 006bf4f | 2015-08-03 12:28:35 +0000 | [diff] [blame] | 529 | @SkylarkSignature(name = "title", objectType = StringModule.class, |
| 530 | returnType = String.class, |
| 531 | doc = |
| 532 | "Converts the input string into title case, i.e. every word starts with an " |
| 533 | + "uppercase letter while the remaining letters are lowercase. In this " |
| 534 | + "context, a word means strictly a sequence of letters. This method does " |
| 535 | + "not support supplementary Unicode characters.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 536 | parameters = { |
Florian Weikert | 006bf4f | 2015-08-03 12:28:35 +0000 | [diff] [blame] | 537 | @Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 538 | private static final BuiltinFunction title = new BuiltinFunction("title") { |
Florian Weikert | 006bf4f | 2015-08-03 12:28:35 +0000 | [diff] [blame] | 539 | @SuppressWarnings("unused") |
| 540 | public String invoke(String self) throws EvalException { |
| 541 | char[] data = self.toCharArray(); |
| 542 | boolean previousWasLetter = false; |
| 543 | |
| 544 | for (int pos = 0; pos < data.length; ++pos) { |
| 545 | char current = data[pos]; |
| 546 | boolean currentIsLetter = Character.isLetter(current); |
| 547 | |
| 548 | if (currentIsLetter) { |
| 549 | if (previousWasLetter && Character.isUpperCase(current)) { |
| 550 | data[pos] = Character.toLowerCase(current); |
| 551 | } else if (!previousWasLetter && Character.isLowerCase(current)) { |
| 552 | data[pos] = Character.toUpperCase(current); |
| 553 | } |
| 554 | } |
| 555 | previousWasLetter = currentIsLetter; |
| 556 | } |
| 557 | |
| 558 | return new String(data); |
| 559 | } |
| 560 | }; |
| 561 | |
Francois-Rene Rideau | 76023b9 | 2015-04-17 15:31:59 +0000 | [diff] [blame] | 562 | /** |
| 563 | * Common implementation for find, rfind, index, rindex. |
| 564 | * @param forward true if we want to return the last matching index. |
| 565 | */ |
| 566 | private static int stringFind(boolean forward, |
| 567 | String self, String sub, int start, Object end, String msg) |
| 568 | throws ConversionException { |
| 569 | String substr = pythonSubstring(self, start, end, msg); |
| 570 | int subpos = forward ? substr.indexOf(sub) : substr.lastIndexOf(sub); |
Jon Brandvein | fab8487 | 2016-11-11 16:27:01 +0000 | [diff] [blame] | 571 | start = EvalUtils.clampRangeEndpoint(start, self.length()); |
Francois-Rene Rideau | 76023b9 | 2015-04-17 15:31:59 +0000 | [diff] [blame] | 572 | return subpos < 0 ? subpos : subpos + start; |
| 573 | } |
| 574 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 575 | @SkylarkSignature(name = "rfind", objectType = StringModule.class, returnType = Integer.class, |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 576 | doc = "Returns the last index where <code>sub</code> is found, " |
| 577 | + "or -1 if no such index exists, optionally restricting to " |
| 578 | + "[<code>start</code>:<code>end</code>], " |
| 579 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 580 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 581 | @Param(name = "self", type = String.class, doc = "This string."), |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 582 | @Param(name = "sub", type = String.class, doc = "The substring to find."), |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 583 | @Param(name = "start", type = Integer.class, defaultValue = "0", |
| 584 | doc = "Restrict to search from this position."), |
| 585 | @Param(name = "end", type = Integer.class, noneable = true, defaultValue = "None", |
| 586 | doc = "optional position before which to restrict to search.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 587 | private static final BuiltinFunction rfind = new BuiltinFunction("rfind") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 588 | public Integer invoke(String self, String sub, Integer start, Object end) |
| 589 | throws ConversionException { |
| 590 | return stringFind(false, self, sub, start, end, "'end' argument to rfind"); |
| 591 | } |
| 592 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 593 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 594 | @SkylarkSignature(name = "find", objectType = StringModule.class, returnType = Integer.class, |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 595 | doc = "Returns the first index where <code>sub</code> is found, " |
| 596 | + "or -1 if no such index exists, optionally restricting to " |
| 597 | + "[<code>start</code>:<code>end]</code>, " |
| 598 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 599 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 600 | @Param(name = "self", type = String.class, doc = "This string."), |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 601 | @Param(name = "sub", type = String.class, doc = "The substring to find."), |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 602 | @Param(name = "start", type = Integer.class, defaultValue = "0", |
| 603 | doc = "Restrict to search from this position."), |
| 604 | @Param(name = "end", type = Integer.class, noneable = true, defaultValue = "None", |
| 605 | doc = "optional position before which to restrict to search.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 606 | private static final BuiltinFunction find = new BuiltinFunction("find") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 607 | public Integer invoke(String self, String sub, Integer start, Object end) |
| 608 | throws ConversionException { |
| 609 | return stringFind(true, self, sub, start, end, "'end' argument to find"); |
| 610 | } |
| 611 | }; |
Laurent Le Brun | 4e116c7 | 2015-03-23 13:48:50 +0000 | [diff] [blame] | 612 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 613 | @SkylarkSignature( |
| 614 | name = "rindex", |
| 615 | objectType = StringModule.class, |
| 616 | returnType = Integer.class, |
| 617 | doc = |
| 618 | "Returns the last index where <code>sub</code> is found, " |
| 619 | + "or raises an error if no such index exists, optionally restricting to " |
| 620 | + "[<code>start</code>:<code>end</code>], " |
| 621 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
| 622 | parameters = { |
| 623 | @Param(name = "self", type = String.class, doc = "This string."), |
| 624 | @Param(name = "sub", type = String.class, doc = "The substring to find."), |
| 625 | @Param( |
| 626 | name = "start", |
| 627 | type = Integer.class, |
| 628 | defaultValue = "0", |
| 629 | doc = "Restrict to search from this position." |
| 630 | ), |
| 631 | @Param( |
| 632 | name = "end", |
| 633 | type = Integer.class, |
| 634 | noneable = true, |
| 635 | defaultValue = "None", |
| 636 | doc = "optional position before which to restrict to search." |
| 637 | ) |
| 638 | }, |
| 639 | useLocation = true |
| 640 | ) |
| 641 | private static final BuiltinFunction rindex = |
| 642 | new BuiltinFunction("rindex") { |
| 643 | public Integer invoke(String self, String sub, Integer start, Object end, Location loc) |
| 644 | throws EvalException { |
| 645 | int res = stringFind(false, self, sub, start, end, "'end' argument to rindex"); |
| 646 | if (res < 0) { |
| 647 | throw new EvalException(loc, Printer.format("substring %r not found in %r", sub, self)); |
| 648 | } |
| 649 | return res; |
| 650 | } |
| 651 | }; |
Laurent Le Brun | 4e116c7 | 2015-03-23 13:48:50 +0000 | [diff] [blame] | 652 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 653 | @SkylarkSignature( |
| 654 | name = "index", |
| 655 | objectType = StringModule.class, |
| 656 | returnType = Integer.class, |
| 657 | doc = |
| 658 | "Returns the first index where <code>sub</code> is found, " |
| 659 | + "or raises an error if no such index exists, optionally restricting to " |
| 660 | + "[<code>start</code>:<code>end]</code>, " |
| 661 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
| 662 | parameters = { |
| 663 | @Param(name = "self", type = String.class, doc = "This string."), |
| 664 | @Param(name = "sub", type = String.class, doc = "The substring to find."), |
| 665 | @Param( |
| 666 | name = "start", |
| 667 | type = Integer.class, |
| 668 | defaultValue = "0", |
| 669 | doc = "Restrict to search from this position." |
| 670 | ), |
| 671 | @Param( |
| 672 | name = "end", |
| 673 | type = Integer.class, |
| 674 | noneable = true, |
| 675 | defaultValue = "None", |
| 676 | doc = "optional position before which to restrict to search." |
| 677 | ) |
| 678 | }, |
| 679 | useLocation = true |
| 680 | ) |
| 681 | private static final BuiltinFunction index = |
| 682 | new BuiltinFunction("index") { |
| 683 | public Integer invoke(String self, String sub, Integer start, Object end, Location loc) |
| 684 | throws EvalException { |
| 685 | int res = stringFind(true, self, sub, start, end, "'end' argument to index"); |
| 686 | if (res < 0) { |
| 687 | throw new EvalException(loc, Printer.format("substring %r not found in %r", sub, self)); |
| 688 | } |
| 689 | return res; |
| 690 | } |
| 691 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 692 | |
Florian Weikert | cb8f278 | 2015-12-10 23:30:23 +0000 | [diff] [blame] | 693 | @SkylarkSignature(name = "splitlines", objectType = StringModule.class, |
Dmitry Lomov | 5fd7da5 | 2016-09-05 09:44:48 +0000 | [diff] [blame] | 694 | returnType = SkylarkList.class, |
Florian Weikert | cb8f278 | 2015-12-10 23:30:23 +0000 | [diff] [blame] | 695 | doc = |
| 696 | "Splits the string at line boundaries ('\\n', '\\r\\n', '\\r') " |
| 697 | + "and returns the result as a list.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 698 | parameters = { |
| 699 | @Param(name = "self", type = String.class, doc = "This string."), |
Florian Weikert | cb8f278 | 2015-12-10 23:30:23 +0000 | [diff] [blame] | 700 | @Param(name = "keepends", type = Boolean.class, defaultValue = "False", |
| 701 | doc = "Whether the line breaks should be included in the resulting list.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 702 | private static final BuiltinFunction splitLines = new BuiltinFunction("splitlines") { |
Florian Weikert | cb8f278 | 2015-12-10 23:30:23 +0000 | [diff] [blame] | 703 | @SuppressWarnings("unused") |
Dmitry Lomov | 5fd7da5 | 2016-09-05 09:44:48 +0000 | [diff] [blame] | 704 | public SkylarkList<String> invoke(String self, Boolean keepEnds) throws EvalException { |
Florian Weikert | cb8f278 | 2015-12-10 23:30:23 +0000 | [diff] [blame] | 705 | List<String> result = new ArrayList<>(); |
| 706 | Matcher matcher = SPLIT_LINES_PATTERN.matcher(self); |
| 707 | while (matcher.find()) { |
| 708 | String line = matcher.group("line"); |
| 709 | String lineBreak = matcher.group("break"); |
| 710 | boolean trailingBreak = lineBreak.isEmpty(); |
| 711 | if (line.isEmpty() && trailingBreak) { |
| 712 | break; |
| 713 | } |
| 714 | if (keepEnds && !trailingBreak) { |
| 715 | result.add(line + lineBreak); |
| 716 | } else { |
| 717 | result.add(line); |
| 718 | } |
| 719 | } |
Dmitry Lomov | 5fd7da5 | 2016-09-05 09:44:48 +0000 | [diff] [blame] | 720 | return SkylarkList.createImmutable(result); |
Florian Weikert | cb8f278 | 2015-12-10 23:30:23 +0000 | [diff] [blame] | 721 | } |
| 722 | }; |
| 723 | |
| 724 | private static final Pattern SPLIT_LINES_PATTERN = |
| 725 | Pattern.compile("(?<line>.*)(?<break>(\\r\\n|\\r|\\n)?)"); |
| 726 | |
Googler | 8e8fa05 | 2015-09-03 18:36:33 +0000 | [diff] [blame] | 727 | @SkylarkSignature(name = "isalpha", objectType = StringModule.class, returnType = Boolean.class, |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 728 | doc = "Returns True if all characters in the string are alphabetic ([a-zA-Z]) and there is " |
| 729 | + "at least one character.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 730 | parameters = { |
Googler | 8e8fa05 | 2015-09-03 18:36:33 +0000 | [diff] [blame] | 731 | @Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 732 | private static final BuiltinFunction isalpha = new BuiltinFunction("isalpha") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 733 | @SuppressWarnings("unused") // Called via Reflection |
Googler | 8e8fa05 | 2015-09-03 18:36:33 +0000 | [diff] [blame] | 734 | public Boolean invoke(String self) throws EvalException { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 735 | return MethodLibrary.matches(self, MethodLibrary.ALPHA, false); |
Florian Weikert | d03485f | 2015-12-15 16:50:40 +0000 | [diff] [blame] | 736 | } |
| 737 | }; |
| 738 | |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 739 | @SkylarkSignature(name = "isalnum", objectType = StringModule.class, returnType = Boolean.class, |
| 740 | doc = |
| 741 | "Returns True if all characters in the string are alphanumeric ([a-zA-Z0-9]) and there is " |
| 742 | + "at least one character.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 743 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 744 | private static final BuiltinFunction isAlnum = new BuiltinFunction("isalnum") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 745 | @SuppressWarnings("unused") // Called via Reflection |
| 746 | public Boolean invoke(String self) throws EvalException { |
| 747 | return MethodLibrary.matches(self, MethodLibrary.ALNUM, false); |
| 748 | } |
| 749 | }; |
| 750 | |
| 751 | @SkylarkSignature(name = "isdigit", objectType = StringModule.class, returnType = Boolean.class, |
| 752 | doc = |
| 753 | "Returns True if all characters in the string are digits ([0-9]) and there is " |
| 754 | + "at least one character.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 755 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 756 | private static final BuiltinFunction isDigit = new BuiltinFunction("isdigit") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 757 | @SuppressWarnings("unused") // Called via Reflection |
| 758 | public Boolean invoke(String self) throws EvalException { |
| 759 | return MethodLibrary.matches(self, MethodLibrary.DIGIT, false); |
| 760 | } |
| 761 | }; |
| 762 | |
| 763 | @SkylarkSignature(name = "isspace", objectType = StringModule.class, returnType = Boolean.class, |
| 764 | doc = |
| 765 | "Returns True if all characters are white space characters and the string " |
| 766 | + "contains at least one character.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 767 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 768 | private static final BuiltinFunction isSpace = new BuiltinFunction("isspace") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 769 | @SuppressWarnings("unused") // Called via Reflection |
| 770 | public Boolean invoke(String self) throws EvalException { |
| 771 | return MethodLibrary.matches(self, MethodLibrary.SPACE, false); |
| 772 | } |
| 773 | }; |
| 774 | |
| 775 | @SkylarkSignature(name = "islower", objectType = StringModule.class, returnType = Boolean.class, |
| 776 | doc = |
| 777 | "Returns True if all cased characters in the string are lowercase and there is " |
| 778 | + "at least one character.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 779 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 780 | private static final BuiltinFunction isLower = new BuiltinFunction("islower") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 781 | @SuppressWarnings("unused") // Called via Reflection |
| 782 | public Boolean invoke(String self) throws EvalException { |
| 783 | // Python also accepts non-cased characters, so we cannot use LOWER. |
| 784 | return MethodLibrary.matches(self, MethodLibrary.UPPER.negate(), true); |
| 785 | } |
| 786 | }; |
| 787 | |
| 788 | @SkylarkSignature(name = "isupper", objectType = StringModule.class, returnType = Boolean.class, |
| 789 | doc = |
| 790 | "Returns True if all cased characters in the string are uppercase and there is " |
| 791 | + "at least one character.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 792 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 793 | private static final BuiltinFunction isUpper = new BuiltinFunction("isupper") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 794 | @SuppressWarnings("unused") // Called via Reflection |
| 795 | public Boolean invoke(String self) throws EvalException { |
| 796 | // Python also accepts non-cased characters, so we cannot use UPPER. |
| 797 | return MethodLibrary.matches(self, MethodLibrary.LOWER.negate(), true); |
| 798 | } |
| 799 | }; |
| 800 | |
| 801 | @SkylarkSignature(name = "istitle", objectType = StringModule.class, returnType = Boolean.class, |
| 802 | doc = |
| 803 | "Returns True if the string is in title case and it contains at least one character. " |
| 804 | + "This means that every uppercase character must follow an uncased one (e.g. whitespace) " |
| 805 | + "and every lowercase character must follow a cased one (e.g. uppercase or lowercase).", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 806 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 807 | private static final BuiltinFunction isTitle = new BuiltinFunction("istitle") { |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 808 | @SuppressWarnings("unused") // Called via Reflection |
| 809 | public Boolean invoke(String self) throws EvalException { |
| 810 | if (self.isEmpty()) { |
| 811 | return false; |
| 812 | } |
| 813 | // From the Python documentation: "uppercase characters may only follow uncased characters |
| 814 | // and lowercase characters only cased ones". |
| 815 | char[] data = self.toCharArray(); |
Googler | e92bfe5 | 2016-03-07 19:32:24 +0000 | [diff] [blame] | 816 | CharMatcher matcher = CharMatcher.any(); |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 817 | char leftMostCased = ' '; |
| 818 | for (int pos = data.length - 1; pos >= 0; --pos) { |
| 819 | char current = data[pos]; |
| 820 | // 1. Check condition that was determined by the right neighbor. |
| 821 | if (!matcher.matches(current)) { |
| 822 | return false; |
| 823 | } |
| 824 | // 2. Determine condition for the left neighbor. |
| 825 | if (LOWER.matches(current)) { |
| 826 | matcher = CASED; |
| 827 | } else if (UPPER.matches(current)) { |
| 828 | matcher = CASED.negate(); |
| 829 | } else { |
Googler | e92bfe5 | 2016-03-07 19:32:24 +0000 | [diff] [blame] | 830 | matcher = CharMatcher.any(); |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 831 | } |
| 832 | // 3. Store character if it is cased. |
| 833 | if (CASED.matches(current)) { |
| 834 | leftMostCased = current; |
| 835 | } |
| 836 | } |
| 837 | // The leftmost cased letter must be uppercase. If leftMostCased is not a cased letter here, |
| 838 | // then the string doesn't have any cased letter, so UPPER.test will return false. |
| 839 | return UPPER.matches(leftMostCased); |
| 840 | } |
| 841 | }; |
| 842 | |
| 843 | private static boolean matches( |
| 844 | String str, CharMatcher matcher, boolean requiresAtLeastOneCasedLetter) { |
| 845 | if (str.isEmpty()) { |
| 846 | return false; |
| 847 | } else if (!requiresAtLeastOneCasedLetter) { |
| 848 | return matcher.matchesAllOf(str); |
| 849 | } |
| 850 | int casedLetters = 0; |
| 851 | for (char current : str.toCharArray()) { |
| 852 | if (!matcher.matches(current)) { |
| 853 | return false; |
| 854 | } else if (requiresAtLeastOneCasedLetter && CASED.matches(current)) { |
| 855 | ++casedLetters; |
| 856 | } |
| 857 | } |
| 858 | return casedLetters > 0; |
| 859 | } |
| 860 | |
| 861 | private static final CharMatcher DIGIT = CharMatcher.javaDigit(); |
| 862 | private static final CharMatcher LOWER = CharMatcher.inRange('a', 'z'); |
| 863 | private static final CharMatcher UPPER = CharMatcher.inRange('A', 'Z'); |
| 864 | private static final CharMatcher ALPHA = LOWER.or(UPPER); |
| 865 | private static final CharMatcher ALNUM = ALPHA.or(DIGIT); |
| 866 | private static final CharMatcher CASED = ALPHA; |
Googler | e92bfe5 | 2016-03-07 19:32:24 +0000 | [diff] [blame] | 867 | private static final CharMatcher SPACE = CharMatcher.whitespace(); |
Florian Weikert | 532d3ba | 2015-12-17 10:36:45 +0000 | [diff] [blame] | 868 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 869 | @SkylarkSignature(name = "count", objectType = StringModule.class, returnType = Integer.class, |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 870 | doc = "Returns the number of (non-overlapping) occurrences of substring <code>sub</code> in " |
| 871 | + "string, optionally restricting to [<code>start</code>:<code>end</code>], " |
| 872 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 873 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 874 | @Param(name = "self", type = String.class, doc = "This string."), |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 875 | @Param(name = "sub", type = String.class, doc = "The substring to count."), |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 876 | @Param(name = "start", type = Integer.class, defaultValue = "0", |
| 877 | doc = "Restrict to search from this position."), |
| 878 | @Param(name = "end", type = Integer.class, noneable = true, defaultValue = "None", |
| 879 | doc = "optional position before which to restrict to search.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 880 | private static final BuiltinFunction count = new BuiltinFunction("count") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 881 | public Integer invoke(String self, String sub, Integer start, Object end) |
| 882 | throws ConversionException { |
| 883 | String str = pythonSubstring(self, start, end, "'end' operand of 'find'"); |
| 884 | if (sub.isEmpty()) { |
| 885 | return str.length() + 1; |
| 886 | } |
| 887 | int count = 0; |
| 888 | int index = -1; |
| 889 | while ((index = str.indexOf(sub)) >= 0) { |
| 890 | count++; |
| 891 | str = str.substring(index + sub.length()); |
| 892 | } |
| 893 | return count; |
| 894 | } |
| 895 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 896 | |
laurentlb | 76972e2 | 2018-03-21 15:39:11 -0700 | [diff] [blame] | 897 | @SkylarkSignature( |
| 898 | name = "elems", |
| 899 | objectType = StringModule.class, |
| 900 | returnType = SkylarkList.class, |
| 901 | doc = |
| 902 | "Returns an iterable value containing successive 1-element substrings of the string. " |
| 903 | + "Equivalent to <code>[s[i] for i in range(len(s))]</code>, except that the " |
| 904 | + "returned value might not be a list.", |
| 905 | parameters = {@Param(name = "self", type = String.class, doc = "This string.")} |
| 906 | ) |
| 907 | private static final BuiltinFunction elems = |
| 908 | new BuiltinFunction("elems") { |
| 909 | public SkylarkList<String> invoke(String self) throws ConversionException { |
| 910 | ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); |
| 911 | for (char c : self.toCharArray()) { |
| 912 | builder.add(String.valueOf(c)); |
| 913 | } |
| 914 | return SkylarkList.createImmutable(builder.build()); |
| 915 | } |
| 916 | }; |
| 917 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 918 | @SkylarkSignature(name = "endswith", objectType = StringModule.class, returnType = Boolean.class, |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 919 | doc = "Returns True if the string ends with <code>sub</code>, " |
| 920 | + "otherwise False, optionally restricting to [<code>start</code>:<code>end</code>], " |
| 921 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 922 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 923 | @Param(name = "self", type = String.class, doc = "This string."), |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 924 | @Param(name = "sub", type = String.class, doc = "The substring to check."), |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 925 | @Param(name = "start", type = Integer.class, defaultValue = "0", |
| 926 | doc = "Test beginning at this position."), |
| 927 | @Param(name = "end", type = Integer.class, noneable = true, defaultValue = "None", |
| 928 | doc = "optional position at which to stop comparing.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 929 | private static final BuiltinFunction endswith = new BuiltinFunction("endswith") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 930 | public Boolean invoke(String self, String sub, Integer start, Object end) |
| 931 | throws ConversionException { |
| 932 | return pythonSubstring(self, start, end, "'end' operand of 'endswith'").endsWith(sub); |
| 933 | } |
| 934 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 935 | |
Laurent Le Brun | aa83c3a | 2015-05-08 15:00:35 +0000 | [diff] [blame] | 936 | // In Python, formatting is very complex. |
| 937 | // We handle here the simplest case which provides most of the value of the function. |
| 938 | // https://docs.python.org/3/library/string.html#formatstrings |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 939 | @SkylarkSignature( |
| 940 | name = "format", |
| 941 | objectType = StringModule.class, |
| 942 | returnType = String.class, |
| 943 | doc = |
| 944 | "Perform string interpolation. Format strings contain replacement fields " |
| 945 | + "surrounded by curly braces <code>{}</code>. Anything that is not contained " |
| 946 | + "in braces is considered literal text, which is copied unchanged to the output." |
| 947 | + "If you need to include a brace character in the literal text, it can be " |
| 948 | + "escaped by doubling: <code>{{</code> and <code>}}</code>" |
| 949 | + "A replacement field can be either a name, a number, or empty. Values are " |
| 950 | + "converted to strings using the <a href=\"globals.html#str\">str</a> function." |
| 951 | + "<pre class=\"language-python\">" |
| 952 | + "# Access in order:\n" |
| 953 | + "\"{} < {}\".format(4, 5) == \"4 < 5\"\n" |
| 954 | + "# Access by position:\n" |
| 955 | + "\"{1}, {0}\".format(2, 1) == \"1, 2\"\n" |
| 956 | + "# Access by name:\n" |
| 957 | + "\"x{key}x\".format(key = 2) == \"x2x\"</pre>\n", |
| 958 | parameters = { |
| 959 | @Param(name = "self", type = String.class, doc = "This string."), |
| 960 | }, |
| 961 | extraPositionals = |
| 962 | @Param( |
| 963 | name = "args", |
| 964 | type = SkylarkList.class, |
| 965 | defaultValue = "()", |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 966 | doc = "List of arguments." |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 967 | ), |
| 968 | extraKeywords = |
| 969 | @Param( |
| 970 | name = "kwargs", |
| 971 | type = SkylarkDict.class, |
| 972 | defaultValue = "{}", |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 973 | doc = "Dictionary of arguments." |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 974 | ), |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 975 | useLocation = true |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 976 | ) |
| 977 | private static final BuiltinFunction format = |
| 978 | new BuiltinFunction("format") { |
| 979 | @SuppressWarnings("unused") |
| 980 | public String invoke( |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 981 | String self, |
| 982 | SkylarkList<Object> args, |
| 983 | SkylarkDict<?, ?> kwargs, |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 984 | Location loc) |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 985 | throws EvalException { |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 986 | return new FormatParser(loc) |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 987 | .format( |
| 988 | self, |
| 989 | args.getImmutableList(), |
| 990 | kwargs.getContents(String.class, Object.class, "kwargs")); |
| 991 | } |
| 992 | }; |
Laurent Le Brun | aa83c3a | 2015-05-08 15:00:35 +0000 | [diff] [blame] | 993 | |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 994 | @SkylarkSignature(name = "startswith", objectType = StringModule.class, |
| 995 | returnType = Boolean.class, |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 996 | doc = "Returns True if the string starts with <code>sub</code>, " |
| 997 | + "otherwise False, optionally restricting to [<code>start</code>:<code>end</code>], " |
| 998 | + "<code>start</code> being inclusive and <code>end</code> being exclusive.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 999 | parameters = { |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 1000 | @Param(name = "self", type = String.class, doc = "This string."), |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1001 | @Param(name = "sub", type = String.class, doc = "The substring to check."), |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 1002 | @Param(name = "start", type = Integer.class, defaultValue = "0", |
| 1003 | doc = "Test beginning at this position."), |
| 1004 | @Param(name = "end", type = Integer.class, noneable = true, defaultValue = "None", |
| 1005 | doc = "Stop comparing at this position.")}) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1006 | private static final BuiltinFunction startswith = new BuiltinFunction("startswith") { |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 1007 | public Boolean invoke(String self, String sub, Integer start, Object end) |
| 1008 | throws ConversionException { |
| 1009 | return pythonSubstring(self, start, end, "'end' operand of 'startswith'").startsWith(sub); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1010 | } |
| 1011 | }; |
| 1012 | |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1013 | @SkylarkSignature( |
| 1014 | name = "min", |
| 1015 | returnType = Object.class, |
| 1016 | doc = |
| 1017 | "Returns the smallest one of all given arguments. " |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1018 | + "If only one argument is provided, it must be a non-empty iterable. " |
| 1019 | + "It is an error if elements are not comparable (for example int with string). " |
| 1020 | + "<pre class=\"language-python\">min(2, 5, 4) == 2\n" |
| 1021 | + "min([5, 6, 3]) == 3</pre>", |
Damien Martin-Guillerez | e3108c5 | 2016-06-08 08:54:45 +0000 | [diff] [blame] | 1022 | extraPositionals = |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1023 | @Param(name = "args", type = SkylarkList.class, doc = "The elements to be checked."), |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1024 | useLocation = true, |
| 1025 | useEnvironment = true |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1026 | ) |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1027 | private static final BuiltinFunction min = |
| 1028 | new BuiltinFunction("min") { |
| 1029 | @SuppressWarnings("unused") // Accessed via Reflection. |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1030 | public Object invoke(SkylarkList<?> args, Location loc, Environment env) |
| 1031 | throws EvalException { |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1032 | try { |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1033 | return findExtreme(args, EvalUtils.SKYLARK_COMPARATOR.reverse(), loc, env); |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1034 | } catch (ComparisonException e) { |
| 1035 | throw new EvalException(loc, e); |
| 1036 | } |
| 1037 | } |
| 1038 | }; |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1039 | |
| 1040 | @SkylarkSignature( |
| 1041 | name = "max", |
| 1042 | returnType = Object.class, |
| 1043 | doc = |
| 1044 | "Returns the largest one of all given arguments. " |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1045 | + "If only one argument is provided, it must be a non-empty iterable." |
| 1046 | + "It is an error if elements are not comparable (for example int with string). " |
| 1047 | + "<pre class=\"language-python\">max(2, 5, 4) == 5\n" |
| 1048 | + "max([5, 6, 3]) == 6</pre>", |
Damien Martin-Guillerez | e3108c5 | 2016-06-08 08:54:45 +0000 | [diff] [blame] | 1049 | extraPositionals = |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1050 | @Param(name = "args", type = SkylarkList.class, doc = "The elements to be checked."), |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1051 | useLocation = true, |
| 1052 | useEnvironment = true |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1053 | ) |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1054 | private static final BuiltinFunction max = |
| 1055 | new BuiltinFunction("max") { |
| 1056 | @SuppressWarnings("unused") // Accessed via Reflection. |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1057 | public Object invoke(SkylarkList<?> args, Location loc, Environment env) |
| 1058 | throws EvalException { |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1059 | try { |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1060 | return findExtreme(args, EvalUtils.SKYLARK_COMPARATOR, loc, env); |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1061 | } catch (ComparisonException e) { |
| 1062 | throw new EvalException(loc, e); |
| 1063 | } |
| 1064 | } |
| 1065 | }; |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1066 | |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1067 | /** Returns the maximum element from this list, as determined by maxOrdering. */ |
| 1068 | private static Object findExtreme( |
| 1069 | SkylarkList<?> args, Ordering<Object> maxOrdering, Location loc, Environment env) |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1070 | throws EvalException { |
Jon Brandvein | 3cfeeec | 2017-01-20 04:23:37 +0000 | [diff] [blame] | 1071 | // Args can either be a list of items to compare, or a singleton list whose element is an |
| 1072 | // iterable of items to compare. In either case, there must be at least one item to compare. |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1073 | try { |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1074 | Iterable<?> items = (args.size() == 1) ? EvalUtils.toIterable(args.get(0), loc, env) : args; |
Jon Brandvein | 3cfeeec | 2017-01-20 04:23:37 +0000 | [diff] [blame] | 1075 | return maxOrdering.max(items); |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1076 | } catch (NoSuchElementException ex) { |
Jon Brandvein | 3cfeeec | 2017-01-20 04:23:37 +0000 | [diff] [blame] | 1077 | throw new EvalException(loc, "expected at least one item"); |
Florian Weikert | 5e8752b | 2015-12-11 21:54:43 +0000 | [diff] [blame] | 1078 | } |
| 1079 | } |
| 1080 | |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1081 | @SkylarkSignature( |
| 1082 | name = "all", |
| 1083 | returnType = Boolean.class, |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1084 | doc = |
| 1085 | "Returns true if all elements evaluate to True or if the collection is empty. " |
mpn | aa0ca5b | 2017-09-15 01:47:53 +0200 | [diff] [blame] | 1086 | + "Elements are converted to boolean using the <a href=\"#bool\">bool</a> function." |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1087 | + "<pre class=\"language-python\">all([\"hello\", 3, True]) == True\n" |
| 1088 | + "all([-1, 0, 1]) == False</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1089 | parameters = { |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1090 | @Param(name = "elements", type = Object.class, doc = "A string or a collection of elements.") |
| 1091 | }, |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1092 | useLocation = true, |
| 1093 | useEnvironment = true |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1094 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1095 | private static final BuiltinFunction all = |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1096 | new BuiltinFunction("all") { |
| 1097 | @SuppressWarnings("unused") // Accessed via Reflection. |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1098 | public Boolean invoke(Object collection, Location loc, Environment env) |
| 1099 | throws EvalException { |
| 1100 | return !hasElementWithBooleanValue(collection, false, loc, env); |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1101 | } |
| 1102 | }; |
| 1103 | |
| 1104 | @SkylarkSignature( |
| 1105 | name = "any", |
| 1106 | returnType = Boolean.class, |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1107 | doc = |
mpn | aa0ca5b | 2017-09-15 01:47:53 +0200 | [diff] [blame] | 1108 | "Returns true if at least one element evaluates to True. " |
| 1109 | + "Elements are converted to boolean using the <a href=\"#bool\">bool</a> function." |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1110 | + "<pre class=\"language-python\">any([-1, 0, 1]) == True\n" |
| 1111 | + "any([False, 0, \"\"]) == False</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1112 | parameters = { |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1113 | @Param(name = "elements", type = Object.class, doc = "A string or a collection of elements.") |
| 1114 | }, |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1115 | useLocation = true, |
| 1116 | useEnvironment = true |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1117 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1118 | private static final BuiltinFunction any = |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1119 | new BuiltinFunction("any") { |
| 1120 | @SuppressWarnings("unused") // Accessed via Reflection. |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1121 | public Boolean invoke(Object collection, Location loc, Environment env) |
| 1122 | throws EvalException { |
| 1123 | return hasElementWithBooleanValue(collection, true, loc, env); |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1124 | } |
| 1125 | }; |
| 1126 | |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1127 | private static boolean hasElementWithBooleanValue( |
| 1128 | Object collection, boolean value, Location loc, Environment env) throws EvalException { |
| 1129 | Iterable<?> iterable = EvalUtils.toIterable(collection, loc, env); |
Florian Weikert | 233a46e | 2015-12-16 12:38:38 +0000 | [diff] [blame] | 1130 | for (Object obj : iterable) { |
| 1131 | if (EvalUtils.toBoolean(obj) == value) { |
| 1132 | return true; |
| 1133 | } |
| 1134 | } |
| 1135 | return false; |
| 1136 | } |
| 1137 | |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1138 | // supported list methods |
Laurent Le Brun | 6a4d36a | 2015-08-21 10:57:41 +0000 | [diff] [blame] | 1139 | @SkylarkSignature( |
| 1140 | name = "sorted", |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 1141 | returnType = MutableList.class, |
Laurent Le Brun | 6a4d36a | 2015-08-21 10:57:41 +0000 | [diff] [blame] | 1142 | doc = |
Vladimir Moskva | 7f0cd62 | 2017-02-16 13:48:37 +0000 | [diff] [blame] | 1143 | "Sort a collection. Elements should all belong to the same orderable type, they are sorted " |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1144 | + "by their value (in ascending order). " |
| 1145 | + "It is an error if elements are not comparable (for example int with string)." |
| 1146 | + "<pre class=\"language-python\">sorted([3, 5, 4]) == [3, 4, 5]</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1147 | parameters = {@Param(name = "self", type = Object.class, doc = "This collection.")}, |
Laurent Le Brun | 6a4d36a | 2015-08-21 10:57:41 +0000 | [diff] [blame] | 1148 | useLocation = true, |
| 1149 | useEnvironment = true |
| 1150 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1151 | private static final BuiltinFunction sorted = |
Laurent Le Brun | 6a4d36a | 2015-08-21 10:57:41 +0000 | [diff] [blame] | 1152 | new BuiltinFunction("sorted") { |
brandjon | c06e746 | 2017-07-11 20:54:58 +0200 | [diff] [blame] | 1153 | public MutableList<?> invoke(Object self, Location loc, Environment env) |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1154 | throws EvalException { |
Laurent Le Brun | 6a4d36a | 2015-08-21 10:57:41 +0000 | [diff] [blame] | 1155 | try { |
michajlo | ff50f28 | 2017-10-05 20:02:51 +0200 | [diff] [blame] | 1156 | return MutableList.copyOf( |
| 1157 | env, |
| 1158 | EvalUtils.SKYLARK_COMPARATOR.sortedCopy(EvalUtils.toCollection(self, loc, env))); |
Laurent Le Brun | 6a4d36a | 2015-08-21 10:57:41 +0000 | [diff] [blame] | 1159 | } catch (EvalUtils.ComparisonException e) { |
| 1160 | throw new EvalException(loc, e); |
| 1161 | } |
| 1162 | } |
| 1163 | }; |
Laurent Le Brun | ef69ec5 | 2015-04-16 18:58:34 +0000 | [diff] [blame] | 1164 | |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1165 | @SkylarkSignature( |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1166 | name = "reversed", |
| 1167 | returnType = MutableList.class, |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1168 | doc = |
| 1169 | "Returns a list that contains the elements of the original sequence in reversed order." |
| 1170 | + "<pre class=\"language-python\">reversed([3, 5, 4]) == [4, 5, 3]</pre>", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1171 | parameters = { |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1172 | @Param( |
| 1173 | name = "sequence", |
| 1174 | type = Object.class, |
| 1175 | doc = "The sequence to be reversed (string, list or tuple)." |
| 1176 | ) |
| 1177 | }, |
| 1178 | useLocation = true, |
| 1179 | useEnvironment = true |
| 1180 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1181 | private static final BuiltinFunction reversed = |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1182 | new BuiltinFunction("reversed") { |
| 1183 | @SuppressWarnings("unused") // Accessed via Reflection. |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1184 | public MutableList<?> invoke(Object sequence, Location loc, Environment env) |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1185 | throws EvalException { |
| 1186 | // We only allow lists and strings. |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1187 | if (sequence instanceof SkylarkDict) { |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1188 | throw new EvalException( |
| 1189 | loc, "Argument to reversed() must be a sequence, not a dictionary."); |
| 1190 | } else if (sequence instanceof NestedSet || sequence instanceof SkylarkNestedSet) { |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1191 | throw new EvalException( |
| 1192 | loc, "Argument to reversed() must be a sequence, not a depset."); |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1193 | } |
brandjon | dc2c550 | 2017-12-07 14:30:04 -0800 | [diff] [blame] | 1194 | ArrayDeque<Object> tmpList = new ArrayDeque<>(); |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1195 | for (Object element : EvalUtils.toIterable(sequence, loc, env)) { |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1196 | tmpList.addFirst(element); |
| 1197 | } |
michajlo | ff50f28 | 2017-10-05 20:02:51 +0200 | [diff] [blame] | 1198 | return MutableList.copyOf(env, tmpList); |
Florian Weikert | d5e3350 | 2015-12-14 12:06:10 +0000 | [diff] [blame] | 1199 | } |
| 1200 | }; |
| 1201 | |
| 1202 | @SkylarkSignature( |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1203 | name = "append", |
| 1204 | objectType = MutableList.class, |
| 1205 | returnType = Runtime.NoneType.class, |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1206 | doc = "Adds an item to the end of the list.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1207 | parameters = { |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1208 | @Param(name = "self", type = MutableList.class, doc = "This list."), |
| 1209 | @Param(name = "item", type = Object.class, doc = "Item to add at the end.") |
| 1210 | }, |
| 1211 | useLocation = true, |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1212 | useEnvironment = true |
| 1213 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1214 | private static final BuiltinFunction append = |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1215 | new BuiltinFunction("append") { |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1216 | public Runtime.NoneType invoke( |
| 1217 | MutableList<Object> self, Object item, Location loc, Environment env) |
| 1218 | throws EvalException { |
brandjon | 0528d5d | 2017-08-04 16:00:56 +0200 | [diff] [blame] | 1219 | self.add(item, loc, env.mutability()); |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1220 | return Runtime.NONE; |
| 1221 | } |
| 1222 | }; |
| 1223 | |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1224 | @SkylarkSignature( |
Yue Gan | 6c2276a | 2016-04-07 08:02:00 +0000 | [diff] [blame] | 1225 | name = "insert", |
| 1226 | objectType = MutableList.class, |
| 1227 | returnType = Runtime.NoneType.class, |
| 1228 | doc = "Inserts an item at a given position.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1229 | parameters = { |
Yue Gan | 6c2276a | 2016-04-07 08:02:00 +0000 | [diff] [blame] | 1230 | @Param(name = "self", type = MutableList.class, doc = "This list."), |
| 1231 | @Param(name = "index", type = Integer.class, doc = "The index of the given position."), |
| 1232 | @Param(name = "item", type = Object.class, doc = "The item.") |
| 1233 | }, |
| 1234 | useLocation = true, |
| 1235 | useEnvironment = true |
| 1236 | ) |
| 1237 | private static final BuiltinFunction insert = |
| 1238 | new BuiltinFunction("insert") { |
| 1239 | public Runtime.NoneType invoke( |
| 1240 | MutableList<Object> self, Integer index, Object item, Location loc, Environment env) |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1241 | throws EvalException { |
brandjon | 0528d5d | 2017-08-04 16:00:56 +0200 | [diff] [blame] | 1242 | self.add(EvalUtils.clampRangeEndpoint(index, self.size()), item, loc, env.mutability()); |
Yue Gan | 6c2276a | 2016-04-07 08:02:00 +0000 | [diff] [blame] | 1243 | return Runtime.NONE; |
| 1244 | } |
| 1245 | }; |
| 1246 | |
| 1247 | @SkylarkSignature( |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1248 | name = "extend", |
| 1249 | objectType = MutableList.class, |
| 1250 | returnType = Runtime.NoneType.class, |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1251 | doc = "Adds all items to the end of the list.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1252 | parameters = { |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1253 | @Param(name = "self", type = MutableList.class, doc = "This list."), |
Yue Gan | 6c2276a | 2016-04-07 08:02:00 +0000 | [diff] [blame] | 1254 | @Param(name = "items", type = SkylarkList.class, doc = "Items to add at the end.") |
| 1255 | }, |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1256 | useLocation = true, |
Yue Gan | 6c2276a | 2016-04-07 08:02:00 +0000 | [diff] [blame] | 1257 | useEnvironment = true |
| 1258 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1259 | private static final BuiltinFunction extend = |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1260 | new BuiltinFunction("extend") { |
Yue Gan | 6c2276a | 2016-04-07 08:02:00 +0000 | [diff] [blame] | 1261 | public Runtime.NoneType invoke( |
| 1262 | MutableList<Object> self, SkylarkList<Object> items, Location loc, Environment env) |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1263 | throws EvalException { |
brandjon | 0528d5d | 2017-08-04 16:00:56 +0200 | [diff] [blame] | 1264 | self.addAll(items, loc, env.mutability()); |
Francois-Rene Rideau | 4e99410 | 2015-09-17 22:41:28 +0000 | [diff] [blame] | 1265 | return Runtime.NONE; |
| 1266 | } |
| 1267 | }; |
| 1268 | |
Laurent Le Brun | 3ef1eea | 2015-11-09 14:35:54 +0000 | [diff] [blame] | 1269 | @SkylarkSignature( |
| 1270 | name = "index", |
| 1271 | objectType = MutableList.class, |
| 1272 | returnType = Integer.class, |
| 1273 | doc = |
| 1274 | "Returns the index in the list of the first item whose value is x. " |
| 1275 | + "It is an error if there is no such item.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1276 | parameters = { |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1277 | @Param(name = "self", type = MutableList.class, doc = "This list."), |
Laurent Le Brun | 3ef1eea | 2015-11-09 14:35:54 +0000 | [diff] [blame] | 1278 | @Param(name = "x", type = Object.class, doc = "The object to search.") |
| 1279 | }, |
| 1280 | useLocation = true |
| 1281 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1282 | private static final BuiltinFunction listIndex = |
Laurent Le Brun | 3ef1eea | 2015-11-09 14:35:54 +0000 | [diff] [blame] | 1283 | new BuiltinFunction("index") { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1284 | public Integer invoke(MutableList<?> self, Object x, Location loc) throws EvalException { |
Laurent Le Brun | 3ef1eea | 2015-11-09 14:35:54 +0000 | [diff] [blame] | 1285 | int i = 0; |
| 1286 | for (Object obj : self) { |
| 1287 | if (obj.equals(x)) { |
| 1288 | return i; |
| 1289 | } |
| 1290 | i++; |
| 1291 | } |
Laurent Le Brun | c31f351 | 2016-12-29 21:41:33 +0000 | [diff] [blame] | 1292 | throw new EvalException(loc, Printer.format("item %r not found in list", x)); |
Laurent Le Brun | 3ef1eea | 2015-11-09 14:35:54 +0000 | [diff] [blame] | 1293 | } |
| 1294 | }; |
| 1295 | |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1296 | @SkylarkSignature( |
| 1297 | name = "remove", |
| 1298 | objectType = MutableList.class, |
| 1299 | returnType = Runtime.NoneType.class, |
| 1300 | doc = |
| 1301 | "Removes the first item from the list whose value is x. " |
| 1302 | + "It is an error if there is no such item.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1303 | parameters = { |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1304 | @Param(name = "self", type = MutableList.class, doc = "This list."), |
| 1305 | @Param(name = "x", type = Object.class, doc = "The object to remove.") |
| 1306 | }, |
| 1307 | useLocation = true, |
| 1308 | useEnvironment = true |
| 1309 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1310 | private static final BuiltinFunction listRemove = |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1311 | new BuiltinFunction("remove") { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1312 | public Runtime.NoneType invoke(MutableList<?> self, Object x, Location loc, Environment env) |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1313 | throws EvalException { |
| 1314 | for (int i = 0; i < self.size(); i++) { |
| 1315 | if (self.get(i).equals(x)) { |
brandjon | 0528d5d | 2017-08-04 16:00:56 +0200 | [diff] [blame] | 1316 | self.remove(i, loc, env.mutability()); |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1317 | return Runtime.NONE; |
| 1318 | } |
| 1319 | } |
Laurent Le Brun | c31f351 | 2016-12-29 21:41:33 +0000 | [diff] [blame] | 1320 | throw new EvalException(loc, Printer.format("item %r not found in list", x)); |
Laurent Le Brun | 8853df9 | 2015-12-16 15:02:03 +0000 | [diff] [blame] | 1321 | } |
| 1322 | }; |
| 1323 | |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1324 | @SkylarkSignature( |
| 1325 | name = "pop", |
| 1326 | objectType = MutableList.class, |
| 1327 | returnType = Object.class, |
| 1328 | doc = |
| 1329 | "Removes the item at the given position in the list, and returns it. " |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1330 | + "If no <code>index</code> is specified, " |
| 1331 | + "it removes and returns the last item in the list.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1332 | parameters = { |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1333 | @Param(name = "self", type = MutableList.class, doc = "This list."), |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1334 | @Param( |
| 1335 | name = "i", |
| 1336 | type = Integer.class, |
| 1337 | noneable = true, |
| 1338 | defaultValue = "None", |
| 1339 | doc = "The index of the item." |
| 1340 | ) |
| 1341 | }, |
| 1342 | useLocation = true, |
| 1343 | useEnvironment = true |
| 1344 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1345 | private static final BuiltinFunction listPop = |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1346 | new BuiltinFunction("pop") { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1347 | public Object invoke(MutableList<?> self, Object i, Location loc, Environment env) |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1348 | throws EvalException { |
| 1349 | int arg = i == Runtime.NONE ? -1 : (Integer) i; |
Jon Brandvein | fab8487 | 2016-11-11 16:27:01 +0000 | [diff] [blame] | 1350 | int index = EvalUtils.getSequenceIndex(arg, self.size(), loc); |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1351 | Object result = self.get(index); |
brandjon | 0528d5d | 2017-08-04 16:00:56 +0200 | [diff] [blame] | 1352 | self.remove(index, loc, env.mutability()); |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1353 | return result; |
| 1354 | } |
| 1355 | }; |
| 1356 | |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1357 | @SkylarkSignature( |
| 1358 | name = "pop", |
| 1359 | objectType = SkylarkDict.class, |
| 1360 | returnType = Object.class, |
| 1361 | doc = |
| 1362 | "Removes a <code>key</code> from the dict, and returns the associated value. " |
| 1363 | + "If entry with that key was found, return the specified <code>default</code> value;" |
| 1364 | + "if no default value was specified, fail instead.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1365 | parameters = { |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1366 | @Param(name = "self", type = SkylarkDict.class, doc = "This dict."), |
| 1367 | @Param(name = "key", type = Object.class, doc = "The key."), |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1368 | @Param(name = "default", type = Object.class, defaultValue = "unbound", |
| 1369 | doc = "a default value if the key is absent."), |
| 1370 | }, |
| 1371 | useLocation = true, |
| 1372 | useEnvironment = true |
| 1373 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1374 | private static final BuiltinFunction dictPop = |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1375 | new BuiltinFunction("pop") { |
| 1376 | public Object invoke(SkylarkDict<Object, Object> self, Object key, Object defaultValue, |
| 1377 | Location loc, Environment env) |
| 1378 | throws EvalException { |
| 1379 | Object value = self.get(key); |
| 1380 | if (value != null) { |
brandjon | 9e65494 | 2017-08-09 23:45:50 +0200 | [diff] [blame] | 1381 | self.remove(key, loc, env.mutability()); |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1382 | return value; |
| 1383 | } |
| 1384 | if (defaultValue != Runtime.UNBOUND) { |
| 1385 | return defaultValue; |
| 1386 | } |
| 1387 | throw new EvalException(loc, Printer.format("KeyError: %r", key)); |
| 1388 | } |
| 1389 | }; |
| 1390 | |
| 1391 | @SkylarkSignature( |
| 1392 | name = "popitem", |
| 1393 | objectType = SkylarkDict.class, |
| 1394 | returnType = Tuple.class, |
| 1395 | doc = |
| 1396 | "Remove and return an arbitrary <code>(key, value)</code> pair from the dictionary. " |
| 1397 | + "<code>popitem()</code> is useful to destructively iterate over a dictionary, " |
| 1398 | + "as often used in set algorithms. " |
| 1399 | + "If the dictionary is empty, calling <code>popitem()</code> fails. " |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1400 | + "It is deterministic which pair is returned.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1401 | parameters = { |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1402 | @Param(name = "self", type = SkylarkDict.class, doc = "This dict.") |
| 1403 | }, |
| 1404 | useLocation = true, |
| 1405 | useEnvironment = true |
| 1406 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1407 | private static final BuiltinFunction dictPopItem = |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1408 | new BuiltinFunction("popitem") { |
| 1409 | public Tuple<Object> invoke(SkylarkDict<Object, Object> self, |
| 1410 | Location loc, Environment env) |
| 1411 | throws EvalException { |
| 1412 | if (self.isEmpty()) { |
| 1413 | throw new EvalException(loc, "popitem(): dictionary is empty"); |
| 1414 | } |
brandjon | 9e65494 | 2017-08-09 23:45:50 +0200 | [diff] [blame] | 1415 | Object key = self.keySet().iterator().next(); |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1416 | Object value = self.get(key); |
brandjon | 9e65494 | 2017-08-09 23:45:50 +0200 | [diff] [blame] | 1417 | self.remove(key, loc, env.mutability()); |
brandjon | c06e746 | 2017-07-11 20:54:58 +0200 | [diff] [blame] | 1418 | return Tuple.of(key, value); |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1419 | } |
| 1420 | }; |
| 1421 | |
| 1422 | @SkylarkSignature( |
| 1423 | name = "clear", |
| 1424 | objectType = SkylarkDict.class, |
| 1425 | returnType = Runtime.NoneType.class, |
| 1426 | doc = "Remove all items from the dictionary.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1427 | parameters = { |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1428 | @Param(name = "self", type = SkylarkDict.class, doc = "This dict.") |
| 1429 | }, |
| 1430 | useLocation = true, |
| 1431 | useEnvironment = true |
| 1432 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1433 | private static final BuiltinFunction dictClear = |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1434 | new BuiltinFunction("clear") { |
| 1435 | public Runtime.NoneType invoke(SkylarkDict<Object, Object> self, |
| 1436 | Location loc, Environment env) |
| 1437 | throws EvalException { |
brandjon | 9e65494 | 2017-08-09 23:45:50 +0200 | [diff] [blame] | 1438 | self.clear(loc, env.mutability()); |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1439 | return Runtime.NONE; |
| 1440 | } |
| 1441 | }; |
| 1442 | |
| 1443 | @SkylarkSignature( |
| 1444 | name = "setdefault", |
| 1445 | objectType = SkylarkDict.class, |
| 1446 | returnType = Object.class, |
| 1447 | doc = |
| 1448 | "If <code>key</code> is in the dictionary, return its value. " |
| 1449 | + "If not, insert key with a value of <code>default</code> " |
| 1450 | + "and return <code>default</code>. " |
| 1451 | + "<code>default</code> defaults to <code>None</code>.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1452 | parameters = { |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1453 | @Param(name = "self", type = SkylarkDict.class, doc = "This dict."), |
| 1454 | @Param(name = "key", type = Object.class, doc = "The key."), |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1455 | @Param( |
| 1456 | name = "default", |
| 1457 | type = Object.class, |
| 1458 | defaultValue = "None", |
| 1459 | doc = "a default value if the key is absent." |
| 1460 | ), |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1461 | }, |
| 1462 | useLocation = true, |
| 1463 | useEnvironment = true |
| 1464 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1465 | private static final BuiltinFunction dictSetDefault = |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1466 | new BuiltinFunction("setdefault") { |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1467 | public Object invoke( |
| 1468 | SkylarkDict<Object, Object> self, |
| 1469 | Object key, |
| 1470 | Object defaultValue, |
| 1471 | Location loc, |
| 1472 | Environment env) |
Francois-Rene Rideau | 432d715 | 2016-02-18 16:33:03 +0000 | [diff] [blame] | 1473 | throws EvalException { |
| 1474 | Object value = self.get(key); |
| 1475 | if (value != null) { |
| 1476 | return value; |
| 1477 | } |
| 1478 | self.put(key, defaultValue, loc, env); |
| 1479 | return defaultValue; |
| 1480 | } |
| 1481 | }; |
| 1482 | |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1483 | @SkylarkSignature( |
| 1484 | name = "update", |
| 1485 | objectType = SkylarkDict.class, |
| 1486 | returnType = Runtime.NoneType.class, |
| 1487 | doc = "Update the dictionary with the key/value pairs from other, overwriting existing keys.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1488 | parameters = { |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1489 | @Param(name = "self", type = SkylarkDict.class, doc = "This dict."), |
| 1490 | @Param(name = "other", type = SkylarkDict.class, doc = "The values to add."), |
| 1491 | }, |
| 1492 | useLocation = true, |
| 1493 | useEnvironment = true |
| 1494 | ) |
| 1495 | private static final BuiltinFunction dictUpdate = |
| 1496 | new BuiltinFunction("update") { |
| 1497 | public Runtime.NoneType invoke( |
| 1498 | SkylarkDict<Object, Object> self, |
| 1499 | SkylarkDict<Object, Object> other, |
| 1500 | Location loc, |
| 1501 | Environment env) |
| 1502 | throws EvalException { |
brandjon | 9e65494 | 2017-08-09 23:45:50 +0200 | [diff] [blame] | 1503 | self.putAll(other, loc, env.mutability()); |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1504 | return Runtime.NONE; |
| 1505 | } |
| 1506 | }; |
| 1507 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1508 | @SkylarkSignature( |
| 1509 | name = "values", |
| 1510 | objectType = SkylarkDict.class, |
| 1511 | returnType = MutableList.class, |
| 1512 | doc = |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1513 | "Returns the list of values:" |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1514 | + "<pre class=\"language-python\">" |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1515 | + "{2: \"a\", 4: \"b\", 1: \"c\"}.values() == [\"a\", \"b\", \"c\"]</pre>\n", |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1516 | parameters = {@Param(name = "self", type = SkylarkDict.class, doc = "This dict.")}, |
| 1517 | useEnvironment = true |
| 1518 | ) |
| 1519 | private static final BuiltinFunction values = |
| 1520 | new BuiltinFunction("values") { |
| 1521 | public MutableList<?> invoke(SkylarkDict<?, ?> self, Environment env) throws EvalException { |
michajlo | ff50f28 | 2017-10-05 20:02:51 +0200 | [diff] [blame] | 1522 | return MutableList.copyOf(env, self.values()); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1523 | } |
| 1524 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1525 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1526 | @SkylarkSignature( |
| 1527 | name = "items", |
| 1528 | objectType = SkylarkDict.class, |
| 1529 | returnType = MutableList.class, |
| 1530 | doc = |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1531 | "Returns the list of key-value tuples:" |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1532 | + "<pre class=\"language-python\">" |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1533 | + "{2: \"a\", 4: \"b\", 1: \"c\"}.items() == [(2, \"a\"), (4, \"b\"), (1, \"c\")]" |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1534 | + "</pre>\n", |
| 1535 | parameters = {@Param(name = "self", type = SkylarkDict.class, doc = "This dict.")}, |
| 1536 | useEnvironment = true |
| 1537 | ) |
| 1538 | private static final BuiltinFunction items = |
| 1539 | new BuiltinFunction("items") { |
| 1540 | public MutableList<?> invoke(SkylarkDict<?, ?> self, Environment env) throws EvalException { |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1541 | ArrayList<Object> list = Lists.newArrayListWithCapacity(self.size()); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1542 | for (Map.Entry<?, ?> entries : self.entrySet()) { |
| 1543 | list.add(Tuple.of(entries.getKey(), entries.getValue())); |
| 1544 | } |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1545 | return MutableList.wrapUnsafe(env, list); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1546 | } |
| 1547 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1548 | |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1549 | @SkylarkSignature(name = "keys", objectType = SkylarkDict.class, |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 1550 | returnType = MutableList.class, |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1551 | doc = "Returns the list of keys:" |
| 1552 | + "<pre class=\"language-python\">{2: \"a\", 4: \"b\", 1: \"c\"}.keys() == [2, 4, 1]" |
Francois-Rene Rideau | a3ac202 | 2015-04-20 18:35:05 +0000 | [diff] [blame] | 1553 | + "</pre>\n", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1554 | parameters = { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1555 | @Param(name = "self", type = SkylarkDict.class, doc = "This dict.")}, |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 1556 | useEnvironment = true) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1557 | private static final BuiltinFunction keys = new BuiltinFunction("keys") { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1558 | // Skylark will only call this on a dict; and |
| 1559 | // allowed keys are all Comparable... if not mutually, it's OK to get a runtime exception. |
| 1560 | @SuppressWarnings("unchecked") |
| 1561 | public MutableList<?> invoke(SkylarkDict<?, ?> self, |
Francois-Rene Rideau | 93ed7f1 | 2015-10-20 15:39:33 +0000 | [diff] [blame] | 1562 | Environment env) throws EvalException { |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1563 | ArrayList<Object> list = Lists.newArrayListWithCapacity(self.size()); |
Vladimir Moskva | 76e31d1 | 2016-12-05 16:28:37 +0000 | [diff] [blame] | 1564 | for (Map.Entry<?, ?> entries : self.entrySet()) { |
| 1565 | list.add(entries.getKey()); |
| 1566 | } |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1567 | return MutableList.wrapUnsafe(env, list); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1568 | } |
| 1569 | }; |
| 1570 | |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1571 | @SkylarkSignature( |
| 1572 | name = "tuple", |
| 1573 | returnType = Tuple.class, |
| 1574 | doc = |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1575 | "Converts a collection (e.g. list, tuple or dictionary) to a tuple." |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1576 | + "<pre class=\"language-python\">tuple([1, 2]) == (1, 2)\n" |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1577 | + "tuple((2, 3, 2)) == (2, 3, 2)\n" |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1578 | + "tuple({5: \"a\", 2: \"b\", 4: \"c\"}) == (5, 2, 4)</pre>", |
| 1579 | parameters = {@Param(name = "x", doc = "The object to convert.")}, |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1580 | useLocation = true, |
| 1581 | useEnvironment = true |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1582 | ) |
| 1583 | private static final BuiltinFunction tuple = |
| 1584 | new BuiltinFunction("tuple") { |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 1585 | public Tuple<?> invoke(Object x, Location loc, Environment env) throws EvalException { |
brandjon | 0528d5d | 2017-08-04 16:00:56 +0200 | [diff] [blame] | 1586 | return Tuple.copyOf(EvalUtils.toCollection(x, loc, env)); |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1587 | } |
| 1588 | }; |
| 1589 | |
| 1590 | @SkylarkSignature( |
| 1591 | name = "list", |
| 1592 | returnType = MutableList.class, |
| 1593 | doc = |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1594 | "Converts a collection (e.g. list, tuple or dictionary) to a list." |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1595 | + "<pre class=\"language-python\">list([1, 2]) == [1, 2]\n" |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1596 | + "list((2, 3, 2)) == [2, 3, 2]\n" |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1597 | + "list({5: \"a\", 2: \"b\", 4: \"c\"}) == [5, 2, 4]</pre>", |
| 1598 | parameters = {@Param(name = "x", doc = "The object to convert.")}, |
| 1599 | useLocation = true, |
| 1600 | useEnvironment = true |
| 1601 | ) |
| 1602 | private static final BuiltinFunction list = |
| 1603 | new BuiltinFunction("list") { |
| 1604 | public MutableList<?> invoke(Object x, Location loc, Environment env) throws EvalException { |
michajlo | ff50f28 | 2017-10-05 20:02:51 +0200 | [diff] [blame] | 1605 | return MutableList.copyOf(env, EvalUtils.toCollection(x, loc, env)); |
Googler | de68913 | 2016-12-12 18:15:52 +0000 | [diff] [blame] | 1606 | } |
| 1607 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1608 | |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1609 | @SkylarkSignature( |
| 1610 | name = "len", |
| 1611 | returnType = Integer.class, |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1612 | doc = "Returns the length of a string, list, tuple, depset, or dictionary.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1613 | parameters = {@Param(name = "x", doc = "The object to check length of.")}, |
laurentlb | c32efc8 | 2017-06-23 16:03:00 +0200 | [diff] [blame] | 1614 | useLocation = true, |
| 1615 | useEnvironment = true |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1616 | ) |
Laurent Le Brun | b525bee | 2016-03-07 17:14:10 +0000 | [diff] [blame] | 1617 | private static final BuiltinFunction len = |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1618 | new BuiltinFunction("len") { |
laurentlb | c32efc8 | 2017-06-23 16:03:00 +0200 | [diff] [blame] | 1619 | public Integer invoke(Object x, Location loc, Environment env) throws EvalException { |
brandjon | 3c16191 | 2017-10-05 05:06:05 +0200 | [diff] [blame] | 1620 | if (env.getSemantics().incompatibleDepsetIsNotIterable() |
| 1621 | && x instanceof SkylarkNestedSet) { |
laurentlb | c32efc8 | 2017-06-23 16:03:00 +0200 | [diff] [blame] | 1622 | throw new EvalException( |
| 1623 | loc, |
| 1624 | EvalUtils.getDataTypeName(x) |
brandjon | f5b8d6f | 2017-06-23 18:03:28 +0200 | [diff] [blame] | 1625 | + " is not iterable. You may use `len(<depset>.to_list())` instead. Use " |
| 1626 | + "--incompatible_depset_is_not_iterable=false to temporarily disable this " |
| 1627 | + "check."); |
laurentlb | c32efc8 | 2017-06-23 16:03:00 +0200 | [diff] [blame] | 1628 | } |
Laurent Le Brun | 3a83747 | 2015-12-22 17:58:40 +0000 | [diff] [blame] | 1629 | int l = EvalUtils.size(x); |
| 1630 | if (l == -1) { |
| 1631 | throw new EvalException(loc, EvalUtils.getDataTypeName(x) + " is not iterable"); |
| 1632 | } |
| 1633 | return l; |
| 1634 | } |
| 1635 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1636 | |
vladmos | 4690793 | 2017-06-30 14:01:45 +0200 | [diff] [blame] | 1637 | @SkylarkSignature( |
| 1638 | name = "str", |
| 1639 | returnType = String.class, |
| 1640 | doc = |
| 1641 | "Converts any object to string. This is useful for debugging." |
laurentlb | ca92903 | 2017-08-03 12:20:46 +0200 | [diff] [blame] | 1642 | + "<pre class=\"language-python\">str(\"ab\") == \"ab\"\n" |
| 1643 | + "str(8) == \"8\"</pre>", |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 1644 | parameters = {@Param(name = "x", doc = "The object to convert.")} |
vladmos | 4690793 | 2017-06-30 14:01:45 +0200 | [diff] [blame] | 1645 | ) |
| 1646 | private static final BuiltinFunction str = |
| 1647 | new BuiltinFunction("str") { |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 1648 | public String invoke(Object x) { |
| 1649 | return Printer.str(x); |
vladmos | 4690793 | 2017-06-30 14:01:45 +0200 | [diff] [blame] | 1650 | } |
| 1651 | }; |
Francois-Rene Rideau | d61f531 | 2015-06-13 03:34:47 +0000 | [diff] [blame] | 1652 | |
vladmos | 4690793 | 2017-06-30 14:01:45 +0200 | [diff] [blame] | 1653 | @SkylarkSignature( |
| 1654 | name = "repr", |
| 1655 | returnType = String.class, |
| 1656 | doc = |
| 1657 | "Converts any object to a string representation. This is useful for debugging.<br>" |
laurentlb | ca92903 | 2017-08-03 12:20:46 +0200 | [diff] [blame] | 1658 | + "<pre class=\"language-python\">repr(\"ab\") == '\"ab\"'</pre>", |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 1659 | parameters = {@Param(name = "x", doc = "The object to convert.")} |
vladmos | 4690793 | 2017-06-30 14:01:45 +0200 | [diff] [blame] | 1660 | ) |
| 1661 | private static final BuiltinFunction repr = |
| 1662 | new BuiltinFunction("repr") { |
vladmos | cd6d8ae | 2017-10-12 15:35:17 +0200 | [diff] [blame] | 1663 | public String invoke(Object x) { |
| 1664 | return Printer.repr(x); |
vladmos | 4690793 | 2017-06-30 14:01:45 +0200 | [diff] [blame] | 1665 | } |
| 1666 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1667 | |
laurentlb | 1059104 | 2017-07-20 18:16:18 +0200 | [diff] [blame] | 1668 | @SkylarkSignature( |
| 1669 | name = "bool", |
| 1670 | returnType = Boolean.class, |
| 1671 | doc = |
| 1672 | "Constructor for the bool type. " |
| 1673 | + "It returns <code>False</code> if the object is <code>None</code>, <code>False" |
| 1674 | + "</code>, an empty string (<code>\"\"</code>), the number <code>0</code>, or an " |
| 1675 | + "empty collection (e.g. <code>()</code>, <code>[]</code>). " |
| 1676 | + "Otherwise, it returns <code>True</code>.", |
| 1677 | parameters = {@Param(name = "x", doc = "The variable to convert.")} |
| 1678 | ) |
| 1679 | private static final BuiltinFunction bool = |
| 1680 | new BuiltinFunction("bool") { |
| 1681 | public Boolean invoke(Object x) throws EvalException { |
| 1682 | return EvalUtils.toBoolean(x); |
| 1683 | } |
| 1684 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1685 | |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1686 | @SkylarkSignature( |
| 1687 | name = "int", |
| 1688 | returnType = Integer.class, |
| 1689 | doc = |
| 1690 | "Converts a value to int. " |
| 1691 | + "If the argument is a string, it is converted using the given base and raises an " |
| 1692 | + "error if the conversion fails. " |
| 1693 | + "The base can be between 2 and 36 (inclusive) and defaults to 10. " |
| 1694 | + "The value can be prefixed with 0b/0o/ox to represent values in base 2/8/16. " |
| 1695 | + "If such a prefix is present, a base of 0 can be used to automatically determine the " |
| 1696 | + "correct base: " |
| 1697 | + "<pre class=\"language-python\">int(\"0xFF\", 0) == int(\"0xFF\", 16) == 255</pre>" |
| 1698 | + "If the argument is a bool, it returns 0 (False) or 1 (True). " |
| 1699 | + "If the argument is an int, it is simply returned." |
| 1700 | + "<pre class=\"language-python\">int(\"123\") == 123</pre>", |
| 1701 | parameters = { |
| 1702 | @Param(name = "x", type = Object.class, doc = "The string to convert."), |
| 1703 | @Param( |
| 1704 | name = "base", |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1705 | type = Object.class, |
| 1706 | defaultValue = "unbound", |
| 1707 | doc = "The base to use to interpret a string value; defaults to 10. This parameter must " |
| 1708 | + "not be supplied if the value is not a string." |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1709 | ) |
| 1710 | }, |
| 1711 | useLocation = true |
| 1712 | ) |
| 1713 | private static final BuiltinFunction int_ = |
| 1714 | new BuiltinFunction("int") { |
| 1715 | private final ImmutableMap<String, Integer> intPrefixes = |
| 1716 | ImmutableMap.of("0b", 2, "0o", 8, "0x", 16); |
| 1717 | |
| 1718 | @SuppressWarnings("unused") |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1719 | public Integer invoke(Object x, Object base, Location loc) throws EvalException { |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1720 | if (x instanceof String) { |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1721 | if (base == Runtime.UNBOUND) { |
| 1722 | base = 10; |
| 1723 | } else if (!(base instanceof Integer)) { |
| 1724 | throw new EvalException( |
| 1725 | loc, "base must be an integer (got '" + EvalUtils.getDataTypeName(base) + "')"); |
| 1726 | } |
| 1727 | return fromString((String) x, loc, (Integer) base); |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1728 | } else { |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1729 | if (base != Runtime.UNBOUND) { |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1730 | throw new EvalException(loc, "int() can't convert non-string with explicit base"); |
| 1731 | } |
| 1732 | if (x instanceof Boolean) { |
| 1733 | return ((Boolean) x).booleanValue() ? 1 : 0; |
| 1734 | } else if (x instanceof Integer) { |
| 1735 | return (Integer) x; |
| 1736 | } |
| 1737 | throw new EvalException( |
| 1738 | loc, Printer.format("%r is not of type string or int or bool", x)); |
| 1739 | } |
Laurent Le Brun | f4648de | 2015-05-07 14:00:32 +0000 | [diff] [blame] | 1740 | } |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1741 | |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1742 | private int fromString(String string, Location loc, int base) throws EvalException { |
| 1743 | String prefix = getIntegerPrefix(string); |
| 1744 | String digits; |
| 1745 | if (prefix == null) { |
| 1746 | // Nothing to strip. Infer base 10 if it was unknown (0). |
| 1747 | digits = string; |
| 1748 | if (base == 0) { |
| 1749 | base = 10; |
| 1750 | } |
| 1751 | } else { |
| 1752 | // Strip prefix. Infer base from prefix if unknown (0), or else verify its consistency. |
| 1753 | digits = string.substring(prefix.length()); |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1754 | int expectedBase = intPrefixes.get(prefix); |
| 1755 | if (base == 0) { |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1756 | base = expectedBase; |
| 1757 | } else if (base != expectedBase) { |
| 1758 | throw new EvalException( |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1759 | loc, Printer.format("invalid literal for int() with base %d: %r", base, string)); |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1760 | } |
| 1761 | } |
| 1762 | |
| 1763 | if (base < 2 || base > 36) { |
| 1764 | throw new EvalException(loc, "int() base must be >= 2 and <= 36"); |
| 1765 | } |
| 1766 | try { |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1767 | return Integer.parseInt(digits, base); |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1768 | } catch (NumberFormatException e) { |
| 1769 | throw new EvalException( |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1770 | loc, Printer.format("invalid literal for int() with base %d: %r", base, string)); |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1771 | } |
| 1772 | } |
| 1773 | |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1774 | @Nullable |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1775 | private String getIntegerPrefix(String value) { |
| 1776 | value = value.toLowerCase(); |
| 1777 | for (String prefix : intPrefixes.keySet()) { |
| 1778 | if (value.startsWith(prefix)) { |
| 1779 | return prefix; |
| 1780 | } |
| 1781 | } |
brandjon | 12b2379 | 2017-09-05 21:39:37 +0200 | [diff] [blame] | 1782 | return null; |
Florian Weikert | bc1ff69 | 2016-07-01 19:11:24 +0000 | [diff] [blame] | 1783 | } |
| 1784 | }; |
Laurent Le Brun | 0c44aa4 | 2015-04-02 11:32:47 +0000 | [diff] [blame] | 1785 | |
Laurent Le Brun | c2fca38 | 2015-10-16 11:46:43 +0000 | [diff] [blame] | 1786 | @SkylarkSignature( |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1787 | name = "dict", |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1788 | returnType = SkylarkDict.class, |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1789 | doc = |
Jon Brandvein | d9d20f7 | 2017-01-27 15:20:23 +0000 | [diff] [blame] | 1790 | "Creates a <a href=\"dict.html\">dictionary</a> from an optional positional " |
Jon Brandvein | df6bbec | 2017-01-28 02:20:31 +0000 | [diff] [blame] | 1791 | + "argument and an optional set of keyword arguments. In the case where the same key " |
| 1792 | + "is given multiple times, the last value will be used. Entries supplied via keyword " |
| 1793 | + "arguments are considered to come after entries supplied via the positional " |
| 1794 | + "argument. Note that the iteration order for dictionaries is deterministic but " |
| 1795 | + "unspecified, and not necessarily related to the order in which keys are given to " |
| 1796 | + "this function.", |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 1797 | parameters = { |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1798 | @Param( |
| 1799 | name = "args", |
| 1800 | type = Object.class, |
| 1801 | defaultValue = "[]", |
| 1802 | doc = |
| 1803 | "Either a dictionary or a list of entries. Entries must be tuples or lists with " |
Jon Brandvein | df6bbec | 2017-01-28 02:20:31 +0000 | [diff] [blame] | 1804 | + "exactly two elements: key, value." |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1805 | ), |
| 1806 | }, |
Damien Martin-Guillerez | e3108c5 | 2016-06-08 08:54:45 +0000 | [diff] [blame] | 1807 | extraKeywords = @Param(name = "kwargs", doc = "Dictionary of additional entries."), |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1808 | useLocation = true, |
| 1809 | useEnvironment = true |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1810 | ) |
| 1811 | private static final BuiltinFunction dict = |
| 1812 | new BuiltinFunction("dict") { |
brandjon | c06e746 | 2017-07-11 20:54:58 +0200 | [diff] [blame] | 1813 | public SkylarkDict<?, ?> invoke( |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1814 | Object args, SkylarkDict<String, Object> kwargs, Location loc, Environment env) |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1815 | throws EvalException { |
brandjon | c06e746 | 2017-07-11 20:54:58 +0200 | [diff] [blame] | 1816 | SkylarkDict<?, ?> argsDict = |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1817 | (args instanceof SkylarkDict) |
brandjon | c06e746 | 2017-07-11 20:54:58 +0200 | [diff] [blame] | 1818 | ? (SkylarkDict<?, ?>) args |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1819 | : getDictFromArgs(args, loc, env); |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1820 | return SkylarkDict.plus(argsDict, kwargs, env); |
Florian Weikert | a6dae6b | 2015-08-04 20:17:23 +0000 | [diff] [blame] | 1821 | } |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1822 | |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1823 | private SkylarkDict<Object, Object> getDictFromArgs( |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1824 | Object args, Location loc, Environment env) throws EvalException { |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1825 | SkylarkDict<Object, Object> result = SkylarkDict.of(env); |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1826 | int pos = 0; |
| 1827 | for (Object element : Type.OBJECT_LIST.convert(args, "parameter args in dict()")) { |
| 1828 | List<Object> pair = convertToPair(element, pos, loc); |
Francois-Rene Rideau | ab049e0 | 2016-02-17 16:13:46 +0000 | [diff] [blame] | 1829 | result.put(pair.get(0), pair.get(1), loc, env); |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1830 | ++pos; |
| 1831 | } |
| 1832 | return result; |
| 1833 | } |
| 1834 | |
| 1835 | private List<Object> convertToPair(Object element, int pos, Location loc) |
| 1836 | throws EvalException { |
| 1837 | try { |
| 1838 | List<Object> tuple = Type.OBJECT_LIST.convert(element, ""); |
| 1839 | int numElements = tuple.size(); |
| 1840 | if (numElements != 2) { |
| 1841 | throw new EvalException( |
| 1842 | location, |
| 1843 | String.format( |
Laurent Le Brun | c31f351 | 2016-12-29 21:41:33 +0000 | [diff] [blame] | 1844 | "item #%d has length %d, but exactly two elements are required", |
Vladimir Moskva | d200daf | 2016-12-23 16:35:37 +0000 | [diff] [blame] | 1845 | pos, numElements)); |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1846 | } |
| 1847 | return tuple; |
| 1848 | } catch (ConversionException e) { |
| 1849 | throw new EvalException( |
Laurent Le Brun | c31f351 | 2016-12-29 21:41:33 +0000 | [diff] [blame] | 1850 | loc, String.format("cannot convert item #%d to a sequence", pos)); |
Dmitry Lomov | 8b1a094 | 2015-11-19 15:14:15 +0000 | [diff] [blame] | 1851 | } |
| 1852 | } |
| 1853 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1854 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1855 | @SkylarkSignature( |
| 1856 | name = "enumerate", |
| 1857 | returnType = MutableList.class, |
| 1858 | doc = |
| 1859 | "Returns a list of pairs (two-element tuples), with the index (int) and the item from" |
| 1860 | + " the input list.\n<pre class=\"language-python\">" |
| 1861 | + "enumerate([24, 21, 84]) == [(0, 24), (1, 21), (2, 84)]</pre>\n", |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 1862 | parameters = {@Param(name = "list", type = SkylarkList.class, doc = "input list.")}, |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1863 | useEnvironment = true |
| 1864 | ) |
| 1865 | private static final BuiltinFunction enumerate = |
| 1866 | new BuiltinFunction("enumerate") { |
| 1867 | public MutableList<?> invoke(SkylarkList<?> input, Environment env) throws EvalException { |
| 1868 | int count = 0; |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1869 | ArrayList<SkylarkList<?>> result = new ArrayList<>(input.size()); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1870 | for (Object obj : input) { |
| 1871 | result.add(Tuple.of(count, obj)); |
| 1872 | count++; |
| 1873 | } |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1874 | return MutableList.wrapUnsafe(env, result); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1875 | } |
| 1876 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1877 | |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 1878 | @SkylarkSignature( |
| 1879 | name = "hash", |
| 1880 | returnType = Integer.class, |
| 1881 | doc = |
| 1882 | "Return a hash value for a string. This is computed deterministically using the same " |
| 1883 | + "algorithm as Java's <code>String.hashCode()</code>, namely: " |
Chaoren Lin | 905914e | 2017-02-06 19:18:44 +0000 | [diff] [blame] | 1884 | + "<pre class=\"language-python\">s[0] * (31^(n-1)) + s[1] * (31^(n-2)) + ... + s[n-1]" |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 1885 | + "</pre> Hashing of values besides strings is not currently supported.", |
| 1886 | // Deterministic hashing is important for the consistency of builds, hence why we |
| 1887 | // promise a specific algorithm. This is in contrast to Java (Object.hashCode()) and |
| 1888 | // Python, which promise stable hashing only within a given execution of the program. |
| 1889 | parameters = {@Param(name = "value", type = String.class, doc = "String value to hash.")} |
| 1890 | ) |
| 1891 | private static final BuiltinFunction hash = |
| 1892 | new BuiltinFunction("hash") { |
| 1893 | public Integer invoke(String value) throws EvalException { |
| 1894 | return value.hashCode(); |
| 1895 | } |
| 1896 | }; |
Jon Brandvein | 9c4629d | 2016-07-20 20:16:33 +0000 | [diff] [blame] | 1897 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1898 | @SkylarkSignature( |
| 1899 | name = "range", |
| 1900 | returnType = MutableList.class, |
| 1901 | doc = |
| 1902 | "Creates a list where items go from <code>start</code> to <code>stop</code>, using a " |
| 1903 | + "<code>step</code> increment. If a single argument is provided, items will " |
| 1904 | + "range from 0 to that element." |
| 1905 | + "<pre class=\"language-python\">range(4) == [0, 1, 2, 3]\n" |
| 1906 | + "range(3, 9, 2) == [3, 5, 7]\n" |
| 1907 | + "range(3, 0, -1) == [3, 2, 1]</pre>", |
| 1908 | parameters = { |
| 1909 | @Param( |
| 1910 | name = "start_or_stop", |
| 1911 | type = Integer.class, |
| 1912 | doc = |
| 1913 | "Value of the start element if stop is provided, " |
| 1914 | + "otherwise value of stop and the actual start is 0" |
| 1915 | ), |
| 1916 | @Param( |
| 1917 | name = "stop_or_none", |
| 1918 | type = Integer.class, |
| 1919 | noneable = true, |
| 1920 | defaultValue = "None", |
| 1921 | doc = |
| 1922 | "optional index of the first item <i>not</i> to be included in the resulting " |
| 1923 | + "list; generation of the list stops before <code>stop</code> is reached." |
| 1924 | ), |
| 1925 | @Param( |
| 1926 | name = "step", |
| 1927 | type = Integer.class, |
| 1928 | defaultValue = "1", |
| 1929 | doc = "The increment (default is 1). It may be negative." |
| 1930 | ) |
| 1931 | }, |
| 1932 | useLocation = true, |
| 1933 | useEnvironment = true |
| 1934 | ) |
| 1935 | private static final BuiltinFunction range = |
| 1936 | new BuiltinFunction("range") { |
| 1937 | public MutableList<?> invoke( |
| 1938 | Integer startOrStop, Object stopOrNone, Integer step, Location loc, Environment env) |
| 1939 | throws EvalException { |
| 1940 | int start; |
| 1941 | int stop; |
| 1942 | if (stopOrNone == Runtime.NONE) { |
| 1943 | start = 0; |
| 1944 | stop = startOrStop; |
| 1945 | } else { |
| 1946 | start = startOrStop; |
| 1947 | stop = Type.INTEGER.convert(stopOrNone, "'stop' operand of 'range'"); |
| 1948 | } |
| 1949 | if (step == 0) { |
| 1950 | throw new EvalException(loc, "step cannot be 0"); |
| 1951 | } |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1952 | ArrayList<Integer> result = new ArrayList<>(Math.abs((stop - start) / step)); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1953 | if (step > 0) { |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1954 | while (start < stop) { |
| 1955 | result.add(start); |
| 1956 | start += step; |
| 1957 | } |
| 1958 | } else { |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1959 | while (start > stop) { |
| 1960 | result.add(start); |
| 1961 | start += step; |
| 1962 | } |
| 1963 | } |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 1964 | return MutableList.wrapUnsafe(env, result); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1965 | } |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1966 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1967 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1968 | /** Returns true if the object has a field of the given name, otherwise false. */ |
| 1969 | @SkylarkSignature( |
| 1970 | name = "hasattr", |
| 1971 | returnType = Boolean.class, |
| 1972 | doc = |
| 1973 | "Returns True if the object <code>x</code> has an attribute or method of the given " |
| 1974 | + "<code>name</code>, otherwise False. Example:<br>" |
| 1975 | + "<pre class=\"language-python\">hasattr(ctx.attr, \"myattr\")</pre>", |
| 1976 | parameters = { |
| 1977 | @Param(name = "x", doc = "The object to check."), |
| 1978 | @Param(name = "name", type = String.class, doc = "The name of the attribute.") |
| 1979 | }, |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1980 | useEnvironment = true |
| 1981 | ) |
| 1982 | private static final BuiltinFunction hasattr = |
| 1983 | new BuiltinFunction("hasattr") { |
| 1984 | @SuppressWarnings("unused") |
Jon Brandvein | d9d20f7 | 2017-01-27 15:20:23 +0000 | [diff] [blame] | 1985 | public Boolean invoke(Object obj, String name, Environment env) |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1986 | throws EvalException { |
| 1987 | if (obj instanceof ClassObject && ((ClassObject) obj).getValue(name) != null) { |
| 1988 | return true; |
| 1989 | } |
Jon Brandvein | d9d20f7 | 2017-01-27 15:20:23 +0000 | [diff] [blame] | 1990 | return hasMethod(obj, name); |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 1991 | } |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 1992 | }; |
| 1993 | |
| 1994 | @SkylarkSignature( |
| 1995 | name = "getattr", |
| 1996 | doc = |
| 1997 | "Returns the struct's field of the given name if it exists. If not, it either returns " |
Jon Brandvein | 29bb662 | 2016-10-27 13:55:43 +0000 | [diff] [blame] | 1998 | + "<code>default</code> (if specified) or raises an error. Built-in methods cannot " |
| 1999 | + "currently be retrieved in this way; doing so will result in an error if a " |
| 2000 | + "<code>default</code> is not given. <code>getattr(x, \"foobar\")</code> is " |
| 2001 | + "equivalent to <code>x.foobar</code>." |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2002 | + "<pre class=\"language-python\">getattr(ctx.attr, \"myattr\")\n" |
| 2003 | + "getattr(ctx.attr, \"myattr\", \"mydefault\")</pre>", |
| 2004 | parameters = { |
| 2005 | @Param(name = "x", doc = "The struct whose attribute is accessed."), |
| 2006 | @Param(name = "name", doc = "The name of the struct attribute."), |
| 2007 | @Param( |
| 2008 | name = "default", |
| 2009 | defaultValue = "unbound", |
| 2010 | doc = |
| 2011 | "The default value to return in case the struct " |
| 2012 | + "doesn't have an attribute of the given name." |
| 2013 | ) |
| 2014 | }, |
| 2015 | useLocation = true, |
| 2016 | useEnvironment = true |
| 2017 | ) |
| 2018 | private static final BuiltinFunction getattr = |
| 2019 | new BuiltinFunction("getattr") { |
| 2020 | @SuppressWarnings("unused") |
| 2021 | public Object invoke( |
| 2022 | Object obj, String name, Object defaultValue, Location loc, Environment env) |
| 2023 | throws EvalException { |
| 2024 | Object result = DotExpression.eval(obj, name, loc, env); |
| 2025 | if (result == null) { |
| 2026 | // 'Real' describes methods with structField() == false. Because DotExpression.eval |
| 2027 | // returned null in this case, we know that structField() cannot return true. |
Jon Brandvein | d9d20f7 | 2017-01-27 15:20:23 +0000 | [diff] [blame] | 2028 | boolean isRealMethod = hasMethod(obj, name); |
Jon Brandvein | 29bb662 | 2016-10-27 13:55:43 +0000 | [diff] [blame] | 2029 | if (defaultValue != Runtime.UNBOUND) { |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2030 | return defaultValue; |
| 2031 | } |
| 2032 | throw new EvalException( |
| 2033 | loc, |
| 2034 | Printer.format( |
Laurent Le Brun | c31f351 | 2016-12-29 21:41:33 +0000 | [diff] [blame] | 2035 | "object of type '%s' has no attribute %r%s", |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2036 | EvalUtils.getDataTypeName(obj), |
| 2037 | name, |
| 2038 | isRealMethod ? ", however, a method of that name exists" : "")); |
| 2039 | } |
| 2040 | return result; |
| 2041 | } |
| 2042 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2043 | |
Florian Weikert | e5e3e91 | 2016-03-08 03:08:26 +0000 | [diff] [blame] | 2044 | /** |
| 2045 | * Returns whether the given object has a method with the given name. |
| 2046 | */ |
Jon Brandvein | d9d20f7 | 2017-01-27 15:20:23 +0000 | [diff] [blame] | 2047 | private static boolean hasMethod(Object obj, String name) throws EvalException { |
brandjon | dc2c550 | 2017-12-07 14:30:04 -0800 | [diff] [blame] | 2048 | if (Runtime.getBuiltinRegistry().getFunctionNames(obj.getClass()).contains(name)) { |
Florian Weikert | e5e3e91 | 2016-03-08 03:08:26 +0000 | [diff] [blame] | 2049 | return true; |
| 2050 | } |
| 2051 | |
Laurent Le Brun | 57badf4 | 2017-01-02 15:12:24 +0000 | [diff] [blame] | 2052 | return FuncallExpression.getMethodNames(obj.getClass()).contains(name); |
Florian Weikert | e5e3e91 | 2016-03-08 03:08:26 +0000 | [diff] [blame] | 2053 | } |
| 2054 | |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2055 | @SkylarkSignature( |
| 2056 | name = "dir", |
| 2057 | returnType = MutableList.class, |
| 2058 | doc = |
vladmos | 6547bde | 2017-04-25 23:07:04 +0200 | [diff] [blame] | 2059 | "Returns a list of strings: the names of the attributes and " |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2060 | + "methods of the parameter object.", |
| 2061 | parameters = {@Param(name = "x", doc = "The object to check.")}, |
| 2062 | useLocation = true, |
| 2063 | useEnvironment = true |
| 2064 | ) |
| 2065 | private static final BuiltinFunction dir = |
| 2066 | new BuiltinFunction("dir") { |
| 2067 | public MutableList<?> invoke(Object object, Location loc, Environment env) |
| 2068 | throws EvalException { |
| 2069 | // Order the fields alphabetically. |
| 2070 | Set<String> fields = new TreeSet<>(); |
| 2071 | if (object instanceof ClassObject) { |
brandjon | d331fa7 | 2017-12-28 07:38:31 -0800 | [diff] [blame] | 2072 | fields.addAll(((ClassObject) object).getFieldNames()); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2073 | } |
brandjon | dc2c550 | 2017-12-07 14:30:04 -0800 | [diff] [blame] | 2074 | fields.addAll(Runtime.getBuiltinRegistry().getFunctionNames(object.getClass())); |
Laurent Le Brun | 57badf4 | 2017-01-02 15:12:24 +0000 | [diff] [blame] | 2075 | fields.addAll(FuncallExpression.getMethodNames(object.getClass())); |
michajlo | ff50f28 | 2017-10-05 20:02:51 +0200 | [diff] [blame] | 2076 | return MutableList.copyOf(env, fields); |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2077 | } |
| 2078 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2079 | |
Laurent Le Brun | f9c4102 | 2016-06-23 16:05:50 +0000 | [diff] [blame] | 2080 | @SkylarkSignature( |
Laurent Le Brun | fe206a4 | 2016-05-23 17:03:49 +0000 | [diff] [blame] | 2081 | name = "fail", |
| 2082 | doc = |
| 2083 | "Raises an error that cannot be intercepted. It can be used anywhere, " |
| 2084 | + "both in the loading phase and in the analysis phase.", |
| 2085 | returnType = Runtime.NoneType.class, |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 2086 | parameters = { |
Laurent Le Brun | fe206a4 | 2016-05-23 17:03:49 +0000 | [diff] [blame] | 2087 | @Param( |
| 2088 | name = "msg", |
| 2089 | type = Object.class, |
| 2090 | doc = "Error to display for the user. The object is converted to a string." |
Damien Martin-Guillerez | 014388c | 2016-06-14 10:28:31 +0000 | [diff] [blame] | 2091 | ), |
Laurent Le Brun | fe206a4 | 2016-05-23 17:03:49 +0000 | [diff] [blame] | 2092 | @Param( |
| 2093 | name = "attr", |
| 2094 | type = String.class, |
| 2095 | noneable = true, |
| 2096 | defaultValue = "None", |
| 2097 | doc = |
| 2098 | "The name of the attribute that caused the error. This is used only for " |
| 2099 | + "error reporting." |
| 2100 | ) |
| 2101 | }, |
| 2102 | useLocation = true |
| 2103 | ) |
| 2104 | private static final BuiltinFunction fail = |
| 2105 | new BuiltinFunction("fail") { |
Laurent Le Brun | e51a4d2 | 2016-10-11 18:04:16 +0000 | [diff] [blame] | 2106 | public Runtime.NoneType invoke(Object msg, Object attr, Location loc) throws EvalException { |
Laurent Le Brun | fe206a4 | 2016-05-23 17:03:49 +0000 | [diff] [blame] | 2107 | String str = Printer.str(msg); |
| 2108 | if (attr != Runtime.NONE) { |
| 2109 | str = String.format("attribute %s: %s", attr, str); |
| 2110 | } |
| 2111 | throw new EvalException(loc, str); |
| 2112 | } |
| 2113 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2114 | |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2115 | @SkylarkSignature( |
| 2116 | name = "print", |
| 2117 | returnType = Runtime.NoneType.class, |
| 2118 | doc = |
cparsons | 7ec3f21 | 2018-02-16 14:21:10 -0800 | [diff] [blame] | 2119 | "Prints <code>args</code> as debug output. It will be prefixed with the string <code>" |
| 2120 | + "\"DEBUG\"</code> and the location (file and line number) of this call. The " |
| 2121 | + "exact way in which the arguments are converted to strings is unspecified and may " |
| 2122 | + "change at any time. In particular, it may be different from (and more detailed " |
| 2123 | + "than) the formatting done by <a href='#str'><code>str()</code></a> and <a " |
| 2124 | + "href='#repr'><code>repr()</code></a>." |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2125 | + "<p>Using <code>print</code> in production code is discouraged due to the spam it " |
| 2126 | + "creates for users. For deprecations, prefer a hard error using <a href=\"#fail\">" |
cparsons | 7ec3f21 | 2018-02-16 14:21:10 -0800 | [diff] [blame] | 2127 | + "<code>fail()</code></a> whenever possible.", |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2128 | parameters = { |
| 2129 | @Param( |
| 2130 | name = "sep", |
| 2131 | type = String.class, |
laurentlb | d1e564b | 2017-07-19 21:18:24 +0200 | [diff] [blame] | 2132 | defaultValue = "\" \"", |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2133 | named = true, |
| 2134 | positional = false, |
| 2135 | doc = "The separator string between the objects, default is space (\" \")." |
| 2136 | ) |
| 2137 | }, |
| 2138 | // NB: as compared to Python3, we're missing optional named-only arguments 'end' and 'file' |
| 2139 | extraPositionals = @Param(name = "args", doc = "The objects to print."), |
| 2140 | useLocation = true, |
| 2141 | useEnvironment = true |
| 2142 | ) |
| 2143 | private static final BuiltinFunction print = |
| 2144 | new BuiltinFunction("print") { |
| 2145 | public Runtime.NoneType invoke( |
| 2146 | String sep, SkylarkList<?> starargs, Location loc, Environment env) |
| 2147 | throws EvalException { |
cparsons | 7ec3f21 | 2018-02-16 14:21:10 -0800 | [diff] [blame] | 2148 | String msg = starargs.stream().map(Printer::debugPrint).collect(joining(sep)); |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2149 | // As part of the integration test "skylark_flag_test.sh", if the |
| 2150 | // "--internal_skylark_flag_test_canary" flag is enabled, append an extra marker string to |
vladmos | 6ff634d | 2017-07-05 10:25:01 -0400 | [diff] [blame] | 2151 | // the output. |
brandjon | 3c16191 | 2017-10-05 05:06:05 +0200 | [diff] [blame] | 2152 | if (env.getSemantics().internalSkylarkFlagTestCanary()) { |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2153 | msg += "<== skylark flag test ==>"; |
| 2154 | } |
vladmos | 72d5109 | 2018-03-22 03:54:13 -0700 | [diff] [blame^] | 2155 | env.handleEvent(Event.debug(loc, msg)); |
laurentlb | 3d2a68c | 2017-06-30 00:32:04 +0200 | [diff] [blame] | 2156 | return Runtime.NONE; |
| 2157 | } |
| 2158 | }; |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2159 | |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 2160 | @SkylarkSignature( |
| 2161 | name = "zip", |
| 2162 | doc = |
| 2163 | "Returns a <code>list</code> of <code>tuple</code>s, where the i-th tuple contains " |
| 2164 | + "the i-th element from each of the argument sequences or iterables. The list has the " |
| 2165 | + "size of the shortest input. With a single iterable argument, it returns a list of " |
| 2166 | + "1-tuples. With no arguments, it returns an empty list. Examples:" |
| 2167 | + "<pre class=\"language-python\">" |
| 2168 | + "zip() # == []\n" |
| 2169 | + "zip([1, 2]) # == [(1,), (2,)]\n" |
| 2170 | + "zip([1, 2], [3, 4]) # == [(1, 3), (2, 4)]\n" |
| 2171 | + "zip([1, 2], [3, 4, 5]) # == [(1, 3), (2, 4)]</pre>", |
| 2172 | extraPositionals = @Param(name = "args", doc = "lists to zip."), |
| 2173 | returnType = MutableList.class, |
| 2174 | useLocation = true, |
| 2175 | useEnvironment = true |
| 2176 | ) |
| 2177 | private static final BuiltinFunction zip = |
| 2178 | new BuiltinFunction("zip") { |
| 2179 | public MutableList<?> invoke(SkylarkList<?> args, Location loc, Environment env) |
| 2180 | throws EvalException { |
| 2181 | Iterator<?>[] iterators = new Iterator<?>[args.size()]; |
| 2182 | for (int i = 0; i < args.size(); i++) { |
laurentlb | c9b6f4a | 2017-06-21 11:58:50 +0200 | [diff] [blame] | 2183 | iterators[i] = EvalUtils.toIterable(args.get(i), loc, env).iterator(); |
Googler | c60ec8c | 2015-03-23 14:20:18 +0000 | [diff] [blame] | 2184 | } |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 2185 | ArrayList<Tuple<?>> result = new ArrayList<>(); |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 2186 | boolean allHasNext; |
| 2187 | do { |
| 2188 | allHasNext = !args.isEmpty(); |
| 2189 | List<Object> elem = Lists.newArrayListWithExpectedSize(args.size()); |
| 2190 | for (Iterator<?> iterator : iterators) { |
| 2191 | if (iterator.hasNext()) { |
| 2192 | elem.add(iterator.next()); |
| 2193 | } else { |
| 2194 | allHasNext = false; |
| 2195 | } |
| 2196 | } |
| 2197 | if (allHasNext) { |
| 2198 | result.add(Tuple.copyOf(elem)); |
| 2199 | } |
| 2200 | } while (allHasNext); |
michajlo | 490eb97 | 2017-10-16 21:30:13 +0200 | [diff] [blame] | 2201 | return MutableList.wrapUnsafe(env, result); |
Googler | c60ec8c | 2015-03-23 14:20:18 +0000 | [diff] [blame] | 2202 | } |
John Cater | d792842 | 2017-01-03 20:06:59 +0000 | [diff] [blame] | 2203 | }; |
Googler | c60ec8c | 2015-03-23 14:20:18 +0000 | [diff] [blame] | 2204 | |
Dmitry Lomov | 34cdae3 | 2016-06-28 16:13:35 +0000 | [diff] [blame] | 2205 | /** Skylark String module. */ |
Florian Weikert | e342196 | 2015-12-17 12:46:08 +0000 | [diff] [blame] | 2206 | @SkylarkModule( |
| 2207 | name = "string", |
Dmitry Lomov | 34cdae3 | 2016-06-28 16:13:35 +0000 | [diff] [blame] | 2208 | category = SkylarkModuleCategory.BUILTIN, |
Florian Weikert | e342196 | 2015-12-17 12:46:08 +0000 | [diff] [blame] | 2209 | doc = |
| 2210 | "A language built-in type to support strings. " |
| 2211 | + "Examples of string literals:<br>" |
| 2212 | + "<pre class=\"language-python\">a = 'abc\\ndef'\n" |
| 2213 | + "b = \"ab'cd\"\n" |
| 2214 | + "c = \"\"\"multiline string\"\"\"\n" |
| 2215 | + "\n" |
| 2216 | + "# Strings support slicing (negative index starts from the end):\n" |
| 2217 | + "x = \"hello\"[2:4] # \"ll\"\n" |
| 2218 | + "y = \"hello\"[1:-1] # \"ell\"\n" |
| 2219 | + "z = \"hello\"[:4] # \"hell\"" |
| 2220 | + "# Slice steps can be used, too:\n" |
| 2221 | + "s = \"hello\"[::2] # \"hlo\"\n" |
| 2222 | + "t = \"hello\"[3:0:-1] # \"lle\"\n</pre>" |
| 2223 | + "Strings are iterable and support the <code>in</code> operator. Examples:<br>" |
| 2224 | + "<pre class=\"language-python\">\"bc\" in \"abcd\" # evaluates to True\n" |
| 2225 | + "x = [s for s in \"abc\"] # x == [\"a\", \"b\", \"c\"]</pre>\n" |
| 2226 | + "Implicit concatenation of strings is not allowed; use the <code>+</code> " |
| 2227 | + "operator instead." |
| 2228 | ) |
Francois-Rene Rideau | 0f7ba34 | 2015-08-31 16:16:21 +0000 | [diff] [blame] | 2229 | static final class StringModule {} |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2230 | |
Laurent Le Brun | 4f3b582 | 2017-02-15 16:20:24 +0000 | [diff] [blame] | 2231 | /** Skylark int type. */ |
| 2232 | @SkylarkModule( |
| 2233 | name = "int", |
| 2234 | category = SkylarkModuleCategory.BUILTIN, |
| 2235 | doc = |
| 2236 | "A type to represent integers. It can represent any number between -2147483648 and " |
| 2237 | + "2147483647 (included). " |
| 2238 | + "Examples of int values:<br>" |
| 2239 | + "<pre class=\"language-python\">" |
| 2240 | + "153\n" |
| 2241 | + "0x2A # hexadecimal literal\n" |
| 2242 | + "054 # octal literal\n" |
| 2243 | + "23 * 2 + 5\n" |
| 2244 | + "100 / -7\n" |
| 2245 | + "100 % -7 # -5 (unlike in some other languages)\n" |
| 2246 | + "int(\"18\")\n" |
| 2247 | + "</pre>" |
| 2248 | ) |
| 2249 | public static final class IntModule {} |
| 2250 | |
| 2251 | /** Skylark bool type. */ |
| 2252 | @SkylarkModule( |
| 2253 | name = "bool", |
| 2254 | category = SkylarkModuleCategory.BUILTIN, |
| 2255 | doc = |
| 2256 | "A type to represent booleans. There are only two possible values: " |
| 2257 | + "<a href=\"globals.html#True\">True</a> and " |
| 2258 | + "<a href=\"globals.html#False\">False</a>. " |
| 2259 | + "Any value can be converted to a boolean using the " |
| 2260 | + "<a href=\"globals.html#bool\">bool</a> function." |
| 2261 | ) |
| 2262 | public static final class BoolModule {} |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2263 | |
Laurent Le Brun | 5e99198 | 2016-10-14 13:39:45 +0000 | [diff] [blame] | 2264 | static final List<BaseFunction> defaultGlobalFunctions = |
brandjon | c06e746 | 2017-07-11 20:54:58 +0200 | [diff] [blame] | 2265 | ImmutableList.of( |
Laurent Le Brun | 5e99198 | 2016-10-14 13:39:45 +0000 | [diff] [blame] | 2266 | all, any, bool, dict, dir, fail, getattr, hasattr, hash, enumerate, int_, len, list, max, |
brandjon | f2ed858 | 2017-06-27 15:05:35 +0200 | [diff] [blame] | 2267 | min, print, range, repr, reversed, sorted, str, tuple, zip); |
Francois-Rene Rideau | 537a90b | 2015-04-22 06:47:31 +0000 | [diff] [blame] | 2268 | |
| 2269 | static { |
| 2270 | SkylarkSignatureProcessor.configureSkylarkFunctions(MethodLibrary.class); |
| 2271 | } |
Han-Wen Nienhuys | d08b27f | 2015-02-25 16:45:20 +0100 | [diff] [blame] | 2272 | } |