omlish 0.0.0.dev46__py3-none-any.whl → 0.0.0.dev48__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.
@@ -0,0 +1,429 @@
1
+ import numbers
2
+ import operator
3
+ import typing as ta
4
+
5
+ from . import exceptions
6
+ from . import functions
7
+ from .scope import ScopedChainDict
8
+
9
+
10
+ def _equals(x, y):
11
+ if _is_special_number_case(x, y):
12
+ return False
13
+ else:
14
+ return x == y
15
+
16
+
17
+ def _is_special_number_case(x, y):
18
+ # We need to special case comparing 0 or 1 to True/False. While normally comparing any integer other than 0/1 to
19
+ # True/False will always return False. However 0/1 have this:
20
+ # >>> 0 == True
21
+ # False
22
+ # >>> 0 == False
23
+ # True
24
+ # >>> 1 == True
25
+ # True
26
+ # >>> 1 == False
27
+ # False
28
+ #
29
+ # Also need to consider that:
30
+ # >>> 0 in [True, False]
31
+ # True
32
+ if _is_actual_number(x) and x in (0, 1):
33
+ return isinstance(y, bool)
34
+
35
+ elif _is_actual_number(y) and y in (0, 1):
36
+ return isinstance(x, bool)
37
+
38
+ else:
39
+ return None
40
+
41
+
42
+ def _is_comparable(x):
43
+ # The spec doesn't officially support string types yet, but enough people are relying on this behavior that it's
44
+ # been added back. This should eventually become part of the official spec.
45
+ return _is_actual_number(x) or isinstance(x, str)
46
+
47
+
48
+ def _is_actual_number(x):
49
+ # We need to handle python's quirkiness with booleans, specifically:
50
+ #
51
+ # >>> isinstance(False, int)
52
+ # True
53
+ # >>> isinstance(True, int)
54
+ # True
55
+ if isinstance(x, bool):
56
+ return False
57
+ return isinstance(x, numbers.Number)
58
+
59
+
60
+ class Options:
61
+ """Options to control how a Jmespath function is evaluated."""
62
+
63
+ def __init__(
64
+ self,
65
+ dict_cls=None,
66
+ custom_functions=None,
67
+ enable_legacy_literals=False,
68
+ ):
69
+ #: The class to use when creating a dict. The interpreter may create dictionaries during the evaluation of a
70
+ # Jmespath expression. For example, a multi-select hash will create a dictionary. By default we use a dict()
71
+ # type. You can set this value to change what dict type is used. The most common reason you would change this
72
+ # is if you want to set a collections.OrderedDict so that you can have predictable key ordering.
73
+ self.dict_cls = dict_cls
74
+ self.custom_functions = custom_functions
75
+
76
+ #: The flag to enable pre-JEP-12 literal compatibility.
77
+ # JEP-12 deprecates `foo` -> "foo" syntax.
78
+ # Valid expressions MUST use: `"foo"` -> "foo"
79
+ # Setting this flag to `True` enables support for legacy syntax.
80
+ self.enable_legacy_literals = enable_legacy_literals
81
+
82
+
83
+ class _Expression:
84
+ def __init__(self, expression, interpreter):
85
+ self.expression = expression
86
+ self.interpreter = interpreter
87
+
88
+ def visit(self, node, *args, **kwargs):
89
+ return self.interpreter.visit(node, *args, **kwargs)
90
+
91
+
92
+ class Visitor:
93
+ def __init__(self):
94
+ self._method_cache = {}
95
+
96
+ def visit(self, node, *args, **kwargs):
97
+ node_type = node['type']
98
+ method = self._method_cache.get(node_type)
99
+ if method is None:
100
+ method = getattr(self, f'visit_{node["type"]}', self.default_visit)
101
+ self._method_cache[node_type] = method
102
+ return method(node, *args, **kwargs) # type: ignore
103
+
104
+ def default_visit(self, node, *args, **kwargs):
105
+ raise NotImplementedError('default_visit')
106
+
107
+
108
+ class TreeInterpreter(Visitor):
109
+ COMPARATOR_FUNC: ta.Mapping[str, ta.Callable] = {
110
+ 'eq': _equals,
111
+ 'ne': lambda x, y: not _equals(x, y),
112
+ 'lt': operator.lt,
113
+ 'gt': operator.gt,
114
+ 'lte': operator.le,
115
+ 'gte': operator.ge,
116
+ }
117
+
118
+ _EQUALITY_OPS: ta.Sequence[str] = ['eq', 'ne']
119
+
120
+ _ARITHMETIC_UNARY_FUNC: ta.Mapping[str, ta.Callable] = {
121
+ 'minus': operator.neg,
122
+ 'plus': lambda x: x,
123
+ }
124
+
125
+ _ARITHMETIC_FUNC: ta.Mapping[str, ta.Callable] = {
126
+ 'div': operator.floordiv,
127
+ 'divide': operator.truediv,
128
+ 'minus': operator.sub,
129
+ 'modulo': operator.mod,
130
+ 'multiply': operator.mul,
131
+ 'plus': operator.add,
132
+ }
133
+
134
+ MAP_TYPE = dict
135
+
136
+ def __init__(self, options=None):
137
+ super().__init__()
138
+
139
+ self._dict_cls = self.MAP_TYPE
140
+
141
+ if options is None:
142
+ options = Options()
143
+ self._options = options
144
+
145
+ if options.dict_cls is not None:
146
+ self._dict_cls = self._options.dict_cls
147
+
148
+ if options.custom_functions is not None:
149
+ self._functions = self._options.custom_functions
150
+ else:
151
+ self._functions = functions.Functions()
152
+
153
+ self._root = None
154
+ self._scope = ScopedChainDict()
155
+
156
+ def default_visit(self, node, *args, **kwargs):
157
+ raise NotImplementedError(node['type'])
158
+
159
+ def evaluate(self, ast, root):
160
+ self._root = root
161
+ return self.visit(ast, root)
162
+
163
+ def visit_subexpression(self, node, value):
164
+ result = value
165
+ for child in node['children']:
166
+ result = self.visit(child, result)
167
+ if result is None:
168
+ return None
169
+ return result
170
+
171
+ def visit_field(self, node, value):
172
+ try:
173
+ return value.get(node['value'])
174
+ except AttributeError:
175
+ return None
176
+
177
+ def visit_comparator(self, node, value):
178
+ # Common case: comparator is == or !=
179
+ comparator_func = self.COMPARATOR_FUNC[node['value']]
180
+ if node['value'] in self._EQUALITY_OPS:
181
+ return comparator_func(
182
+ self.visit(node['children'][0], value),
183
+ self.visit(node['children'][1], value),
184
+ )
185
+
186
+ else:
187
+ # Ordering operators are only valid for numbers. Evaluating any other type with a comparison operator will
188
+ # yield a None value.
189
+ left = self.visit(node['children'][0], value)
190
+ right = self.visit(node['children'][1], value)
191
+ # num_types = (int, float)
192
+ if not (_is_comparable(left) and _is_comparable(right)):
193
+ return None
194
+ return comparator_func(left, right)
195
+
196
+ def visit_arithmetic_unary(self, node, value):
197
+ operation = self._ARITHMETIC_UNARY_FUNC[node['value']]
198
+ return operation(
199
+ self.visit(node['children'][0], value),
200
+ )
201
+
202
+ def visit_arithmetic(self, node, value):
203
+ operation = self._ARITHMETIC_FUNC[node['value']]
204
+ return operation(
205
+ self.visit(node['children'][0], value),
206
+ self.visit(node['children'][1], value),
207
+ )
208
+
209
+ def visit_current(self, node, value):
210
+ return value
211
+
212
+ def visit_root(self, node, value):
213
+ return self._root
214
+
215
+ def visit_expref(self, node, value):
216
+ return _Expression(node['children'][0], self)
217
+
218
+ def visit_function_expression(self, node, value):
219
+ resolved_args = []
220
+ for child in node['children']:
221
+ current = self.visit(child, value)
222
+ resolved_args.append(current)
223
+
224
+ return self._functions.call_function(node['value'], resolved_args)
225
+
226
+ def visit_filter_projection(self, node, value):
227
+ base = self.visit(node['children'][0], value)
228
+ if not isinstance(base, list):
229
+ return None
230
+
231
+ comparator_node = node['children'][2]
232
+ collected = []
233
+ for element in base:
234
+ if self._is_true(self.visit(comparator_node, element)):
235
+ current = self.visit(node['children'][1], element)
236
+ if current is not None:
237
+ collected.append(current)
238
+
239
+ return collected
240
+
241
+ def visit_flatten(self, node, value):
242
+ base = self.visit(node['children'][0], value)
243
+ if not isinstance(base, list):
244
+ # Can't flatten the object if it's not a list.
245
+ return None
246
+
247
+ merged_list = []
248
+ for element in base:
249
+ if isinstance(element, list):
250
+ merged_list.extend(element)
251
+ else:
252
+ merged_list.append(element)
253
+
254
+ return merged_list
255
+
256
+ def visit_identity(self, node, value):
257
+ return value
258
+
259
+ def visit_index(self, node, value):
260
+ # Even though we can index strings, we don't want to support that.
261
+ if not isinstance(value, list):
262
+ return None
263
+
264
+ try:
265
+ return value[node['value']]
266
+ except IndexError:
267
+ return None
268
+
269
+ def visit_index_expression(self, node, value):
270
+ result = value
271
+ for child in node['children']:
272
+ result = self.visit(child, result)
273
+
274
+ return result
275
+
276
+ def visit_slice(self, node, value):
277
+ if isinstance(value, str):
278
+ start = node['children'][0]
279
+ end = node['children'][1]
280
+ step = node['children'][2]
281
+ return value[start:end:step]
282
+
283
+ if not isinstance(value, list):
284
+ return None
285
+
286
+ s = slice(*node['children'])
287
+ return value[s]
288
+
289
+ def visit_key_val_pair(self, node, value):
290
+ return self.visit(node['children'][0], value)
291
+
292
+ def visit_literal(self, node, value):
293
+ return node['value']
294
+
295
+ def visit_multi_select_dict(self, node, value):
296
+ collected = self._dict_cls()
297
+ for child in node['children']:
298
+ collected[child['value']] = self.visit(child, value)
299
+
300
+ return collected
301
+
302
+ def visit_multi_select_list(self, node, value):
303
+ collected = []
304
+ for child in node['children']:
305
+ collected.append(self.visit(child, value))
306
+
307
+ return collected
308
+
309
+ def visit_or_expression(self, node, value):
310
+ matched = self.visit(node['children'][0], value)
311
+
312
+ if self._is_false(matched):
313
+ matched = self.visit(node['children'][1], value)
314
+
315
+ return matched
316
+
317
+ def visit_and_expression(self, node, value):
318
+ matched = self.visit(node['children'][0], value)
319
+
320
+ if self._is_false(matched):
321
+ return matched
322
+
323
+ return self.visit(node['children'][1], value)
324
+
325
+ def visit_not_expression(self, node, value):
326
+ original_result = self.visit(node['children'][0], value)
327
+
328
+ if _is_actual_number(original_result) and original_result == 0:
329
+ # Special case for 0, !0 should be false, not true. 0 is not a special cased integer in jmespath.
330
+ return False
331
+
332
+ return not original_result
333
+
334
+ def visit_pipe(self, node, value):
335
+ result = value
336
+ for child in node['children']:
337
+ result = self.visit(child, result)
338
+ return result
339
+
340
+ def visit_projection(self, node, value):
341
+ base = self.visit(node['children'][0], value)
342
+
343
+ allow_string = False
344
+ first_child = node['children'][0]
345
+ if first_child['type'] == 'index_expression':
346
+ nested_children = first_child['children']
347
+ if len(nested_children) > 1 and nested_children[1]['type'] == 'slice':
348
+ allow_string = True
349
+
350
+ if isinstance(base, str) and allow_string:
351
+ # projections are really sub-expressions in disguise evaluate the rhs when lhs is a sliced string
352
+ return self.visit(node['children'][1], base)
353
+
354
+ if not isinstance(base, list):
355
+ return None
356
+ collected = []
357
+ for element in base:
358
+ current = self.visit(node['children'][1], element)
359
+ if current is not None:
360
+ collected.append(current)
361
+
362
+ return collected
363
+
364
+ def visit_let_expression(self, node, value):
365
+ *bindings, expr = node['children']
366
+ scope = {}
367
+ for assign in bindings:
368
+ scope.update(self.visit(assign, value))
369
+ self._scope.push_scope(scope)
370
+ result = self.visit(expr, value)
371
+ self._scope.pop_scope()
372
+ return result
373
+
374
+ def visit_assign(self, node, value):
375
+ name = node['value']
376
+ value = self.visit(node['children'][0], value)
377
+ return {name: value}
378
+
379
+ def visit_variable_ref(self, node, value):
380
+ try:
381
+ return self._scope[node['value']]
382
+ except KeyError:
383
+ raise exceptions.UndefinedVariableError(node['value']) # noqa
384
+
385
+ def visit_value_projection(self, node, value):
386
+ base = self.visit(node['children'][0], value)
387
+ try:
388
+ base = base.values()
389
+ except AttributeError:
390
+ return None
391
+
392
+ collected = []
393
+ for element in base:
394
+ current = self.visit(node['children'][1], element)
395
+ if current is not None:
396
+ collected.append(current)
397
+
398
+ return collected
399
+
400
+ def _is_false(self, value):
401
+ # This looks weird, but we're explicitly using equality checks because the truth/false values are different
402
+ # between python and jmespath.
403
+ return (value == '' or value == [] or value == {} or value is None or value is False) # noqa
404
+
405
+ def _is_true(self, value):
406
+ return not self._is_false(value)
407
+
408
+
409
+ class GraphvizVisitor(Visitor):
410
+ def __init__(self):
411
+ super().__init__()
412
+ self._lines = []
413
+ self._count = 1
414
+
415
+ def visit(self, node, *args, **kwargs):
416
+ self._lines.append('digraph AST {')
417
+ current = f"{node['type']}{self._count}"
418
+ self._count += 1
419
+ self._visit(node, current)
420
+ self._lines.append('}')
421
+ return '\n'.join(self._lines)
422
+
423
+ def _visit(self, node, current):
424
+ self._lines.append('%s [label="%s(%s)"]' % (current, node['type'], node.get('value', ''))) # noqa
425
+ for child in node.get('children', []):
426
+ child_name = f"{child['type']}{self._count}"
427
+ self._count += 1
428
+ self._lines.append(f' {current} -> {child_name}')
429
+ self._visit(child, child_name)
@@ -17,6 +17,12 @@ from .metadata import ( # noqa
17
17
  )
