rule-engine 5.0.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.
- rule_engine/__init__.py +65 -0
- rule_engine/_vendor/__init__.py +4 -0
- rule_engine/_vendor/ply/LICENSE +32 -0
- rule_engine/_vendor/ply/__init__.py +5 -0
- rule_engine/_vendor/ply/lex.py +1098 -0
- rule_engine/_vendor/ply/yacc.py +3433 -0
- rule_engine/ast/__init__.py +92 -0
- rule_engine/ast/base.py +343 -0
- rule_engine/ast/binary/__init__.py +103 -0
- rule_engine/ast/binary/arithmetic.py +211 -0
- rule_engine/ast/binary/base.py +112 -0
- rule_engine/ast/binary/comparison.py +154 -0
- rule_engine/ast/expression/__init__.py +35 -0
- rule_engine/ast/expression/access.py +434 -0
- rule_engine/ast/expression/control.py +256 -0
- rule_engine/ast/expression/resolution.py +220 -0
- rule_engine/ast/literal.py +183 -0
- rule_engine/builtins.py +230 -0
- rule_engine/debug_ast.py +65 -0
- rule_engine/debug_repl.py +159 -0
- rule_engine/engine/__init__.py +34 -0
- rule_engine/engine/_attribute_resolver.py +353 -0
- rule_engine/engine/context.py +438 -0
- rule_engine/engine/rule.py +148 -0
- rule_engine/errors.py +359 -0
- rule_engine/parser/__init__.py +614 -0
- rule_engine/parser/base.py +86 -0
- rule_engine/parser/utilities.py +114 -0
- rule_engine/suggestions.py +105 -0
- rule_engine/types/__init__.py +61 -0
- rule_engine/types/_object.py +318 -0
- rule_engine/types/coercion.py +141 -0
- rule_engine/types/dataclass.py +149 -0
- rule_engine/types/datatype.py +398 -0
- rule_engine/types/definitions.py +454 -0
- rule_engine/types/sqlalchemy.py +171 -0
- rule_engine-5.0.0.dist-info/METADATA +126 -0
- rule_engine-5.0.0.dist-info/RECORD +41 -0
- rule_engine-5.0.0.dist-info/WHEEL +5 -0
- rule_engine-5.0.0.dist-info/licenses/LICENSE +28 -0
- rule_engine-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
#
|
|
4
|
+
# rule_engine/ast/expression/access.py
|
|
5
|
+
#
|
|
6
|
+
# Redistribution and use in source and binary forms, with or without
|
|
7
|
+
# modification, are permitted provided that the following conditions are
|
|
8
|
+
# met:
|
|
9
|
+
#
|
|
10
|
+
# * Redistributions of source code must retain the above copyright
|
|
11
|
+
# notice, this list of conditions and the following disclaimer.
|
|
12
|
+
# * Redistributions in binary form must reproduce the above
|
|
13
|
+
# copyright notice, this list of conditions and the following disclaimer
|
|
14
|
+
# in the documentation and/or other materials provided with the
|
|
15
|
+
# distribution.
|
|
16
|
+
# * Neither the name of the project nor the names of its
|
|
17
|
+
# contributors may be used to endorse or promote products derived from
|
|
18
|
+
# this software without specific prior written permission.
|
|
19
|
+
#
|
|
20
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
21
|
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
22
|
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
23
|
+
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
24
|
+
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
25
|
+
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
26
|
+
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
27
|
+
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
28
|
+
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
29
|
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
30
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
31
|
+
#
|
|
32
|
+
|
|
33
|
+
import collections.abc
|
|
34
|
+
import operator
|
|
35
|
+
from typing import TYPE_CHECKING, Any
|
|
36
|
+
|
|
37
|
+
from ... import builtins as _builtins
|
|
38
|
+
from ... import errors
|
|
39
|
+
from ...suggestions import suggest_symbol
|
|
40
|
+
from ...types import DataType, coerce_value
|
|
41
|
+
from ...types import _DataTypeDef
|
|
42
|
+
|
|
43
|
+
from ..base import (
|
|
44
|
+
ExpressionBase,
|
|
45
|
+
LiteralExpressionBase,
|
|
46
|
+
_assert_is_integer_number,
|
|
47
|
+
_assert_not_nullable,
|
|
48
|
+
_is_reduced,
|
|
49
|
+
_resolve_type,
|
|
50
|
+
)
|
|
51
|
+
from ..literal import BooleanExpression, NullExpression
|
|
52
|
+
|
|
53
|
+
if TYPE_CHECKING:
|
|
54
|
+
from ...engine.context import Context
|
|
55
|
+
|
|
56
|
+
class ContainsExpression(ExpressionBase):
|
|
57
|
+
"""An expression used to test whether an item exists within a container."""
|
|
58
|
+
__slots__ = ('container', 'member')
|
|
59
|
+
result_type: _DataTypeDef = DataType.BOOLEAN
|
|
60
|
+
def __init__(self, context: 'Context', container: ExpressionBase, member: ExpressionBase) -> None:
|
|
61
|
+
_assert_not_nullable(container.result_type, role='containment container')
|
|
62
|
+
container_type = container.result_type
|
|
63
|
+
member_type = DataType.NULLABLE.unwrap(member.result_type)
|
|
64
|
+
if container_type == DataType.BYTES or container_type == DataType.STRING:
|
|
65
|
+
if member_type != DataType.UNDEFINED and member_type != container_type:
|
|
66
|
+
raise errors.EvaluationError('data type mismatch')
|
|
67
|
+
elif DataType.is_type(_resolve_type(container_type, context), DataType.OBJECT):
|
|
68
|
+
raise errors.EvaluationError('data type mismatch (containment check on OBJECT)')
|
|
69
|
+
elif container_type != DataType.UNDEFINED and container_type.is_scalar:
|
|
70
|
+
raise errors.EvaluationError('data type mismatch')
|
|
71
|
+
self.context = context
|
|
72
|
+
self.member = member
|
|
73
|
+
self.container = container
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def build(cls, context: 'Context', container: ExpressionBase, member: ExpressionBase) -> ExpressionBase: # type: ignore[override]
|
|
77
|
+
container_built = container.build()
|
|
78
|
+
assert isinstance(container_built, ExpressionBase)
|
|
79
|
+
member_built = member.build()
|
|
80
|
+
assert isinstance(member_built, ExpressionBase)
|
|
81
|
+
reduced = cls(context, container_built, member_built).reduce()
|
|
82
|
+
assert isinstance(reduced, ExpressionBase)
|
|
83
|
+
return reduced
|
|
84
|
+
|
|
85
|
+
def __repr__(self) -> str:
|
|
86
|
+
return "<{0} container={1!r} member={2!r} >".format(self.__class__.__name__, self.container, self.member)
|
|
87
|
+
|
|
88
|
+
def evaluate(self, thing: Any) -> bool:
|
|
89
|
+
container_value = self.container.evaluate(thing)
|
|
90
|
+
container_value_type = DataType.from_value(container_value)
|
|
91
|
+
member_value = self.member.evaluate(thing)
|
|
92
|
+
if container_value_type == DataType.BYTES or container_value_type == DataType.STRING:
|
|
93
|
+
if DataType.from_value(member_value) != container_value_type:
|
|
94
|
+
raise errors.EvaluationError('data type mismatch')
|
|
95
|
+
return bool(member_value in container_value)
|
|
96
|
+
|
|
97
|
+
def reduce(self) -> ExpressionBase:
|
|
98
|
+
if not _is_reduced(self.container, self.member):
|
|
99
|
+
return self
|
|
100
|
+
return BooleanExpression(self.context, self.evaluate(None))
|
|
101
|
+
|
|
102
|
+
def to_graphviz(self, digraph: Any, *args: Any, **kwargs: Any) -> None:
|
|
103
|
+
super(ContainsExpression, self).to_graphviz(digraph, *args, **kwargs)
|
|
104
|
+
self.container.to_graphviz(digraph, *args, **kwargs)
|
|
105
|
+
self.member.to_graphviz(digraph, *args, **kwargs)
|
|
106
|
+
digraph.edge(str(id(self)), str(id(self.container)), label='container')
|
|
107
|
+
digraph.edge(str(id(self)), str(id(self.member)), label='member')
|
|
108
|
+
|
|
109
|
+
class GetAttributeExpression(ExpressionBase):
|
|
110
|
+
"""A class representing an expression in which *name* is retrieved as an attribute of *object*."""
|
|
111
|
+
__slots__ = ('name', 'object', 'safe', '_object_type')
|
|
112
|
+
def __init__(self, context: 'Context', object_: ExpressionBase, name: str, safe: bool = False) -> None:
|
|
113
|
+
"""
|
|
114
|
+
:param context: The context to use for evaluating the expression.
|
|
115
|
+
:type context: :py:class:`~rule_engine.engine.Context`
|
|
116
|
+
:param object_: The parent object from which to retrieve the attribute.
|
|
117
|
+
:param str name: The name of the attribute to retrieve.
|
|
118
|
+
:param bool safe: Whether or not the safe version should be invoked.
|
|
119
|
+
|
|
120
|
+
.. versionchanged:: 2.4.0
|
|
121
|
+
Added the *safe* parameter.
|
|
122
|
+
"""
|
|
123
|
+
self.context = context
|
|
124
|
+
self.object = object_
|
|
125
|
+
self._object_type = None
|
|
126
|
+
if not safe:
|
|
127
|
+
_assert_not_nullable(self.object.result_type, role='attribute access target')
|
|
128
|
+
object_type = DataType.NULLABLE.unwrap(self.object.result_type)
|
|
129
|
+
if object_type != DataType.UNDEFINED:
|
|
130
|
+
if not (object_type == DataType.NULL and safe):
|
|
131
|
+
resolved_object_type = _resolve_type(object_type, context)
|
|
132
|
+
if DataType.is_type(resolved_object_type, DataType.OBJECT):
|
|
133
|
+
if name not in resolved_object_type.attributes:
|
|
134
|
+
raise errors.ObjectAttributeError(
|
|
135
|
+
name,
|
|
136
|
+
resolved_object_type,
|
|
137
|
+
suggestion=suggest_symbol(name, resolved_object_type.attributes.keys())
|
|
138
|
+
)
|
|
139
|
+
self._object_type = resolved_object_type
|
|
140
|
+
attribute_type = _resolve_type(resolved_object_type.attributes[name], context)
|
|
141
|
+
self.result_type = attribute_type
|
|
142
|
+
else:
|
|
143
|
+
try:
|
|
144
|
+
self.result_type = context.resolve_attribute_type(object_type, name)
|
|
145
|
+
except errors.AttributeResolutionError as error:
|
|
146
|
+
# this is necessary because MAPPING objects can have their keys accessed as attributes
|
|
147
|
+
if not DataType.is_type(object_type, DataType.MAPPING):
|
|
148
|
+
raise error
|
|
149
|
+
if not context.mapping_attribute_lookup:
|
|
150
|
+
raise errors.EvaluationError(
|
|
151
|
+
"attribute access on a MAPPING is disabled - use mapping[{0!r}] instead, "
|
|
152
|
+
"or set mapping_attribute_lookup=True on the Context for v4-compatible "
|
|
153
|
+
"behavior (deprecated, removal scheduled for v6.0)".format(name)
|
|
154
|
+
)
|
|
155
|
+
# leave the result type undefined because the name could be a mapping key or attribute
|
|
156
|
+
if DataType.is_type(self.object.result_type, DataType.NULLABLE) and self.result_type != DataType.UNDEFINED:
|
|
157
|
+
self.result_type = DataType.NULLABLE.wrap(self.result_type)
|
|
158
|
+
self.name = name
|
|
159
|
+
self.safe = safe
|
|
160
|
+
|
|
161
|
+
@classmethod
|
|
162
|
+
def build(cls, context: 'Context', object_: ExpressionBase, name: str, safe: bool = False) -> ExpressionBase: # type: ignore[override]
|
|
163
|
+
object_built = object_.build()
|
|
164
|
+
assert isinstance(object_built, ExpressionBase)
|
|
165
|
+
reduced = cls(context, object_built, name, safe=safe).reduce()
|
|
166
|
+
assert isinstance(reduced, ExpressionBase)
|
|
167
|
+
return reduced
|
|
168
|
+
|
|
169
|
+
def __repr__(self) -> str:
|
|
170
|
+
return "<{0} name={1!r} >".format(self.__class__.__name__, self.name)
|
|
171
|
+
|
|
172
|
+
def evaluate(self, thing: Any) -> Any:
|
|
173
|
+
resolved_obj = self.object.evaluate(thing)
|
|
174
|
+
if resolved_obj is None and self.safe:
|
|
175
|
+
return resolved_obj
|
|
176
|
+
if resolved_obj is None and DataType.is_type(self.object.result_type, DataType.NULLABLE):
|
|
177
|
+
raise errors.EvaluationError(
|
|
178
|
+
"attribute access on a null value (use ?. to safely navigate a NULLABLE expression)"
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if self._object_type is not None:
|
|
182
|
+
try:
|
|
183
|
+
value = self._object_type.accessor(resolved_obj, self.name)
|
|
184
|
+
except (AttributeError, KeyError):
|
|
185
|
+
default_value = self.context.default_value
|
|
186
|
+
if default_value is errors.UNDEFINED:
|
|
187
|
+
raise errors.ObjectAttributeError(
|
|
188
|
+
self.name,
|
|
189
|
+
self._object_type,
|
|
190
|
+
thing=thing,
|
|
191
|
+
suggestion=suggest_symbol(self.name, self._object_type.attributes.keys())
|
|
192
|
+
) from None
|
|
193
|
+
value = default_value
|
|
194
|
+
return self._new_value(value, verify_type=False)
|
|
195
|
+
|
|
196
|
+
attribute_error = None
|
|
197
|
+
try:
|
|
198
|
+
value = self.context.resolve_attribute(thing, resolved_obj, self.name)
|
|
199
|
+
except errors.AttributeResolutionError as error:
|
|
200
|
+
attribute_error = error
|
|
201
|
+
else:
|
|
202
|
+
return self._new_value(value, verify_type=False)
|
|
203
|
+
|
|
204
|
+
if isinstance(resolved_obj, collections.abc.Mapping) and not isinstance(resolved_obj, _builtins.Builtins):
|
|
205
|
+
if not self.context.mapping_attribute_lookup:
|
|
206
|
+
raise attribute_error
|
|
207
|
+
self.context._warn_mapping_fallback(self.name)
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
value = self.context.resolve(resolved_obj, self.name)
|
|
211
|
+
except errors.SymbolResolutionError as symbol_error:
|
|
212
|
+
default_value = self.context.default_value
|
|
213
|
+
if default_value is errors.UNDEFINED:
|
|
214
|
+
suggestion = attribute_error.suggestion or symbol_error.suggestion
|
|
215
|
+
if attribute_error.suggestion and symbol_error.suggestion:
|
|
216
|
+
# if there are two suggestions, select the best one
|
|
217
|
+
suggestion = suggest_symbol(self.name, (attribute_error.suggestion, symbol_error.suggestion))
|
|
218
|
+
attribute_error.suggestion = suggestion
|
|
219
|
+
raise attribute_error from None
|
|
220
|
+
value = default_value
|
|
221
|
+
return self._new_value(value, verify_type=False)
|
|
222
|
+
|
|
223
|
+
def reduce(self) -> ExpressionBase:
|
|
224
|
+
if not _is_reduced(self.object):
|
|
225
|
+
return self
|
|
226
|
+
literal = LiteralExpressionBase.from_value(self.context, self.evaluate(None))
|
|
227
|
+
if literal.result_type == DataType.FUNCTION and DataType.is_compatible(self.result_type, DataType.FUNCTION):
|
|
228
|
+
literal.result_type = self.result_type
|
|
229
|
+
return literal
|
|
230
|
+
|
|
231
|
+
def to_graphviz(self, digraph: Any, *args: Any, **kwargs: Any) -> None:
|
|
232
|
+
digraph.node(str(id(self)), "{}\nname={!r}".format(self.__class__.__name__, self.name))
|
|
233
|
+
self.object.to_graphviz(digraph, *args, **kwargs)
|
|
234
|
+
digraph.edge(str(id(self)), str(id(self.object)))
|
|
235
|
+
|
|
236
|
+
class GetItemExpression(ExpressionBase):
|
|
237
|
+
"""A class representing an expression in which an *item* is retrieved from a container *object*."""
|
|
238
|
+
__slots__ = ('container', 'item', 'safe')
|
|
239
|
+
def __init__(self, context: 'Context', container: ExpressionBase, item: ExpressionBase, safe: bool = False) -> None:
|
|
240
|
+
"""
|
|
241
|
+
:param context: The context to use for evaluating the expression.
|
|
242
|
+
:type context: :py:class:`~rule_engine.engine.Context`
|
|
243
|
+
:param container: The container object from which to retrieve the item.
|
|
244
|
+
:param str item: The item to retrieve from the container.
|
|
245
|
+
:param bool safe: Whether or not the safe version should be invoked.
|
|
246
|
+
|
|
247
|
+
.. versionchanged:: 2.4.0
|
|
248
|
+
Added the *safe* parameter.
|
|
249
|
+
"""
|
|
250
|
+
self.context = context
|
|
251
|
+
self.container = container
|
|
252
|
+
if not safe:
|
|
253
|
+
_assert_not_nullable(container.result_type, role='item access container')
|
|
254
|
+
container_type = DataType.NULLABLE.unwrap(container.result_type)
|
|
255
|
+
resolved_container_type = _resolve_type(container_type, context)
|
|
256
|
+
if container_type == DataType.BYTES:
|
|
257
|
+
if not DataType.is_compatible(item.result_type, DataType.FLOAT):
|
|
258
|
+
raise errors.EvaluationError('data type mismatch (not an integer number)')
|
|
259
|
+
self.result_type = DataType.FLOAT
|
|
260
|
+
elif container_type == DataType.STRING:
|
|
261
|
+
if not DataType.is_compatible(item.result_type, DataType.FLOAT):
|
|
262
|
+
raise errors.EvaluationError('data type mismatch (not an integer number)')
|
|
263
|
+
self.result_type = DataType.STRING
|
|
264
|
+
elif DataType.is_type(resolved_container_type, DataType.ARRAY):
|
|
265
|
+
if not DataType.is_compatible(item.result_type, DataType.FLOAT):
|
|
266
|
+
raise errors.EvaluationError('data type mismatch (not an integer number)')
|
|
267
|
+
self.result_type = _resolve_type(resolved_container_type.value_type, context)
|
|
268
|
+
elif DataType.is_type(resolved_container_type, DataType.MAPPING):
|
|
269
|
+
if not (safe or DataType.is_compatible(item.result_type, resolved_container_type.key_type)):
|
|
270
|
+
raise errors.LookupError(errors.UNDEFINED, errors.UNDEFINED)
|
|
271
|
+
self.result_type = _resolve_type(resolved_container_type.value_type, context)
|
|
272
|
+
elif DataType.is_type(resolved_container_type, DataType.SET):
|
|
273
|
+
raise errors.EvaluationError('data type mismatch (container is a set)')
|
|
274
|
+
elif DataType.is_type(resolved_container_type, DataType.OBJECT):
|
|
275
|
+
raise errors.EvaluationError(
|
|
276
|
+
"data type mismatch (item access on OBJECT - use {0}.attribute instead)".format(resolved_container_type.name)
|
|
277
|
+
)
|
|
278
|
+
elif container_type != DataType.UNDEFINED:
|
|
279
|
+
if not (container_type == DataType.NULL and safe):
|
|
280
|
+
raise errors.EvaluationError('data type mismatch')
|
|
281
|
+
if DataType.is_type(container.result_type, DataType.NULLABLE) and self.result_type != DataType.UNDEFINED:
|
|
282
|
+
self.result_type = DataType.NULLABLE.wrap(self.result_type)
|
|
283
|
+
self.item = item
|
|
284
|
+
self.safe = safe
|
|
285
|
+
|
|
286
|
+
@classmethod
|
|
287
|
+
def build(cls, context: 'Context', container: ExpressionBase, item: ExpressionBase, safe: bool = False) -> ExpressionBase: # type: ignore[override]
|
|
288
|
+
container_built = container.build()
|
|
289
|
+
assert isinstance(container_built, ExpressionBase)
|
|
290
|
+
item_built = item.build()
|
|
291
|
+
assert isinstance(item_built, ExpressionBase)
|
|
292
|
+
reduced = cls(context, container_built, item_built, safe=safe).reduce()
|
|
293
|
+
assert isinstance(reduced, ExpressionBase)
|
|
294
|
+
return reduced
|
|
295
|
+
|
|
296
|
+
def __repr__(self) -> str:
|
|
297
|
+
return "<{0} container={1!r} item={2!r} >".format(self.__class__.__name__, self.container, self.item)
|
|
298
|
+
|
|
299
|
+
def evaluate(self, thing: Any) -> Any:
|
|
300
|
+
resolved_obj = self.container.evaluate(thing)
|
|
301
|
+
if resolved_obj is None:
|
|
302
|
+
if self.safe:
|
|
303
|
+
return resolved_obj
|
|
304
|
+
raise errors.EvaluationError('data type mismatch (container is null)')
|
|
305
|
+
|
|
306
|
+
resolved_item = self.item.evaluate(thing)
|
|
307
|
+
if isinstance(resolved_obj, (bytes, str, tuple)):
|
|
308
|
+
_assert_is_integer_number(resolved_item)
|
|
309
|
+
resolved_item = int(resolved_item)
|
|
310
|
+
try:
|
|
311
|
+
value = operator.getitem(resolved_obj, resolved_item)
|
|
312
|
+
except (IndexError, KeyError):
|
|
313
|
+
if self.safe:
|
|
314
|
+
return None
|
|
315
|
+
raise errors.LookupError(resolved_obj, resolved_item)
|
|
316
|
+
return self._new_value(value, verify_type=False)
|
|
317
|
+
|
|
318
|
+
def reduce(self) -> ExpressionBase:
|
|
319
|
+
if DataType.is_type(self.container.result_type, DataType.MAPPING):
|
|
320
|
+
if self.safe and not DataType.is_compatible(self.item.result_type, self.container.result_type.key_type):
|
|
321
|
+
return NullExpression(self.context)
|
|
322
|
+
if _is_reduced(self.container, self.item):
|
|
323
|
+
return LiteralExpressionBase.from_value(self.context, self.evaluate(None))
|
|
324
|
+
return self
|
|
325
|
+
|
|
326
|
+
def to_graphviz(self, digraph: Any, *args: Any, **kwargs: Any) -> None:
|
|
327
|
+
super(GetItemExpression, self).to_graphviz(digraph, *args, **kwargs)
|
|
328
|
+
self.container.to_graphviz(digraph, *args, **kwargs)
|
|
329
|
+
self.item.to_graphviz(digraph, *args, **kwargs)
|
|
330
|
+
digraph.edge(str(id(self)), str(id(self.container)), label='container')
|
|
331
|
+
digraph.edge(str(id(self)), str(id(self.item)), label='item')
|
|
332
|
+
|
|
333
|
+
class GetSliceExpression(ExpressionBase):
|
|
334
|
+
"""A class representing an expression in which a range of items is retrieved from a container *object*."""
|
|
335
|
+
__slots__ = ('container', 'start', 'stop', 'safe')
|
|
336
|
+
def __init__(
|
|
337
|
+
self,
|
|
338
|
+
context: 'Context',
|
|
339
|
+
container: ExpressionBase,
|
|
340
|
+
start: ExpressionBase | None = None,
|
|
341
|
+
stop: ExpressionBase | None = None, safe: bool = False
|
|
342
|
+
) -> None:
|
|
343
|
+
"""
|
|
344
|
+
:param context: The context to use for evaluating the expression.
|
|
345
|
+
:type context: :py:class:`~rule_engine.engine.Context`
|
|
346
|
+
:param container: The container object from which to retrieve the item.
|
|
347
|
+
:param start: The expression that represents the starting index of the slice.
|
|
348
|
+
:param stop: The expression that represents the stopping index of the slice.
|
|
349
|
+
:param bool safe: Whether or not the safe version should be invoked.
|
|
350
|
+
|
|
351
|
+
.. versionchanged:: 2.4.0
|
|
352
|
+
Added the *safe* parameter.
|
|
353
|
+
"""
|
|
354
|
+
self.context = context
|
|
355
|
+
self.container = container
|
|
356
|
+
if not safe:
|
|
357
|
+
_assert_not_nullable(container.result_type, role='slice container')
|
|
358
|
+
container_type = DataType.NULLABLE.unwrap(container.result_type)
|
|
359
|
+
if container_type == DataType.BYTES:
|
|
360
|
+
self.result_type = DataType.BYTES
|
|
361
|
+
elif container_type == DataType.STRING:
|
|
362
|
+
self.result_type = DataType.STRING
|
|
363
|
+
# check against __class__ so the parent class is dynamic in case it changes in the future, what we're doing here
|
|
364
|
+
# is explicitly checking if result_type is an array with out checking the value_type
|
|
365
|
+
elif DataType.is_type(container_type, DataType.ARRAY):
|
|
366
|
+
self.result_type = container_type
|
|
367
|
+
elif DataType.is_type(container_type, DataType.SET):
|
|
368
|
+
raise errors.EvaluationError('data type mismatch (container is a set)')
|
|
369
|
+
elif container_type != DataType.UNDEFINED:
|
|
370
|
+
if not (container_type == DataType.NULL and safe):
|
|
371
|
+
raise errors.EvaluationError('data type mismatch')
|
|
372
|
+
if DataType.is_type(container.result_type, DataType.NULLABLE) and self.result_type != DataType.UNDEFINED:
|
|
373
|
+
self.result_type = DataType.NULLABLE.wrap(self.result_type)
|
|
374
|
+
self.start = start or LiteralExpressionBase.from_value(context, 0)
|
|
375
|
+
self.stop = stop or LiteralExpressionBase.from_value(context, None)
|
|
376
|
+
self.safe = safe
|
|
377
|
+
|
|
378
|
+
@classmethod
|
|
379
|
+
def build( # type: ignore[override]
|
|
380
|
+
cls,
|
|
381
|
+
context: 'Context',
|
|
382
|
+
container: ExpressionBase,
|
|
383
|
+
start: ExpressionBase | None = None,
|
|
384
|
+
stop: ExpressionBase | None = None,
|
|
385
|
+
safe: bool = False
|
|
386
|
+
) -> ExpressionBase:
|
|
387
|
+
if start is not None:
|
|
388
|
+
start_built = start.build()
|
|
389
|
+
assert isinstance(start_built, ExpressionBase)
|
|
390
|
+
start = start_built
|
|
391
|
+
if stop is not None:
|
|
392
|
+
stop_built = stop.build()
|
|
393
|
+
assert isinstance(stop_built, ExpressionBase)
|
|
394
|
+
stop = stop_built
|
|
395
|
+
container_built = container.build()
|
|
396
|
+
assert isinstance(container_built, ExpressionBase)
|
|
397
|
+
reduced = cls(context, container_built, start=start, stop=stop, safe=safe).reduce()
|
|
398
|
+
assert isinstance(reduced, ExpressionBase)
|
|
399
|
+
return reduced
|
|
400
|
+
|
|
401
|
+
def __repr__(self) -> str:
|
|
402
|
+
return "<{0} container={1!r} start={2!r} stop={3!r} >".format(self.__class__.__name__, self.container, self.start, self.stop)
|
|
403
|
+
|
|
404
|
+
def evaluate(self, thing: Any) -> Any:
|
|
405
|
+
resolved_obj = self.container.evaluate(thing)
|
|
406
|
+
if resolved_obj is None:
|
|
407
|
+
if self.safe:
|
|
408
|
+
return resolved_obj
|
|
409
|
+
raise errors.EvaluationError('data type mismatch')
|
|
410
|
+
|
|
411
|
+
resolved_start = self.start.evaluate(thing)
|
|
412
|
+
if resolved_start is not None:
|
|
413
|
+
_assert_is_integer_number(resolved_start)
|
|
414
|
+
resolved_start = int(resolved_start)
|
|
415
|
+
resolved_stop = self.stop.evaluate(thing)
|
|
416
|
+
if resolved_stop is not None:
|
|
417
|
+
_assert_is_integer_number(resolved_stop)
|
|
418
|
+
resolved_stop = int(resolved_stop)
|
|
419
|
+
value = operator.getitem(resolved_obj, slice(resolved_start, resolved_stop))
|
|
420
|
+
return coerce_value(value, verify_type=False)
|
|
421
|
+
|
|
422
|
+
def reduce(self) -> ExpressionBase:
|
|
423
|
+
if not _is_reduced(self.container, self.start, self.stop):
|
|
424
|
+
return self
|
|
425
|
+
return LiteralExpressionBase.from_value(self.context, self.evaluate(None))
|
|
426
|
+
|
|
427
|
+
def to_graphviz(self, digraph: Any, *args: Any, **kwargs: Any) -> None:
|
|
428
|
+
super(GetSliceExpression, self).to_graphviz(digraph, *args, **kwargs)
|
|
429
|
+
self.container.to_graphviz(digraph, *args, **kwargs)
|
|
430
|
+
self.start.to_graphviz(digraph, *args, **kwargs)
|
|
431
|
+
self.stop.to_graphviz(digraph, *args, **kwargs)
|
|
432
|
+
digraph.edge(str(id(self)), str(id(self.container)), label='container')
|
|
433
|
+
digraph.edge(str(id(self)), str(id(self.start)), label='start')
|
|
434
|
+
digraph.edge(str(id(self)), str(id(self.stop)), label='stop')
|