aisexpr 0.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aisexpr/__init__.py +20 -0
- aisexpr/errors.py +38 -0
- aisexpr/evaluator.py +303 -0
- aisexpr/expression.py +53 -0
- aisexpr/lexer.py +366 -0
- aisexpr/parser.py +366 -0
- aisexpr/tokens.py +135 -0
- aisexpr-0.9.0.dist-info/METADATA +225 -0
- aisexpr-0.9.0.dist-info/RECORD +11 -0
- aisexpr-0.9.0.dist-info/WHEEL +4 -0
- aisexpr-0.9.0.dist-info/licenses/LICENSE +21 -0
aisexpr/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
__version__ = "0.9.0"
|
|
2
|
+
|
|
3
|
+
from .errors import AISExprError, EvaluationError, LexerError, ParserError
|
|
4
|
+
from .lexer import DEFAULT_VARIABLE_PREFIXES, Lexer
|
|
5
|
+
from .expression import AISExpression
|
|
6
|
+
from .parser import Parser
|
|
7
|
+
from .tokens import Token, TokenType
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AISExprError",
|
|
11
|
+
"LexerError",
|
|
12
|
+
"ParserError",
|
|
13
|
+
"EvaluationError",
|
|
14
|
+
"Token",
|
|
15
|
+
"TokenType",
|
|
16
|
+
"Lexer",
|
|
17
|
+
"DEFAULT_VARIABLE_PREFIXES",
|
|
18
|
+
"Parser",
|
|
19
|
+
"AISExpression",
|
|
20
|
+
]
|
aisexpr/errors.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
class AISExprError(Exception):
|
|
2
|
+
"""Base class for every error aisexpr raises.
|
|
3
|
+
|
|
4
|
+
Catch this to handle any problem with an expression:
|
|
5
|
+
try:
|
|
6
|
+
...
|
|
7
|
+
except AISExprError as e:
|
|
8
|
+
print(e.message, e.pos)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, message: str, pos: int | None = None) -> None:
|
|
12
|
+
self.message = message
|
|
13
|
+
# Position (0-based) in the expression where the error was found, or
|
|
14
|
+
# None when there isn't one (e.g. a missing variable at evaluation).
|
|
15
|
+
self.pos = pos
|
|
16
|
+
if pos is None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
else:
|
|
19
|
+
super().__init__(f"{message} at position {pos}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class LexerError(AISExprError):
|
|
23
|
+
"""Invalid characters or tokens, e.g. an unknown keyword or an unclosed string."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ParserError(AISExprError):
|
|
27
|
+
"""Valid tokens in an invalid order, e.g. ${flow.x} == 1 and ) or True."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EvaluationError(AISExprError):
|
|
31
|
+
"""Errors found while evaluating, e.g. an index out of range, a type
|
|
32
|
+
mismatch, or a missing variable.
|
|
33
|
+
|
|
34
|
+
For example, the expression ${flow.x.y} == "abc" evaluated with this data,
|
|
35
|
+
which has no key y under x:
|
|
36
|
+
{"flow": {"x": {"z": "abc"}}}
|
|
37
|
+
raises EvaluationError: Variable '${flow.x.y}' not found at position 0
|
|
38
|
+
"""
|
aisexpr/evaluator.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from .errors import EvaluationError
|
|
5
|
+
from .parser import (
|
|
6
|
+
BoolOpNode,
|
|
7
|
+
CompareNode,
|
|
8
|
+
FieldNode,
|
|
9
|
+
FunctionCallNode,
|
|
10
|
+
IndexNode,
|
|
11
|
+
LiteralNode,
|
|
12
|
+
NotNode,
|
|
13
|
+
TreeNode,
|
|
14
|
+
VariableNode,
|
|
15
|
+
)
|
|
16
|
+
from .tokens import TokenType
|
|
17
|
+
|
|
18
|
+
# Values reach the evaluator as nested dicts, lists, strings, numbers, booleans
|
|
19
|
+
# and None (JSON null): AgentFlow serializes objects to dicts first, so there
|
|
20
|
+
# is no attribute access, a field is a dict key lookup.
|
|
21
|
+
#
|
|
22
|
+
# Type rules, checked at evaluation since variable types are only known then:
|
|
23
|
+
# - and, or, not and the whole expression need real booleans, no truthiness:
|
|
24
|
+
# "abc" and True, not [] and len(${a}) as a whole condition are errors
|
|
25
|
+
# - == and != need values of the same type: 1 == 1.0 is fine, ${a} == "5"
|
|
26
|
+
# with a number, or True == 1, is an error. None may be compared with
|
|
27
|
+
# anything: ${a} == "x" is False when a is None, never an error.
|
|
28
|
+
# - < <= > >= need two numbers or two strings
|
|
29
|
+
# - functions check their argument types, see _call()
|
|
30
|
+
|
|
31
|
+
# Marks a path step that doesn't resolve, used by exists().
|
|
32
|
+
_MISSING = object()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Missing(Exception):
|
|
36
|
+
"""Raised instead of EvaluationError while resolving a path for exists()."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def type_name(value: Any) -> str:
|
|
40
|
+
"""How a value's type is shown in error messages."""
|
|
41
|
+
if value is None:
|
|
42
|
+
return "null"
|
|
43
|
+
if isinstance(value, bool):
|
|
44
|
+
return "boolean"
|
|
45
|
+
if isinstance(value, (int, float)):
|
|
46
|
+
return "number"
|
|
47
|
+
if isinstance(value, str):
|
|
48
|
+
return "string"
|
|
49
|
+
if isinstance(value, Mapping):
|
|
50
|
+
return "dict"
|
|
51
|
+
if isinstance(value, (list, tuple)):
|
|
52
|
+
return "list"
|
|
53
|
+
return type(value).__name__
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def is_number(value: Any) -> bool:
|
|
57
|
+
# bool is a subclass of int in Python, so True would pass isinstance(int)
|
|
58
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def same_type(a: Any, b: Any) -> bool:
|
|
62
|
+
return type_name(a) == type_name(b)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_equal(a: Any, b: Any) -> bool:
|
|
66
|
+
"""== without errors: values of different types are simply not equal."""
|
|
67
|
+
return same_type(a, b) and a == b
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# Evaluates a whole expression and returns True or False.
|
|
71
|
+
# data holds the variables as nested dicts: ${flow.x.y} is
|
|
72
|
+
# data["flow"]["x"]["y"]. Flat keys such as {"flow.x.y": 1} are not supported.
|
|
73
|
+
# Evaluation errors raised by this function:
|
|
74
|
+
# - the expression doesn't give a boolean, e.g. ${flow.name} or len(${a})
|
|
75
|
+
# - anything raised while evaluating its parts, see _eval()
|
|
76
|
+
def evaluate(tree: TreeNode, data: Mapping[str, Any] | None = None) -> bool:
|
|
77
|
+
result = _Evaluator(data if data is not None else {}).eval(tree)
|
|
78
|
+
if not isinstance(result, bool):
|
|
79
|
+
raise EvaluationError(
|
|
80
|
+
f"The expression must give True or False, got {type_name(result)}",
|
|
81
|
+
tree.pos,
|
|
82
|
+
)
|
|
83
|
+
return result
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class _Evaluator:
|
|
87
|
+
def __init__(self, data: Mapping[str, Any]) -> None:
|
|
88
|
+
if not isinstance(data, Mapping):
|
|
89
|
+
raise EvaluationError(
|
|
90
|
+
f"Variables must be passed as a dict, got {type_name(data)}"
|
|
91
|
+
)
|
|
92
|
+
self.data = data
|
|
93
|
+
|
|
94
|
+
# Evaluates any node and returns its value.
|
|
95
|
+
# Evaluation errors raised by this function, besides those of the
|
|
96
|
+
# helpers it calls:
|
|
97
|
+
# - and/or/not with something that isn't a boolean
|
|
98
|
+
# - a comparison of values of different types, or < > on anything but
|
|
99
|
+
# two numbers or two strings
|
|
100
|
+
# "and" and "or" short-circuit: in
|
|
101
|
+
# len(${a}) > 0 and ${a}[0] == "x"
|
|
102
|
+
# the right side isn't evaluated when ${a} is empty, so it can't fail.
|
|
103
|
+
def eval(self, node: TreeNode) -> Any:
|
|
104
|
+
match node:
|
|
105
|
+
case LiteralNode(value=value):
|
|
106
|
+
return value
|
|
107
|
+
case VariableNode() | IndexNode() | FieldNode():
|
|
108
|
+
return self._resolve(node, missing_ok=False)
|
|
109
|
+
case NotNode(operand=operand):
|
|
110
|
+
return not self._bool(operand, "not")
|
|
111
|
+
case BoolOpNode(op=TokenType.AND, left=left, right=right):
|
|
112
|
+
return self._bool(left, "and") and self._bool(right, "and")
|
|
113
|
+
case BoolOpNode(op=TokenType.OR, left=left, right=right):
|
|
114
|
+
return self._bool(left, "or") or self._bool(right, "or")
|
|
115
|
+
case CompareNode():
|
|
116
|
+
return self._compare(node)
|
|
117
|
+
case FunctionCallNode():
|
|
118
|
+
return self._call(node)
|
|
119
|
+
raise TypeError(f"Not a node: {node!r}")
|
|
120
|
+
|
|
121
|
+
def _bool(self, node: TreeNode, op: str) -> bool:
|
|
122
|
+
value = self.eval(node)
|
|
123
|
+
if not isinstance(value, bool):
|
|
124
|
+
raise EvaluationError(
|
|
125
|
+
f"'{op}' needs True or False, got {type_name(value)}", node.pos
|
|
126
|
+
)
|
|
127
|
+
return value
|
|
128
|
+
|
|
129
|
+
def _compare(self, node: CompareNode) -> bool:
|
|
130
|
+
left = self.eval(node.left)
|
|
131
|
+
right = self.eval(node.right)
|
|
132
|
+
op = node.op
|
|
133
|
+
if op in (TokenType.EQ, TokenType.NOTEQ):
|
|
134
|
+
if left is not None and right is not None and not same_type(left, right):
|
|
135
|
+
raise EvaluationError(
|
|
136
|
+
f"Can't compare {type_name(left)} with {type_name(right)}",
|
|
137
|
+
node.pos,
|
|
138
|
+
)
|
|
139
|
+
return (left == right) == (op == TokenType.EQ)
|
|
140
|
+
both_numbers = is_number(left) and is_number(right)
|
|
141
|
+
both_strings = isinstance(left, str) and isinstance(right, str)
|
|
142
|
+
if not (both_numbers or both_strings):
|
|
143
|
+
raise EvaluationError(
|
|
144
|
+
f"'<', '<=', '>' and '>=' need two numbers or two strings, "
|
|
145
|
+
f"got {type_name(left)} and {type_name(right)}",
|
|
146
|
+
node.pos,
|
|
147
|
+
)
|
|
148
|
+
if op == TokenType.LT:
|
|
149
|
+
return left < right
|
|
150
|
+
if op == TokenType.LTEQ:
|
|
151
|
+
return left <= right
|
|
152
|
+
if op == TokenType.GT:
|
|
153
|
+
return left > right
|
|
154
|
+
return left >= right
|
|
155
|
+
|
|
156
|
+
# Resolves a path: a variable, followed by any [index] and .field steps,
|
|
157
|
+
# e.g. ${flow.orders}[0].status
|
|
158
|
+
# With missing_ok (used by exists()), a step that doesn't resolve, for any
|
|
159
|
+
# of the reasons below, raises _Missing instead of EvaluationError. An expression inside [ ] is not a
|
|
160
|
+
# step, it is evaluated normally, so in exists(${a}[${flow.i}]) a missing
|
|
161
|
+
# flow.i is still an error.
|
|
162
|
+
# Evaluation errors raised by this function:
|
|
163
|
+
# - variable not found: a part of its name is missing, or a part before
|
|
164
|
+
# it isn't a dict
|
|
165
|
+
# - index on a list or string that isn't a whole number, or is out of
|
|
166
|
+
# range (negative indexes count from the end, -1 is the last)
|
|
167
|
+
# - index on a dict that isn't a string, or a key not found
|
|
168
|
+
# - field on something other than a dict, or a field not found
|
|
169
|
+
# - index or field on a value that has neither, e.g. a number
|
|
170
|
+
def _resolve(self, node: TreeNode, missing_ok: bool) -> Any:
|
|
171
|
+
def fail(message: str, pos: int) -> Any:
|
|
172
|
+
if missing_ok:
|
|
173
|
+
raise _Missing()
|
|
174
|
+
raise EvaluationError(message, pos)
|
|
175
|
+
|
|
176
|
+
match node:
|
|
177
|
+
case VariableNode(name=name, pos=pos):
|
|
178
|
+
value: Any = self.data
|
|
179
|
+
for part in name.split("."):
|
|
180
|
+
if not isinstance(value, Mapping) or part not in value:
|
|
181
|
+
return fail(f"Variable '${{{name}}}' not found", pos)
|
|
182
|
+
value = value[part]
|
|
183
|
+
return value
|
|
184
|
+
|
|
185
|
+
case IndexNode(target=target, index=index_node, pos=pos):
|
|
186
|
+
value = self._resolve(target, missing_ok)
|
|
187
|
+
index = self.eval(index_node)
|
|
188
|
+
if isinstance(value, (list, tuple, str)):
|
|
189
|
+
if not isinstance(index, int) or isinstance(index, bool):
|
|
190
|
+
return fail(
|
|
191
|
+
f"A {type_name(value)} index must be a whole number, "
|
|
192
|
+
f"got {type_name(index)}",
|
|
193
|
+
index_node.pos,
|
|
194
|
+
)
|
|
195
|
+
if not -len(value) <= index < len(value):
|
|
196
|
+
return fail(
|
|
197
|
+
f"Index {index} out of range for a {type_name(value)} "
|
|
198
|
+
f"of length {len(value)}",
|
|
199
|
+
pos,
|
|
200
|
+
)
|
|
201
|
+
return value[index]
|
|
202
|
+
if isinstance(value, Mapping):
|
|
203
|
+
if not isinstance(index, str):
|
|
204
|
+
return fail(
|
|
205
|
+
f"A dict key must be a string, got {type_name(index)}",
|
|
206
|
+
index_node.pos,
|
|
207
|
+
)
|
|
208
|
+
if index not in value:
|
|
209
|
+
return fail(f"Key '{index}' not found", pos)
|
|
210
|
+
return value[index]
|
|
211
|
+
return fail(f"Can't index a {type_name(value)}", pos)
|
|
212
|
+
|
|
213
|
+
case FieldNode(target=target, name=name, pos=pos):
|
|
214
|
+
value = self._resolve(target, missing_ok)
|
|
215
|
+
if not isinstance(value, Mapping):
|
|
216
|
+
return fail(
|
|
217
|
+
f"Can't read field '.{name}' of a {type_name(value)}", pos
|
|
218
|
+
)
|
|
219
|
+
if name not in value:
|
|
220
|
+
return fail(f"Field '.{name}' not found", pos)
|
|
221
|
+
return value[name]
|
|
222
|
+
|
|
223
|
+
# Any other node at the start of a path, e.g. "abc"[0] or lower(x)[0]
|
|
224
|
+
return self.eval(node)
|
|
225
|
+
|
|
226
|
+
# Calls a function. The parser has already checked the number of
|
|
227
|
+
# arguments, and that exists() was given a path.
|
|
228
|
+
# contains(x, v) x string: v must be a string, is it a substring?
|
|
229
|
+
# x list: is v one of the elements?
|
|
230
|
+
# x dict: v must be a string, is it a key?
|
|
231
|
+
# startswith/endswith(s, v), lower(s), upper(s): strings only
|
|
232
|
+
# len(x) string, list or dict
|
|
233
|
+
# index(x, v) x string: v must be a string, where it starts
|
|
234
|
+
# x list: position of the first element equal to v
|
|
235
|
+
# -1 if not found; a dict is an error
|
|
236
|
+
# exists(path) True if every step of the path resolves
|
|
237
|
+
# List elements are compared with is_equal(), so contains([1], True)
|
|
238
|
+
# is False, not an error.
|
|
239
|
+
# Evaluation errors raised by this function:
|
|
240
|
+
# - an argument of the wrong type
|
|
241
|
+
def _call(self, node: FunctionCallNode) -> Any:
|
|
242
|
+
func = node.func
|
|
243
|
+
if func == TokenType.FN_EXISTS:
|
|
244
|
+
try:
|
|
245
|
+
self._resolve(node.args[0], missing_ok=True)
|
|
246
|
+
return True
|
|
247
|
+
except _Missing:
|
|
248
|
+
return False
|
|
249
|
+
|
|
250
|
+
args = [self.eval(arg) for arg in node.args]
|
|
251
|
+
|
|
252
|
+
def wrong_type(i: int, expected: str) -> EvaluationError:
|
|
253
|
+
return EvaluationError(
|
|
254
|
+
f"{node.name}() needs {expected} as argument {i + 1}, "
|
|
255
|
+
f"got {type_name(args[i])}",
|
|
256
|
+
node.args[i].pos,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
if func == TokenType.FN_LEN:
|
|
260
|
+
if not isinstance(args[0], (str, list, tuple, Mapping)):
|
|
261
|
+
raise wrong_type(0, "a string, list or dict")
|
|
262
|
+
return len(args[0])
|
|
263
|
+
|
|
264
|
+
if func in (TokenType.FN_LOWER, TokenType.FN_UPPER):
|
|
265
|
+
if not isinstance(args[0], str):
|
|
266
|
+
raise wrong_type(0, "a string")
|
|
267
|
+
return args[0].lower() if func == TokenType.FN_LOWER else args[0].upper()
|
|
268
|
+
|
|
269
|
+
if func in (TokenType.FN_STARTSWITH, TokenType.FN_ENDSWITH):
|
|
270
|
+
for i in (0, 1):
|
|
271
|
+
if not isinstance(args[i], str):
|
|
272
|
+
raise wrong_type(i, "a string")
|
|
273
|
+
if func == TokenType.FN_STARTSWITH:
|
|
274
|
+
return args[0].startswith(args[1])
|
|
275
|
+
return args[0].endswith(args[1])
|
|
276
|
+
|
|
277
|
+
x, v = args
|
|
278
|
+
if func == TokenType.FN_CONTAINS:
|
|
279
|
+
if isinstance(x, str):
|
|
280
|
+
if not isinstance(v, str):
|
|
281
|
+
raise wrong_type(1, "a string")
|
|
282
|
+
return v in x
|
|
283
|
+
if isinstance(x, (list, tuple)):
|
|
284
|
+
return any(is_equal(e, v) for e in x)
|
|
285
|
+
if isinstance(x, Mapping):
|
|
286
|
+
if not isinstance(v, str):
|
|
287
|
+
raise wrong_type(1, "a string")
|
|
288
|
+
return v in x
|
|
289
|
+
raise wrong_type(0, "a string, list or dict")
|
|
290
|
+
|
|
291
|
+
if func == TokenType.FN_INDEX:
|
|
292
|
+
if isinstance(x, str):
|
|
293
|
+
if not isinstance(v, str):
|
|
294
|
+
raise wrong_type(1, "a string")
|
|
295
|
+
return x.find(v)
|
|
296
|
+
if isinstance(x, (list, tuple)):
|
|
297
|
+
for i, e in enumerate(x):
|
|
298
|
+
if is_equal(e, v):
|
|
299
|
+
return i
|
|
300
|
+
return -1
|
|
301
|
+
raise wrong_type(0, "a string or list")
|
|
302
|
+
|
|
303
|
+
raise TypeError(f"Unknown function: {node.name}")
|
aisexpr/expression.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from collections.abc import Iterable, Mapping
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from .evaluator import evaluate
|
|
5
|
+
from .lexer import Lexer
|
|
6
|
+
from .parser import Parser, TreeNode
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# A parsed expression, ready to be evaluated any number of times:
|
|
10
|
+
# expr = AISExpression('${flow.x.y} == "abcd"', variable_prefixes=["flow"])
|
|
11
|
+
# expr.variables -> frozenset({"flow.x.y"})
|
|
12
|
+
# expr.evaluate({"flow": {"x": {"y": "abcd"}}}) -> True
|
|
13
|
+
# variable_prefixes is required: the prefixes a variable may start with,
|
|
14
|
+
# which depend on where the expression is used.
|
|
15
|
+
# The constructor parses, so a bad expression raises LexerError or
|
|
16
|
+
# ParserError right there, like Decimal("abc") raises.
|
|
17
|
+
# The expression is parsed only once, in the constructor. After that you can
|
|
18
|
+
# call evaluate() as many times as you like with different data, and it is
|
|
19
|
+
# never parsed again:
|
|
20
|
+
# expr.evaluate({"flow": {"x": {"y": "abcd"}}}) -> True
|
|
21
|
+
# expr.evaluate({"flow": {"x": {"y": "zzz"}}}) -> False
|
|
22
|
+
# For a one-off check, parse and evaluate in one go:
|
|
23
|
+
# AISExpression('${flow.x} == 1', variable_prefixes=["flow"]).evaluate(data)
|
|
24
|
+
class AISExpression:
|
|
25
|
+
def __init__(self, text: str, *, variable_prefixes: Iterable[str]) -> None:
|
|
26
|
+
parser = Parser(Lexer(text, variable_prefixes=variable_prefixes))
|
|
27
|
+
self._tree = parser.parse()
|
|
28
|
+
self._text = text
|
|
29
|
+
self._variables = frozenset(parser.variables)
|
|
30
|
+
|
|
31
|
+
# Read-only: the tree and variables always belong to this text.
|
|
32
|
+
@property
|
|
33
|
+
def text(self) -> str:
|
|
34
|
+
return self._text
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def tree(self) -> TreeNode:
|
|
38
|
+
return self._tree
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def variables(self) -> frozenset[str]:
|
|
42
|
+
"""Names of all variables used in the expression, as written between
|
|
43
|
+
${ and }. For ${flow.x.y} == 1 and len(${user.roles}) > 0 this is
|
|
44
|
+
frozenset({"flow.x.y", "user.roles"})."""
|
|
45
|
+
return self._variables
|
|
46
|
+
|
|
47
|
+
def evaluate(self, data: Mapping[str, Any] | None = None) -> bool:
|
|
48
|
+
"""Evaluate with variables as nested dicts, {"flow": {"x": 1}}.
|
|
49
|
+
Returns True or False, raises EvaluationError."""
|
|
50
|
+
return evaluate(self._tree, data)
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return f"AISExpression({self._text!r})"
|