18
18
 
19
19
  from .parse import ( # noqa
20
+ DEFAULT_KEYWORD_SUPERTYPES,
21
+ DEFAULT_KEYWORD_TYPES,
22
+ DEFAULT_KEYWORD_TYPES_BY_TAG,
23
+ DEFAULT_PARSER,
24
+ Parser,
25
+ build_keyword_types_by_tag,
20
26
  parse_keyword,
21
27
  parse_keywords,
22
28
  )
@@ -14,7 +14,7 @@ KeywordT = ta.TypeVar('KeywordT', bound='Keyword')
14
14
  ##
15
15
 
16
16
 
17
- class Keyword(lang.Abstract, lang.PackageSealed):
17
+ class Keyword(lang.Abstract):
18
18
  tag: ta.ClassVar[str]
19
19
 
20
20
  def __init_subclass__(cls, *, tag: str | None = None, **kwargs: ta.Any) -> None:
@@ -6,7 +6,7 @@ from .base import StrKeyword
6
6
  ##
7
7
 
8
8
 
9
- class CoreKeyword(Keyword, lang.Abstract):
9
+ class CoreKeyword(Keyword, lang.Abstract, lang.Sealed):
10
10
  pass
11
11
 
12
12
 
@@ -6,7 +6,7 @@ from .base import StrKeyword
6
6
  ##
