forked from google/cel-go
/
decls.go
1133 lines (1050 loc) · 35.3 KB
/
decls.go
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
// Copyright 2022 Google 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.
package cel
import (
"fmt"
"strings"
"github.com/google/cel-go/checker/decls"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/interpreter/functions"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// Kind indicates a CEL type's kind which is used to differentiate quickly between simple and complex types.
type Kind uint
const (
// DynKind represents a dynamic type. This kind only exists at type-check time.
DynKind Kind = iota
// AnyKind represents a google.protobuf.Any type. This kind only exists at type-check time.
AnyKind
// BoolKind represents a boolean type.
BoolKind
// BytesKind represents a bytes type.
BytesKind
// DoubleKind represents a double type.
DoubleKind
// DurationKind represents a CEL duration type.
DurationKind
// IntKind represents an integer type.
IntKind
// ListKind represents a list type.
ListKind
// MapKind represents a map type.
MapKind
// NullTypeKind represents a null type.
NullTypeKind
// OpaqueKind represents an abstract type which has no accessible fields.
OpaqueKind
// StringKind represents a string type.
StringKind
// StructKind represents a structured object with typed fields.
StructKind
// TimestampKind represents a a CEL time type.
TimestampKind
// TypeKind represents the CEL type.
TypeKind
// TypeParamKind represents a parameterized type whose type name will be resolved at type-check time, if possible.
TypeParamKind
// UintKind represents a uint type.
UintKind
)
var (
// AnyType represents the google.protobuf.Any type.
AnyType = &Type{
kind: AnyKind,
runtimeType: types.NewTypeValue("google.protobuf.Any"),
}
// BoolType represents the bool type.
BoolType = &Type{
kind: BoolKind,
runtimeType: types.BoolType,
}
// BytesType represents the bytes type.
BytesType = &Type{
kind: BytesKind,
runtimeType: types.BytesType,
}
// DoubleType represents the double type.
DoubleType = &Type{
kind: DoubleKind,
runtimeType: types.DoubleType,
}
// DurationType represents the CEL duration type.
DurationType = &Type{
kind: DurationKind,
runtimeType: types.DurationType,
}
// DynType represents a dynamic CEL type whose type will be determined at runtime from context.
DynType = &Type{
kind: DynKind,
runtimeType: types.NewTypeValue("dyn"),
}
// IntType represents the int type.
IntType = &Type{
kind: IntKind,
runtimeType: types.IntType,
}
// NullType represents the type of a null value.
NullType = &Type{
kind: NullTypeKind,
runtimeType: types.NullType,
}
// StringType represents the string type.
StringType = &Type{
kind: StringKind,
runtimeType: types.StringType,
}
// TimestampType represents the time type.
TimestampType = &Type{
kind: TimestampKind,
runtimeType: types.TimestampType,
}
// TypeType represents a CEL type
TypeType = &Type{
kind: TypeKind,
runtimeType: types.TypeType,
}
//UintType represents a uint type.
UintType = &Type{
kind: UintKind,
runtimeType: types.UintType,
}
)
// Type holds a reference to a runtime type with an optional type-checked set of type parameters.
type Type struct {
// kind indicates general category of the type.
kind Kind
// runtimeType is the runtime type of the declaration.
runtimeType ref.Type
// parameters holds the optional type-checked set of type parameters that are used during static analysis.
parameters []*Type
// isAssignableType function determines whether one type is assignable to this type.
// A nil value for the isAssignableType function falls back to equality of kind, runtimeType, and parameters.
isAssignableType func(other *Type) bool
// isAssignableRuntimeType function determines whether the runtime type (with erasure) is assignable to this type.
// A nil value for the isAssignableRuntimeType function falls back to the equality of the type or type name.
isAssignableRuntimeType func(other ref.Type) bool
}
// IsAssignableType determines whether the current type is type-check assignable from the input fromType.
func (t *Type) IsAssignableType(fromType *Type) bool {
if t.isAssignableType != nil {
return t.isAssignableType(fromType)
}
return t.defaultIsAssignableType(fromType)
}
// IsAssignableRuntimeType determines whether the current type is runtime assignable from the input runtimeType.
//
// At runtime, parameterized types are erased and so a function which type-checks to support a map(string, string)
// will have a runtime assignable type of a map.
func (t *Type) IsAssignableRuntimeType(runtimeType ref.Type) bool {
if t.isAssignableRuntimeType != nil {
return t.isAssignableRuntimeType(runtimeType)
}
return t.defaultIsAssignableRuntimeType(runtimeType)
}
// String returns a human-readable definition of the type name.
func (t *Type) String() string {
if len(t.parameters) == 0 {
return t.runtimeType.TypeName()
}
params := make([]string, len(t.parameters))
for i, p := range t.parameters {
params[i] = p.String()
}
return fmt.Sprintf("%s(%s)", t.runtimeType.TypeName(), strings.Join(params, ", "))
}
// isDyn indicates whether the type is dynamic in any way.
func (t *Type) isDyn() bool {
return t.kind == DynKind || t.kind == AnyKind || t.kind == TypeParamKind
}
// equals indicates whether two types have the same kind, type name, and parameters.
func (t *Type) equals(other *Type) bool {
if t.kind != other.kind ||
t.runtimeType.TypeName() != other.runtimeType.TypeName() ||
len(t.parameters) != len(other.parameters) {
return false
}
for i, p := range t.parameters {
if !p.equals(other.parameters[i]) {
return false
}
}
return true
}
// defaultIsAssignableType provides the standard definition of what it means for one type to be assignable to another
// where any of the following may return a true result:
// - The from types are the same instance
// - The target type is dynamic
// - The fromType has the same kind and type name as the target type, and all parameters of the target type
// are IsAssignableType() from the parameters of the fromType.
func (t *Type) defaultIsAssignableType(fromType *Type) bool {
if t == fromType || t.isDyn() {
return true
}
if t.kind != fromType.kind ||
t.runtimeType.TypeName() != fromType.runtimeType.TypeName() ||
len(t.parameters) != len(fromType.parameters) {
return false
}
for i, tp := range t.parameters {
fp := fromType.parameters[i]
if !tp.IsAssignableType(fp) {
return false
}
}
return true
}
func (t *Type) defaultIsAssignableRuntimeType(runtimeType ref.Type) bool {
return t.runtimeType == runtimeType || t.isDyn() || t.runtimeType.TypeName() == runtimeType.TypeName()
}
// ListType creates an instances of a list type value with the provided element type.
func ListType(elemType *Type) *Type {
return &Type{
kind: ListKind,
runtimeType: types.ListType,
parameters: []*Type{elemType},
}
}
// MapType creates an instance of a map type value with the provided key and value types.
func MapType(keyType, valueType *Type) *Type {
return &Type{
kind: MapKind,
runtimeType: types.MapType,
parameters: []*Type{keyType, valueType},
}
}
// NullableType creates an instance of a nullable type with the provided wrapped type.
//
// Note: only primitive types are supported as wrapped types.
func NullableType(wrapped *Type) *Type {
return &Type{
kind: wrapped.kind,
runtimeType: wrapped.runtimeType,
parameters: wrapped.parameters,
isAssignableType: func(other *Type) bool {
return NullType.IsAssignableType(other) || wrapped.IsAssignableType(other)
},
isAssignableRuntimeType: func(other ref.Type) bool {
return NullType.IsAssignableRuntimeType(other) || wrapped.IsAssignableRuntimeType(other)
},
}
}
// OpaqueType creates an abstract parameterized type with a given name.
func OpaqueType(name string, params ...*Type) *Type {
return &Type{
kind: OpaqueKind,
runtimeType: types.NewTypeValue(name),
parameters: params,
}
}
// ObjectType creates a type references to an externally defined type, e.g. a protobuf message type.
func ObjectType(typeName string) *Type {
return &Type{
kind: StructKind,
runtimeType: types.NewObjectTypeValue(typeName),
}
}
// TypeParamType creates a parameterized type instance.
func TypeParamType(paramName string) *Type {
return &Type{
kind: TypeParamKind,
runtimeType: types.NewTypeValue(paramName),
}
}
// Variable creates an instance of a variable declaration with a variable name and type.
func Variable(name string, t *Type) EnvOption {
return func(e *Env) (*Env, error) {
et, err := TypeToExprType(t)
if err != nil {
return nil, err
}
e.declarations = append(e.declarations, decls.NewVar(name, et))
return e, nil
}
}
// Function defines a function and overloads with optional singleton or per-overload bindings.
//
// Using Function is roughly equivalent to calling Declarations() to declare the function signatures
// and Functions() to define the function bindings, if they have been defined. Specifying the
// same function name more than once will result in the aggregation of the function overloads. If any
// signatures conflict between the existing and new function definition an error will be raised.
// However, if the signatures are identical and the overload ids are the same, the redefinition will
// be considered a no-op.
//
// One key difference with using Function() is that each FunctionDecl provided will handle dynamic
// dispatch based on the type-signatures of the overloads provided which means overload resolution at
// runtime is handled out of the box rather than via a custom binding for overload resolution via
// Functions().
func Function(name string, opts ...FunctionOpt) EnvOption {
return func(e *Env) (*Env, error) {
fn := &functionDecl{
name: name,
overloads: map[string]*overloadDecl{},
options: opts,
}
err := fn.init()
if err != nil {
return nil, err
}
_, err = functionDeclToExprDecl(fn)
if err != nil {
return nil, err
}
if existing, found := e.functions[fn.name]; found {
fn, err = existing.merge(fn)
if err != nil {
return nil, err
}
}
e.functions[name] = fn
return e, nil
}
}
// FunctionOpt defines a functional option for configuring a function declaration.
type FunctionOpt func(*functionDecl) (*functionDecl, error)
// SingletonUnaryBinding creates a singleton function defintion to be used for all function overloads.
//
// Note, this approach works well if operand is expected to have a specific trait which it implements,
// e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings.
func SingletonUnaryBinding(fn functions.UnaryOp, traits ...int) FunctionOpt {
trait := 0
for _, t := range traits {
trait = trait | t
}
return func(f *functionDecl) (*functionDecl, error) {
if f.singleton != nil {
return nil, fmt.Errorf("function already has a singleton binding: %s", f.name)
}
f.singleton = &functions.Overload{
Operator: f.name,
Unary: fn,
OperandTrait: trait,
}
return f, nil
}
}
// SingletonBinaryImpl creates a singleton function definition to be used with all function overloads.
//
// Note, this approach works well if operand is expected to have a specific trait which it implements,
// e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings.
func SingletonBinaryImpl(fn functions.BinaryOp, traits ...int) FunctionOpt {
trait := 0
for _, t := range traits {
trait = trait | t
}
return func(f *functionDecl) (*functionDecl, error) {
if f.singleton != nil {
return nil, fmt.Errorf("function already has a singleton binding: %s", f.name)
}
f.singleton = &functions.Overload{
Operator: f.name,
Binary: fn,
OperandTrait: trait,
}
return f, nil
}
}
// SingletonFunctionImpl creates a singleton function definition to be used with all function overloads.
//
// Note, this approach works well if operand is expected to have a specific trait which it implements,
// e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings.
func SingletonFunctionImpl(fn functions.FunctionOp, traits ...int) FunctionOpt {
trait := 0
for _, t := range traits {
trait = trait | t
}
return func(f *functionDecl) (*functionDecl, error) {
if f.singleton != nil {
return nil, fmt.Errorf("function already has a singleton binding: %s", f.name)
}
f.singleton = &functions.Overload{
Operator: f.name,
Function: fn,
OperandTrait: trait,
}
return f, nil
}
}
// Overload defines a new global overload with an overload id, argument types, and result type. Through the
// use of OverloadOpt options, the overload may also be configured with a binding, an operand trait, and to
// be non-strict.
//
// Note: function bindings should be commonly configured with Overload instances whereas operand traits and
// strict-ness should be rare occurrences.
func Overload(overloadID string, args []*Type, resultType *Type, opts ...OverloadOpt) FunctionOpt {
return newOverload(overloadID, false, args, resultType, opts...)
}
// MemberOverload defines a new receiver-style overload (or member function) with an overload id, argument types,
// and result type. Through the use of OverloadOpt options, the overload may also be configured with a binding,
// an operand trait, and to be non-strict.
//
// Note: function bindings should be commonly configured with Overload instances whereas operand traits and
// strict-ness should be rare occurrences.
func MemberOverload(overloadID string, args []*Type, resultType *Type, opts ...OverloadOpt) FunctionOpt {
return newOverload(overloadID, true, args, resultType, opts...)
}
// OverloadOpt is a functional option for configuring a function overload.
type OverloadOpt func(*overloadDecl) (*overloadDecl, error)
// UnaryBinding provides the implementation of a unary overload. The provided function is protected by a runtime
// type-guard which ensures runtime type agreement between the overload signature and runtime argument types.
func UnaryBinding(binding functions.UnaryOp) OverloadOpt {
return func(o *overloadDecl) (*overloadDecl, error) {
if o.hasBinding() {
return nil, fmt.Errorf("overload already has a binding: %s", o.id)
}
if len(o.argTypes) != 1 {
return nil, fmt.Errorf("unary function bound to non-unary overload: %s", o.id)
}
o.unaryOp = binding
return o, nil
}
}
// BinaryBinding provides the implementation of a binary overload. The provided function is protected by a runtime
// type-guard which ensures runtime type agreement between the overload signature and runtime argument types.
func BinaryBinding(binding functions.BinaryOp) OverloadOpt {
return func(o *overloadDecl) (*overloadDecl, error) {
if o.hasBinding() {
return nil, fmt.Errorf("overload already has a binding: %s", o.id)
}
if len(o.argTypes) != 2 {
return nil, fmt.Errorf("binary function bound to non-binary overload: %s", o.id)
}
o.binaryOp = binding
return o, nil
}
}
// FunctionBinding provides the implementation of a variadic overload. The provided function is protected by a runtime
// type-guard which ensures runtime type agreement between the overload signature and runtime argument types.
func FunctionBinding(binding functions.FunctionOp) OverloadOpt {
return func(o *overloadDecl) (*overloadDecl, error) {
if o.hasBinding() {
return nil, fmt.Errorf("overload already has a binding: %s", o.id)
}
o.functionOp = binding
return o, nil
}
}
// OverloadIsNonStrict enables the function to be called with error and unknown argument values.
//
// Note: do not use this option unless absoluately necessary as it should be an uncommon feature.
func OverloadIsNonStrict() OverloadOpt {
return func(o *overloadDecl) (*overloadDecl, error) {
o.nonStrict = true
return o, nil
}
}
// OverloadOperandTrait configures a set of traits which the first argument to the overload must implement in order to be
// successfully invoked.
func OverloadOperandTrait(trait int) OverloadOpt {
return func(o *overloadDecl) (*overloadDecl, error) {
o.operandTrait = trait
return o, nil
}
}
type functionDecl struct {
name string
overloads map[string]*overloadDecl
options []FunctionOpt
singleton *functions.Overload
initialized bool
}
// init ensures that a function's options have been applied.
//
// This function is used in both the environment configuration and internally for function merges.
func (f *functionDecl) init() error {
if f.initialized {
return nil
}
f.initialized = true
var err error
for _, opt := range f.options {
f, err = opt(f)
if err != nil {
return err
}
}
if len(f.overloads) == 0 {
return fmt.Errorf("function %s must have at least one overload", f.name)
}
return nil
}
// bindings produces a set of function bindings, if any are defined.
func (f *functionDecl) bindings() ([]*functions.Overload, error) {
overloads := []*functions.Overload{}
nonStrict := false
for _, o := range f.overloads {
if o.hasBinding() {
overload := &functions.Overload{
Operator: o.id,
Unary: o.guardedUnaryOp(f.name),
Binary: o.guardedBinaryOp(f.name),
Function: o.guardedFunctionOp(f.name),
OperandTrait: o.operandTrait,
NonStrict: o.nonStrict,
}
overloads = append(overloads, overload)
nonStrict = nonStrict || o.nonStrict
}
}
if f.singleton != nil {
if len(overloads) != 0 {
return nil, fmt.Errorf("singleton function incompatible with specialized overloads: %s", f.name)
}
return []*functions.Overload{
{
Operator: f.name,
Unary: f.singleton.Unary,
Binary: f.singleton.Binary,
Function: f.singleton.Function,
OperandTrait: f.singleton.OperandTrait,
},
}, nil
}
if len(overloads) == 0 {
return overloads, nil
}
// Single overload. Replicate an entry for it using the function name as well.
if len(overloads) == 1 {
if overloads[0].Operator == f.name {
return overloads, nil
}
return append(overloads, &functions.Overload{
Operator: f.name,
Unary: overloads[0].Unary,
Binary: overloads[0].Binary,
Function: overloads[0].Function,
NonStrict: overloads[0].NonStrict,
OperandTrait: overloads[0].OperandTrait,
}), nil
}
// All of the defined overloads are wrapped into a top-level function which
// performs dynamic dispatch to the proper overload based on the argument types.
bindings := append([]*functions.Overload{}, overloads...)
funcDispatch := func(args ...ref.Val) ref.Val {
for _, overloadDecl := range f.overloads {
if !overloadDecl.matchesRuntimeSignature(args...) {
continue
}
switch len(args) {
case 1:
if overloadDecl.unaryOp != nil {
return overloadDecl.unaryOp(args[0])
}
case 2:
if overloadDecl.binaryOp != nil {
return overloadDecl.binaryOp(args[0], args[1])
}
}
if overloadDecl.functionOp != nil {
return overloadDecl.functionOp(args...)
}
// eventually this will fall through to the noSuchOverload below.
}
return noSuchOverload(f.name, args...)
}
function := &functions.Overload{
Operator: f.name,
Function: funcDispatch,
NonStrict: nonStrict,
}
return append(bindings, function), nil
}
// merge one function declaration with another.
//
// If a function is extended, by say adding new overloads to an existing function, then it is merged with the
// prior definition of the function at which point its overloads must not collide with pre-existing overloads
// and its bindings (singleton, or per-overload) must not conflict with previous definitions either.
func (f *functionDecl) merge(other *functionDecl) (*functionDecl, error) {
if f.name != other.name {
return nil, fmt.Errorf("cannot merge unrelated functions. %s and %s", f.name, other.name)
}
err := f.init()
if err != nil {
return nil, err
}
err = other.init()
if err != nil {
return nil, err
}
merged := &functionDecl{
name: f.name,
overloads: map[string]*overloadDecl{},
options: []FunctionOpt{},
initialized: true,
singleton: f.singleton,
}
for id, o := range f.overloads {
merged.overloads[id] = o
}
for _, o := range other.overloads {
err := merged.addOverload(o)
if err != nil {
return nil, fmt.Errorf("function declaration merge failed: %v", err)
}
}
if other.singleton != nil {
if merged.singleton != nil {
return nil, fmt.Errorf("function already has a binding: %s", f.name)
}
merged.singleton = other.singleton
}
return merged, nil
}
// addOverload ensures that the new overload does not collide with an existing overload signature;
// however, if the function signatures are identical, the implementation may be rewritten as its
// difficult to compare functions by object identity.
func (f *functionDecl) addOverload(overload *overloadDecl) error {
for id, o := range f.overloads {
if id != overload.id && o.signatureOverlaps(overload) {
return fmt.Errorf("overload signature collision in function %s: %s collides with %s", f.name, o.id, overload.id)
}
if id == overload.id {
if o.signatureEquals(overload) && o.nonStrict == overload.nonStrict {
// Allow redefinition of an overload implementation so long as the signatures match.
f.overloads[id] = overload
} else {
return fmt.Errorf("overload redefinition in function. %s: %s has multiple definitions", f.name, o.id)
}
}
}
f.overloads[overload.id] = overload
return nil
}
func noSuchOverload(funcName string, args ...ref.Val) ref.Val {
argTypes := make([]string, len(args))
for i, arg := range args {
argTypes[i] = arg.Type().TypeName()
}
signature := strings.Join(argTypes, ", ")
return types.NewErr("no such overload: %s(%s)", funcName, signature)
}
// overloadDecl contains all of the relevant information regarding a specific function overload.
type overloadDecl struct {
id string
argTypes []*Type
resultType *Type
memberFunction bool
// binding options, optional but encouraged.
unaryOp functions.UnaryOp
binaryOp functions.BinaryOp
functionOp functions.FunctionOp
// behavioral options, uncommon
nonStrict bool
operandTrait int
}
func (o *overloadDecl) hasBinding() bool {
return o.unaryOp != nil || o.binaryOp != nil || o.functionOp != nil
}
// guardedUnaryOp creates an invocation guard around the provided unary operator, if one is defined.
func (o *overloadDecl) guardedUnaryOp(funcName string) functions.UnaryOp {
if o.unaryOp == nil {
return nil
}
return func(arg ref.Val) ref.Val {
if !o.matchesRuntimeUnarySignature(arg) {
return noSuchOverload(funcName, arg)
}
return o.unaryOp(arg)
}
}
// guardedBinaryOp creates an invocation guard around the provided binary operator, if one is defined.
func (o *overloadDecl) guardedBinaryOp(funcName string) functions.BinaryOp {
if o.binaryOp == nil {
return nil
}
return func(arg1, arg2 ref.Val) ref.Val {
if !o.matchesRuntimeBinarySignature(arg1, arg2) {
return noSuchOverload(funcName, arg1, arg2)
}
return o.binaryOp(arg1, arg2)
}
}
// guardedFunctionOp creates an invocation guard around the provided variadic function binding, if one is provided.
func (o *overloadDecl) guardedFunctionOp(funcName string) functions.FunctionOp {
if o.functionOp == nil {
return nil
}
return func(args ...ref.Val) ref.Val {
if !o.matchesRuntimeSignature(args...) {
return noSuchOverload(funcName, args...)
}
return o.functionOp(args...)
}
}
// matchesRuntimeUnarySignature indicates whether the argument type is runtime assiganble to the overload's expected argument.
func (o *overloadDecl) matchesRuntimeUnarySignature(arg ref.Val) bool {
if o.nonStrict && types.IsUnknownOrError(arg) {
return true
}
return o.argTypes[0].IsAssignableRuntimeType(arg.Type()) && (o.operandTrait == 0 || arg.Type().HasTrait(o.operandTrait))
}
// matchesRuntimeBinarySignature indicates whether the argument types are runtime assiganble to the overload's expected arguments.
func (o *overloadDecl) matchesRuntimeBinarySignature(arg1, arg2 ref.Val) bool {
if o.nonStrict {
if types.IsUnknownOrError(arg1) {
return types.IsUnknownOrError(arg2) || o.argTypes[1].IsAssignableRuntimeType(arg2.Type())
}
} else if !o.argTypes[1].IsAssignableRuntimeType(arg2.Type()) {
return false
}
return o.argTypes[0].IsAssignableRuntimeType(arg1.Type()) && (o.operandTrait == 0 || arg1.Type().HasTrait(o.operandTrait))
}
// matchesRuntimeSignature indicates whether the argument types are runtime assiganble to the overload's expected arguments.
func (o *overloadDecl) matchesRuntimeSignature(args ...ref.Val) bool {
if len(args) != len(o.argTypes) {
return false
}
if len(args) == 0 {
return true
}
allArgsMatch := true
for i, arg := range args {
if o.nonStrict && types.IsUnknownOrError(arg) {
continue
}
allArgsMatch = allArgsMatch && o.argTypes[i].IsAssignableRuntimeType(arg.Type())
}
arg := args[0]
return allArgsMatch && (o.operandTrait == 0 || (o.nonStrict && types.IsUnknownOrError(arg)) || arg.Type().HasTrait(o.operandTrait))
}
// signatureEquals indicates whether one overload has an identical signature to another overload.
//
// Providing a duplicate signature is not an issue, but an overloapping signature is problematic.
func (o *overloadDecl) signatureEquals(other *overloadDecl) bool {
if o.id != other.id || o.memberFunction != other.memberFunction || len(o.argTypes) != len(other.argTypes) {
return false
}
for i, at := range o.argTypes {
oat := other.argTypes[i]
if !at.equals(oat) {
return false
}
}
return o.resultType.equals(other.resultType)
}
// signatureOverlaps indicates whether one overload has an overlapping signature with another overload.
//
// The 'other' overload must first be checked for equality before determining whether it overlaps in order to be completely accurate.
func (o *overloadDecl) signatureOverlaps(other *overloadDecl) bool {
if o.memberFunction != other.memberFunction || len(o.argTypes) != len(other.argTypes) {
return false
}
argsOverlap := true
for i, argType := range o.argTypes {
otherArgType := other.argTypes[i]
argsOverlap = argsOverlap &&
(argType.IsAssignableType(otherArgType) ||
otherArgType.IsAssignableType(argType))
}
return argsOverlap
}
func newOverload(overloadID string, memberFunction bool, args []*Type, resultType *Type, opts ...OverloadOpt) FunctionOpt {
return func(f *functionDecl) (*functionDecl, error) {
overload := &overloadDecl{
id: overloadID,
argTypes: args,
resultType: resultType,
memberFunction: memberFunction,
}
var err error
for _, opt := range opts {
overload, err = opt(overload)
if err != nil {
return nil, err
}
}
err = f.addOverload(overload)
if err != nil {
return nil, err
}
return f, nil
}
}
func maybeWrapper(t *Type, pbType *exprpb.Type) *exprpb.Type {
if t.IsAssignableType(NullType) {
return decls.NewWrapperType(pbType)
}
return pbType
}
// TypeToExprType converts a CEL-native type representation to a protobuf CEL Type representation.
func TypeToExprType(t *Type) (*exprpb.Type, error) {
switch t.kind {
case AnyKind:
return decls.Any, nil
case BoolKind:
return maybeWrapper(t, decls.Bool), nil
case BytesKind:
return maybeWrapper(t, decls.Bytes), nil
case DoubleKind:
return maybeWrapper(t, decls.Double), nil
case DurationKind:
return decls.Duration, nil
case DynKind:
return decls.Dyn, nil
case IntKind:
return maybeWrapper(t, decls.Int), nil
case ListKind:
et, err := TypeToExprType(t.parameters[0])
if err != nil {
return nil, err
}
return decls.NewListType(et), nil
case MapKind:
kt, err := TypeToExprType(t.parameters[0])
if err != nil {
return nil, err
}
vt, err := TypeToExprType(t.parameters[1])
if err != nil {
return nil, err
}
return decls.NewMapType(kt, vt), nil
case NullTypeKind:
return decls.Null, nil
case OpaqueKind:
params := make([]*exprpb.Type, len(t.parameters))
for i, p := range t.parameters {
pt, err := TypeToExprType(p)
if err != nil {
return nil, err
}
params[i] = pt
}
return decls.NewAbstractType(t.runtimeType.TypeName(), params...), nil
case StringKind:
return maybeWrapper(t, decls.String), nil
case StructKind:
switch t.runtimeType.TypeName() {
case "google.protobuf.Any":
return decls.Any, nil
case "google.protobuf.Duration":
return decls.Duration, nil
case "google.protobuf.Timestamp":
return decls.Timestamp, nil
case "google.protobuf.Value":
return decls.Dyn, nil
case "google.protobuf.ListValue":
return decls.NewListType(decls.Dyn), nil
case "google.protobuf.Struct":
return decls.NewMapType(decls.String, decls.Dyn), nil
case "google.protobuf.BoolValue":
return decls.NewWrapperType(decls.Bool), nil
case "google.protobuf.BytesValue":
return decls.NewWrapperType(decls.Bytes), nil
case "google.protobuf.DoubleValue", "google.protobuf.FloatValue":
return decls.NewWrapperType(decls.Double), nil
case "google.protobuf.Int32Value", "google.protobuf.Int64Value":
return decls.NewWrapperType(decls.Int), nil
case "google.protobuf.StringValue":
return decls.NewWrapperType(decls.String), nil
case "google.protobuf.UInt32Value", "google.protobuf.UInt64Value":
return decls.NewWrapperType(decls.Uint), nil
default:
return decls.NewObjectType(t.runtimeType.TypeName()), nil
}
case TimestampKind:
return decls.Timestamp, nil
case TypeParamKind:
return decls.NewTypeParamType(t.runtimeType.TypeName()), nil
case TypeKind:
return decls.NewTypeType(decls.Dyn), nil
case UintKind:
return maybeWrapper(t, decls.Uint), nil
}
return nil, fmt.Errorf("missing type conversion to proto: %v", t)
}
// ExprTypeToType converts a protobuf CEL type representation to a CEL-native type representation.
func ExprTypeToType(t *exprpb.Type) (*Type, error) {
switch t.GetTypeKind().(type) {
case *exprpb.Type_Dyn:
return DynType, nil
case *exprpb.Type_AbstractType_:
paramTypes := make([]*Type, len(t.GetAbstractType().GetParameterTypes()))
for i, p := range t.GetAbstractType().GetParameterTypes() {
pt, err := ExprTypeToType(p)
if err != nil {
return nil, err
}
paramTypes[i] = pt
}
return OpaqueType(t.GetAbstractType().GetName(), paramTypes...), nil
case *exprpb.Type_ListType_:
et, err := ExprTypeToType(t.GetListType().GetElemType())
if err != nil {
return nil, err
}
return ListType(et), nil
case *exprpb.Type_MapType_:
kt, err := ExprTypeToType(t.GetMapType().GetKeyType())
if err != nil {
return nil, err
}
vt, err := ExprTypeToType(t.GetMapType().GetValueType())
if err != nil {
return nil, err
}
return MapType(kt, vt), nil
case *exprpb.Type_MessageType:
switch t.GetMessageType() {
case "google.protobuf.Any":
return AnyType, nil
case "google.protobuf.Duration":
return DurationType, nil
case "google.protobuf.Timestamp":
return TimestampType, nil
case "google.protobuf.Value":
return DynType, nil
case "google.protobuf.ListValue":
return ListType(DynType), nil
case "google.protobuf.Struct":
return MapType(StringType, DynType), nil
case "google.protobuf.BoolValue":
return NullableType(BoolType), nil
case "google.protobuf.BytesValue":
return NullableType(BytesType), nil
case "google.protobuf.DoubleValue", "google.protobuf.FloatValue":
return NullableType(DoubleType), nil
case "google.protobuf.Int32Value", "google.protobuf.Int64Value":
return NullableType(IntType), nil
case "google.protobuf.StringValue":
return NullableType(StringType), nil