forked from cloud-custodian/cel-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathceltypes.py
More file actions
1495 lines (1152 loc) · 48 KB
/
celtypes.py
File metadata and controls
1495 lines (1152 loc) · 48 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.
"""
Provides wrappers over Python types to provide CEL semantics.
This can be used by a Python module to work with CEL-friendly values and CEL results.
Examples of distinctions between CEL and Python:
- Unlike Python ``bool``, CEL :py:class:`BoolType` won't do some math.
- CEL has ``int64`` and ``uint64`` subclasses of integer. These have specific ranges and
raise :exc:`ValueError` errors on overflow.
CEL types will raise :exc:`ValueError` for out-of-range values and :exc:`TypeError`
for operations they refuse.
The :py:mod:`evaluation` module can capture these exceptions and turn them into result values.
This can permit the logic operators to quietly silence them via "short-circuiting".
In the normal course of events, CEL's evaluator may attempt operations between a
CEL exception result and an instance of one of CEL types.
We rely on this leading to an ordinary Python :exc:`TypeError` to be raised to propogate
the error. Or. A logic operator may discard the error object.
The :py:mod:`evaluation` module extends these types with it's own :exc:`CELEvalError` exception.
We try to keep that as a separate concern from the core operator implementations here.
We leverage Python features, which means raising exceptions when there is a problem.
Types
=============
See https://github.com/google/cel-go/tree/master/common/types
These are the Go type definitions that are used by CEL:
- BoolType
- BytesType
- DoubleType
- DurationType
- IntType
- ListType
- MapType
- NullType
- StringType
- TimestampType
- TypeType
- UintType
The above types are handled directly byt CEL syntax.
e.g., ``42`` vs. ``42u`` vs. ``"42"`` vs. ``b"42"`` vs. ``42.``.
We provide matching Python class names for each of these types. The Python type names
are subclasses of Python native types, allowing a client to transparently work with
CEL results. A Python host should be able to provide values to CEL that will be tolerated.
A type hint of ``Value`` unifies these into a common hint.
The CEL Go implementation also supports protobuf types:
- dpb.Duration
- tpb.Timestamp
- structpb.ListValue
- structpb.NullValue
- structpb.Struct
- structpb.Value
- wrapperspb.BoolValue
- wrapperspb.BytesValue
- wrapperspb.DoubleValue
- wrapperspb.FloatValue
- wrapperspb.Int32Value
- wrapperspb.Int64Value
- wrapperspb.StringValue
- wrapperspb.UInt32Value
- wrapperspb.UInt64Value
These types involve expressions like the following::
google.protobuf.UInt32Value{value: 123u}
In this case, the well-known protobuf name is directly visible as CEL syntax.
There's a ``google`` package with the needed definitions.
Type Provider
==============================
A type provider can be bound to the environment, this will support additional types.
This appears to be a factory to map names of types to type classes.
Run-time type binding is shown by a CEL expression like the following::
TestAllTypes{single_uint32_wrapper: 432u}
The ``TestAllTypes`` is a protobuf type added to the CEL run-time. The syntax
is defined by this syntax rule::
member_object : member "{" [fieldinits] "}"
The ``member`` is part of a type provider library,
either a standard protobuf definition or an extension. The field inits build
values for the protobuf object.
See https://github.com/google/cel-go/blob/master/test/proto3pb/test_all_types.proto
for the ``TestAllTypes`` protobuf definition that is registered as a type provider.
This expression will describes a Protobuf ``uint32`` object.
Type Adapter
=============
So far, it appears that a type adapter wraps existing Go or C++ types
with CEL-required methods. This seems like it does not need to be implemented
in Python.
Numeric Details
===============
Integer division truncates toward zero.
The Go definition of modulus::
// Mod returns the floating-point remainder of x/y.
// The magnitude of the result is less than y and its
// sign agrees with that of x.
https://golang.org/ref/spec#Arithmetic_operators
"Go has the nice property that -a/b == -(a/b)."
::
x y x / y x % y
5 3 1 2
-5 3 -1 -2
5 -3 -1 2
-5 -3 1 -2
Python definition::
The modulo operator always yields a result
with the same sign as its second operand (or zero);
the absolute value of the result is strictly smaller than
the absolute value of the second operand.
Here's the essential rule::
x//y * y + x%y == x
However. Python ``//`` truncates toward negative infinity. Go ``/`` truncates toward zero.
To get Go-like behavior, we need to use absolute values and restore the signs later.
::
x_sign = -1 if x < 0 else +1
go_mod = x_sign * (abs(x) % abs(y))
return go_mod
Timzone Details
===============
An implementation may have additional timezone names that must be injected into
the ``pendulum`` processing. (Formerly ``dateutil.gettz()``.)
For example, there may be the following sequence:
1. A lowercase match for an alias or an existing timezone.
2. A titlecase match for an existing timezone.
3. The fallback, which is a +/-HH:MM string.
.. TODO: Permit an extension into the timezone lookup.
"""
import datetime
import logging
import re
from functools import reduce, wraps
from math import fsum, trunc
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
NoReturn,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
import pendulum
from pendulum import timezone
import pendulum.tz.exceptions
logger = logging.getLogger(f"celpy.{__name__}")
Value = Union[
"BoolType",
"BytesType",
"DoubleType",
"DurationType",
"IntType",
"ListType",
"MapType",
None, # Used instead of NullType
"StringType",
"TimestampType",
"UintType",
]
# The domain of types used to build Annotations.
CELType = Union[
Type["BoolType"],
Type["BytesType"],
Type["DoubleType"],
Type["DurationType"],
Type["IntType"],
Type["ListType"],
Type["MapType"],
Callable[..., None], # Used instead of NullType
Type["StringType"],
Type["TimestampType"],
Type["TypeType"], # Used to mark Protobuf Type values
Type["UintType"],
Type["PackageType"],
Type["MessageType"],
]
def type_matched(method: Callable[[Any, Any], Any]) -> Callable[[Any, Any], Any]:
"""Decorates a method to assure the "other" value has the same type."""
@wraps(method)
def type_matching_method(self: Any, other: Any) -> Any:
if not (
issubclass(type(other), type(self)) or issubclass(type(self), type(other))
):
raise TypeError(
f"no such overload: {self!r} {type(self)} != {other!r} {type(other)}"
)
return method(self, other)
return type_matching_method
def logical_condition(e: Value, x: Value, y: Value) -> Value:
"""
CEL e ? x : y operator.
Choose one of x or y. Exceptions in the unchosen expression are ignored.
Example::
2 / 0 > 4 ? 'baz' : 'quux'
is a "division by zero" error.
::
>>> logical_condition(
... BoolType(True), StringType("this"), StringType("Not That"))
StringType('this')
>>> logical_condition(
... BoolType(False), StringType("Not This"), StringType("that"))
StringType('that')
.. TODO:: Consider passing closures instead of Values.
The function can evaluate e().
If it's True, return x().
If it's False, return y().
Otherwise, it's a CELEvalError, which is the result
"""
if not isinstance(e, BoolType):
raise TypeError(f"Unexpected {type(e)} ? {type(x)} : {type(y)}")
result_value = x if e else y
logger.debug("logical_condition(%r, %r, %r) = %r", e, x, y, result_value)
return result_value
def logical_and(x: Value, y: Value) -> Value:
"""
Native Python has a left-to-right rule.
CEL && is commutative with non-Boolean values, including error objects.
.. TODO:: Consider passing closures instead of Values.
The function can evaluate x().
If it's False, then return False.
Otherwise, it's True or a CELEvalError, return y().
"""
if not isinstance(x, BoolType) and not isinstance(y, BoolType):
raise TypeError(f"{type(x)} {x!r} and {type(y)} {y!r}")
elif not isinstance(x, BoolType) and isinstance(y, BoolType):
if y:
return x # whatever && true == whatever
else:
return y # whatever && false == false
elif isinstance(x, BoolType) and not isinstance(y, BoolType):
if x:
return y # true && whatever == whatever
else:
return x # false && whatever == false
else:
return BoolType(cast(BoolType, x) and cast(BoolType, y))
def logical_not(x: Value) -> Value:
"""
A function for native python `not`.
This could almost be `logical_or = evaluation.boolean(operator.not_)`,
but the definition would expose Python's notion of "truthiness", which isn't appropriate for CEL.
"""
if isinstance(x, BoolType):
result_value = BoolType(not x)
else:
raise TypeError(f"not {type(x)}")
logger.debug("logical_not(%r) = %r", x, result_value)
return result_value
def logical_or(x: Value, y: Value) -> Value:
"""
Native Python has a left-to-right rule: ``(True or y)`` is True, ``(False or y)`` is y.
CEL ``||`` is commutative with non-Boolean values, including errors.
``(x || false)`` is ``x``, and ``(false || y)`` is ``y``.
Example 1::
false || 1/0 != 0
is a "no matching overload" error.
Example 2::
(2 / 0 > 3 ? false : true) || true
is a "True"
If the operand(s) are not ``BoolType``, we'll create an ``TypeError`` that will become a ``CELEvalError``.
.. TODO:: Consider passing closures instead of Values.
The function can evaluate x().
If it's True, then return True.
Otherwise, it's False or a CELEvalError, return y().
"""
if not isinstance(x, BoolType) and not isinstance(y, BoolType):
raise TypeError(f"{type(x)} {x!r} or {type(y)} {y!r}")
elif not isinstance(x, BoolType) and isinstance(y, BoolType):
if y:
return y # whatever || true == true
else:
return x # whatever || false == whatever
elif isinstance(x, BoolType) and not isinstance(y, BoolType):
if x:
return x # true || whatever == true
else:
return y # false || whatever == whatever
else:
return BoolType(cast(BoolType, x) or cast(BoolType, y))
class BoolType(int):
"""
Native Python permits all unary operators to work on ``bool`` objects.
For CEL, we need to prevent the CEL expression ``-false`` from working.
"""
def __new__(cls: Type["BoolType"], source: Any) -> "BoolType":
if source is None:
return super().__new__(cls, 0)
elif isinstance(source, BoolType):
return source
elif isinstance(source, MessageType):
return super().__new__(cls, cast(int, source.get(StringType("value"))))
elif isinstance(source, (str, StringType)):
if source in ("False", "f", "FALSE", "false"):
return super().__new__(cls, 0)
elif source in ("True", "t", "TRUE", "true"):
return super().__new__(cls, 1)
return super().__new__(cls, source)
else:
return super().__new__(cls, source)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({bool(self)})"
def __str__(self) -> str:
return str(bool(self))
def __neg__(self) -> NoReturn:
raise TypeError("no such overload")
def __hash__(self) -> int:
return super().__hash__()
class BytesType(bytes):
"""Python's bytes semantics are close to CEL."""
def __new__(
cls: Type["BytesType"],
source: Union[str, bytes, Iterable[int], "BytesType", "StringType"],
*args: Any,
**kwargs: Any,
) -> "BytesType":
if source is None:
return super().__new__(cls, b"")
elif isinstance(source, (bytes, BytesType)):
return super().__new__(cls, source)
elif isinstance(source, (str, StringType)):
return super().__new__(cls, source.encode("utf-8"))
elif isinstance(source, MessageType):
return super().__new__(
cls,
cast(bytes, source.get(StringType("value"))),
)
elif isinstance(source, Iterable):
return super().__new__(cls, source)
else:
raise TypeError(f"Invalid initial value type: {type(source)}")
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def contains(self, item: Value) -> BoolType:
return BoolType(cast(BytesType, item) in self) # type: ignore [comparison-overlap]
class DoubleType(float):
"""
Native Python permits mixed type comparisons, doing conversions as needed.
For CEL, we need to prevent mixed-type comparisons from working.
TODO: Conversions from string? IntType? UintType? DoubleType?
"""
def __new__(cls: Type["DoubleType"], source: Any) -> "DoubleType":
if source is None:
return super().__new__(cls, 0)
elif isinstance(source, MessageType):
return super().__new__(cls, cast(float, source.get(StringType("value"))))
else:
return super().__new__(cls, source)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def __str__(self) -> str:
text = str(float(self))
return text
def __neg__(self) -> "DoubleType":
return DoubleType(super().__neg__())
def __mod__(self, other: Any) -> NoReturn:
raise TypeError(
f"found no matching overload for '_%_' applied to '(double, {type(other)})'"
)
def __truediv__(self, other: Any) -> "DoubleType":
if cast(float, other) == 0.0:
return DoubleType("inf")
else:
return DoubleType(super().__truediv__(other))
def __rmod__(self, other: Any) -> NoReturn:
raise TypeError(
f"found no matching overload for '_%_' applied to '({type(other)}, double)'"
)
def __rtruediv__(self, other: Any) -> "DoubleType":
if self == 0.0:
return DoubleType("inf")
else:
return DoubleType(super().__rtruediv__(other))
@type_matched
def __eq__(self, other: Any) -> bool:
return super().__eq__(other)
@type_matched
def __ne__(self, other: Any) -> bool:
return super().__ne__(other)
def __hash__(self) -> int:
return super().__hash__()
IntOperator = TypeVar("IntOperator", bound=Callable[..., int])
def int64(operator: IntOperator) -> IntOperator:
"""Apply an operation, but assure the value is within the int64 range."""
@wraps(operator)
def clamped_operator(*args: Any, **kwargs: Any) -> int:
result_value: int = operator(*args, **kwargs)
if -(2**63) <= result_value < 2**63:
return result_value
raise ValueError("overflow")
return cast(IntOperator, clamped_operator)
class IntType(int):
"""
A version of int with overflow errors outside int64 range.
features/integer_math.feature:277 "int64_overflow_positive"
>>> IntType(9223372036854775807) + IntType(1)
Traceback (most recent call last):
...
ValueError: overflow
>>> 2**63
9223372036854775808
features/integer_math.feature:285 "int64_overflow_negative"
>>> -IntType(9223372036854775808) - IntType(1)
Traceback (most recent call last):
...
ValueError: overflow
>>> IntType(DoubleType(1.9))
IntType(1)
>>> IntType(DoubleType(-123.456))
IntType(-123)
"""
def __new__(
cls: Type["IntType"], source: Any, *args: Any, **kwargs: Any
) -> "IntType":
convert: Callable[..., int]
if source is None:
return super().__new__(cls, 0)
elif isinstance(source, IntType):
return source
elif isinstance(source, MessageType):
# Used by protobuf.
return super().__new__(cls, cast(int, source.get(StringType("value"))))
elif isinstance(source, (float, DoubleType)):
convert = int64(trunc)
elif isinstance(source, TimestampType):
convert = int64(lambda src: src.timestamp())
elif isinstance(source, (str, StringType)) and source[:2] in {"0x", "0X"}:
convert = int64(lambda src: int(src[2:], 16))
elif isinstance(source, (str, StringType)) and source[:3] in {"-0x", "-0X"}:
convert = int64(lambda src: -int(src[3:], 16))
else:
# Must tolerate "-" as part of the literal.
# See https://github.com/google/cel-spec/issues/126
convert = int64(int)
return super().__new__(cls, convert(source))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def __str__(self) -> str:
text = str(int(self))
return text
@int64
def __neg__(self) -> "IntType":
return IntType(super().__neg__())
@int64
def __add__(self, other: Any) -> "IntType":
return IntType(super().__add__(cast(IntType, other)))
@int64
def __sub__(self, other: Any) -> "IntType":
return IntType(super().__sub__(cast(IntType, other)))
@int64
def __mul__(self, other: Any) -> "IntType":
return IntType(super().__mul__(cast(IntType, other)))
@int64
def __truediv__(self, other: Any) -> "IntType":
other = cast(IntType, other)
self_sign = -1 if self < IntType(0) else +1
other_sign = -1 if other < IntType(0) else +1
go_div = self_sign * other_sign * (abs(self) // abs(other))
return IntType(go_div)
__floordiv__ = __truediv__
@int64
def __mod__(self, other: Any) -> "IntType":
self_sign = -1 if self < IntType(0) else +1
go_mod = self_sign * (abs(self) % abs(cast(IntType, other)))
return IntType(go_mod)
@int64
def __radd__(self, other: Any) -> "IntType":
return IntType(super().__radd__(cast(IntType, other)))
@int64
def __rsub__(self, other: Any) -> "IntType":
return IntType(super().__rsub__(cast(IntType, other)))
@int64
def __rmul__(self, other: Any) -> "IntType":
return IntType(super().__rmul__(cast(IntType, other)))
@int64
def __rtruediv__(self, other: Any) -> "IntType":
other = cast(IntType, other)
self_sign = -1 if self < IntType(0) else +1
other_sign = -1 if other < IntType(0) else +1
go_div = self_sign * other_sign * (abs(other) // abs(self))
return IntType(go_div)
__rfloordiv__ = __rtruediv__
@int64
def __rmod__(self, other: Any) -> "IntType":
left_sign = -1 if other < IntType(0) else +1
go_mod = left_sign * (abs(other) % abs(self))
return IntType(go_mod)
@type_matched
def __eq__(self, other: Any) -> bool:
return super().__eq__(other)
@type_matched
def __ne__(self, other: Any) -> bool:
return super().__ne__(other)
@type_matched
def __lt__(self, other: Any) -> bool:
return super().__lt__(other)
@type_matched
def __le__(self, other: Any) -> bool:
return super().__le__(other)
@type_matched
def __gt__(self, other: Any) -> bool:
return super().__gt__(other)
@type_matched
def __ge__(self, other: Any) -> bool:
return super().__ge__(other)
def __hash__(self) -> int:
return super().__hash__()
def uint64(operator: IntOperator) -> IntOperator:
"""Apply an operation, but assure the value is within the uint64 range."""
@wraps(operator)
def clamped_operator(*args: Any, **kwargs: Any) -> int:
result_value = operator(*args, **kwargs)
if 0 <= result_value < 2**64:
return result_value
raise ValueError("overflow")
return cast(IntOperator, clamped_operator)
class UintType(int):
"""
A version of int with overflow errors outside uint64 range.
Alternatives:
Option 1 - Use https://pypi.org/project/fixedint/
Option 2 - use array or struct modules to access an unsigned object.
Test Cases:
features/integer_math.feature:149 "unary_minus_no_overload"
>>> -UintType(42)
Traceback (most recent call last):
...
TypeError: no such overload
uint64_overflow_positive
>>> UintType(18446744073709551615) + UintType(1)
Traceback (most recent call last):
...
ValueError: overflow
uint64_overflow_negative
>>> UintType(0) - UintType(1)
Traceback (most recent call last):
...
ValueError: overflow
>>> - UintType(5)
Traceback (most recent call last):
...
TypeError: no such overload
"""
def __new__(
cls: Type["UintType"], source: Any, *args: Any, **kwargs: Any
) -> "UintType":
convert: Callable[..., int]
if isinstance(source, UintType):
return source
elif isinstance(source, (float, DoubleType)):
convert = uint64(trunc)
elif isinstance(source, TimestampType):
convert = uint64(lambda src: src.timestamp())
elif isinstance(source, (str, StringType)) and source[:2] in {"0x", "0X"}:
convert = uint64(lambda src: int(src[2:], 16))
elif isinstance(source, MessageType):
# Used by protobuf.
convert = uint64(
lambda src: src["value"] if src["value"] is not None else 0
)
elif source is None:
convert = uint64(lambda src: 0)
else:
convert = uint64(int)
return super().__new__(cls, convert(source))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def __str__(self) -> str:
text = str(int(self))
return text
def __neg__(self) -> NoReturn:
raise TypeError("no such overload")
@uint64
def __add__(self, other: Any) -> "UintType":
return UintType(super().__add__(cast(IntType, other)))
@uint64
def __sub__(self, other: Any) -> "UintType":
return UintType(super().__sub__(cast(IntType, other)))
@uint64
def __mul__(self, other: Any) -> "UintType":
return UintType(super().__mul__(cast(IntType, other)))
@uint64
def __truediv__(self, other: Any) -> "UintType":
return UintType(super().__floordiv__(cast(IntType, other)))
__floordiv__ = __truediv__
@uint64
def __mod__(self, other: Any) -> "UintType":
return UintType(super().__mod__(cast(IntType, other)))
@uint64
def __radd__(self, other: Any) -> "UintType":
return UintType(super().__radd__(cast(IntType, other)))
@uint64
def __rsub__(self, other: Any) -> "UintType":
return UintType(super().__rsub__(cast(IntType, other)))
@uint64
def __rmul__(self, other: Any) -> "UintType":
return UintType(super().__rmul__(cast(IntType, other)))
@uint64
def __rtruediv__(self, other: Any) -> "UintType":
return UintType(super().__rfloordiv__(cast(IntType, other)))
__rfloordiv__ = __rtruediv__
@uint64
def __rmod__(self, other: Any) -> "UintType":
return UintType(super().__rmod__(cast(IntType, other)))
@type_matched
def __eq__(self, other: Any) -> bool:
return super().__eq__(other)
@type_matched
def __ne__(self, other: Any) -> bool:
return super().__ne__(other)
def __hash__(self) -> int:
return super().__hash__()
class ListType(List[Value]):
"""
Native Python implements comparison operations between list objects.
For CEL, we prevent list comparison operators from working.
We provide an :py:meth:`__eq__` and :py:meth:`__ne__` that
gracefully ignore type mismatch problems, calling them not equal.
See https://github.com/google/cel-spec/issues/127
An implied logical And means a singleton behaves in a distinct way from a non-singleton list.
"""
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def __lt__(self, other: Any) -> NoReturn:
raise TypeError("no such overload")
def __le__(self, other: Any) -> NoReturn:
raise TypeError("no such overload")
def __gt__(self, other: Any) -> NoReturn:
raise TypeError("no such overload")
def __ge__(self, other: Any) -> NoReturn:
raise TypeError("no such overload")
def __eq__(self, other: Any) -> bool:
if other is None:
return False
if not isinstance(other, (list, ListType)):
raise TypeError(f"no such overload: ListType == {type(other)}")
def equal(s: Any, o: Any) -> Value:
try:
return BoolType(s == o)
except TypeError as ex:
return cast(BoolType, ex) # Instead of Union[BoolType, TypeError]
result_value = len(self) == len(other) and reduce(
logical_and, # type: ignore [arg-type]
(equal(item_s, item_o) for item_s, item_o in zip(self, other)),
BoolType(True),
)
if isinstance(result_value, TypeError):
raise result_value
return bool(result_value)
def __ne__(self, other: Any) -> bool:
if not isinstance(other, (list, ListType)):
raise TypeError(f"no such overload: ListType != {type(other)}")
def not_equal(s: Any, o: Any) -> Value:
try:
return BoolType(s != o)
except TypeError as ex:
return cast(BoolType, ex) # Instead of Union[BoolType, TypeError]
result_value = len(self) != len(other) or reduce(
logical_or, # type: ignore [arg-type]
(not_equal(item_s, item_o) for item_s, item_o in zip(self, other)),
BoolType(False),
)
if isinstance(result_value, TypeError):
raise result_value
return bool(result_value)
def contains(self, item: Value) -> BoolType:
return BoolType(item in self)
BaseMapTypes = Union[Mapping[Any, Any], Sequence[Tuple[Any, Any]], None]
MapKeyTypes = Union["IntType", "UintType", "BoolType", "StringType", str]
class MapType(Dict[Value, Value]):
"""
Native Python allows mapping updates and any hashable type as a kay.
CEL prevents mapping updates and has a limited domain of key types.
int, uint, bool, or string keys
We provide an :py:meth:`__eq__` and :py:meth:`__ne__` that
gracefully ignore type mismatch problems for the values, calling them not equal.
See https://github.com/google/cel-spec/issues/127
An implied logical And means a singleton behaves in a distinct way from a non-singleton mapping.
"""
def __init__(self, items: BaseMapTypes = None) -> None:
super().__init__()
if items is None:
pass
elif isinstance(items, Sequence):
# Must Be Unique
for name, value in items:
if name in self:
raise ValueError(f"Duplicate key {name!r}")
self[name] = value
elif isinstance(items, Mapping):
for name, value in items.items():
self[name] = value
else:
raise TypeError(f"Invalid initial value type: {type(items)}")
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def __getitem__(self, key: Any) -> Any:
if not MapType.valid_key_type(key):
raise TypeError(f"unsupported key type: {type(key)}")
return super().__getitem__(key)
def __eq__(self, other: Any) -> bool:
if other is None:
return False
if not isinstance(other, (Mapping, MapType)):
raise TypeError(f"no such overload: MapType == {type(other)}")
def equal(s: Any, o: Any) -> BoolType:
try:
return BoolType(s == o)
except TypeError as ex:
return cast(BoolType, ex) # Instead of Union[BoolType, TypeError]
keys_s = self.keys()
keys_o = other.keys()
result_value = keys_s == keys_o and reduce(
logical_and, # type: ignore [arg-type]
(equal(self[k], other[k]) for k in keys_s),
BoolType(True),
)
if isinstance(result_value, TypeError):
raise result_value
return bool(result_value)
def __ne__(self, other: Any) -> bool:
if not isinstance(other, (Mapping, MapType)):
raise TypeError(f"no such overload: MapType != {type(other)}")
# Singleton special case, may return no-such overload.
if len(self) == 1 and len(other) == 1 and self.keys() == other.keys():
k = next(iter(self.keys()))
return cast(
bool, self[k] != other[k]
) # Instead of Union[BoolType, TypeError]
def not_equal(s: Any, o: Any) -> BoolType:
try:
return BoolType(s != o)
except TypeError as ex:
return cast(BoolType, ex) # Instead of Union[BoolType, TypeError]
keys_s = self.keys()
keys_o = other.keys()
result_value = keys_s != keys_o or reduce(
logical_or, # type: ignore [arg-type]
(not_equal(self[k], other[k]) for k in keys_s),
BoolType(False),
)
if isinstance(result_value, TypeError):
raise result_value
return bool(result_value)
def get(self, key: Any, default: Optional[Any] = None) -> Value:
"""There is no default provision in CEL, that's a Python feature."""
if not MapType.valid_key_type(key):
raise TypeError(f"unsupported key type: {type(key)}")
if key in self:
return super().get(key)
elif default is not None:
return cast(Value, default)
else:
raise KeyError(key)