7
7
 
8
8
 
9
- class MetadataKeyword(Keyword, lang.Abstract):
9
+ class MetadataKeyword(Keyword, lang.Abstract, lang.Sealed):
10
10
  pass
11
11
 
12
12
 
@@ -4,9 +4,6 @@ import typing as ta
4
4
  from .... import check
5
5
  from .... import collections as col
6
6
  from .... import lang
7
- from . import core # noqa
8
- from . import metadata # noqa
9
- from . import validation # noqa
10
7
  from .base import BooleanKeyword
11
8
  from .base import Keyword
12
9
  from .base import Keywords
@@ -15,6 +12,9 @@ from .base import NumberKeyword
15
12
  from .base import StrKeyword
16
13
  from .base import StrOrStrsKeyword
17
14
  from .base import StrToKeywordsKeyword
15
+ from .core import CoreKeyword
16
+ from .metadata import MetadataKeyword
17
+ from .validation import ValidationKeyword
18
18
 
19
19
 
20
20
  KeywordT = ta.TypeVar('KeywordT', bound=Keyword)
@@ -23,46 +23,79 @@ KeywordT = ta.TypeVar('KeywordT', bound=Keyword)
23
23
  ##
24
24
 
25
25
 
26
- KEYWORD_TYPES_BY_TAG: ta.Mapping[str, type[Keyword]] = col.make_map_by( # noqa
27
- operator.attrgetter('tag'),
28
- (cls for cls in lang.deep_subclasses(Keyword) if not lang.is_abstract_class(cls)),
29
- strict=True,
30
- )
26
+ def build_keyword_types_by_tag(keyword_types: ta.Iterable[type[Keyword]]) -> ta.Mapping[str, type[Keyword]]:
27
+ return col.make_map_by(operator.attrgetter('tag'), keyword_types, strict=True)
31
28
 
