diff options
author | Nirbheek Chauhan <nirbheek@centricular.com> | 2017-01-26 23:42:50 +0530 |
---|---|---|
committer | Jussi Pakkanen <jpakkane@gmail.com> | 2017-01-26 23:22:14 +0200 |
commit | 0e078adf5a7d47d5ad168f75e39d4a044032b197 (patch) | |
tree | 84ace01b986dee180ffd184c96a237e6ddbdaa88 | |
parent | b81d00b4b6144b8b62d6bd7cfc247c95b9b015c3 (diff) | |
download | meson-0e078adf5a7d47d5ad168f75e39d4a044032b197.zip meson-0e078adf5a7d47d5ad168f75e39d4a044032b197.tar.gz meson-0e078adf5a7d47d5ad168f75e39d4a044032b197.tar.bz2 |
interpreter: Implement array.get(index, fallback)
If the index is out of range, the fallback value is used. Includes
a test.
Closes #1337
-rw-r--r-- | mesonbuild/interpreterbase.py | 16 | ||||
-rw-r--r-- | test cases/common/67 foreach/meson.build | 8 |
2 files changed, 20 insertions, 4 deletions
diff --git a/mesonbuild/interpreterbase.py b/mesonbuild/interpreterbase.py index 837a4f8..12e4fc4 100644 --- a/mesonbuild/interpreterbase.py +++ b/mesonbuild/interpreterbase.py @@ -501,12 +501,24 @@ class InterpreterBase: return len(obj) elif method_name == 'get': index = args[0] + fallback = None + if len(args) == 2: + fallback = args[1] + elif len(args) > 2: + m = 'Array method \'get()\' only takes two arguments: the ' \ + 'index and an optional fallback value if the index is ' \ + 'out of range.' + raise InvalidArguments(m) if not isinstance(index, int): raise InvalidArguments('Array index must be a number.') if index < -len(obj) or index >= len(obj): - raise InvalidArguments('Array index %s is out of bounds for array of size %d.' % (index, len(obj))) + if fallback is None: + m = 'Array index {!r} is out of bounds for array of size {!r}.' + raise InvalidArguments(m.format(index, len(obj))) + return fallback return obj[index] - raise InterpreterException('Arrays do not have a method called "%s".' % method_name) + m = 'Arrays do not have a method called {!r}.' + raise InterpreterException(m.format(method_name)) def reduce_arguments(self, args): assert(isinstance(args, mparser.ArgumentNode)) diff --git a/test cases/common/67 foreach/meson.build b/test cases/common/67 foreach/meson.build index 0e81d3d..e633de8 100644 --- a/test cases/common/67 foreach/meson.build +++ b/test cases/common/67 foreach/meson.build @@ -1,8 +1,12 @@ project('foreach', 'c') tests = [['test1', 'prog1', 'prog1.c'], - ['test2', 'prog2', 'prog2.c'], - ['test3', 'prog3', 'prog3.c']] + ['test2', 'prog2', 'prog2.c', 'fallback'], + ['test3', 'prog3', 'prog3.c', 'urgh']] + +assert(tests[0].get(3, 'fallbck') == 'fallbck', 'array #1 fallback did not match') +assert(tests[1].get(3, 'failbk') == 'fallback', 'array #2 value did not match') +assert(tests[2].get(3, 'urgh') == 'urgh', 'array #3 value did not match') foreach i : tests test(i.get(0), executable(i.get(1), i.get(2), install : true)) |