-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathevaluation.py
More file actions
3887 lines (3249 loc) · 149 KB
/
evaluation.py
File metadata and controls
3887 lines (3249 loc) · 149 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
"""
Evaluates CEL expressions given an AST.
There are two implementations:
- Evaluator -- interprets the AST directly.
- Transpiler -- transpiles the AST to Python, compiles the Python to create a code object, and then uses :py:func:`exec` to evaluate the code object.
The general idea is to map CEL operators to Python operators and push the
real work off to Python objects defined by the :py:mod:`celpy.celtypes` module.
CEL operator ``+`` is implemented by a ``"_+_"`` function.
We map this name to :py:func:`operator.add`.
This will then look for :py:meth:`__add__` methods in the various :py:mod:`celpy.celtypes`
types.
In order to deal gracefully with missing and incomplete data,
checked exceptions are used.
A raised exception is turned into first-class :py:class:`celpy.celtypes.Result` object.
They're not raised directly, but instead saved as part of the evaluation so that
short-circuit operators can ignore the exceptions.
This means that Python exceptions like :exc:`TypeError`, :exc:`IndexError`, and :exc:`KeyError`
are caught and transformed into :exc:`CELEvalError` objects.
The :py:class:`celpy.celtypes.Result` type hint is a union of the various values that are encountered
during evaluation. It's a union of the :py:class:`celpy.celtypes.CELTypes` type and the
:exc:`CELEvalError` exception.
.. important:: Debugging
If the OS environment variable :envvar:`CEL_TRACE` is set, then detailed tracing of methods is made available.
To see the trace, set the logging level for ``celpy.Evaluator`` to ``logging.DEBUG``.
"""
import collections
import logging
import operator
import os
import re
import sys
from functools import reduce, wraps
from string import Template
from textwrap import dedent
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Match,
Optional,
Sequence,
Sized,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import lark
import lark.visitors
import re2
import celpy.celtypes
from celpy.celparser import tree_dump
# An Annotation describes a union of types, functions, and function types.
Annotation = Union[
celpy.celtypes.TypeType,
Callable[
..., celpy.celtypes.Value
], # Conversion functions and protobuf message type
Type[celpy.celtypes.FunctionType], # Concrete class for annotations
]
logger = logging.getLogger(f"celpy.{__name__}")
class CELSyntaxError(Exception):
"""CEL Syntax error -- the AST did not have the expected structure."""
def __init__(
self, arg: Any, line: Optional[int] = None, column: Optional[int] = None
) -> None:
super().__init__(arg)
self.line = line
self.column = column
class CELUnsupportedError(Exception):
"""Feature unsupported by this implementation of CEL."""
def __init__(self, arg: Any, line: int, column: int) -> None:
super().__init__(arg)
self.line = line
self.column = column
class CELEvalError(Exception):
"""CEL evaluation problem. This can be saved as a temporary value for later use.
This is politely ignored by logic operators to provide commutative short-circuit.
We provide operator-like special methods so an instance of an error
returns itself when operated on.
"""
def __init__(
self,
*args: Any,
tree: Optional[lark.Tree] = None,
token: Optional[lark.Token] = None,
) -> None:
super().__init__(*args)
self.tree = tree
self.token = token
self.line: Optional[int] = None
self.column: Optional[int] = None
if self.tree:
self.line = self.tree.meta.line
self.column = self.tree.meta.column
if self.token:
self.line = self.token.line
self.column = self.token.column
def __repr__(self) -> str:
cls = self.__class__.__name__
if self.tree and self.token:
# This is rare
return f"{cls}(*{self.args}, tree={tree_dump(self.tree)!r}, token={self.token!r})" # pragma: no cover
elif self.tree:
return f"{cls}(*{self.args}, tree={tree_dump(self.tree)!r})" # pragma: no cover
else:
# Some unit tests do not provide a mock tree.
return f"{cls}(*{self.args})" # pragma: no cover
def with_traceback(self, tb: Any) -> "CELEvalError":
return super().with_traceback(tb)
def __neg__(self) -> "CELEvalError":
return self
def __add__(self, other: Any) -> "CELEvalError":
return self
def __sub__(self, other: Any) -> "CELEvalError":
return self
def __mul__(self, other: Any) -> "CELEvalError":
return self
def __truediv__(self, other: Any) -> "CELEvalError":
return self
def __floordiv__(self, other: Any) -> "CELEvalError":
return self
def __mod__(self, other: Any) -> "CELEvalError":
return self
def __pow__(self, other: Any) -> "CELEvalError":
return self
def __radd__(self, other: Any) -> "CELEvalError":
return self
def __rsub__(self, other: Any) -> "CELEvalError":
return self
def __rmul__(self, other: Any) -> "CELEvalError":
return self
def __rtruediv__(self, other: Any) -> "CELEvalError":
return self
def __rfloordiv__(self, other: Any) -> "CELEvalError":
return self
def __rmod__(self, other: Any) -> "CELEvalError":
return self
def __rpow__(self, other: Any) -> "CELEvalError":
return self
def __eq__(self, other: Any) -> bool:
if isinstance(other, CELEvalError):
return self.args == other.args
return NotImplemented
def __call__(self, *args: Any) -> "CELEvalError":
return self
# The interim results extend ``celtypes`` to include intermediate ``CELEvalError`` exception objects.
# These can be deferred as part of commutative logical_and and logical_or operations.
# It includes the responses to ``type()`` queries, also.
Result = Union[
celpy.celtypes.Value,
CELEvalError,
celpy.celtypes.CELType,
]
# The various functions that apply to CEL data.
# The evaluator's functions expand on the CELTypes to include CELEvalError and the
# celpy.celtypes.CELType union type, also.
CELFunction = Callable[..., Result]
# A combination of a CELType result or a function resulting from identifier evaluation.
Result_Function = Union[
Result,
CELFunction,
]
Exception_Filter = Union[Type[BaseException], Sequence[Type[BaseException]]]
TargetFunc = TypeVar("TargetFunc", bound=CELFunction)
def eval_error(
new_text: str, exc_class: Exception_Filter
) -> Callable[[TargetFunc], TargetFunc]:
"""
Wrap a function to transform native Python exceptions to CEL CELEvalError values.
Any exception of the given class is replaced with the new CELEvalError object.
:param new_text: Text of the exception, e.g., "divide by zero", "no such overload",
this is the return value if the :exc:`CELEvalError` becomes the result.
:param exc_class: A Python exception class to match, e.g. ZeroDivisionError,
or a sequence of exception classes (e.g. (ZeroDivisionError, ValueError))
:return: A decorator that can be applied to a function
to map Python exceptions to :exc:`CELEvalError` instances.
This is used in the ``all()`` and ``exists()`` macros to silently ignore TypeError exceptions.
"""
def concrete_decorator(function: TargetFunc) -> TargetFunc:
@wraps(function)
def new_function(
*args: celpy.celtypes.Value, **kwargs: celpy.celtypes.Value
) -> Result:
try:
return function(*args, **kwargs)
except exc_class as ex: # type: ignore[misc]
logger.debug(
"%s(*%s, **%s) --> %s", function.__name__, args, kwargs, ex
)
_, _, tb = sys.exc_info()
value = CELEvalError(new_text, ex.__class__, ex.args).with_traceback(tb)
value.__cause__ = ex
return value
except Exception:
logger.error("%s(*%s, **%s)", function.__name__, args, kwargs)
raise
return cast(TargetFunc, new_function)
return concrete_decorator
def boolean(
function: Callable[..., celpy.celtypes.Value],
) -> Callable[..., celpy.celtypes.BoolType]:
"""
Wraps operators to create CEL BoolType results.
:param function: One of the operator.lt, operator.gt, etc. comparison functions
:return: Decorated function with type coercion.
"""
@wraps(function)
def bool_function(
a: celpy.celtypes.Value, b: celpy.celtypes.Value
) -> celpy.celtypes.BoolType:
if isinstance(a, CELEvalError):
return a
if isinstance(b, CELEvalError):
return b
result_value = function(a, b)
if result_value == NotImplemented:
return cast(celpy.celtypes.BoolType, result_value)
return celpy.celtypes.BoolType(bool(result_value))
return bool_function
def operator_in(item: Result, container: Result) -> Result:
"""
CEL contains test; ignores type errors.
During evaluation of ``'elem' in [1, 'elem', 2]``,
CEL will raise internal exceptions for ``'elem' == 1`` and ``'elem' == 2``.
The :exc:`TypeError` exceptions are gracefully ignored.
During evaluation of ``'elem' in [1u, 'str', 2, b'bytes']``, however,
CEL will raise internal exceptions every step of the way, and an exception
value is the final result. (Not ``False`` from the one non-exceptional comparison.)
It would be nice to make use of the following::
eq_test = eval_error("no such overload", TypeError)(lambda x, y: x == y)
It seems like ``next(iter(filter(lambda x: eq_test(c, x) for c in container))))``
would do it. But. It's not quite right for the job.
There need to be three results, something :py:func:`filter` doesn't handle.
These are the choices:
- True. There was a item found. Exceptions may or may not have been found.
- False. No item found AND no exceptions.
- CELEvalError. Either:
- No item found AND at least one exception or
- The input item or container itself was already an error
To an extent this is a little like the ``exists()`` macro.
We can think of ``container.contains(item)`` as ``container.exists(r, r == item)``.
However, exists() tends to silence exceptions, where this can expose them.
.. todo:: This may be better done as
``reduce(logical_or, (item == c for c in container), BoolType(False))``
"""
if isinstance(item, CELEvalError):
return item
if isinstance(container, CELEvalError):
return container
result_value: Result = celpy.celtypes.BoolType(False)
for c in cast(Iterable[Result], container):
try:
if c == item:
return celpy.celtypes.BoolType(True)
except TypeError as ex:
logger.debug("operator_in(%s, %s) --> %s", item, container, ex)
result_value = CELEvalError("no such overload", ex.__class__, ex.args)
logger.debug("operator_in(%r, %r) = %r", item, container, result_value)
return result_value
def function_size(container: Result) -> Result:
"""
The size() function applied to a Value.
This is delegated to Python's :py:func:`len`.
size(string) -> int string length
size(bytes) -> int bytes length
size(list(A)) -> int list size
size(map(A, B)) -> int map size
For other types, this will raise a Python :exc:`TypeError`.
(This is captured and becomes an :exc:`CELEvalError` Result.)
.. todo:: check container type for celpy.celtypes.StringType, celpy.celtypes.BytesType,
celpy.celtypes.ListType and celpy.celtypes.MapType
"""
if container is None:
return celpy.celtypes.IntType(0)
sized_container = cast(Sized, container)
result_value = celpy.celtypes.IntType(len(sized_container))
logger.debug("function_size(%r) = %r", container, result_value)
return result_value
def function_contains(
container: Union[
celpy.celtypes.ListType, celpy.celtypes.MapType, celpy.celtypes.StringType
],
item: Result,
) -> Result:
"""
The contains() function applied to a Container and a Value.
THis is delegated to the `contains` method of a class.
"""
return celpy.celtypes.BoolType(container.contains(cast(celpy.celtypes.Value, item)))
def function_startsWith(
string: celpy.celtypes.StringType, fragment: celpy.celtypes.StringType
) -> Result:
return celpy.celtypes.BoolType(string.startswith(fragment))
def function_endsWith(
string: celpy.celtypes.StringType, fragment: celpy.celtypes.StringType
) -> Result:
return celpy.celtypes.BoolType(string.endswith(fragment))
def function_matches(text: str, pattern: str) -> Result:
"""Implementation of the ``match()`` function using ``re2``"""
try:
m = re2.search(pattern, text)
except re2.error as ex:
return CELEvalError("match error", ex.__class__, ex.args)
return celpy.celtypes.BoolType(m is not None)
def function_getDate(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getDate(tz_name))
def function_getDayOfMonth(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getDayOfMonth(tz_name))
def function_getDayOfWeek(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getDayOfWeek(tz_name))
def function_getDayOfYear(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getDayOfYear(tz_name))
def function_getFullYear(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getFullYear(tz_name))
def function_getMonth(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getMonth(tz_name))
def function_getHours(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getHours(tz_name))
def function_getMilliseconds(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getMilliseconds(tz_name))
def function_getMinutes(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getMinutes(tz_name))
def function_getSeconds(
ts: celpy.celtypes.TimestampType,
tz_name: Optional[celpy.celtypes.StringType] = None,
) -> Result:
return celpy.celtypes.IntType(ts.getSeconds(tz_name))
def bool_lt(a: Result, b: Result) -> Result:
return boolean(operator.lt)(a, b)
def bool_le(a: Result, b: Result) -> Result:
return boolean(operator.le)(a, b)
def bool_gt(a: Result, b: Result) -> Result:
return boolean(operator.gt)(a, b)
def bool_ge(a: Result, b: Result) -> Result:
return boolean(operator.ge)(a, b)
def bool_eq(a: Result, b: Result) -> Result:
return boolean(operator.eq)(a, b)
def bool_ne(a: Result, b: Result) -> Result:
return boolean(operator.ne)(a, b)
# User-defined functions can override items in this mapping.
base_functions: dict[str, CELFunction] = {
"!_": celpy.celtypes.logical_not,
"-_": operator.neg,
"_+_": operator.add,
"_-_": operator.sub,
"_*_": operator.mul,
"_/_": operator.truediv,
"_%_": operator.mod,
"_<_": bool_lt,
"_<=_": bool_le,
"_>_": bool_gt,
"_>=_": bool_ge,
"_==_": bool_eq,
"_!=_": bool_ne,
"_in_": operator_in,
"_||_": celpy.celtypes.logical_or,
"_&&_": celpy.celtypes.logical_and,
"_?_:_": celpy.celtypes.logical_condition,
"_[_]": operator.getitem,
# The "methods" are actually named functions that can be overridden.
# The function version delegates to class methods.
# Yes, it's a bunch of indirection, but it permits simple overrides.
# A number of types support "size" and "contains": StringType, MapType, ListType
# This is generally made available via the _in_ operator.
"size": function_size,
"contains": function_contains,
# Universally available
"type": celpy.celtypes.TypeType,
# StringType methods, used by :py:meth:`Evaluator.method_eval`
"endsWith": function_endsWith,
"startsWith": function_startsWith,
"matches": function_matches,
# TimestampType methods. Type details are redundant, but required because of the lambdas
"getDate": function_getDate,
"getDayOfMonth": function_getDayOfMonth,
"getDayOfWeek": function_getDayOfWeek,
"getDayOfYear": function_getDayOfYear,
"getFullYear": function_getFullYear,
"getMonth": function_getMonth,
# TimestampType and DurationType methods
"getHours": function_getHours,
"getMilliseconds": function_getMilliseconds,
"getMinutes": function_getMinutes,
"getSeconds": function_getSeconds,
# type conversion functions
"bool": celpy.celtypes.BoolType,
"bytes": celpy.celtypes.BytesType,
"double": celpy.celtypes.DoubleType,
"duration": celpy.celtypes.DurationType,
"int": celpy.celtypes.IntType,
"list": celpy.celtypes.ListType, # https://github.com/google/cel-spec/issues/123
"map": celpy.celtypes.MapType,
"null_type": type(None),
"string": celpy.celtypes.StringType,
"timestamp": celpy.celtypes.TimestampType,
"uint": celpy.celtypes.UintType,
}
class Referent:
"""
A Name can refer to any of the following things:
- ``Annotation`` -- initially most names are these.
Must be provided as part of the initialization.
- ``CELFunction`` -- a Python function to implement a CEL function or method.
Must be provided as part of the initialization.
The type conversion functions are names in a ``NameContainer``.
- ``NameContainer`` -- some names are these.
This is true when the name is *not* provided as part of the initialization because
we discovered the name during type or environment binding.
- ``celpy.celtypes.Value`` -- many annotations also have values.
These are provided **after** Annotations, and require them.
- ``CELEvalError`` -- This seems unlikely, but we include it because it's possible.
A name can be ambiguous and refer to a nested ``NameContainer`` as well
as a ``celpy.celtypes.Value`` (usually a ``MapType`` instance.)
Object ``b`` has two possible meanings:
- ``b`` is a ``NameContainer`` with ``c``, a string or some other object.
- ``b`` is a ``MapType`` or ``MessageType``, and ``b.c`` is syntax sugar for ``b['c']``.
The "longest name" rule means that the useful value is the "c" object
in the nested ``NameContainer``.
The syntax sugar interpretation is done in the rare case we can't find the ``NameContainer``.
>>> nc = NameContainer("c", celpy.celtypes.StringType)
>>> b = Referent(celpy.celtypes.MapType)
>>> b.value = celpy.celtypes.MapType({"c": "oops"})
>>> b.value == celpy.celtypes.MapType({"c": "oops"})
True
>>> b.container = nc
>>> b.value == nc
True
.. note:: Future Design
A ``Referent`` is (almost) a ``tuple[Annotation, NameContainer | None, Value | NotSetSentinel]``.
The current implementation is stateful, because values are optional and may be added later.
The use of a special sentinel to indicate the value was not set is a little akward.
It's not really a 3-tuple, because NameContainers don't have values; they are a kind of value.
(``None`` is a valid value, and can't be used for this.)
It may be slightly simpler to use a union of two types:
``tuple[Annotation] | tuple[Annotation, NameContainer | Value]``.
One-tuples capture the Annotation for a name; two-tuples capture Annotation and Value (or subsidiary NameContainer).
"""
def __init__(
self,
ref_to: Optional[Annotation] = None,
# TODO: Add value here, also, as a handy short-cut to avoid the value setter.
) -> None:
self.annotation: Optional[Annotation] = None
self.container: Optional["NameContainer"] = None
self._value: Union[
None,
Annotation,
celpy.celtypes.Value,
CELEvalError,
CELFunction,
"NameContainer",
] = None
self._value_set = False # Should NOT be private.
if ref_to:
self.annotation = ref_to
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(annotation={self.annotation!r}, "
f"container={self.container!r}, "
f"_value={self._value!r})"
)
def __eq__(self, other: Any) -> bool:
# TODO: When minimum version >= 3.10, use match statement
if isinstance(other, type(self)):
same = (
self.annotation == other.annotation
and self.container == other.container
and self._value_set == other._value_set
and (self._value == other._value if self._value_set else True)
)
return same
return NotImplemented # pragma: no cover
@property
def value(
self,
) -> Union[
Annotation, celpy.celtypes.Value, CELEvalError, CELFunction, "NameContainer"
]:
"""
The longest-path rule means we prefer ``NameContainer`` over any locally defined value.
Otherwise, we'll provide a value if there is one.
Finally, we'll provide the annotation if there's no value.
:return:
"""
if self.container is not None:
return self.container
elif self._value_set:
return self._value
else:
# Not part of a namespace path. Nor was a value set.
return self.annotation
@value.setter
def value(
self,
ref_to: Union[
Annotation, celpy.celtypes.Value, CELEvalError, CELFunction, "NameContainer"
],
) -> None:
self._value = ref_to
self._value_set = True
def clone(self) -> "Referent":
new = Referent(self.annotation)
new.container = self.container
new._value = self._value
new._value_set = self._value_set
return new
# A name resolution context is a mapping from an identifier to a Value or a ``NameContainer``.
# This reflects some murkiness in the name resolution algorithm that needs to be cleaned up.
Context = Mapping[str, Union[Result, "NameContainer", "CELFunction"]]
# Copied from cel.lark
IDENT = r"[_a-zA-Z][_a-zA-Z0-9]*"
class NameContainer(Dict[str, Referent]):
"""
A namespace that fulfills the CEL name resolution requirement.
::
Scenario: "qualified_identifier_resolution_unchecked"
"namespace resolution should try to find the longest prefix for the evaluator."
NameContainer instances can be chained (via parent) to create a sequence of searchable
locations for a name.
- Local-most is an Activation with local variables within a macro.
These are part of a nested chain of Activations for each macro. Each local activation
is a child with a reference to the parent Activation.
- Parent of any local Activation is the overall Activation for this CEL evaluation.
The overall Activation contains a number of NameContainers:
- The global variable bindings.
- Bindings of function definitions. This is the default set of functions for CEL
plus any add-on functions introduced by C7N.
- The run-time annotations from the environment. There are two kinds:
- Protobuf message definitions. These are types, really.
- Annotations for global variables. The annotations tend to be hidden by the values.
They're in the lookup chain to simplify access to protobuf messages.
- The environment also provides the built-in type names and aliases for the
:mod:`celtypes` package of built-in types.
This means name resolution marches from local-most to remote-most, searching for a binding.
The global variable bindings have a local-most value and a more remote annotation.
The annotations (i.e. protobuf message types) have only a fairly remote annotation without
a value.
.. rubric:: Structure
A ``NameContainer`` is a mapping from names to ``Referent`` instances.
A `Referent` can be one of several things, including...
- A NameContainer further down the path
- An Annotation
- An Annotation and a value
- A CELFunction (In effect, an Annotation of CELFunction, and a value of the function implementation.)
.. rubric:: Life and Content
There are two phases to building the chain of ``NameContainer`` instances.
1. The ``Activation`` creates the initial ``name : annotation`` bindings.
Generally, the names are type names, like "int", bound to :py:class:`celtypes.IntType`.
In some cases, the name is a future variable name, "resource",
bound to :py:class:`celtypes.MapType`.
2. The ``Activation`` updates some variables to provide values.
A name is decomposed into a path to make a tree of nested ``NameContainers``.
Upper-level containers don't (necessarily) have types or values -- they're merely
``NameContainer`` along the path to the target names.
.. rubric:: Resolving Names
See https://github.com/google/cel-spec/blob/master/doc/langdef.md#name-resolution
There are three cases required in the :py:class:`Evaluator` engine.
- Variables and Functions. These are ``Result_Function`` instances: i.e., ordinary values.
- ``Name.Name`` can be navigation into a protobuf package, when ``Name`` is protobuf package.
The idea is to locate the longest possible match.
If a.b is a name to be resolved in the context of a protobuf declaration with scope A.B,
then resolution is attempted, in order, as A.B.a.b, A.a.b, and finally a.b.
To override this behavior, one can use .a.b;
this name will only be attempted to be resolved in the root scope, i.e. as a.b.
- ``Name.Name`` can be syntactic sugar for indexing into a mapping when ``Name`` is a value of
``MapType`` or a ``MessageType``. It's evaluated as if it was ``Name["Name"]``.
This is a fall-back plan if the previous resolution failed.
The longest chain of nested packages *should* be resolved first.
This will happen when each name is a ``NameContainer`` object containing
other ``NameContainer`` objects.
The chain of evaluations for ``IDENT . IDENT . IDENT`` is (in effect)
::
member_dot(member_dot(primary(IDENT), IDENT), IDENT)
This makes the ``member_dot`` processing left associative.
The ``primary(IDENT)`` resolves to a CEL object of some kind.
Once the ``primary(IDENT)`` has been resolved, it establishes a context
for subsequent ``member_dot`` methods.
- If this is a ``MapType`` or a ``MessageType`` with an object,
then ``member_dot`` will pluck out a field value and return this.
- If this is a ``NameContainer`` or a ``PackageType`` then the ``member_dot``
will pluck out a sub-package or ``EnumType`` or ``MessageType``
and return the type object instead of a value.
At some point a ``member_object`` production will build an object from the type.
The evaluator's :meth:`ident_value` method resolves the identifier into the ``Referent``.
.. rubric:: Acceptance Test Cases
We have two names
- `a.b` -> NameContainer in which c = "yeah". (i.e., a.b.c : "yeah")
- `a.b` -> Mapping with {"c": "oops"}.
This means any given name can have as many as three meanings:
- Primarily as a NameContainer. This resolves name.name.name to find the longest
namespace possible.
- Secondarily as a Mapping. This will be a fallback when name.name.name is really
syntactic sugar for name.name['name'].
- Finally as a type annotation.
"""
ident_pat = re.compile(IDENT)
extended_name_path = re.compile(f"^\\.?{IDENT}(?:\\.{IDENT})*$")
logger = logging.getLogger("celpy.NameContainer")
def __init__(
self,
name: Optional[str] = None,
ref_to: Optional[Referent] = None,
parent: Optional["NameContainer"] = None,
) -> None:
if name and ref_to:
super().__init__({name: ref_to})
else:
super().__init__()
self.parent: Optional[NameContainer] = parent
def load_annotations(
self,
names: Mapping[str, Annotation],
) -> None:
"""
Used by an ``Activation`` to build a container used to resolve
long path names into nested NameContainers.
Sets annotations for all supplied identifiers.
``{"name1.name2": annotation}`` becomes two things:
1. nc2 = NameContainer({"name2" : Referent(annotation)})
2. nc1 = NameContainer({"name1" : Referent(nc2)})
:param names: A dictionary of {"name1.name1....": Referent, ...} items.
"""
for name, refers_to in names.items():
# self.logger.debug("load_annotations %r : %r", name, refers_to)
if not self.extended_name_path.match(name):
raise ValueError(f"Invalid name {name}")
context = self
# Expand "name1.name2....": refers_to into ["name1", "name2", ...]: refers_to
*path, final = self.ident_pat.findall(name)
for name in path:
ref = context.setdefault(name, Referent())
if ref.container is None:
ref.container = NameContainer(parent=self.parent)
context = ref.container
context.setdefault(final, Referent(refers_to))
def load_values(self, values: Context) -> None:
"""Update any annotations with actual values."""
for name, refers_to in values.items():
# self.logger.debug("load_values %r : %r", name, refers_to)
if not self.extended_name_path.match(name):
raise ValueError(f"Invalid name {name}")
context = self
# Expand "name1.name2....": refers_to into ["name1", "name2", ...]: refers_to
# Update NameContainer("name1", NameContainer("name2", NameContainer(..., refers_to)))
*path, final = self.ident_pat.findall(name)
for name in path:
ref = context.setdefault(name, Referent())
if ref.container is None:
ref.container = NameContainer(parent=self.parent)
context = ref.container
context.setdefault(final, Referent()) # No annotation previously present.
context[final].value = refers_to
class NotFound(Exception):
"""
Raised locally when a name is not found in the middle of package search.
We can't return ``None`` from find_name because that's a valid value.
"""
pass
@staticmethod
def dict_find_name(
some_dict: Union[Dict[str, Referent], Referent], path: Sequence[str]
) -> Referent:
"""
Recursive navigation into mappings, messages, and packages.
These are not NameContainers (or Activations).
:param some_dict: An instance of a ``MapType``, ``MessageType``, or ``PackageType``.
:param path: sequence of names to follow into the structure.
:returns: Value found down inside the structure.
"""
if path:
head, *tail = path
try:
return NameContainer.dict_find_name(
cast(Dict[str, Referent], some_dict)[head], tail
)
except KeyError:
NameContainer.logger.debug(
"%r not found in %s",
head,
cast(Dict[str, Referent], some_dict).keys(),
)
raise NameContainer.NotFound(path)
else:
# End of the path, we found it.
if isinstance(some_dict, Referent): # pragma: no cover
# Seems unlikely, but, just to be sure...
return some_dict
referent = Referent(celpy.celtypes.MapType)
referent.value = cast(celpy.celtypes.MapType, some_dict)
return referent
def find_name(self, path: List[str]) -> Referent:
"""
Find the name by searching down through nested packages or raise NotFound.
Returns the Value associated with this Name.
This is a kind of in-order tree walk of contained packages.
The collaborator must choose the annotation or the value from the Referent.
.. todo:: Refactored to return Referent.
The collaborator must handle two distinct errors:
1. ``self[head]`` has a ``KeyError`` exception -- while not found on this path, the collaborator should keep searching.
Eventually it will raise a final ``KeyError`` that maps to a ``CELEvalError``
This should be exposed as f"no such member in mapping: {ex.args[0]!r}"
2. ``self[head].value`` has no value and the ``Referent`` returned the annotation instead of the value.
In transpiled Python code, this **should** be exposed as f"undeclared reference to {ex.args[0]!r} (in container {ex.args[1]!r})"
"""
if not path:
# Already fully matched. This ``NameContainer`` is what they were looking for.
referent = Referent()
referent.value = self
return referent
# Find the head of the path.
head, *tail = path
try:
sub_context = self[head]
except KeyError:
self.logger.debug("%r not found in %r", head, list(self.keys()))
raise NameContainer.NotFound(path)
if not tail:
# Found what they were looking for
return sub_context
# There are several special cases for the continued search.
self.logger.debug("%r %r %r", head, tail, sub_context)
# We found a NameContainer, simple recursion will do.
item: Referent
if sub_context.container: # isinstance(sub_context, NameContainer):
return sub_context.container.find_name(tail)
# Uncommon case: value with no annotation, and the value is a Message, Mapping, or Package
elif sub_context._value_set and isinstance(
sub_context.value,