32
29
 
33
- def parse_keyword(cls: type[KeywordT], v: ta.Any) -> KeywordT:
34
- if issubclass(cls, BooleanKeyword):
35
- return cls(check.isinstance(v, bool)) # type: ignore
30
+ DEFAULT_KEYWORD_SUPERTYPES: ta.AbstractSet = frozenset([
31
+ CoreKeyword,
32
+ MetadataKeyword,
33
+ ValidationKeyword,
34
+ ])
36
35
 
37
- elif issubclass(cls, NumberKeyword):
38
- return cls(check.isinstance(v, (int, float))) # type: ignore
36
+ DEFAULT_KEYWORD_TYPES: ta.AbstractSet = frozenset(lang.flatten(
37
+ lang.deep_subclasses(st, concrete_only=True) for st in DEFAULT_KEYWORD_SUPERTYPES
38
+ ))
39
39
 
40
- elif issubclass(cls, StrKeyword):
41
- return cls(check.isinstance(v, str)) # type: ignore
40
+ DEFAULT_KEYWORD_TYPES_BY_TAG: ta.Mapping[str, type[Keyword]] = build_keyword_types_by_tag(DEFAULT_KEYWORD_TYPES)
42
41
 
43
- elif issubclass(cls, StrOrStrsKeyword):
44
- ss: str | ta.Sequence[str]
45
- if isinstance(v, str):
46
- ss = v
47
- elif isinstance(v, ta.Iterable):
48
- ss = col.seq_of(check.of_isinstance(str))(v)
42
+
43
+ ##
44
+
45
+
46
+ class Parser:
47
+ def __init__(
48
+ self,
49
+ keyword_types: ta.Iterable[type[Keyword]] | ta.Mapping[str, type[Keyword]] = DEFAULT_KEYWORD_TYPES_BY_TAG,
50
+ ) -> None:
51
+ super().__init__()
52
+
53
+ if isinstance(keyword_types, ta.Mapping):
54
+ self._keyword_types_by_tag = keyword_types
49
55
  else:
