forked from fgmacedo/python-statemachine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspec_parser.py
More file actions
240 lines (188 loc) · 7.92 KB
/
Copy pathspec_parser.py
File metadata and controls
240 lines (188 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import ast
import operator
import re
from collections.abc import Callable
from functools import reduce
from inspect import isawaitable
replacements = {"!": "not ", "^": " and ", "v": " or "}
pattern = re.compile(r"\!(?!=)|\^|\bv\b")
comparison_repr = {
operator.eq: "==",
operator.ne: "!=",
operator.gt: ">",
operator.ge: ">=",
operator.lt: "<",
operator.le: "<=",
}
def _unique_key(left, right, operator) -> str:
left_key = getattr(left, "unique_key", "")
right_key = getattr(right, "unique_key", "")
return f"{left_key} {operator} {right_key}"
def replace_operators(expr: str) -> str:
# preprocess the expression adding support for classical logical operators
def match_func(match):
return replacements[match.group(0)]
return pattern.sub(match_func, expr)
def custom_not(predicate: Callable) -> Callable:
def decorated(*args, **kwargs):
result = predicate(*args, **kwargs)
if isawaitable(result):
async def _negate():
return not await result
return _negate()
return not result
decorated.__name__ = f"not({predicate.__name__})"
unique_key = getattr(predicate, "unique_key", "")
decorated.unique_key = f"not({unique_key})" # type: ignore[attr-defined]
return decorated
def custom_and(left: Callable, right: Callable) -> Callable:
def decorated(*args, **kwargs):
left_result = left(*args, **kwargs)
if isawaitable(left_result):
async def _async_and():
lr = await left_result
if not lr:
return lr
rr = right(*args, **kwargs)
if isawaitable(rr):
return await rr
return rr
return _async_and()
if not left_result:
return left_result
right_result = right(*args, **kwargs)
if isawaitable(right_result):
return right_result
return right_result
decorated.__name__ = f"({left.__name__} and {right.__name__})"
decorated.unique_key = _unique_key(left, right, "and") # type: ignore[attr-defined]
return decorated
def custom_or(left: Callable, right: Callable) -> Callable:
def decorated(*args, **kwargs):
left_result = left(*args, **kwargs)
if isawaitable(left_result):
async def _async_or():
lr = await left_result
if lr:
return lr
rr = right(*args, **kwargs)
if isawaitable(rr):
return await rr
return rr
return _async_or()
if left_result:
return left_result
right_result = right(*args, **kwargs)
if isawaitable(right_result):
return right_result
return right_result
decorated.__name__ = f"({left.__name__} or {right.__name__})"
decorated.unique_key = _unique_key(left, right, "or") # type: ignore[attr-defined]
return decorated
def build_constant(constant) -> Callable:
def decorated(*args, **kwargs):
return constant
decorated.__name__ = str(constant)
decorated.unique_key = str(constant) # type: ignore[attr-defined]
return decorated
class Functions:
registry: dict[str, Callable] = {}
@classmethod
def register(cls, id) -> Callable:
def register(func):
cls.registry[id] = func
return func
return register
@classmethod
def get(cls, func_id):
func_id = func_id.lower()
if func_id not in cls.registry:
raise ValueError(f"Unsupported function: {func_id}")
return cls.registry[func_id]
class InState:
def __init__(self, machine):
self.machine = machine
def __call__(self, *state_ids: str):
return set(state_ids).issubset({s.id for s in self.machine.configuration})
@Functions.register("in")
def build_in_call(*state_ids: str) -> Callable:
state_ids_set = set(state_ids)
def decorated(*args, **kwargs):
machine = kwargs["machine"]
return InState(machine)(*state_ids)
decorated.__name__ = f"in({state_ids_set})"
decorated.unique_key = f"in({state_ids_set})" # type: ignore[attr-defined]
return decorated
def build_custom_operator(operator) -> Callable:
operator_repr = comparison_repr[operator]
def custom_comparator(left: Callable, right: Callable) -> Callable:
def decorated(*args, **kwargs):
left_result = left(*args, **kwargs)
right_result = right(*args, **kwargs)
if isawaitable(left_result) or isawaitable(right_result):
async def _async_compare():
lr = (await left_result) if isawaitable(left_result) else left_result
rr = (await right_result) if isawaitable(right_result) else right_result
return bool(operator(lr, rr))
return _async_compare()
return bool(operator(left_result, right_result))
decorated.__name__ = f"({left.__name__} {operator_repr} {right.__name__})"
decorated.unique_key = _unique_key(left, right, operator_repr) # type: ignore[attr-defined]
return decorated
return custom_comparator
def build_expression(node, variable_hook, operator_mapping):
match node:
case ast.BoolOp():
# `and` / `or` operations
operator_fn = operator_mapping[type(node.op)]
left_expr = build_expression(node.values[0], variable_hook, operator_mapping)
for right in node.values[1:]:
right_expr = build_expression(right, variable_hook, operator_mapping)
left_expr = operator_fn(left_expr, right_expr)
return left_expr
case ast.Compare():
# `==` / `!=` / `>` / `<` / `>=` / `<=` operations
expressions = []
left_expr = build_expression(node.left, variable_hook, operator_mapping)
for right_op, right in zip(node.ops, node.comparators, strict=True):
right_expr = build_expression(right, variable_hook, operator_mapping)
operator_fn = operator_mapping[type(right_op)]
expression = operator_fn(left_expr, right_expr)
left_expr = right_expr
expressions.append(expression)
return reduce(custom_and, expressions)
case ast.Call():
assert isinstance(node.func, ast.Name)
constructor = Functions.get(node.func.id)
params = [arg.value for arg in node.args if isinstance(arg, ast.Constant)]
return constructor(*params)
case ast.UnaryOp(op=ast.Not()):
operand_expr = build_expression(node.operand, variable_hook, operator_mapping)
return operator_mapping[type(node.op)](operand_expr)
case ast.Name(id=name):
return variable_hook(name)
case ast.Constant(value=value):
return build_constant(value)
case _:
raise ValueError(f"Unsupported expression structure: {node.__class__.__name__}")
def parse_boolean_expr(expr, variable_hook, operator_mapping):
"""Parses the expression into an AST and build a custom expression tree"""
if expr.strip() == "":
raise SyntaxError("Empty expression")
# Optimization trying to avoid parsing the expression if not needed
if "!" not in expr and " " not in expr and "In(" not in expr:
return variable_hook(expr)
expr = replace_operators(expr)
tree = ast.parse(expr, mode="eval")
return build_expression(tree.body, variable_hook, operator_mapping)
operator_mapping = {
ast.Or: custom_or,
ast.And: custom_and,
ast.Not: custom_not,
ast.GtE: build_custom_operator(operator.ge),
ast.Gt: build_custom_operator(operator.gt),
ast.LtE: build_custom_operator(operator.le),
ast.Lt: build_custom_operator(operator.lt),
ast.Eq: build_custom_operator(operator.eq),
ast.NotEq: build_custom_operator(operator.ne),
}