Skip to content

Commit

Permalink
Implement in operator on string
Browse files Browse the repository at this point in the history
  • Loading branch information
xclaesse authored and jpakkane committed Nov 6, 2022
1 parent 8abbcf7 commit a6db624
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/markdown/snippets/str_in.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## `in` operator for strings

`in` and `not in` operators now works on strings, in addition to arrays and
dictionaries.

```
fs = import('fs')
if 'something' in fs.read('somefile')
# True
endif
```
12 changes: 12 additions & 0 deletions mesonbuild/interpreter/primitives/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ def __init__(self, obj: str, interpreter: 'Interpreter') -> None:
self.operators.update({
MesonOperator.DIV: self.op_div,
MesonOperator.INDEX: self.op_index,
MesonOperator.IN: self.op_in,
MesonOperator.NOT_IN: self.op_notin,
})

def display_name(self) -> str:
Expand Down Expand Up @@ -173,6 +175,16 @@ def op_index(self, other: int) -> str:
except IndexError:
raise InvalidArguments(f'Index {other} out of bounds of string of size {len(self.held_object)}.')

@FeatureNew('"in" string operator', '0.64.0')
@typed_operator(MesonOperator.IN, str)
def op_in(self, other: str) -> bool:
return other in self.held_object

@FeatureNew('"not in" string operator', '0.64.0')
@typed_operator(MesonOperator.NOT_IN, str)
def op_notin(self, other: str) -> bool:
return other not in self.held_object


class MesonVersionString(str):
pass
Expand Down
3 changes: 3 additions & 0 deletions test cases/common/16 comparison/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,6 @@ assert(exe3 not in [exe1, exe2], ''''exe3 shouldn't be in [exe1, exe2]''')

assert('a' in {'a': 'b'}, '''1 should be in {'a': 'b'}''')
assert('b' not in {'a': 'b'}, '''1 should be in {'a': 'b'}''')

assert('a' in 'abc')
assert('b' not in 'def')

0 comments on commit a6db624

Please sign in to comment.