50
- raise TypeError(v)
51
- return cls(ss) # type: ignore
56
+ self._keyword_types_by_tag = build_keyword_types_by_tag(keyword_types)
57
+
58
+ def parse_keyword(self, cls: type[KeywordT], v: ta.Any) -> KeywordT:
59
+ if issubclass(cls, BooleanKeyword):
60
+ return cls(check.isinstance(v, bool)) # type: ignore
61
+
62
+ elif issubclass(cls, NumberKeyword):
63
+ return cls(check.isinstance(v, (int, float))) # type: ignore
64
+
65
+ elif issubclass(cls, StrKeyword):
66
+ return cls(check.isinstance(v, str)) # type: ignore
52
67
 
53
- elif issubclass(cls, KeywordsKeyword):
54
- return cls(parse_keywords(v)) # type: ignore
68
+ elif issubclass(cls, StrOrStrsKeyword):
69
+ ss: str | ta.Sequence[str]
70
+ if isinstance(v, str):
71
+ ss = v
72
+ elif isinstance(v, ta.Iterable):
73
+ ss = col.seq_of(check.of_isinstance(str))(v)
74
+ else:
75
+ raise TypeError(v)
76
+ return cls(ss) # type: ignore
55
77
 
56
- elif issubclass(cls, StrToKeywordsKeyword):
57
- return cls({k: parse_keywords(mv) for k, mv in v.items()}) # type: ignore
78
+ elif issubclass(cls, KeywordsKeyword):
79
+ return cls(parse_keywords(v)) # type: ignore
80
+
81
+ elif issubclass(cls, StrToKeywordsKeyword):
82
+ return cls({k: parse_keywords(mv) for k, mv in v.items()}) # type: ignore
83
+
84
+ else:
85
+ raise TypeError(cls)
86
+
87
+ def parse_keywords(self, dct: ta.Mapping[str, ta.Any]) -> Keywords:
88
+ lst: list[Keyword] = []
89
+ for k, v in dct.items():
90
+ cls = self._keyword_types_by_tag[k]
91
+ lst.append(self.parse_keyword(cls, v))
92
+ return Keywords(lst)
93
+
94
+
95
+ ##
58
96
 
59
- else:
60
- raise TypeError(cls)
61
97
 
98
+ DEFAULT_PARSER = Parser()
62
99
 
63
- def parse_keywords(dct: ta.Mapping[str, ta.Any]) -> Keywords:
64
- lst: list[Keyword] = []
65
- for k, v in dct.items():
66
- cls = KEYWORD_TYPES_BY_TAG[k]
67
- lst.append(parse_keyword(cls, v))
68
- return Keywords(lst)
100
+ parse_keyword = DEFAULT_PARSER.parse_keyword
101
+ parse_keywords = DEFAULT_PARSER.parse_keywords
@@ -10,7 +10,7 @@ from .base import StrToKeywordsKeyword
10
10
  ##
11
11
 
12
12
 
13
- class ValidationKeyword(Keyword, lang.Abstract):
13
+ class ValidationKeyword(Keyword, lang.Abstract, lang.Sealed):
14
14
  pass
15
15
 
16
16
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: omlish
3
- Version: 0.0.0.dev46
3
+ Version: 0.0.0.dev48
4
4
  Summary: omlish
5
5
  Author: wrmsr
6
6
  License: BSD-3-Clause