Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/cel/cel_test.go

raw symbols SCIP
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package cel
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "os"
24 "reflect"
25 "strings"
26 "sync"
27 "testing"
28 "time"
29
30 "google.golang.org/protobuf/proto"
31 "google.golang.org/protobuf/reflect/protodesc"
32 "google.golang.org/protobuf/reflect/protoreflect"
33
34 "github.com/google/cel-go/checker"
35 celast "github.com/google/cel-go/common/ast"
36 "github.com/google/cel-go/common/env"
37 "github.com/google/cel-go/common/operators"
38 "github.com/google/cel-go/common/overloads"
39 "github.com/google/cel-go/common/types"
40 "github.com/google/cel-go/common/types/ref"
41 "github.com/google/cel-go/common/types/traits"
42 "github.com/google/cel-go/interpreter"
43 "github.com/google/cel-go/parser"
44 "github.com/google/cel-go/test"
45
46 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
47 descpb "google.golang.org/protobuf/types/descriptorpb"
48 dynamicpb "google.golang.org/protobuf/types/dynamicpb"
49 durationpb "google.golang.org/protobuf/types/known/durationpb"
50 timestamppb "google.golang.org/protobuf/types/known/timestamppb"
51 wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
52
53 proto2pb "github.com/google/cel-go/test/proto2pb"
54 proto3pb "github.com/google/cel-go/test/proto3pb"
55 )
56
57 func Test_ExampleWithBuiltins(t *testing.T) {
58 // Variables used within this expression environment.
59 env, err := NewEnv(
60 Variable("i", StringType),
61 Variable("you", StringType),
62 )
63 if err != nil {
64 t.Fatalf("environment creation error: %s\n", err)
65 }
66
67 // Compile the expression.
68 ast, iss := env.Compile(`"Hello " + you + "! I'm " + i + "."`)
69 if iss.Err() != nil {
70 t.Fatal(iss.Err())
71 }
72
73 // Create the program, and evaluate it against some input.
74 prg, err := env.Program(ast)
75 if err != nil {
76 t.Fatalf("program creation error: %s\n", err)
77 }
78
79 // If the Eval() call were provided with cel.EvalOptions(OptTrackState) the details response
80 // (2nd return) would be non-nil.
81 out, _, err := prg.Eval(
82 map[string]any{
83 "i": "CEL",
84 "you": "world",
85 },
86 )
87 if err != nil {
88 t.Fatalf("runtime error: %s\n", err)
89 }
90
91 // Hello world! I'm CEL.
92 if out.Equal(types.String("Hello world! I'm CEL.")) != types.True {
93 t.Errorf(`got '%v', wanted "Hello world! I'm CEL."`, out.Value())
94 }
95 }
96
97 func TestEval(t *testing.T) {
98 env, err := NewEnv(
99 Variable("input", ListType(IntType)),
100 CostEstimatorOptions(
101 checker.OverloadCostEstimate(overloads.TimestampToYear, estimateTimestampToYear),
102 ),
103 )
104 if err != nil {
105 t.Fatalf("NewEnv() failed: %v", err)
106 }
107 tests := []struct {
108 expr string
109 in any
110 }{
111 {
112 expr: `input.size() != 0`,
113 in: map[string]any{"input": []int{1, 2, 3}},
114 },
115 }
116 for i, tst := range tests {
117 tc := tst
118 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
119 ast, iss := env.Compile(tc.expr)
120 if iss.Err() != nil {
121 t.Fatalf("env.Compile(%s) failed: %v", tc.expr, iss.Err())
122 }
123 ctx := context.Background()
124 prgOpts := []ProgramOption{
125 CostTracking(testRuntimeCostEstimator{}),
126 CostTrackerOptions(
127 interpreter.OverloadCostTracker(overloads.TimestampToYear, trackTimestampToYear),
128 ),
129 EvalOptions(OptOptimize, OptTrackCost),
130 InterruptCheckFrequency(100),
131 }
132 prg, err := env.Program(ast, prgOpts...)
133 if err != nil {
134 t.Fatalf("env.Program() failed: %v", err)
135 }
136 for k := 0; k < 100; k++ {
137 t.Run(fmt.Sprintf("[%d]", k), func(t *testing.T) {
138 t.Parallel()
139 prg.Eval(tc.in)
140 evalCtx, cancel := context.WithTimeout(ctx, time.Minute)
141 defer cancel()
142 _, _, err := prg.ContextEval(evalCtx, tc.in)
143 if err != nil {
144 t.Fatalf("prg.ContextEval() failed: %v", err)
145 }
146 })
147 }
148 })
149 }
150 }
151
152 func TestAbbrevsCompiled(t *testing.T) {
153 // Test whether abbreviations successfully resolve at type-check time (compile time).
154 env := testEnv(t,
155 Abbrevs("qualified.identifier.name"),
156 Variable("qualified.identifier.name.first", StringType),
157 )
158 prg := compile(t, env, `"hello "+ name.first`) // abbreviation resolved here.
159 out, _, err := prg.Eval(
160 map[string]any{
161 "qualified.identifier.name.first": "Jim",
162 },
163 )
164 if err != nil {
165 t.Fatal(err)
166 }
167 if out.Value() != "hello Jim" {
168 t.Errorf("got %v, wanted 'hello Jim'", out)
169 }
170 }
171
172 func TestAbbrevsParsed(t *testing.T) {
173 // Test whether abbreviations are resolved properly at evaluation time.
174 env := testEnv(t,
175 Abbrevs("qualified.identifier.name"),
176 )
177 ast, iss := env.Parse(`"hello " + name.first`)
178 if iss.Err() != nil {
179 t.Fatal(iss.Err())
180 }
181 prg, err := env.Program(ast) // abbreviation resolved here.
182 if err != nil {
183 t.Fatal(err)
184 }
185 out, _, err := prg.Eval(
186 map[string]any{
187 "qualified.identifier.name": map[string]string{
188 "first": "Jim",
189 },
190 },
191 )
192 if err != nil {
193 t.Fatal(err)
194 }
195 if out.Value() != "hello Jim" {
196 t.Errorf("got %v, wanted 'hello Jim'", out)
197 }
198 }
199
200 func TestAbbrevsDisambiguation(t *testing.T) {
201 env := testEnv(t,
202 Abbrevs("external.Expr"),
203 Container("google.api.expr.v1alpha1"),
204 Types(&exprpb.Expr{}),
205
206 Variable("test", BoolType),
207 Variable("external.Expr", StringType),
208 )
209 // This expression will return either a string or a protobuf Expr value depending on the value
210 // of the 'test' argument. The fully qualified type name is used indicate that the protobuf
211 // typed 'Expr' should be used rather than the abbreviatation for 'external.Expr'.
212 out, err := interpret(t, env, `test ? dyn(Expr) : google.api.expr.v1alpha1.Expr{id: 1}`,
213 map[string]any{
214 "test": true,
215 "external.Expr": "string expr",
216 },
217 )
218 if err != nil {
219 t.Fatal(err)
220 }
221 if out.Value() != "string expr" {
222 t.Errorf("got %v, wanted 'string expr'", out)
223 }
224 out, err = interpret(t, env, `test ? dyn(Expr) : google.api.expr.v1alpha1.Expr{id: 1}`,
225 map[string]any{
226 "test": false,
227 "external.Expr": "wrong expr",
228 },
229 )
230 if err != nil {
231 t.Fatal(err)
232 }
233 want := &exprpb.Expr{Id: 1}
234 got, err := out.ConvertToNative(reflect.TypeOf(want))
235 if err != nil {
236 t.Fatal(err)
237 }
238 if !proto.Equal(got.(*exprpb.Expr), want) {
239 t.Errorf("got %v, wanted '%v'", out, want)
240 }
241 }
242
243 func TestConvertToNativeJSONStructure(t *testing.T) {
244 env, err := NewEnv()
245 if err != nil {
246 t.Fatalf("NewEnv() failed: %v", err)
247 }
248 ast, issues := env.Compile(`{
249 "parts": [{"kind": "text"}]
250 }`)
251 if issues != nil && issues.Err() != nil {
252 t.Fatal(issues.Err())
253 }
254
255 prg, err := env.Program(ast)
256 if err != nil {
257 t.Fatal(err)
258 }
259
260 result, _, err := prg.Eval(map[string]any{})
261 if err != nil {
262 t.Fatal(err)
263 }
264
265 native, err := result.ConvertToNative(types.JSONValueType)
266 if err != nil {
267 t.Fatal(err)
268 }
269
270 jsonBytes, err := json.Marshal(native)
271 if err != nil {
272 t.Fatalf("json.Marshal failed: %v", err)
273 }
274 want := `{"parts":[{"kind":"text"}]}`
275 if string(jsonBytes) != want {
276 t.Errorf("json.Marshal() failed, got : %s, wanted ", jsonBytes)
277 }
278 }
279
280 func TestCustomEnvError(t *testing.T) {
281 env, err := NewCustomEnv(StdLib(), StdLib())
282 if err != nil {
283 t.Fatalf("NewCustomEnv() failed: %v", err)
284 }
285 _, iss := compileOrError(t, env, "a.b.c == true")
286 if iss == nil {
287 t.Error("got successful compile, expected error for duplicate function declarations.")
288 }
289 }
290
291 func TestCustomEnv(t *testing.T) {
292 env, err := NewCustomEnv(Variable("a.b.c", BoolType))
293 if err != nil {
294 t.Fatalf("NewCustomEnv(a.b.c:bool) failed: %v", err)
295 }
296 t.Run("err", func(t *testing.T) {
297 _, iss := compileOrError(t, env, "a.b.c == true")
298 if iss == nil {
299 t.Error("got successful compile, expected error for missing operator '_==_'")
300 }
301 })
302
303 t.Run("ok", func(t *testing.T) {
304 out, err := interpret(t, env, "a.b.c", map[string]any{"a.b.c": true})
305 if err != nil {
306 t.Fatal(err)
307 }
308 if out != types.True {
309 t.Errorf("got '%v', wanted 'true'", out.Value())
310 }
311 })
312 }
313
314 func TestCrossTypeNumericComparisons(t *testing.T) {
315 tests := []struct {
316 name string
317 expr string
318 iss string
319 opt EnvOption
320 out ref.Val
321 }{
322 // Statically typed expressions need to opt in to cross-type numeric comparisons
323 {
324 name: "double_less_than_int_err",
325 expr: `1.0 < 2`,
326 opt: CrossTypeNumericComparisons(false),
327 iss: `
328 ERROR: <input>:1:5: found no matching overload for '_<_' applied to '(double, int)'
329 | 1.0 < 2
330 | ....^`,
331 },
332 {
333 name: "double_less_than_int_success",
334 expr: `1.0 < 2`,
335 opt: CrossTypeNumericComparisons(true),
336 out: types.True,
337 },
338 // Dynamic data already benefits from cross-type numeric comparisons
339 {
340 name: "dyn_less_than_int_success",
341 expr: `dyn(1.0) < 2`,
342 opt: CrossTypeNumericComparisons(false),
343 out: types.True,
344 },
345 {
346 name: "dyn_less_than_int_success",
347 expr: `dyn(1.0) < 2`,
348 opt: CrossTypeNumericComparisons(true),
349 out: types.True,
350 },
351 }
352 for _, tst := range tests {
353 tc := tst
354 t.Run(tc.name, func(t *testing.T) {
355 e := testEnv(t, tc.opt)
356 ast, iss := e.Compile(tc.expr)
357 if tc.iss != "" {
358 if iss.Err() == nil {
359 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
360 }
361 if !test.Compare(iss.Err().Error(), tc.iss) {
362 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
363 }
364 return
365 }
366 if iss.Err() != nil {
367 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
368 }
369 prg, err := e.Program(ast)
370 if err != nil {
371 t.Fatalf("e.Program() failed: %v", err)
372 }
373 out, _, err := prg.Eval(NoVars())
374 if err != nil {
375 t.Fatalf("prg.Eval() errored: %v", err)
376 }
377 if out != tc.out {
378 t.Errorf("program eval got %v, wanted %v", out, tc.out)
379 }
380 })
381 }
382 }
383
384 func TestExtendStdlibFunction(t *testing.T) {
385 env := testEnv(t,
386 Function(overloads.Contains,
387 MemberOverload("bytes_contains_bytes", []*Type{BytesType, BytesType}, BoolType,
388 BinaryBinding(func(bstr, bsub ref.Val) ref.Val {
389 return types.Bool(bytes.Contains([]byte(bstr.(types.Bytes)), []byte(bsub.(types.Bytes))))
390 }))),
391 )
392 prg := compile(t, env, `b'string'.contains(b'tri') && 'string'.contains('tri')`)
393 out, _, err := prg.Eval(NoVars())
394 if err != nil {
395 t.Fatalf("contains check errored: %v", err)
396 }
397 if out != types.True {
398 t.Errorf("contains check got %v, wanted true", out)
399 }
400 }
401
402 func TestSubsetStdLib(t *testing.T) {
403 env, err := NewCustomEnv(
404 StdLib(StdLibSubset(
405 &env.LibrarySubset{
406 IncludeMacros: []string{"has"},
407 IncludeFunctions: []*env.Function{
408 {Name: operators.Equals},
409 {Name: operators.NotEquals},
410 {Name: operators.LogicalAnd},
411 {Name: operators.LogicalOr},
412 {Name: operators.LogicalNot},
413 {Name: overloads.Size, Overloads: []*env.Overload{{ID: "list_size"}}},
414 },
415 },
416 )))
417 if err != nil {
418 t.Fatalf("StdLib() subsetting failed: %v", err)
419 }
420 tests := []struct {
421 name string
422 expr string
423 compiles bool
424 want ref.Val
425 }{
426 {
427 name: "has macro",
428 expr: "!has({}.a)",
429 compiles: true,
430 want: types.True,
431 },
432 {
433 name: "not equals",
434 expr: "has({}.a) != true",
435 compiles: true,
436 want: types.True,
437 },
438 {
439 name: "logical operators",
440 expr: "has({}.a) != true && has({'b': 1}.b) == true",
441 compiles: true,
442 want: types.True,
443 },
444 {
445 name: "list size - allowed",
446 expr: "[1, 2, 3].size()",
447 compiles: true,
448 want: types.Int(3),
449 },
450 {
451 name: "excluded macro",
452 expr: "[1, 2, 3].exists(i, i != 0)",
453 compiles: false,
454 },
455 {
456 name: "string size - not allowed",
457 expr: "'hello'.size()",
458 compiles: false,
459 },
460 }
461 for _, tst := range tests {
462 tc := tst
463 t.Run(tc.name, func(t *testing.T) {
464 ast, iss := env.Compile(tc.expr)
465 if tc.compiles && iss.Err() != nil {
466 t.Fatalf("env.Compile(%q) failed: %v", tc.expr, iss.Err())
467 }
468 if !tc.compiles && iss.Err() != nil {
469 return
470 }
471 prg, err := env.Program(ast)
472 if err != nil {
473 t.Fatalf("env.Program() failed: %v", err)
474 }
475 out, _, err := prg.Eval(NoVars())
476 if err != nil {
477 t.Fatalf("prg.Eval() failed: %s", err)
478 }
479 if out.Equal(tc.want) != types.True {
480 t.Errorf("prg.Eval() got %v, wanted %v", out, tc.want)
481 }
482 })
483 }
484 }
485
486 func TestSubsetStdLibError(t *testing.T) {
487 _, err := NewCustomEnv(
488 StdLib(StdLibSubset(
489 env.NewLibrarySubset().AddIncludedMacros("has").AddExcludedMacros("exists")),
490 ))
491 if err == nil || !strings.Contains(err.Error(), "invalid subset") {
492 t.Errorf("StdLib() subsetting got %v, wanted error 'invalid subset'", err)
493 }
494 }
495
496 func TestSubsetStdLibMerge(t *testing.T) {
497 _, err := NewCustomEnv(
498 Function("size", MemberOverload("string_size", []*Type{StringType}, IntType)),
499 StdLib(StdLibSubset(
500 env.NewLibrarySubset().AddIncludedFunctions([]*env.Function{
501 {Name: overloads.Size, Overloads: []*env.Overload{{ID: "string_size"}}},
502 }...),
503 )))
504 if err != nil {
505 t.Errorf("StdLib() subsetting failed to merge: %v", err)
506 }
507 }
508
509 func TestSubsetStdLibMergeError(t *testing.T) {
510 _, err := NewCustomEnv(
511 Function("size", MemberOverload("string_size", []*Type{StringType}, UintType)),
512 StdLib(StdLibSubset(
513 env.NewLibrarySubset().AddIncludedFunctions([]*env.Function{
514 {Name: overloads.Size, Overloads: []*env.Overload{{ID: "string_size"}}},
515 }...),
516 )))
517 if err == nil || !strings.Contains(err.Error(), "merge failed") {
518 t.Errorf("StdLib() subsetting got %v, wanted error 'merge failed'", err)
519 }
520 }
521
522 func TestCustomTypes(t *testing.T) {
523 reg := types.NewEmptyRegistry()
524 env := testEnv(t,
525 CustomTypeAdapter(reg),
526 CustomTypeProvider(reg),
527 Container("google.api.expr.v1alpha1"),
528 Types(
529 &exprpb.Expr{},
530 types.BoolType,
531 types.IntType,
532 types.StringType),
533 Variable("expr", ObjectType("google.api.expr.v1alpha1.Expr")),
534 )
535 ast, iss := env.Compile(`
536 expr == Expr{id: 2,
537 call_expr: Expr.Call{
538 function: "_==_",
539 args: [
540 Expr{id: 1, ident_expr: Expr.Ident{ name: "a" }},
541 Expr{id: 3, ident_expr: Expr.Ident{ name: "b" }}]
542 }}`)
543 if iss.Err() != nil {
544 t.Fatalf("Compile() failed: %v", iss.Err())
545 }
546 if ast.OutputType() != BoolType {
547 t.Fatalf("got %v, wanted type bool", ast.OutputType())
548 }
549 prg, _ := env.Program(ast)
550 vars := map[string]any{"expr": &exprpb.Expr{
551 Id: 2,
552 ExprKind: &exprpb.Expr_CallExpr{
553 CallExpr: &exprpb.Expr_Call{
554 Function: "_==_",
555 Args: []*exprpb.Expr{
556 {
557 Id: 1,
558 ExprKind: &exprpb.Expr_IdentExpr{
559 IdentExpr: &exprpb.Expr_Ident{Name: "a"},
560 },
561 },
562 {
563 Id: 3,
564 ExprKind: &exprpb.Expr_IdentExpr{
565 IdentExpr: &exprpb.Expr_Ident{Name: "b"},
566 },
567 },
568 },
569 },
570 },
571 }}
572 out, _, _ := prg.Eval(vars)
573 if out != types.True {
574 t.Errorf("got '%v', wanted 'true'", out.Value())
575 }
576 }
577
578 func TestTypeIsolation(t *testing.T) {
579 b, err := os.ReadFile("testdata/team.fds")
580 if err != nil {
581 t.Fatal("can't read fds file: ", err)
582 }
583 var fds descpb.FileDescriptorSet
584 if err = proto.Unmarshal(b, &fds); err != nil {
585 t.Fatal("can't unmarshal descriptor data: ", err)
586 }
587
588 env := testEnv(t,
589 TypeDescs(&fds),
590 Variable("myteam", ObjectType("cel.testdata.Team")),
591 )
592 src := "myteam.members[0].name == 'Cyclops'"
593 compile(t, env, src)
594
595 // Ensure that isolated types don't leak through.
596 e2 := testEnv(t, Variable("myteam", ObjectType("cel.testdata.Team")))
597 _, iss := compileOrError(t, e2, src)
598 if iss == nil {
599 t.Errorf("wanted compile failure for unknown message.")
600 }
601 }
602
603 func TestDynamicProto(t *testing.T) {
604 b, err := os.ReadFile("testdata/team.fds")
605 if err != nil {
606 t.Fatalf("os.ReadFile() failed: %v", err)
607 }
608 var fds descpb.FileDescriptorSet
609 if err = proto.Unmarshal(b, &fds); err != nil {
610 t.Fatalf("proto.Unmarshal() failed: %v", err)
611 }
612 files := (&fds).GetFile()
613 fileCopy := make([]any, len(files))
614 for i := 0; i < len(files); i++ {
615 fileCopy[i] = files[i]
616 }
617 pbFiles, err := protodesc.NewFiles(&fds)
618 if err != nil {
619 t.Fatalf("protodesc.NewFiles() failed: %v", err)
620 }
621 e := testEnv(t,
622 Container("cel"),
623 // The following is identical to registering the FileDescriptorSet;
624 // however, it tests a different code path which aggregates individual
625 // FileDescriptorProto values together.
626 TypeDescs(fileCopy...),
627 // Additionally, demonstrate that double registration of files doesn't
628 // cause any problems.
629 TypeDescs(pbFiles),
630 )
631 src := `testdata.Team{name: 'X-Men', members: [
632 testdata.Mutant{name: 'Jean Grey', level: 20},
633 testdata.Mutant{name: 'Cyclops', level: 7},
634 testdata.Mutant{name: 'Storm', level: 7},
635 testdata.Mutant{name: 'Wolverine', level: 11}
636 ]}`
637 ast, iss := e.Compile(src)
638 if iss.Err() != nil {
639 t.Fatalf("env.Compile(%s) failed: %v", src, iss.Err())
640 }
641 prg, err := e.Program(ast, EvalOptions(OptOptimize))
642 if err != nil {
643 t.Fatalf("env.Program() failed: %v", err)
644 }
645 out, _, err := prg.Eval(NoVars())
646 if err != nil {
647 t.Fatalf("program.Eval() failed: %v", err)
648 }
649 obj, ok := out.(traits.Indexer)
650 if !ok {
651 t.Fatalf("unable to convert output to object: %v", out)
652 }
653 if obj.Get(types.String("name")).Equal(types.String("X-Men")) == types.False {
654 t.Fatalf("got field 'name' %v, wanted X-Men", obj.Get(types.String("name")))
655 }
656 }
657
658 func TestDynamicProtoFileDescriptors(t *testing.T) {
659 b, err := os.ReadFile("testdata/team.fds")
660 if err != nil {
661 t.Fatalf("os.ReadFile() failed: %v", err)
662 }
663 var fds descpb.FileDescriptorSet
664 if err = proto.Unmarshal(b, &fds); err != nil {
665 t.Fatalf("proto.Unmarshal() failed: %v", err)
666 }
667 files := (&fds).GetFile()
668 fileCopy := make([]any, len(files))
669 for i := 0; i < len(files); i++ {
670 fileCopy[i] = files[i]
671 }
672 pbFiles, err := protodesc.NewFiles(&fds)
673 if err != nil {
674 t.Fatalf("protodesc.NewFiles() failed: %v", err)
675 }
676 desc, err := pbFiles.FindDescriptorByName("cel.testdata.Mutant")
677 if err != nil {
678 t.Fatalf("pbFiles.FindDescriptorByName() could not find Mutant: %v", err)
679 }
680 msgDesc, ok := desc.(protoreflect.MessageDescriptor)
681 if !ok {
682 t.Fatalf("desc not convertible to MessageDescriptor: %T", desc)
683 }
684 wolverine := dynamicpb.NewMessage(msgDesc)
685 wolverine.ProtoReflect().Set(msgDesc.Fields().ByName("name"), protoreflect.ValueOfString("Wolverine"))
686 env := testEnv(t,
687 // The following is identical to registering the FileDescriptorSet;
688 // however, it tests a different code path which aggregates individual
689 // FileDescriptorProto values together.
690 TypeDescs(fileCopy...),
691 Variable("mutant", ObjectType("cel.testdata.Mutant")),
692 )
693 src := `has(mutant.name) && mutant.name == 'Wolverine'`
694 ast, iss := env.Compile(src)
695 if iss.Err() != nil {
696 t.Fatalf("env.Compile(%s) failed: %v", src, iss.Err())
697 }
698 prg, err := env.Program(ast, EvalOptions(OptOptimize))
699 if err != nil {
700 t.Fatalf("env.Program() failed: %v", err)
701 }
702 out, _, err := prg.Eval(map[string]any{
703 "mutant": wolverine,
704 })
705 if err != nil {
706 t.Fatalf("program.Eval() failed: %v", err)
707 }
708 obj, ok := out.(types.Bool)
709 if !ok {
710 t.Fatalf("unable to convert output to object: %v", out)
711 }
712 if obj != types.True {
713 t.Errorf("got %v, wanted true", out)
714 }
715 }
716
717 func TestGlobalVars(t *testing.T) {
718 env := testEnv(t,
719 Variable("attrs", MapType(StringType, DynType)),
720 Variable("default", DynType),
721 Function("get",
722 MemberOverload("get_map", []*Type{MapType(StringType, DynType), StringType, DynType}, DynType,
723 FunctionBinding(func(args ...ref.Val) ref.Val {
724 attrs, ok := args[0].(traits.Mapper)
725 if !ok {
726 return types.NewErr(
727 "invalid operand of type '%v' to obj.get(key, def)",
728 args[0].Type())
729 }
730 key := args[1]
731 defVal := args[2]
732 if attrs.Contains(key) == types.True {
733 return attrs.Get(key)
734 }
735 return defVal
736 }),
737 ),
738 ),
739 )
740 ast, iss := env.Compile(`attrs.get("first", attrs.get("second", default))`)
741 if iss.Err() != nil {
742 t.Fatalf("e.Parse() failed: %v", iss.Err())
743 }
744
745 // Global variables can be configured as a ProgramOption and optionally overridden on Eval.
746 // Add a previous globals map to confirm the order of shadowing and a final empty global
747 // map to show that globals are not clobbered.
748 prg, err := env.Program(ast,
749 Globals(map[string]any{
750 "default": "shadow me",
751 }),
752 Globals(map[string]any{
753 "default": "third",
754 }),
755 Globals(map[string]any{}),
756 )
757 if err != nil {
758 t.Fatalf("e.Program() failed: %v", err)
759 }
760
761 t.Run("bad_attrs", func(t *testing.T) {
762 out, _, err := prg.Eval(map[string]any{
763 "attrs": []string{"one", "two"},
764 })
765 if err == nil {
766 t.Errorf("prg.Eval() of incorrect arg type invoked function, wanted error, got %v", out)
767 }
768 })
769
770 t.Run("global_default", func(t *testing.T) {
771 vars := map[string]any{
772 "attrs": map[string]any{},
773 }
774 out, _, err := prg.Eval(vars)
775 if err != nil {
776 t.Fatalf("prg.Eval() failed: %v", err)
777 }
778 if out.Equal(types.String("third")) != types.True {
779 t.Errorf("got '%v', expected 'third'.", out.Value())
780 }
781 })
782
783 t.Run("attrs_alt", func(t *testing.T) {
784 vars := map[string]any{
785 "attrs": map[string]any{"second": "yep"}}
786 out, _, err := prg.Eval(vars)
787 if err != nil {
788 t.Fatalf("prg.Eval(vars) failed: %v", err)
789 }
790 if out.Equal(types.String("yep")) != types.True {
791 t.Errorf("got '%v', expected 'yep'.", out.Value())
792 }
793 })
794
795 t.Run("local_default", func(t *testing.T) {
796 vars := map[string]any{
797 "attrs": map[string]any{},
798 "default": "fourth"}
799 out, _, _ := prg.Eval(vars)
800 if out.Equal(types.String("fourth")) != types.True {
801 t.Errorf("got '%v', expected 'fourth'.", out.Value())
802 }
803 })
804 }
805
806 func TestMacroSubset(t *testing.T) {
807 // Only enable the 'has' macro rather than all parser macros.
808 env := testEnv(t,
809 ClearMacros(), Macros(HasMacro),
810 Variable("name", MapType(StringType, StringType)),
811 )
812 out, err := interpret(t, env, `has(name.first)`,
813 map[string]any{
814 "name": map[string]string{
815 "first": "Jim",
816 },
817 })
818 if err != nil {
819 t.Fatal(err)
820 }
821 if out != types.True {
822 t.Errorf("got %v, wanted true", out)
823 }
824 out, err = interpret(t, env, `[1, 2].all(i, i > 0)`, NoVars())
825 if err == nil {
826 t.Errorf("got %v, wanted err", out)
827 }
828 }
829
830 func TestCustomMacro(t *testing.T) {
831 joinMacro := NewReceiverMacro("join", 1,
832 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
833 delim := args[0]
834 iterIdent := meh.Ident("__iter__")
835 accuIdent := meh.AccuIdent()
836 accuInit := meh.LiteralString("")
837 condition := meh.LiteralBool(true)
838 step := meh.GlobalCall(
839 // __result__.size() > 0 ? __result__ + delim + __iter__ : __iter__
840 operators.Conditional,
841 meh.GlobalCall(operators.Greater, meh.ReceiverCall("size", accuIdent), meh.LiteralInt(0)),
842 meh.GlobalCall(operators.Add, meh.GlobalCall(operators.Add, accuIdent, delim), iterIdent),
843 iterIdent)
844 return meh.Fold(
845 "__iter__",
846 iterRange,
847 accuIdent.GetIdentExpr().GetName(),
848 accuInit,
849 condition,
850 step,
851 accuIdent), nil
852 })
853 env := testEnv(t, Macros(joinMacro))
854 ast, iss := env.Compile(`['hello', 'cel', 'friend'].join(',')`)
855 if iss.Err() != nil {
856 t.Fatal(iss.Err())
857 }
858 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
859 if err != nil {
860 t.Fatalf("program creation error: %s\n", err)
861 }
862 out, _, err := prg.Eval(NoVars())
863 if err != nil {
864 t.Fatal(err)
865 }
866 if out.Equal(types.String("hello,cel,friend")) != types.True {
867 t.Errorf("got %v, wanted 'hello,cel,friend'", out)
868 }
869 }
870
871 func TestMacroInterop(t *testing.T) {
872 existsOneMacro := NewReceiverMacro("exists_one", 2,
873 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
874 return ExistsOneMacroExpander(meh, iterRange, args)
875 })
876 transformMacro := NewReceiverMacro("transform", 2,
877 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
878 return MapMacroExpander(meh, iterRange, args)
879 })
880 filterMacro := NewReceiverMacro("filter", 2,
881 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
882 return FilterMacroExpander(meh, iterRange, args)
883 })
884 pairMacro := NewGlobalMacro("pair", 2,
885 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
886 return meh.NewMap(meh.NewMapEntry(args[0], args[1], false)), nil
887 })
888 getMacro := NewReceiverMacro("get", 2,
889 func(meh MacroExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
890 return meh.GlobalCall(
891 operators.Conditional,
892 meh.PresenceTest(meh.Copy(target), args[0].GetIdentExpr().GetName()),
893 meh.Select(meh.Copy(target), args[0].GetIdentExpr().GetName()),
894 meh.Copy(args[1]),
895 ), nil
896 })
897 env := testEnv(t, Macros(existsOneMacro, transformMacro, filterMacro, pairMacro, getMacro))
898 tests := []struct {
899 expr string
900 out ref.Val
901 }{
902 {
903 expr: `['tr', 's', 'fri'].filter(i, i.size() > 1).transform(i, i + 'end').exists_one(i, i == 'friend')`,
904 out: types.True,
905 },
906 {
907 expr: `pair('a', 'b')`,
908 out: types.DefaultTypeAdapter.NativeToValue(map[string]string{"a": "b"}),
909 },
910 {
911 expr: `{}.get(a, 'default')`,
912 out: types.String("default"),
913 },
914 {
915 expr: `{'a': 'b'}.get(a, 'default')`,
916 out: types.String("b"),
917 },
918 }
919
920 for _, tst := range tests {
921 ast, iss := env.Compile(tst.expr)
922 if iss.Err() != nil {
923 t.Fatal(iss.Err())
924 }
925 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
926 if err != nil {
927 t.Fatalf("program creation error: %s\n", err)
928 }
929 out, _, err := prg.Eval(NoVars())
930 if err != nil {
931 t.Fatal(err)
932 }
933 if out.Equal(tst.out) != types.True {
934 t.Errorf("got %v, wanted %v", out, tst.out)
935 }
936 }
937 }
938
939 func TestMacroModern(t *testing.T) {
940 existsOneMacro := ReceiverMacro("exists_one", 2, parser.MakeExistsOne)
941 transformMacro := ReceiverMacro("transform", 2, parser.MakeMap)
942 filterMacro := ReceiverMacro("filter", 2, parser.MakeFilter)
943 pairMacro := GlobalMacro("pair", 2,
944 func(mef MacroExprFactory, iterRange celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
945 return mef.NewMap(mef.NewMapEntry(args[0], args[1], false)), nil
946 })
947 getMacro := ReceiverMacro("get", 2,
948 func(mef MacroExprFactory, target celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
949 return mef.NewCall(
950 operators.Conditional,
951 mef.NewPresenceTest(mef.Copy(target), args[0].AsIdent()),
952 mef.NewSelect(mef.Copy(target), args[0].AsIdent()),
953 mef.Copy(args[1]),
954 ), nil
955 })
956 env := testEnv(t, Macros(existsOneMacro, transformMacro, filterMacro, pairMacro, getMacro))
957 tests := []struct {
958 expr string
959 out ref.Val
960 }{
961 {
962 expr: `['tr', 's', 'fri'].filter(i, i.size() > 1).transform(i, i + 'end').exists_one(i, i == 'friend')`,
963 out: types.True,
964 },
965 {
966 expr: `pair('a', 'b')`,
967 out: types.DefaultTypeAdapter.NativeToValue(map[string]string{"a": "b"}),
968 },
969 {
970 expr: `{}.get(a, 'default')`,
971 out: types.String("default"),
972 },
973 {
974 expr: `{'a': 'b'}.get(a, 'default')`,
975 out: types.String("b"),
976 },
977 }
978
979 for _, tst := range tests {
980 ast, iss := env.Compile(tst.expr)
981 if iss.Err() != nil {
982 t.Fatal(iss.Err())
983 }
984 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
985 if err != nil {
986 t.Fatalf("program creation error: %s\n", err)
987 }
988 out, _, err := prg.Eval(NoVars())
989 if err != nil {
990 t.Fatal(err)
991 }
992 if out.Equal(tst.out) != types.True {
993 t.Errorf("got %v, wanted %v", out, tst.out)
994 }
995 }
996 }
997
998 func TestCustomExistsMacro(t *testing.T) {
999 env := testEnv(t,
1000 Variable("attr", MapType(StringType, BoolType)),
1001 Macros(
1002 NewGlobalVarArgMacro("kleeneOr",
1003 func(meh MacroExprHelper, unused *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
1004 inputs := meh.NewList(args...)
1005 eqOne, err := ExistsMacroExpander(meh, inputs, []*exprpb.Expr{
1006 meh.Ident("__iter__"),
1007 meh.GlobalCall(operators.Equals, meh.Ident("__iter__"), meh.LiteralInt(1)),
1008 })
1009 if err != nil {
1010 return nil, err
1011 }
1012 eqZero, err := ExistsMacroExpander(meh, meh.Copy(inputs), []*exprpb.Expr{
1013 meh.Ident("__iter__"),
1014 meh.GlobalCall(operators.Equals, meh.Ident("__iter__"), meh.LiteralInt(0)),
1015 })
1016 if err != nil {
1017 return nil, err
1018 }
1019 return meh.GlobalCall(
1020 operators.Conditional,
1021 eqOne,
1022 meh.LiteralInt(1),
1023 meh.GlobalCall(
1024 operators.Conditional,
1025 eqZero,
1026 meh.LiteralInt(0),
1027 meh.LiteralInt(-1),
1028 ),
1029 ), nil
1030 },
1031 ),
1032 NewGlobalMacro("kleeneEq", 2,
1033 func(meh MacroExprHelper, unused *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
1034 attr := args[0]
1035 value := args[1]
1036 hasAttr, err := HasMacroExpander(meh, nil, []*exprpb.Expr{meh.Copy(attr)})
1037 if err != nil {
1038 return nil, err
1039 }
1040 return meh.GlobalCall(
1041 operators.Conditional,
1042 meh.GlobalCall(operators.LogicalNot, hasAttr),
1043 meh.LiteralInt(0),
1044 meh.GlobalCall(
1045 operators.Conditional,
1046 meh.GlobalCall(operators.Equals, attr, value),
1047 meh.LiteralInt(1),
1048 meh.LiteralInt(-1),
1049 ),
1050 ), nil
1051 },
1052 ),
1053 ),
1054 )
1055 prg := compile(t, env, "kleeneOr(kleeneEq(attr.value, true), kleeneOr(0, 1, 1)) == 1")
1056 out, _, err := prg.Eval(map[string]any{"attr": map[string]bool{"value": false}})
1057 if err != nil {
1058 t.Errorf("prg.Eval() got %v, wanted non-error", err)
1059 }
1060 if out != types.True {
1061 t.Errorf("prg.Eval() got %v, wanted true", out)
1062 }
1063 }
1064
1065 func TestAstIsChecked(t *testing.T) {
1066 env := testEnv(t)
1067 ast, iss := env.Compile("true")
1068 if iss.Err() != nil {
1069 t.Fatalf("e.Compile('true') failed: %v", iss.Err())
1070 }
1071 if !ast.IsChecked() {
1072 t.Error("got ast.IsChecked() 'false', wanted 'true'.")
1073 }
1074 ce, err := AstToCheckedExpr(ast)
1075 if err != nil {
1076 t.Fatalf("AstToCheckedExpr(%v) failed: %v", ast, err)
1077 }
1078 ast2 := CheckedExprToAst(ce)
1079 if !ast2.IsChecked() {
1080 t.Error("got ast2.IsChecked() 'false', wanted 'true'")
1081 }
1082 if !proto.Equal(ast.Expr(), ast2.Expr()) {
1083 t.Errorf("AST exprs did not roundtrip properly: ast1: %v, ast2: %v", ast, ast2)
1084 }
1085 }
1086
1087 func TestExhaustiveEval(t *testing.T) {
1088 env := testEnv(t,
1089 Variable("k", StringType),
1090 Variable("v", BoolType),
1091 )
1092 ast, iss := env.Compile(`{k: true}[k] || v != false`)
1093 if iss.Err() != nil {
1094 t.Fatalf("env.Compile() failed: %v", iss.Err())
1095 }
1096 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
1097 if err != nil {
1098 t.Fatalf("env.Program() failed: %s\n", err)
1099 }
1100 out, details, err := prg.Eval(
1101 map[string]any{
1102 "k": "key",
1103 "v": true})
1104 if err != nil {
1105 t.Fatalf("runtime error: %s\n", err)
1106 }
1107 if out != types.True {
1108 t.Errorf("got '%v', expected 'true'", out.Value())
1109 }
1110
1111 // Test to see whether 'v != false' was resolved to a value.
1112 // With short-circuiting it normally wouldn't be.
1113 s := details.State()
1114 lhsVal, found := s.Value(ast.Expr().GetCallExpr().GetArgs()[0].Id)
1115 if !found {
1116 t.Error("got not found, wanted evaluation of left hand side expression.")
1117 return
1118 }
1119 if lhsVal != types.True {
1120 t.Errorf("got '%v', expected 'true'", lhsVal)
1121 }
1122 rhsVal, found := s.Value(ast.Expr().GetCallExpr().GetArgs()[1].Id)
1123 if !found {
1124 t.Error("got not found, wanted evaluation of right hand side expression.")
1125 return
1126 }
1127 if rhsVal != types.True {
1128 t.Errorf("got '%v', expected 'true'", rhsVal)
1129 }
1130 }
1131
1132 func TestContextEval(t *testing.T) {
1133 env := testEnv(t, Variable("items", ListType(IntType)))
1134 ast, iss := env.Compile("items.map(i, i * 2).filter(i, i >= 50).size()")
1135 if iss.Err() != nil {
1136 t.Fatalf("env.Compile(expr) failed: %v", iss.Err())
1137 }
1138 prg, err := env.Program(ast, EvalOptions(OptOptimize|OptTrackState), InterruptCheckFrequency(100))
1139 if err != nil {
1140 t.Fatalf("env.Program() failed: %v", err)
1141 }
1142
1143 ctx := context.TODO()
1144 items := make([]int64, 2000)
1145 for i := int64(0); i < 2000; i++ {
1146 items[i] = i
1147 }
1148 out, _, err := prg.ContextEval(ctx, map[string]any{"items": items})
1149 if err != nil {
1150 t.Fatalf("prg.ContextEval() failed: %v", err)
1151 }
1152 if out != types.Int(1975) {
1153 t.Errorf("prg.ContextEval() got %v, wanted 1975", out)
1154 }
1155
1156 evalCtx, cancel := context.WithTimeout(ctx, time.Microsecond)
1157 defer cancel()
1158
1159 out, _, err = prg.ContextEval(evalCtx, map[string]any{"items": items})
1160 if err == nil {
1161 t.Errorf("Got result %v, wanted timeout error", out)
1162 }
1163 if err != nil && err.Error() != "operation interrupted" {
1164 t.Errorf("Got %v, wanted operation interrupted error", err)
1165 }
1166 }
1167
1168 func TestContextEvalUnknowns(t *testing.T) {
1169 env, err := NewEnv(
1170 Variable("groups", ListType(IntType)),
1171 Variable("id", IntType),
1172 )
1173 if err != nil {
1174 t.Fatalf("NewEnv() failed: %v", err)
1175 }
1176
1177 pvars, err := PartialVars(
1178 map[string]any{
1179 "groups": []int{1, 2, 3},
1180 },
1181 AttributePattern("id"),
1182 )
1183 if err != nil {
1184 t.Fatalf("PartialVars() failed: %v", err)
1185 }
1186
1187 ast, iss := env.Compile(`groups.exists(t, t == id)`)
1188 if iss.Err() != nil {
1189 t.Fatalf("env.Compile() failed: %v", iss.Err())
1190 }
1191
1192 prg, err := env.Program(ast, EvalOptions(OptTrackState, OptPartialEval), InterruptCheckFrequency(100))
1193 if err != nil {
1194 t.Fatalf("env.Program() failed: %v", err)
1195 }
1196
1197 out, _, err := prg.Eval(pvars)
1198 if err != nil {
1199 t.Fatalf("prg.Eval() failed: %v", err)
1200 }
1201 ctxOut, _, err := prg.ContextEval(context.Background(), pvars)
1202 if err != nil {
1203 t.Fatalf("prg.ContextEval() failed: %v", err)
1204 }
1205 if !reflect.DeepEqual(out, ctxOut) {
1206 t.Errorf("got %v, wanted %v", out, ctxOut)
1207 }
1208 }
1209
1210 func BenchmarkContextEval(b *testing.B) {
1211 env := testEnv(b,
1212 Variable("items", ListType(IntType)),
1213 )
1214 ast, iss := env.Compile("items.map(i, i * 2).filter(i, i >= 50).size()")
1215 if iss.Err() != nil {
1216 b.Fatalf("env.Compile(expr) failed: %v", iss.Err())
1217 }
1218 prg, err := env.Program(ast, EvalOptions(OptOptimize), InterruptCheckFrequency(200))
1219 if err != nil {
1220 b.Fatalf("env.Program() failed: %v", err)
1221 }
1222
1223 ctx := context.TODO()
1224 items := make([]int64, 100)
1225 for i := int64(0); i < 100; i++ {
1226 items[i] = i
1227 }
1228 for i := 0; i < b.N; i++ {
1229 out, _, err := prg.ContextEval(ctx, map[string]any{"items": items})
1230 if err != nil {
1231 b.Fatalf("prg.ContextEval() failed: %v", err)
1232 }
1233 if out != types.Int(75) {
1234 b.Errorf("prg.ContextEval() got %v, wanted 75", out)
1235 }
1236 }
1237 }
1238
1239 func TestEvalRecover(t *testing.T) {
1240 e := testEnv(t,
1241 Function("panic",
1242 Overload("global_panic", []*Type{}, BoolType,
1243 FunctionBinding(func(args ...ref.Val) ref.Val {
1244 panic("watch me recover")
1245 }),
1246 ),
1247 ),
1248 )
1249 // Test standard evaluation.
1250 pAst, iss := e.Parse("panic()")
1251 if iss.Err() != nil {
1252 t.Fatalf("e.Parse('panic()') failed: %v", iss.Err())
1253 }
1254 prgm, err := e.Program(pAst)
1255 if err != nil {
1256 t.Fatalf("e.Program(Ast) failed: %v", err)
1257 }
1258 _, _, err = prgm.Eval(map[string]any{})
1259 if err.Error() != "internal error: watch me recover" {
1260 t.Errorf("got '%v', wanted 'internal error: watch me recover'", err)
1261 }
1262 // Test the factory-based evaluation.
1263 prgm, _ = e.Program(pAst, EvalOptions(OptTrackState))
1264 _, _, err = prgm.Eval(map[string]any{})
1265 if err.Error() != "internal error: watch me recover" {
1266 t.Errorf("got '%v', wanted 'internal error: watch me recover'", err)
1267 }
1268 }
1269
1270 func TestResidualAst(t *testing.T) {
1271 env := testEnv(t,
1272 Variable("x", IntType),
1273 Variable("y", IntType),
1274 )
1275 unkVars := env.UnknownVars()
1276 ast, iss := env.Parse(`x < 10 && (y == 0 || 'hello' != 'goodbye')`)
1277 if iss.Err() != nil {
1278 t.Fatalf("env.Parse() failed: %v", iss.Err())
1279 }
1280 prg, err := env.Program(ast,
1281 EvalOptions(OptTrackState, OptPartialEval),
1282 )
1283 if err != nil {
1284 t.Fatalf("env.Program() failed: %v", err)
1285 }
1286 out, det, err := prg.Eval(unkVars)
1287 if !types.IsUnknown(out) {
1288 t.Fatalf("got %v, expected unknown", out)
1289 }
1290 if err != nil {
1291 t.Fatal(err)
1292 }
1293 residual, err := env.ResidualAst(ast, det)
1294 if err != nil {
1295 t.Fatal(err)
1296 }
1297 expr, err := AstToString(residual)
1298 if err != nil {
1299 t.Fatal(err)
1300 }
1301 if expr != "x < 10" {
1302 t.Errorf("got expr: %s, wanted x < 10", expr)
1303 }
1304 }
1305
1306 func TestResidualAstComplex(t *testing.T) {
1307 env := testEnv(t,
1308 Variable("resource.name", StringType),
1309 Variable("request.time", TimestampType),
1310 Variable("request.auth.claims", MapType(StringType, StringType)),
1311 )
1312 unkVars, _ := PartialVars(
1313 map[string]any{
1314 "resource.name": "bucket/my-bucket/objects/private",
1315 "request.auth.claims": map[string]string{
1316 "email_verified": "true",
1317 },
1318 },
1319 AttributePattern("request.auth.claims").QualString("email"),
1320 )
1321 ast, iss := env.Compile(
1322 `resource.name.startsWith("bucket/my-bucket") &&
1323 bool(request.auth.claims.email_verified) == true &&
1324 request.auth.claims.email == "[email protected]"`)
1325 if iss.Err() != nil {
1326 t.Fatalf("env.Compile() failed: %v", iss.Err())
1327 }
1328 prg, err := env.Program(ast,
1329 EvalOptions(OptTrackState, OptPartialEval),
1330 )
1331 if err != nil {
1332 t.Fatalf("env.Program() failed: %v", err)
1333 }
1334 out, det, err := prg.Eval(unkVars)
1335 if !types.IsUnknown(out) {
1336 t.Fatalf("got %v, expected unknown", out)
1337 }
1338 if err != nil {
1339 t.Fatal(err)
1340 }
1341 residual, err := env.ResidualAst(ast, det)
1342 if err != nil {
1343 t.Fatal(err)
1344 }
1345 expr, err := AstToString(residual)
1346 if err != nil {
1347 t.Fatal(err)
1348 }
1349 if expr != `request.auth.claims.email == "[email protected]"` {
1350 t.Errorf("got expr: %s, wanted request.auth.claims.email == \"[email protected]\"", expr)
1351 }
1352 }
1353
1354 func TestResidualAstMacros(t *testing.T) {
1355 tests := []struct {
1356 env *Env
1357 in map[string]any
1358 unks []*interpreter.AttributePattern
1359 expr string
1360 residual string
1361 }{
1362 {
1363 env: testEnv(t,
1364 Variable("x", ListType(IntType)),
1365 Variable("y", IntType),
1366 EnableMacroCallTracking()),
1367 in: map[string]any{"y": 11},
1368 unks: []*interpreter.AttributePattern{AttributePattern("x")},
1369 expr: `x.exists(i, i < 10) && [11, 12, 13].all(i, i in [y, 12, 13])`,
1370 residual: `x.exists(i, i < 10)`,
1371 },
1372 {
1373 env: testEnv(t,
1374 Variable("bar", MapType(StringType, DynType)),
1375 Variable("foo", MapType(StringType, DynType)),
1376 EnableMacroCallTracking()),
1377 in: map[string]any{"foo": map[string]any{"a": "b"}},
1378 unks: []*interpreter.AttributePattern{
1379 AttributePattern("bar").QualString("baz").Wildcard(),
1380 },
1381 expr: `foo.exists(t, t == bar.baz.x)`,
1382 residual: `{"a": "b"}.exists(t, t == bar.baz.x)`,
1383 },
1384 }
1385
1386 for i, tst := range tests {
1387 tc := tst
1388 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
1389 env := tc.env
1390 unkVars, err := PartialVars(tc.in, tc.unks...)
1391 if err != nil {
1392 t.Fatalf("PartialVars() failed: %v", err)
1393 }
1394 ast, iss := env.Compile(tc.expr)
1395 if iss.Err() != nil {
1396 t.Fatalf("env.Compile() failed: %v", iss.Err())
1397 }
1398 prg, err := env.Program(ast, EvalOptions(OptTrackState, OptPartialEval))
1399 if err != nil {
1400 t.Fatalf("env.Program() failed: %v", err)
1401 }
1402 out, det, err := prg.Eval(unkVars)
1403 if !types.IsUnknown(out) {
1404 t.Fatalf("got %v, expected unknown", out)
1405 }
1406 if err != nil {
1407 t.Fatalf("prg.Eval() failed: %v", err)
1408 }
1409 residual, err := env.ResidualAst(ast, det)
1410 if err != nil {
1411 t.Fatalf("env.ResidualAst() failed: %v", err)
1412 }
1413 expr, err := AstToString(residual)
1414 if err != nil {
1415 t.Fatalf("AstToString() failed: %v", err)
1416 }
1417 if expr != tc.residual {
1418 t.Errorf("got expr: %s, wanted %s", expr, tc.residual)
1419 }
1420 })
1421 }
1422 }
1423
1424 func TestResidualAstNil(t *testing.T) {
1425 env := testEnv(t)
1426 ast, err := env.ResidualAst(nil, nil)
1427 if err == nil || !strings.Contains(err.Error(), "unsupported expr") {
1428 t.Errorf("env.ResidualAst() got (%v, %v) wanted unsupported expr error", ast, err)
1429 }
1430 }
1431
1432 func BenchmarkEvalOptions(b *testing.B) {
1433 env := testEnv(b,
1434 Variable("ai", IntType),
1435 Variable("ar", MapType(StringType, StringType)),
1436 )
1437 ast, _ := env.Compile("ai == 20 || ar['foo'] == 'bar'")
1438 vars := map[string]any{
1439 "ai": 2,
1440 "ar": map[string]string{
1441 "foo": "bar",
1442 },
1443 }
1444
1445 opts := map[string]EvalOption{
1446 "track-state": OptTrackState,
1447 "exhaustive-eval": OptExhaustiveEval,
1448 "optimize": OptOptimize,
1449 }
1450 for k, opt := range opts {
1451 b.Run(k, func(bb *testing.B) {
1452 prg, err := env.Program(ast, EvalOptions(opt))
1453 if err != nil {
1454 b.Fatalf("env.Program() failed: %v", err)
1455 }
1456 b.ResetTimer()
1457 b.ReportAllocs()
1458 for i := 0; i < bb.N; i++ {
1459 _, _, err := prg.Eval(vars)
1460 if err != nil {
1461 b.Fatal(err)
1462 }
1463 }
1464 })
1465 }
1466 }
1467
1468 func TestEnvExtension(t *testing.T) {
1469 env := testEnv(t,
1470 Container("google.api.expr.v1alpha1"),
1471 Types(&exprpb.Expr{}),
1472 Variable("expr", ObjectType("google.api.expr.v1alpha1.Expr")),
1473 Variable("m", MapType(TypeParamType("K"), TypeParamType("V"))),
1474 OptionalTypes(),
1475 )
1476 e2, err := env.Extend(
1477 CustomTypeAdapter(types.DefaultTypeAdapter),
1478 Types(&proto3pb.TestAllTypes{}),
1479 OptionalTypes(),
1480 OptionalTypes(),
1481 OptionalTypes(),
1482 )
1483 if err != nil {
1484 t.Fatalf("env.Extend() failed: %v", err)
1485 }
1486 if env == e2 {
1487 t.Error("got object equality, wanted separate objects")
1488 }
1489 if env.TypeAdapter() == e2.TypeAdapter() {
1490 t.Error("got the same type adapter, wanted isolated instances.")
1491 }
1492 if env.TypeProvider() == e2.TypeProvider() {
1493 t.Error("got the same type provider, wanted isolated instances.")
1494 }
1495 e3, err := e2.Extend(OptionalTypes())
1496 if err != nil {
1497 t.Fatalf("env.Extend() failed: %v", err)
1498 }
1499 if e2.TypeAdapter() != e3.TypeAdapter() {
1500 t.Error("got different type adapters, wanted immutable adapter reference")
1501 }
1502 if e2.TypeProvider() == e3.TypeProvider() {
1503 t.Error("got the same type provider, wanted isolated instances.")
1504 }
1505 }
1506
1507 func TestEnvExtensionIsolation(t *testing.T) {
1508 baseEnv := testEnv(t,
1509 Container("google.expr"),
1510 Variable("age", IntType),
1511 Variable("gender", StringType),
1512 Variable("country", StringType),
1513 )
1514 env1, err := baseEnv.Extend(
1515 Types(&proto2pb.TestAllTypes{}),
1516 Variable("name", StringType),
1517 )
1518 if err != nil {
1519 t.Fatal(err)
1520 }
1521 env2, err := baseEnv.Extend(
1522 Types(&proto3pb.TestAllTypes{}),
1523 Variable("group", StringType),
1524 )
1525 if err != nil {
1526 t.Fatal(err)
1527 }
1528 _, issues := env2.Compile(`size(group) > 10
1529 && !has(proto3.test.TestAllTypes{}.single_int32)`)
1530 if issues.Err() != nil {
1531 t.Fatal(issues.Err())
1532 }
1533 _, issues = env2.Compile(`size(name) > 10`)
1534 if issues.Err() == nil {
1535 t.Fatal("env2 contains 'name', but should not")
1536 }
1537 _, issues = env2.Compile(`!has(proto2.test.TestAllTypes{}.single_int32)`)
1538 if issues.Err() == nil {
1539 t.Fatal("env2 contains 'proto2.test.TestAllTypes', but should not")
1540 }
1541
1542 _, issues = env1.Compile(`size(name) > 10
1543 && !has(proto2.test.TestAllTypes{}.single_int32)`)
1544 if issues.Err() != nil {
1545 t.Fatal(issues.Err())
1546 }
1547 _, issues = env1.Compile("size(group) > 10")
1548 if issues.Err() == nil {
1549 t.Fatal("env1 contains 'group', but should not")
1550 }
1551 _, issues = env1.Compile(`!has(proto3.test.TestAllTypes{}.single_int32)`)
1552 if issues.Err() == nil {
1553 t.Fatal("env1 contains 'proto3.test.TestAllTypes', but should not")
1554 }
1555 }
1556
1557 func TestVariadicLogicalOperators(t *testing.T) {
1558 env := testEnv(t, variadicLogicalOperatorASTs())
1559 ast, iss := env.Compile(
1560 `(false || false || false || false || true) &&
1561 (true && true && true && true && false)`)
1562 if iss.Err() != nil {
1563 t.Fatalf("Compile() failed: %v", iss.Err())
1564 }
1565 prg, err := env.Program(ast)
1566 if err != nil {
1567 t.Fatalf("Program(ast) failed: %v", err)
1568 }
1569 out, _, err := prg.Eval(NoVars())
1570 if err != nil {
1571 t.Errorf("Eval() got error %v, wanted false", err)
1572 }
1573 if out != types.False {
1574 t.Errorf("Eval() got %v, wanted false", out)
1575 }
1576 }
1577
1578 func TestParseError(t *testing.T) {
1579 env := testEnv(t)
1580 _, iss := env.Parse("invalid & logical_and")
1581 if iss.Err() == nil {
1582 t.Fatal("e.Parse('invalid & logical_and') did not error")
1583 }
1584 }
1585
1586 func TestParseWithMacroTracking(t *testing.T) {
1587 env := testEnv(t, EnableMacroCallTracking())
1588 ast, iss := env.Parse("has(a.b) && a.b.exists(c, c < 10)")
1589 if iss.Err() != nil {
1590 t.Fatalf("e.Parse() failed: %v", iss.Err())
1591 }
1592 pe, err := AstToParsedExpr(ast)
1593 if err != nil {
1594 t.Fatalf("AstToParsedExpr(%v) failed: %v", ast, err)
1595 }
1596 macroCalls := pe.GetSourceInfo().GetMacroCalls()
1597 if len(macroCalls) != 2 {
1598 t.Errorf("got %d macro calls, wanted 2", len(macroCalls))
1599 }
1600 callsFound := map[string]bool{"has": false, "exists": false}
1601 for _, expr := range macroCalls {
1602 f := expr.GetCallExpr().GetFunction()
1603 _, found := callsFound[f]
1604 if !found {
1605 t.Errorf("Unexpected macro call: %v", expr)
1606 }
1607 callsFound[f] = true
1608 }
1609 callsWanted := map[string]bool{"has": true, "exists": true}
1610 if !reflect.DeepEqual(callsFound, callsWanted) {
1611 t.Errorf("Tracked calls %v, but wanted %v", callsFound, callsWanted)
1612 }
1613 }
1614
1615 func TestParseAndCheckConcurrently(t *testing.T) {
1616 env := testEnv(t,
1617 Container("google.api.expr.v1alpha1"),
1618 Types(&exprpb.Expr{}),
1619 Variable("expr", ObjectType("google.api.expr.v1alpha1.Expr")),
1620 )
1621 parseAndCheck := func(expr string) {
1622 _, iss := env.Compile(expr)
1623 if iss.Err() != nil {
1624 t.Fatalf("e.Compile('%s') failed: %v", expr, iss.Err())
1625 }
1626 }
1627
1628 const concurrency = 10
1629 wgDone := sync.WaitGroup{}
1630 wgDone.Add(concurrency)
1631
1632 for i := 0; i < concurrency; i++ {
1633 go func(i int) {
1634 defer wgDone.Done()
1635 parseAndCheck(fmt.Sprintf("expr.id + %d", i))
1636 }(i)
1637 }
1638 wgDone.Wait()
1639 }
1640
1641 func TestCustomInterpreterDecorator(t *testing.T) {
1642 var lastInstruction interpreter.Interpretable
1643 optimizeArith := func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
1644 lastInstruction = i
1645 // Only optimize the instruction if it is a call.
1646 call, ok := i.(interpreter.InterpretableCall)
1647 if !ok {
1648 return i, nil
1649 }
1650 // Only optimize the math functions when they have constant arguments.
1651 switch call.Function() {
1652 case operators.Add,
1653 operators.Subtract,
1654 operators.Multiply,
1655 operators.Divide:
1656 // These are all binary operators so they should have to arguments
1657 args := call.Args()
1658 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1659 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1660 // When the values are constant then the call can be evaluated with
1661 // an empty activation and the value returns as a constant.
1662 if !lhsIsConst || !rhsIsConst {
1663 return i, nil
1664 }
1665 val := call.Eval(interpreter.EmptyActivation())
1666 if types.IsError(val) {
1667 return nil, val.(*types.Err)
1668 }
1669 return interpreter.NewConstValue(call.ID(), val), nil
1670 default:
1671 return i, nil
1672 }
1673 }
1674
1675 env := testEnv(t, Variable("foo", IntType))
1676 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1677 if iss.Err() != nil {
1678 t.Fatalf("env.Compile() failed: %v", iss.Err())
1679 }
1680 _, err := env.Program(ast,
1681 EvalOptions(OptPartialEval),
1682 CustomDecorator(optimizeArith))
1683 if err != nil {
1684 t.Fatalf("env.Program() failed: %v", err)
1685 }
1686 call, ok := lastInstruction.(interpreter.InterpretableCall)
1687 if !ok {
1688 t.Errorf("got %v, expected call", lastInstruction)
1689 }
1690 args := call.Args()
1691 lhs := args[0]
1692 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1693 if !ok {
1694 t.Errorf("got %v, wanted attribute", lhs)
1695 }
1696 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1697 varNames := absAttr.CandidateVariableNames()
1698 if len(varNames) != 1 || varNames[0] != "foo" {
1699 t.Errorf("got variables %v, wanted foo", varNames)
1700 }
1701 rhs := args[1]
1702 lastConst, ok := rhs.(interpreter.InterpretableConst)
1703 if !ok {
1704 t.Errorf("got %v, wanted constant", rhs)
1705 }
1706 // This is the last number produced by the optimization.
1707 if lastConst.Value().Equal(types.IntOne) == types.False {
1708 t.Errorf("got %v as the last observed constant, wanted 1", lastConst)
1709 }
1710 }
1711
1712 // TestEstimateCostAndRuntimeCost sanity checks that the cost systems are usable from the program API.
1713 func TestEstimateCostAndRuntimeCost(t *testing.T) {
1714 intList := ListType(IntType)
1715 zeroCost := checker.CostEstimate{}
1716 cases := []struct {
1717 name string
1718 expr string
1719 decls []EnvOption
1720 hints map[string]uint64
1721 want checker.CostEstimate
1722 in any
1723 }{
1724 {
1725 name: "const",
1726 expr: `"Hello World!"`,
1727 want: zeroCost,
1728 in: map[string]any{},
1729 },
1730 {
1731 name: "identity",
1732 expr: `input`,
1733 decls: []EnvOption{Variable("input", intList)},
1734 want: checker.CostEstimate{Min: 1, Max: 1},
1735 in: map[string]any{"input": []int{1, 2}},
1736 },
1737 {
1738 name: "str concat",
1739 expr: `"abcdefg".contains(str1 + str2)`,
1740 decls: []EnvOption{
1741 Variable("str1", StringType),
1742 Variable("str2", StringType),
1743 },
1744 hints: map[string]uint64{"str1": 10, "str2": 10},
1745 want: checker.CostEstimate{Min: 2, Max: 6},
1746 in: map[string]any{"str1": "val1111111", "str2": "val2222222"},
1747 },
1748 }
1749
1750 for _, tst := range cases {
1751 tc := tst
1752 t.Run(tc.name, func(t *testing.T) {
1753 t.Parallel()
1754 if tc.hints == nil {
1755 tc.hints = map[string]uint64{}
1756 }
1757 envOpts := []EnvOption{
1758 CostEstimatorOptions(
1759 checker.OverloadCostEstimate(overloads.TimestampToYear, estimateTimestampToYear),
1760 ),
1761 }
1762 envOpts = append(envOpts, tc.decls...)
1763 env := testEnv(t, envOpts...)
1764 ast, iss := env.Compile(tc.expr)
1765 if iss.Err() != nil {
1766 t.Fatalf("env.Compile(%v) failed: %v", tc.expr, iss.Err())
1767 }
1768 est, err := env.EstimateCost(ast, testCostEstimator{hints: tc.hints})
1769 if err != nil {
1770 t.Fatalf("Env.EstimateCost(ast *Ast, estimator checker.CostEstimator) failed to estimate cost: %s\n", err)
1771 }
1772 if est.Min != tc.want.Min || est.Max != tc.want.Max {
1773 t.Fatalf("Env.EstimateCost(ast *Ast, estimator checker.CostEstimator) failed to return the right cost interval. Got [%v, %v], wanted [%v, %v]",
1774 est.Min, est.Max, tc.want.Min, tc.want.Max)
1775 }
1776
1777 checkedAst, iss := env.Check(ast)
1778 if iss.Err() != nil {
1779 t.Fatalf(`Env.Check(ast *Ast) failed to check expression: %v`, iss.Err())
1780 }
1781 // Evaluate expression.
1782 program, err := env.Program(checkedAst,
1783 CostTracking(testRuntimeCostEstimator{}),
1784 CostTrackerOptions(
1785 interpreter.OverloadCostTracker(overloads.TimestampToYear, trackTimestampToYear),
1786 ),
1787 )
1788 if err != nil {
1789 t.Fatalf(`Env.Program(ast *Ast, opts ...ProgramOption) failed to construct program: %v`, err)
1790 }
1791 _, details, err := program.Eval(tc.in)
1792 if err != nil {
1793 t.Fatalf(`Program.Eval(vars any) failed to evaluate expression: %v`, err)
1794 }
1795 actualCost := details.ActualCost()
1796 if actualCost == nil {
1797 t.Errorf(`EvalDetails.ActualCost() got nil for "%s" cost, wanted %d`, tc.expr, actualCost)
1798 }
1799
1800 if est.Min > *actualCost || est.Max < *actualCost {
1801 t.Errorf("EvalDetails.ActualCost() failed to return a runtime cost %d is the range of estimate cost [%d, %d]", *actualCost,
1802 est.Min, est.Max)
1803 }
1804 })
1805 }
1806 }
1807
1808 func TestCostLimit(t *testing.T) {
1809 cases := []struct {
1810 name string
1811 expr string
1812 decls []EnvOption
1813 costLimit uint64
1814 in any
1815 err error
1816 }{
1817 {
1818 name: "greater",
1819 expr: `val1 > val2`,
1820 decls: []EnvOption{
1821 Variable("val1", IntType),
1822 Variable("val2", IntType),
1823 },
1824 in: map[string]any{"val1": 1, "val2": 2},
1825 costLimit: 10,
1826 },
1827 {
1828 name: "greater - error",
1829 expr: `val1 > val2`,
1830 decls: []EnvOption{
1831 Variable("val1", IntType),
1832 Variable("val2", IntType),
1833 },
1834 in: map[string]any{"val1": 1, "val2": 2},
1835 costLimit: 0,
1836 err: errors.New("actual cost limit exceeded"),
1837 },
1838 }
1839
1840 for _, tst := range cases {
1841 tc := tst
1842 t.Run(tc.name, func(t *testing.T) {
1843 t.Parallel()
1844 envOpts := []EnvOption{
1845 CostEstimatorOptions(
1846 checker.OverloadCostEstimate(overloads.TimestampToYear, estimateTimestampToYear),
1847 ),
1848 }
1849 envOpts = append(envOpts, tc.decls...)
1850 env := testEnv(t, envOpts...)
1851 ast, iss := env.Compile(tc.expr)
1852 if iss.Err() != nil {
1853 t.Fatalf("env.Compile(%v) failed: %v", tc.expr, iss.Err())
1854 }
1855 est, err := env.EstimateCost(ast, testCostEstimator{hints: map[string]uint64{}})
1856 if err != nil {
1857 t.Fatalf("Env.EstimateCost(ast *Ast, estimator checker.CostEstimator) failed to estimate cost: %s\n", err)
1858 }
1859
1860 checkedAst, iss := env.Check(ast)
1861 if iss.Err() != nil {
1862 t.Fatalf(`Env.Check(ast *Ast) failed to check expression: %v`, iss.Err())
1863 }
1864 // Evaluate expression.
1865 program, err := env.Program(checkedAst,
1866 CostTracking(testRuntimeCostEstimator{}),
1867 CostTrackerOptions(
1868 interpreter.OverloadCostTracker(overloads.TimestampToYear, trackTimestampToYear),
1869 ),
1870 CostLimit(tc.costLimit),
1871 )
1872 if err != nil {
1873 t.Fatalf(`Env.Program(ast *Ast, opts ...ProgramOption) failed to construct program: %v`, err)
1874 }
1875 _, details, err := program.Eval(tc.in)
1876 if err != nil && tc.err == nil {
1877 t.Fatalf(`Program.Eval(vars any) failed to evaluate expression: %v`, err)
1878 }
1879 actualCost := details.ActualCost()
1880 if actualCost == nil {
1881 t.Errorf(`EvalDetails.ActualCost() got nil for "%s" cost, wanted %d`, tc.expr, actualCost)
1882 }
1883 if err == nil {
1884 if est.Min > *actualCost || est.Max < *actualCost {
1885 t.Errorf("EvalDetails.ActualCost() failed to return a runtime cost %d is the range of estimate cost [%d, %d]", *actualCost,
1886 est.Min, est.Max)
1887 }
1888 } else {
1889 if !strings.Contains(err.Error(), tc.err.Error()) {
1890 t.Fatalf("program.Eval() got error %v, wanted error containing %v", err, tc.err)
1891 }
1892 }
1893 })
1894 }
1895 }
1896
1897 func TestPartialVars(t *testing.T) {
1898 env := testEnv(t,
1899 Variable("x", StringType),
1900 Variable("y", IntType),
1901 )
1902 ast, iss := env.Compile("x == string(y)")
1903 if iss.Err() != nil {
1904 t.Fatalf("env.Compile() failed: %v", iss.Err())
1905 }
1906 prg, err := env.Program(ast, EvalOptions(OptPartialEval))
1907 if err != nil {
1908 t.Fatalf("env.Program() failed: %v", err)
1909 }
1910
1911 tests := []struct {
1912 in map[string]any
1913 unk []*interpreter.AttributePattern
1914 out ref.Val
1915 partialOut ref.Val
1916 }{
1917 {
1918 in: map[string]any{},
1919 unk: []*interpreter.AttributePattern{
1920 interpreter.NewAttributePattern("x"),
1921 interpreter.NewAttributePattern("y"),
1922 },
1923 out: types.NewUnknown(1, types.NewAttributeTrail("x")),
1924 },
1925 {
1926 in: map[string]any{"x": "10"},
1927 unk: []*interpreter.AttributePattern{
1928 interpreter.NewAttributePattern("y"),
1929 },
1930 out: types.NewUnknown(4, types.NewAttributeTrail("y")),
1931 },
1932 {
1933 in: map[string]any{"y": 10},
1934 unk: []*interpreter.AttributePattern{
1935 interpreter.NewAttributePattern("x"),
1936 },
1937 out: types.NewUnknown(1, types.NewAttributeTrail("x")),
1938 },
1939 {
1940 in: map[string]any{"x": "10", "y": 10},
1941 unk: []*interpreter.AttributePattern{},
1942 out: types.True,
1943 },
1944 {
1945 in: map[string]any{"x": "10", "y": 9},
1946 unk: []*interpreter.AttributePattern{},
1947 out: types.False,
1948 },
1949 {
1950 in: map[string]any{"y": 10},
1951 unk: []*interpreter.AttributePattern{},
1952 out: types.NewErr("no such attribute: x"),
1953 partialOut: types.NewUnknown(1, types.NewAttributeTrail("x")),
1954 },
1955 {
1956 in: map[string]any{"x": "10"},
1957 unk: []*interpreter.AttributePattern{},
1958 out: types.NewErr("no such attribute: y"),
1959 partialOut: types.NewUnknown(4, types.NewAttributeTrail("y")),
1960 },
1961 {
1962 in: map[string]any{},
1963 unk: []*interpreter.AttributePattern{},
1964 out: types.NewErr("no such attribute: x"),
1965 partialOut: types.NewUnknown(1, types.NewAttributeTrail("x")),
1966 },
1967 }
1968 for i, tst := range tests {
1969 tc := tst
1970 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
1971 // Manually configured unknown patterns
1972 vars, err := PartialVars(tc.in, tc.unk...)
1973 if err != nil {
1974 t.Fatalf("PartialVars() failed: %v", err)
1975 }
1976 out, _, err := prg.Eval(vars)
1977 if err != nil {
1978 if types.IsError(out) {
1979 if !out.(*types.Err).Is(err) {
1980 t.Errorf("Eval() got %v, wanted error %v", err, out)
1981 }
1982 }
1983 } else if types.IsUnknown(out) {
1984 if !reflect.DeepEqual(out, tc.out) {
1985 t.Errorf("Eval() got unknown %v, wanted %v", out, tc.out)
1986 }
1987 } else if out.Equal(tc.out) != types.True {
1988 t.Errorf("Eval() got %v, wanted %v", out, tc.out)
1989 }
1990 // Inferred unknown patterns
1991 vars2, err := env.PartialVars(tc.in)
1992 if err != nil {
1993 t.Fatalf("env.PartialVars() failed: %v", err)
1994 }
1995 out2, _, err := prg.Eval(vars2)
1996 if err != nil {
1997 t.Fatalf("prg.Eval() with inferred unknowns failed: %v", err)
1998 }
1999 want := tc.out
2000 if tc.partialOut != nil {
2001 want = tc.partialOut
2002 }
2003 if types.IsUnknown(out2) {
2004 if !reflect.DeepEqual(out2, want) {
2005 t.Errorf("Eval() got unknown %v, wanted %v", out2, want)
2006 }
2007 } else if out2.Equal(want) != types.True {
2008 t.Errorf("Eval() got %v, wanted %v", out2, want)
2009 }
2010 })
2011 }
2012 }
2013
2014 func TestResidualAstAttributeQualifiers(t *testing.T) {
2015 env := testEnv(t,
2016 Variable("x", MapType(StringType, DynType)),
2017 Variable("y", ListType(IntType)),
2018 Variable("u", IntType),
2019 )
2020 ast, iss := env.Parse(`x.abc == u && x["abc"] == u && x[x.string] == u && y[0] == u && y[x.zero] == u && (true ? x : y).abc == u && (false ? y : x).abc == u`)
2021 if iss.Err() != nil {
2022 t.Fatalf("env.Parse() failed: %v", iss.Err())
2023 }
2024 prg, err := env.Program(ast,
2025 EvalOptions(OptTrackState, OptPartialEval),
2026 )
2027 if err != nil {
2028 t.Fatalf("env.Program() failed: %v", err)
2029 }
2030 vars, _ := PartialVars(map[string]any{
2031 "x": map[string]any{
2032 "zero": 0,
2033 "abc": 123,
2034 "string": "abc",
2035 },
2036 "y": []int{123},
2037 }, AttributePattern("u"))
2038 out, det, err := prg.ContextEval(context.TODO(), vars)
2039 if !types.IsUnknown(out) {
2040 t.Fatalf("got %v, expected unknown", out)
2041 }
2042 if err != nil {
2043 t.Fatal(err)
2044 }
2045 residual, err := env.ResidualAst(ast, det)
2046 if err != nil {
2047 t.Fatal(err)
2048 }
2049 expr, err := AstToString(residual)
2050 if err != nil {
2051 t.Fatal(err)
2052 }
2053 const want = "123 == u && 123 == u && 123 == u && 123 == u && 123 == u && 123 == u && 123 == u"
2054 if expr != want {
2055 t.Errorf("got expr: %s, wanted %s", expr, want)
2056 }
2057 }
2058
2059 func TestPartialVarsEnv(t *testing.T) {
2060 env := testEnv(t,
2061 Variable("x", IntType),
2062 Variable("y", IntType),
2063 )
2064
2065 // Use env to make sure internals are all initialized.
2066 ast, iss := env.Compile("x == y")
2067
2068 if iss.Err() != nil {
2069 t.Fatalf("env.Compile() failed: %v", iss.Err())
2070 }
2071 prg, err := env.Program(ast, EvalOptions(OptPartialEval))
2072 if err != nil {
2073 t.Fatalf("env.Program() failed: %v", err)
2074 }
2075
2076 act, err := env.PartialVars(map[string]any{"x": 1, "y": 1})
2077
2078 if err != nil {
2079 t.Fatalf("env.PartialVars failed: %v", err)
2080 }
2081 val, _, err := prg.Eval(act)
2082 if err != nil {
2083 t.Fatalf("Eval failed: %v", err)
2084 }
2085
2086 if val != types.True {
2087 t.Fatalf("want: %v, got: %v", types.True, val)
2088 }
2089 }
2090
2091 func TestPartialVarsExtendedEnv(t *testing.T) {
2092 env := testEnv(t,
2093 Variable("x", IntType),
2094 Variable("y", IntType),
2095 )
2096
2097 env.Compile("x == y")
2098 // Now test that a sub environment is correctly copied.
2099 env2, err := env.Extend(Variable("z", IntType))
2100 if err != nil {
2101 t.Fatalf("env.Extend failed: %v", err)
2102 }
2103
2104 ast, iss := env2.Compile("x == y && y == z")
2105
2106 if iss.Err() != nil {
2107 t.Fatalf("env.Compile() failed: %v", iss.Err())
2108 }
2109 prg, err := env2.Program(ast, EvalOptions(OptPartialEval))
2110 if err != nil {
2111 t.Fatalf("env.Program() failed: %v", err)
2112 }
2113
2114 act, err := env2.PartialVars(map[string]any{"z": 1, "y": 1})
2115
2116 if err != nil {
2117 t.Fatalf("env.PartialVars failed: %v", err)
2118 }
2119 val, _, err := prg.Eval(act)
2120 if err != nil {
2121 t.Fatalf("Eval failed: %v", err)
2122 }
2123 if !types.IsUnknown(val) {
2124 t.Fatalf("Wanted unknown, got %v", val)
2125 }
2126
2127 if !reflect.DeepEqual(val, types.NewUnknown(1, types.NewAttributeTrail("x"))) {
2128 t.Fatalf("Wanted Unknown(x (1)), got: %v", val)
2129 }
2130 }
2131
2132 func TestResidualAstModified(t *testing.T) {
2133 env := testEnv(t,
2134 Variable("x", MapType(StringType, IntType)),
2135 Variable("y", IntType),
2136 )
2137 ast, iss := env.Parse("x == y")
2138 if iss.Err() != nil {
2139 t.Fatalf("env.Parse() failed: %v", iss.Err())
2140 }
2141 prg, err := env.Program(ast,
2142 EvalOptions(OptTrackState, OptPartialEval),
2143 )
2144 if err != nil {
2145 t.Fatalf("env.Program() failed: %v", err)
2146 }
2147 for _, x := range []int{123, 456} {
2148 vars, _ := PartialVars(map[string]any{
2149 "x": x,
2150 }, AttributePattern("y"))
2151 out, det, err := prg.Eval(vars)
2152 if !types.IsUnknown(out) {
2153 t.Fatalf("got %v, expected unknown", out)
2154 }
2155 if err != nil {
2156 t.Fatal(err)
2157 }
2158 residual, err := env.ResidualAst(ast, det)
2159 if err != nil {
2160 t.Fatal(err)
2161 }
2162 orig, err := AstToString(ast)
2163 if err != nil {
2164 t.Fatal(err)
2165 }
2166 if orig != "x == y" {
2167 t.Errorf("parsed ast: got expr: %s, wanted x == y", orig)
2168 }
2169 expr, err := AstToString(residual)
2170 if err != nil {
2171 t.Fatal(err)
2172 }
2173 want := fmt.Sprintf("%d == y", x)
2174 if expr != want {
2175 t.Errorf("residual ast: got expr: %s, wanted %s", expr, want)
2176 }
2177 }
2178 }
2179
2180 func TestContextProto(t *testing.T) {
2181 descriptor := new(proto3pb.TestAllTypes).ProtoReflect().Descriptor()
2182 option := DeclareContextProto(descriptor)
2183 env := testEnv(t, option)
2184 expression := `
2185 single_int64 == 1
2186 && single_double == 1.0
2187 && single_bool == true
2188 && single_string == ''
2189 && single_nested_message == google.expr.proto3.test.TestAllTypes.NestedMessage{}
2190 && standalone_enum == google.expr.proto3.test.TestAllTypes.NestedEnum.FOO
2191 && single_duration == duration('5s')
2192 && single_timestamp == timestamp(63154820)
2193 && single_any == null
2194 && single_uint32_wrapper == null
2195 && single_uint64_wrapper == 0u
2196 && repeated_int32 == [1,2]
2197 && map_string_string == {'': ''}
2198 && map_int64_nested_type == {0 : google.expr.proto3.test.NestedTestAllTypes{}}`
2199 ast, iss := env.Compile(expression)
2200 if iss.Err() != nil {
2201 t.Fatalf("env.Compile(%s) failed: %s", expression, iss.Err())
2202 }
2203 prg, err := env.Program(ast)
2204 if err != nil {
2205 t.Fatalf("env.Program() failed: %v", err)
2206 }
2207 in := &proto3pb.TestAllTypes{
2208 SingleInt64: 1,
2209 SingleDouble: 1.0,
2210 SingleBool: true,
2211 NestedType: &proto3pb.TestAllTypes_SingleNestedMessage{
2212 SingleNestedMessage: &proto3pb.TestAllTypes_NestedMessage{},
2213 },
2214 StandaloneEnum: proto3pb.TestAllTypes_FOO,
2215 SingleDuration: &durationpb.Duration{Seconds: 5},
2216 SingleTimestamp: &timestamppb.Timestamp{
2217 Seconds: 63154820,
2218 },
2219 SingleUint64Wrapper: wrapperspb.UInt64(0),
2220 RepeatedInt32: []int32{1, 2},
2221 MapStringString: map[string]string{"": ""},
2222 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{0: {}},
2223 }
2224 vars, err := ContextProtoVars(in)
2225 if err != nil {
2226 t.Fatalf("ContextProtoVars(%v) failed: %v", in, err)
2227 }
2228 out, _, err := prg.Eval(vars)
2229 if err != nil {
2230 t.Fatalf("prg.Eval() failed: %v", err)
2231 }
2232 if out.Equal(types.True) != types.True {
2233 t.Errorf("prg.Eval() got %v, wanted true", out)
2234 }
2235 }
2236
2237 func TestRegexOptimizer(t *testing.T) {
2238 var stringTests = []struct {
2239 expr string
2240 optimizeRegex bool
2241 progErr string
2242 err string
2243 parseOnly bool
2244 }{
2245 {expr: `"123 abc 456".matches('[0-9]*')`},
2246 {expr: `"123 abc 456".matches('[0-9]' + '*')`},
2247 {expr: `"123 abc 456".matches('[0-9]*')`, optimizeRegex: true},
2248 {expr: `"123 abc 456".matches('[0-9]' + '*')`, optimizeRegex: true},
2249 {
2250 // Verify that a regex compilation error for an optimized regex is
2251 // reported at program creation time.
2252 expr: `"123 abc 456".matches(')[0-9]*')`, optimizeRegex: true,
2253 progErr: "error parsing regexp: unexpected ): `)[0-9]*`",
2254 },
2255 {
2256 expr: `"123 abc 456".matches(')[0-9]*')`,
2257 err: "error parsing regexp: unexpected ): `)[0-9]*`",
2258 },
2259 }
2260
2261 env := testEnv(t)
2262 for i, tst := range stringTests {
2263 tc := tst
2264 t.Run(fmt.Sprintf("[%d]", i), func(tt *testing.T) {
2265 var asts []*Ast
2266 pAst, iss := env.Parse(tc.expr)
2267 if iss.Err() != nil {
2268 tt.Fatal(iss.Err())
2269 }
2270 asts = append(asts, pAst)
2271 if !tc.parseOnly {
2272 cAst, iss := env.Check(pAst)
2273 if iss.Err() != nil {
2274 tt.Fatal(iss.Err())
2275 }
2276 asts = append(asts, cAst)
2277 }
2278 for _, ast := range asts {
2279 var opts []ProgramOption
2280 if tc.optimizeRegex {
2281 opts = append(opts, EvalOptions(OptOptimize))
2282 }
2283 prg, progErr := env.Program(ast, opts...)
2284 if tc.progErr != "" {
2285 if progErr == nil {
2286 tt.Fatalf("wanted error %s for expr: %s", tc.progErr, tc.expr)
2287 }
2288 if tc.progErr != progErr.Error() {
2289 tt.Errorf("got error %v, wanted error %s for expr: %s", progErr, tc.progErr, tc.expr)
2290 }
2291 continue
2292 } else if progErr != nil {
2293 tt.Fatal(progErr)
2294 }
2295 out, _, err := prg.Eval(NoVars())
2296 if tc.err != "" {
2297 if err == nil {
2298 tt.Fatalf("got value %v, wanted error %s for expr: %s",
2299 out.Value(), tc.err, tc.expr)
2300 }
2301 if tc.err != err.Error() {
2302 tt.Errorf("got error %v, wanted error %s for expr: %s", err, tc.err, tc.expr)
2303 }
2304 } else if err != nil {
2305 tt.Fatal(err)
2306 } else if out.Value() != true {
2307 tt.Errorf("got %v, wanted true for expr: %s", out.Value(), tc.expr)
2308 }
2309 }
2310 })
2311 }
2312 }
2313
2314 func TestDefaultUTCTimeZoneDisabled(t *testing.T) {
2315 testEnvs := []struct {
2316 name string
2317 env *Env
2318 }{
2319 {"default", testEnv(t, Variable("x", TimestampType))},
2320 {"enabled", testEnv(t, Variable("x", TimestampType), DefaultUTCTimeZone(true))},
2321 {"disabled", testEnv(t, Variable("x", TimestampType), DefaultUTCTimeZone(false))},
2322 }
2323 exprs := []struct {
2324 name string
2325 value string
2326 envOut map[string]ref.Val
2327 }{
2328 {
2329 name: "default-timezone",
2330 value: `
2331 x.getFullYear() == 1970
2332 && x.getMonth() == 0
2333 && x.getDayOfYear() == 0
2334 && x.getDayOfMonth() == 0
2335 && x.getDate() == 1
2336 && x.getDayOfWeek() == 4
2337 && x.getHours() == 2
2338 && x.getMinutes() == 5
2339 && x.getSeconds() == 6
2340 && x.getMilliseconds() == 1`,
2341 envOut: map[string]ref.Val{
2342 "default": types.True,
2343 "enabled": types.True,
2344 "disabled": types.False,
2345 },
2346 },
2347 {
2348 name: "default-local-year",
2349 value: `x.getFullYear()`,
2350 envOut: map[string]ref.Val{
2351 "default": types.Int(1970),
2352 "enabled": types.Int(1970),
2353 "disabled": types.Int(1969),
2354 },
2355 },
2356 {
2357 name: "default-local-day-of-year",
2358 value: `x.getDayOfYear()`,
2359 envOut: map[string]ref.Val{
2360 "default": types.Int(0),
2361 "enabled": types.Int(0),
2362 "disabled": types.Int(364),
2363 },
2364 },
2365 {
2366 name: "default-local-month",
2367 value: `x.getMonth()`,
2368 envOut: map[string]ref.Val{
2369 "default": types.Int(0),
2370 "enabled": types.Int(0),
2371 "disabled": types.Int(11),
2372 },
2373 },
2374 {
2375 name: "default-local-day-of-month",
2376 value: `
2377 x.getDayOfMonth() == 30
2378 && x.getDate() == 31`,
2379 envOut: map[string]ref.Val{
2380 "default": types.False,
2381 "enabled": types.False,
2382 "disabled": types.True,
2383 },
2384 },
2385 {
2386 name: "default-local-dates",
2387 value: `x.getDayOfWeek()`,
2388 envOut: map[string]ref.Val{
2389 "default": types.Int(4),
2390 "enabled": types.Int(4),
2391 "disabled": types.Int(3),
2392 },
2393 },
2394 {
2395 name: "default-local-times",
2396 value: `
2397 x.getHours() == 18
2398 && x.getMinutes() == 5
2399 && x.getSeconds() == 6
2400 && x.getMilliseconds() == 1`,
2401 envOut: map[string]ref.Val{
2402 "default": types.False,
2403 "enabled": types.False,
2404 "disabled": types.True,
2405 },
2406 },
2407 {
2408 name: "explicit",
2409 value: `
2410 x.getFullYear('-07:30') == 1969
2411 && x.getDayOfYear('-07:30') == 364
2412 && x.getMonth('-07:30') == 11
2413 && x.getDayOfMonth('-07:30') == 30
2414 && x.getDate('-07:30') == 31
2415 && x.getDayOfWeek('-07:30') == 3
2416 && x.getHours('-07:30') == 18
2417 && x.getMinutes('-07:30') == 35
2418 && x.getSeconds('-07:30') == 6
2419 && x.getMilliseconds('-07:30') == 1
2420 && x.getFullYear('23:15') == 1970
2421 && x.getDayOfYear('23:15') == 1
2422 && x.getMonth('23:15') == 0
2423 && x.getDayOfMonth('23:15') == 1
2424 && x.getDate('23:15') == 2
2425 && x.getDayOfWeek('23:15') == 5
2426 && x.getHours('23:15') == 1
2427 && x.getMinutes('23:15') == 20
2428 && x.getSeconds('23:15') == 6
2429 && x.getMilliseconds('23:15') == 1`,
2430 envOut: map[string]ref.Val{
2431 "default": types.True,
2432 "enabled": types.True,
2433 "disabled": types.True,
2434 },
2435 },
2436 }
2437
2438 offset, _ := time.ParseDuration("-8h")
2439 vars := map[string]any{
2440 "x": time.Unix(7506, 1000000).In(time.FixedZone("", int(offset.Seconds()))),
2441 }
2442 for _, e := range testEnvs {
2443 te := e
2444 for _, expr := range exprs {
2445 ex := expr
2446 t.Run(fmt.Sprintf("%s/%s", te.name, ex.name), func(t *testing.T) {
2447 env := te.env
2448 expr := ex.value
2449 out, err := interpret(t, env, expr, vars)
2450 if err != nil {
2451 t.Fatal(err)
2452 }
2453 if out.Equal(ex.envOut[te.name]) != types.True {
2454 t.Errorf("interpret got %v, wanted %v", out, ex.envOut[te.name])
2455 }
2456 })
2457 }
2458 }
2459 }
2460
2461 func TestDefaultUTCTimeZoneExtension(t *testing.T) {
2462 env := testEnv(t,
2463 Variable("x", TimestampType),
2464 Variable("y", DurationType),
2465 )
2466 env, err := env.Extend()
2467 if err != nil {
2468 t.Fatalf("env.Extend() failed: %v", err)
2469 }
2470 out, err := interpret(t, env, `
2471 x.getFullYear() == 1970
2472 && y.getHours() == 2
2473 && y.getMinutes() == 120
2474 && y.getSeconds() == 7235
2475 && y.getMilliseconds() == 7235000`,
2476 map[string]any{
2477 "x": time.Unix(7506, 1000000).Local(),
2478 "y": time.Duration(7235) * time.Second,
2479 },
2480 )
2481 if err != nil {
2482 t.Fatalf("prg.Eval() failed: %v", err)
2483 }
2484 if out != types.True {
2485 t.Errorf("Eval() got %v, wanted true", out.Value())
2486 }
2487 }
2488
2489 func TestDefaultUTCTimeZoneError(t *testing.T) {
2490 env := testEnv(t, Variable("x", TimestampType))
2491 out, err := interpret(t, env, `
2492 x.getFullYear(':xx') == 1969
2493 || x.getDayOfYear('xx:') == 364
2494 || x.getMonth('Am/Ph') == 11
2495 || x.getDayOfMonth('Am/Ph') == 30
2496 || x.getDate('Am/Ph') == 31
2497 || x.getDayOfWeek('Am/Ph') == 3
2498 || x.getHours('Am/Ph') == 19
2499 || x.getMinutes('Am/Ph') == 5
2500 || x.getSeconds('Am/Ph') == 6
2501 || x.getMilliseconds('Am/Ph') == 1
2502 `, map[string]any{
2503 "x": time.Unix(7506, 1000000).Local(),
2504 })
2505 if err == nil {
2506 t.Fatalf("prg.Eval() got %v wanted error", out)
2507 }
2508 }
2509
2510 func TestParserRecursionLimit(t *testing.T) {
2511 testCases := []struct {
2512 expr string
2513 errorSubstr string
2514 out ref.Val
2515 }{
2516 {
2517 expr: `0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11`,
2518 errorSubstr: "max recursion depth exceeded",
2519 },
2520 {
2521 expr: `0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10`,
2522 out: types.Int(55),
2523 },
2524 {
2525 expr: `0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 == 45`,
2526 errorSubstr: "max recursion depth exceeded",
2527 },
2528 {
2529 // Operator precedence means that '==' is the root.
2530 expr: `0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 == 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9`,
2531 out: types.True,
2532 },
2533 }
2534 for _, tc := range testCases {
2535 tc := tc
2536 t.Run(tc.expr, func(t *testing.T) {
2537 env := testEnv(t, ParserRecursionLimit(10))
2538 out, err := interpret(t, env,
2539 tc.expr, map[string]any{})
2540
2541 if tc.errorSubstr != "" {
2542 if err == nil || !strings.Contains(err.Error(), tc.errorSubstr) {
2543 t.Fatalf("prg.Eval() wanted error containing '%s' got %v", tc.errorSubstr, err)
2544 }
2545 }
2546
2547 if tc.out != nil {
2548 if tc.out != out {
2549 t.Errorf("prg.Eval() wanted %v got %v", tc.out, out)
2550 }
2551 }
2552 })
2553
2554 }
2555 }
2556
2557 func TestQuotedFields(t *testing.T) {
2558 testCases := []struct {
2559 expr string
2560 errorSubstr string
2561 out ref.Val
2562 }{
2563 {
2564 expr: "{'key-1': 64}.`key-1`",
2565 out: types.Int(64),
2566 },
2567 {
2568 expr: "{'key-1': 64}.`key-2`",
2569 errorSubstr: "no such key: key-2",
2570 },
2571 {
2572 expr: "has({'key-1': 64}.`key-1`)",
2573 out: types.True,
2574 },
2575 {
2576 expr: "has({'key-1': 64}.`key-2`)",
2577 out: types.False,
2578 },
2579 }
2580 for _, tc := range testCases {
2581 tc := tc
2582 t.Run(tc.expr, func(t *testing.T) {
2583 env := testEnv(t, ParserRecursionLimit(10),
2584 EnableIdentifierEscapeSyntax())
2585 out, err := interpret(t, env,
2586 tc.expr, map[string]any{})
2587
2588 if tc.errorSubstr != "" {
2589 if err == nil || !strings.Contains(err.Error(), tc.errorSubstr) {
2590 t.Fatalf("prg.Eval() wanted error containing '%s' got %v", tc.errorSubstr, err)
2591 }
2592 }
2593
2594 if tc.out != nil {
2595 if tc.out != out {
2596 t.Errorf("prg.Eval() wanted %v got %v", tc.out, out)
2597 }
2598 }
2599 })
2600
2601 }
2602 }
2603
2604 func TestDynamicDispatch(t *testing.T) {
2605 env := testEnv(t,
2606 HomogeneousAggregateLiterals(),
2607 Function("first",
2608 MemberOverload("first_list_int", []*Type{ListType(IntType)}, IntType,
2609 UnaryBinding(func(list ref.Val) ref.Val {
2610 l := list.(traits.Lister)
2611 if l.Size() == types.IntZero {
2612 return types.IntZero
2613 }
2614 return l.Get(types.IntZero)
2615 }),
2616 ),
2617 MemberOverload("first_list_double", []*Type{ListType(DoubleType)}, DoubleType,
2618 UnaryBinding(func(list ref.Val) ref.Val {
2619 l := list.(traits.Lister)
2620 if l.Size() == types.IntZero {
2621 return types.Double(0.0)
2622 }
2623 return l.Get(types.IntZero)
2624 }),
2625 ),
2626 MemberOverload("first_list_string", []*Type{ListType(StringType)}, StringType,
2627 UnaryBinding(func(list ref.Val) ref.Val {
2628 l := list.(traits.Lister)
2629 if l.Size() == types.IntZero {
2630 return types.String("")
2631 }
2632 return l.Get(types.IntZero)
2633 }),
2634 ),
2635 MemberOverload("first_list_list_string", []*Type{ListType(ListType(StringType))}, ListType(StringType),
2636 UnaryBinding(func(list ref.Val) ref.Val {
2637 l := list.(traits.Lister)
2638 if l.Size() == types.IntZero {
2639 return types.DefaultTypeAdapter.NativeToValue([]string{})
2640 }
2641 return l.Get(types.IntZero)
2642 }),
2643 ),
2644 ),
2645 )
2646 out, err := interpret(t, env, `
2647 dyn([]).first() == 0
2648 && [1, 2].first() == 1
2649 && [1.0, 2.0].first() == 1.0
2650 && ["hello", "world"].first() == "hello"
2651 && [["hello"], ["world", "!"]].first().first() == "hello"
2652 && [[], ["empty"]].first().first() == ""
2653 && dyn([1, 2]).first() == 1
2654 && dyn([1.0, 2.0]).first() == 1.0
2655 && dyn(["hello", "world"]).first() == "hello"
2656 && dyn([["hello"], ["world", "!"]]).first().first() == "hello"
2657 `, map[string]any{},
2658 )
2659 if err != nil {
2660 t.Fatalf("prg.Eval() failed: %v", err)
2661 }
2662 if out != types.True {
2663 t.Fatalf("prg.Eval() got %v wanted true", out)
2664 }
2665 }
2666
2667 func TestOptionalValuesCompile(t *testing.T) {
2668 env := testEnv(t,
2669 OptionalTypes(),
2670 // Test variables.
2671 Variable("m", MapType(StringType, MapType(StringType, StringType))),
2672 Variable("optm", OptionalType(MapType(StringType, MapType(StringType, StringType)))),
2673 Variable("l", ListType(StringType)),
2674 Variable("optl", OptionalType(ListType(StringType))),
2675 Variable("x", OptionalType(IntType)),
2676 Variable("y", IntType),
2677 )
2678 tests := []struct {
2679 expr string
2680 references map[int64]*celast.ReferenceInfo
2681 }{
2682 {
2683 expr: `x.or(optional.of(y)).orValue(42)`,
2684 references: map[int64]*celast.ReferenceInfo{
2685 1: {Name: "x"},
2686 2: {OverloadIDs: []string{"optional_or_optional"}},
2687 4: {OverloadIDs: []string{"optional_of"}},
2688 5: {Name: "y"},
2689 6: {OverloadIDs: []string{"optional_orValue_value"}},
2690 },
2691 },
2692 {
2693 expr: `m.?x.hasValue()`,
2694 references: map[int64]*celast.ReferenceInfo{
2695 1: {Name: "m"},
2696 3: {OverloadIDs: []string{"select_optional_field"}},
2697 4: {OverloadIDs: []string{"optional_hasValue"}},
2698 },
2699 },
2700 {
2701 expr: `has(m.?x.y)`,
2702 references: map[int64]*celast.ReferenceInfo{
2703 2: {Name: "m"},
2704 4: {OverloadIDs: []string{"select_optional_field"}},
2705 },
2706 },
2707 {
2708 // Optional index selection in map.
2709 expr: `m.k[?'dashed-index'].orValue('default value')`,
2710 references: map[int64]*celast.ReferenceInfo{
2711 1: {Name: "m"},
2712 3: {OverloadIDs: []string{"map_optindex_optional_value"}},
2713 5: {OverloadIDs: []string{"optional_orValue_value"}},
2714 },
2715 },
2716 {
2717 // Optional index selection in list.
2718 expr: `l[?y]`,
2719 references: map[int64]*celast.ReferenceInfo{
2720 1: {Name: "l"},
2721 2: {OverloadIDs: []string{"list_optindex_optional_int"}},
2722 3: {Name: "y"},
2723 },
2724 },
2725 {
2726 // Index selection against a value in an optional map.
2727 expr: `optm.c['index'].orValue('default value')`,
2728 references: map[int64]*celast.ReferenceInfo{
2729 1: {Name: "optm"},
2730 3: {OverloadIDs: []string{"optional_map_index_value"}},
2731 5: {OverloadIDs: []string{"optional_orValue_value"}},
2732 },
2733 },
2734 {
2735 // Index selection against a value in an optional map.
2736 expr: `optm.c[?'index']`,
2737 references: map[int64]*celast.ReferenceInfo{
2738 1: {Name: "optm"},
2739 3: {OverloadIDs: []string{"optional_map_optindex_optional_value"}},
2740 },
2741 },
2742 {
2743 // Index selection against a value in an optional list.
2744 expr: `optl[0]`,
2745 references: map[int64]*celast.ReferenceInfo{
2746 1: {Name: "optl"},
2747 2: {OverloadIDs: []string{"optional_list_index_int"}},
2748 },
2749 },
2750 {
2751 // Index selection against a value in an optional list.
2752 expr: `optl[?0]`,
2753 references: map[int64]*celast.ReferenceInfo{
2754 1: {Name: "optl"},
2755 2: {OverloadIDs: []string{"optional_list_optindex_optional_int"}},
2756 },
2757 },
2758 }
2759
2760 for i, tst := range tests {
2761 tc := tst
2762 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
2763 ast, iss := env.Compile(tc.expr)
2764 if iss.Err() != nil {
2765 t.Fatalf("%v failed: %v", tc.expr, iss.Err())
2766 }
2767 for id, reference := range ast.NativeRep().ReferenceMap() {
2768 other, found := tc.references[id]
2769 if !found {
2770 t.Errorf("Compile(%v) expected reference %d: %v", tc.expr, id, reference)
2771 } else if !reference.Equals(other) {
2772 t.Errorf("Compile(%v) got reference %d: %v, wanted %v", tc.expr, id, reference, other)
2773 }
2774 }
2775 })
2776 }
2777 }
2778
2779 func TestOptionalValuesEval(t *testing.T) {
2780 env := testEnv(t,
2781 OptionalTypes(),
2782 // Container and test message types.
2783 Container("google.expr.proto2.test"),
2784 Types(&proto2pb.TestAllTypes{}),
2785 // Test variables.
2786 Variable("m", MapType(StringType, MapType(StringType, StringType))),
2787 Variable("l", ListType(StringType)),
2788 Variable("optm", OptionalType(MapType(StringType, MapType(StringType, StringType)))),
2789 Variable("optl", OptionalType(ListType(StringType))),
2790 Variable("x", OptionalType(IntType)),
2791 Variable("y", OptionalType(IntType)),
2792 Variable("z", IntType),
2793 )
2794 adapter := env.TypeAdapter()
2795 tests := []struct {
2796 expr string
2797 in map[string]any
2798 out any
2799 }{
2800 {
2801 expr: `has({'foo': optional.none()}.foo)`,
2802 out: types.True,
2803 },
2804 {
2805 expr: `has({'foo': optional.none()}.foo.value)`,
2806 out: types.False,
2807 },
2808 {
2809 expr: `has({?'foo': optional.none()}.foo)`,
2810 out: types.False,
2811 },
2812 {
2813 expr: `has({?'foo': optional.none()}.foo.value)`,
2814 out: "no such key: foo",
2815 },
2816 {
2817 expr: `{}.?invalid`,
2818 out: types.OptionalNone,
2819 },
2820 {
2821 expr: `{'null_field': dyn(null)}.?null_field`,
2822 out: types.OptionalOf(types.NullValue),
2823 },
2824 {
2825 expr: `{'null_field': dyn(null)}.?null_field.?nested`,
2826 out: types.OptionalNone,
2827 },
2828 {
2829 expr: `{'zero_field': dyn(0)}.?zero_field.?invalid`,
2830 out: types.OptionalNone,
2831 },
2832 {
2833 expr: `{0: dyn(0)}[?0].?invalid`,
2834 out: types.OptionalNone,
2835 },
2836 {
2837 expr: `{true: dyn(0)}[?false].?invalid`,
2838 out: types.OptionalNone,
2839 },
2840 {
2841 expr: `{true: dyn(0)}[?true].?invalid`,
2842 out: types.OptionalNone,
2843 },
2844 {
2845 expr: `x.or(y).orValue(z)`,
2846 in: map[string]any{
2847 "x": types.OptionalNone,
2848 "y": types.OptionalNone,
2849 "z": 42,
2850 },
2851 out: 42,
2852 },
2853 {
2854 expr: `x.optMap(y, y + 1)`,
2855 in: map[string]any{
2856 "x": types.OptionalNone,
2857 },
2858 out: types.OptionalNone,
2859 },
2860 {
2861 expr: `m.?key.optFlatMap(k, k.?subkey)`,
2862 in: map[string]any{
2863 "m": map[string]any{},
2864 },
2865 out: types.OptionalNone,
2866 },
2867 {
2868 expr: `m.?key.optFlatMap(k, k.?subkey)`,
2869 in: map[string]any{
2870 "m": map[string]any{
2871 "key": map[string]string{},
2872 },
2873 },
2874 out: types.OptionalNone,
2875 },
2876 {
2877 expr: `m.?key.optFlatMap(k, k.?subkey)`,
2878 in: map[string]any{
2879 "m": map[string]any{
2880 "key": map[string]string{
2881 "subkey": "subvalue",
2882 },
2883 },
2884 },
2885 out: types.OptionalOf(types.String("subvalue")),
2886 },
2887 {
2888 expr: `m.?key.optFlatMap(k, k.?subkey)`,
2889 in: map[string]any{
2890 "m": map[string]any{
2891 "key": map[string]string{
2892 "subkey": "",
2893 },
2894 },
2895 },
2896 out: types.OptionalOf(types.String("")),
2897 },
2898 {
2899 expr: `m.?key.optFlatMap(k, optional.ofNonZeroValue(k.subkey))`,
2900 in: map[string]any{
2901 "m": map[string]any{
2902 "key": map[string]string{
2903 "subkey": "",
2904 },
2905 },
2906 },
2907 out: types.OptionalNone,
2908 },
2909 {
2910 expr: `x.optMap(y, y + 1)`,
2911 in: map[string]any{
2912 "x": types.OptionalOf(types.Int(42)),
2913 },
2914 out: types.OptionalOf(types.Int(43)),
2915 },
2916 {
2917 expr: `optional.ofNonZeroValue(z).or(optional.of(10)).value() == 42`,
2918 in: map[string]any{
2919 "z": 42,
2920 },
2921 out: true,
2922 },
2923 {
2924 // Equivalent to m.?x.hasValue()
2925 expr: `(has(m.x) ? optional.of(m.x) : optional.none()).hasValue()`,
2926 in: map[string]any{
2927 "m": map[string]map[string]string{},
2928 },
2929 out: false,
2930 },
2931 {
2932 expr: `m.?x.hasValue()`,
2933 in: map[string]any{
2934 "m": map[string]any{},
2935 },
2936 out: false,
2937 },
2938 {
2939 expr: `has(m.?x.y)`,
2940 in: map[string]any{
2941 "m": map[string]any{},
2942 },
2943 out: false,
2944 },
2945 {
2946 expr: `has(m.?x.y)`,
2947 in: map[string]any{
2948 "m": map[string]any{
2949 "x": map[string]string{
2950 "y": "z",
2951 },
2952 },
2953 },
2954 out: true,
2955 },
2956 {
2957 expr: `type(optional.none()) == optional_type`,
2958 out: true,
2959 },
2960 {
2961 // return the value of m.c['dashed-index'], no magic in the optional.of() call.
2962 expr: `optional.ofNonZeroValue('').or(optional.of(m.c['dashed-index'])).orValue('default value')`,
2963 in: map[string]any{
2964 "m": map[string]any{
2965 "c": map[string]string{
2966 "dashed-index": "goodbye",
2967 },
2968 },
2969 },
2970 out: "goodbye",
2971 },
2972 {
2973 // Optional index selection in map where the index is found.
2974 expr: `m.c[?'dashed-index'].orValue('default value')`,
2975 in: map[string]any{
2976 "m": map[string]any{
2977 "c": map[string]string{
2978 "dashed-index": "goodbye",
2979 },
2980 },
2981 },
2982 out: "goodbye",
2983 },
2984 {
2985 // Optional index selection in map where the index is absent.
2986 expr: `m.c[?'missing-index'].orValue('default value')`,
2987 in: map[string]any{
2988 "m": map[string]any{
2989 "c": map[string]string{},
2990 },
2991 },
2992 out: "default value",
2993 },
2994 {
2995 // Traditional index selection against an optional value in map where the index is found.
2996 expr: `optm.c.index.orValue('default value')`,
2997 in: map[string]any{
2998 "optm": types.OptionalOf(
2999 adapter.NativeToValue(
3000 map[string]any{
3001 "c": map[string]string{
3002 "index": "goodbye",
3003 },
3004 },
3005 ),
3006 ),
3007 },
3008 out: "goodbye",
3009 },
3010 {
3011 // Traditional index selection against an optional value in map where the index is absent.
3012 expr: `optm.c.missing.or(optl[0]).orValue('default value')`,
3013 in: map[string]any{
3014 "optm": types.OptionalOf(
3015 adapter.NativeToValue(
3016 map[string]any{
3017 "c": map[string]string{},
3018 },
3019 ),
3020 ),
3021 "optl": types.OptionalNone,
3022 },
3023 out: "default value",
3024 },
3025 {
3026 // Traditional index selection against an optional value in map where the index is absent.
3027 expr: `optm.c.missing.or(optl[0]).orValue('default value')`,
3028 in: map[string]any{
3029 "optm": types.OptionalOf(
3030 adapter.NativeToValue(
3031 map[string]any{
3032 "c": map[string]string{},
3033 },
3034 ),
3035 ),
3036 "optl": types.OptionalOf(
3037 adapter.NativeToValue([]string{"list-value"}),
3038 ),
3039 },
3040 out: "list-value",
3041 },
3042 {
3043 // Traditional index selection against an optional value in map where the index is found.
3044 expr: `optm.c['index'].orValue('default value')`,
3045 in: map[string]any{
3046 "optm": types.OptionalOf(
3047 adapter.NativeToValue(
3048 map[string]any{
3049 "c": map[string]string{
3050 "index": "goodbye",
3051 },
3052 },
3053 ),
3054 ),
3055 },
3056 out: "goodbye",
3057 },
3058 {
3059 // Traditional index selection against an optional value in map where the index is absent.
3060 expr: `optm.c['missing'].orValue('default value')`,
3061 in: map[string]any{
3062 "optm": types.OptionalOf(
3063 adapter.NativeToValue(
3064 map[string]any{
3065 "c": map[string]string{},
3066 },
3067 ),
3068 ),
3069 },
3070 out: "default value",
3071 },
3072 {
3073 // Presence test using optional value where the field is absent.
3074 expr: `has(optm.c) && !has(optm.c.missing)`,
3075 in: map[string]any{
3076 "optm": types.OptionalOf(
3077 adapter.NativeToValue(
3078 map[string]any{
3079 "c": map[string]string{
3080 "entry": "hello world",
3081 },
3082 },
3083 ),
3084 ),
3085 },
3086 out: true,
3087 },
3088 {
3089 // ensure an error is propagated to the result.
3090 expr: `optional.ofNonZeroValue(m.a.z).orValue(m.c['dashed-index'])`,
3091 in: map[string]any{
3092 "m": map[string]any{
3093 "c": map[string]string{
3094 "dashed-index": "goodbye",
3095 },
3096 },
3097 },
3098 out: "no such key: a",
3099 },
3100 {
3101 expr: `m.?c.missing.or(m.?c['dashed-index']).orValue('').size()`,
3102 in: map[string]any{
3103 "m": map[string]any{
3104 "c": map[string]string{
3105 "dashed-index": "goodbye",
3106 },
3107 },
3108 },
3109 out: 7,
3110 },
3111 {
3112 expr: `{?'nested_map': optional.ofNonZeroValue({?'map': m.?c})}`,
3113 in: map[string]any{
3114 "m": map[string]any{
3115 "c": map[string]string{
3116 "dashed-index": "goodbye",
3117 },
3118 },
3119 },
3120 out: map[string]any{
3121 "nested_map": map[string]any{
3122 "map": map[string]string{
3123 "dashed-index": "goodbye",
3124 },
3125 },
3126 },
3127 },
3128 {
3129 expr: `{?'nested_map': optional.ofNonZeroValue({?'map': m.?c}), 'singleton': true}`,
3130 in: map[string]any{
3131 "m": map[string]any{},
3132 },
3133 out: map[string]any{
3134 "singleton": true,
3135 },
3136 },
3137 {
3138 expr: `[?m.?c, ?x, ?y]`,
3139 in: map[string]any{
3140 "m": map[string]any{},
3141 "x": types.OptionalOf(types.Int(42)),
3142 "y": types.OptionalNone,
3143 },
3144 out: []any{42},
3145 },
3146 {
3147 expr: `[?optional.ofNonZeroValue(m.?c.orValue({}))]`,
3148 in: map[string]any{
3149 "m": map[string]any{
3150 "c": []string{},
3151 },
3152 },
3153 out: []any{},
3154 },
3155 {
3156 expr: `optional.ofNonZeroValue({?'nested_map': optional.ofNonZeroValue({?'map': m.?c})})`,
3157 in: map[string]any{
3158 "m": map[string]any{},
3159 },
3160 out: types.OptionalNone,
3161 },
3162 {
3163 expr: `TestAllTypes{?single_double_wrapper: optional.ofNonZeroValue(0.0)}`,
3164 out: &proto2pb.TestAllTypes{},
3165 },
3166 {
3167 expr: `optional.ofNonZeroValue(TestAllTypes{?single_double_wrapper: optional.ofNonZeroValue(0.0)})`,
3168 out: types.OptionalNone,
3169 },
3170 {
3171 expr: `TestAllTypes{
3172 ?map_string_string: m[?'nested']
3173 }`,
3174 in: map[string]any{
3175 "m": map[string]any{
3176 "nested": map[string]any{},
3177 },
3178 },
3179 out: &proto2pb.TestAllTypes{},
3180 },
3181 {
3182 expr: `TestAllTypes{
3183 ?map_string_string: optional.ofNonZeroValue(m[?'nested'].orValue({}))
3184 }`,
3185 in: map[string]any{
3186 "m": map[string]any{
3187 "nested": map[string]any{},
3188 },
3189 },
3190 out: &proto2pb.TestAllTypes{},
3191 },
3192 {
3193 expr: `TestAllTypes{
3194 ?map_string_string: m[?'nested']
3195 }`,
3196 in: map[string]any{
3197 "m": map[string]any{
3198 "nested": map[string]any{
3199 "hello": "world",
3200 },
3201 },
3202 },
3203 out: &proto2pb.TestAllTypes{
3204 MapStringString: map[string]string{"hello": "world"},
3205 },
3206 },
3207 {
3208 expr: `TestAllTypes{
3209 repeated_string: ['greetings', ?m.nested.?hello],
3210 ?repeated_int32: optional.ofNonZeroValue([?x, ?y]),
3211 }`,
3212 in: map[string]any{
3213 "m": map[string]any{
3214 "nested": map[string]any{
3215 "hello": "world",
3216 },
3217 },
3218 "x": types.OptionalNone,
3219 "y": types.OptionalNone,
3220 },
3221 out: &proto2pb.TestAllTypes{
3222 RepeatedString: []string{"greetings", "world"},
3223 },
3224 },
3225 {expr: `[].first()`, out: types.OptionalNone},
3226 {expr: `['a','b','c'].first()`, out: types.OptionalOf(types.String("a"))},
3227 {expr: `[].last()`, out: types.OptionalNone},
3228 {expr: `[1, 2, 3].last()`, out: types.OptionalOf(types.Int(3))},
3229 {expr: `optional.unwrap([])`, out: []any{}},
3230 {expr: `optional.unwrap([optional.none(), optional.none()])`, out: []any{}},
3231 {expr: `optional.unwrap([optional.of(42), optional.none(), optional.of("a")])`, out: []any{types.Int(42), types.String("a")}},
3232 {expr: `optional.unwrap([optional.of(42), optional.of("a")])`, out: []any{types.Int(42), types.String("a")}},
3233 {expr: `[].unwrapOpt()`, out: []any{}},
3234 {expr: `[optional.none(), optional.none()].unwrapOpt()`, out: []any{}},
3235 {expr: `[optional.of(42), optional.none(), optional.of("a")].unwrapOpt()`, out: []any{types.Int(42), types.String("a")}},
3236 {expr: `[optional.of(42), optional.of("a")].unwrapOpt()`, out: []any{types.Int(42), types.String("a")}},
3237 }
3238
3239 for i, tst := range tests {
3240 tc := tst
3241 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
3242 ast, iss := env.Compile(tc.expr)
3243 if iss.Err() != nil {
3244 t.Fatalf("%v failed: %v", tc.expr, iss.Err())
3245 }
3246 prg, err := env.Program(ast)
3247 if err != nil {
3248 t.Errorf("env.Program() failed: %v", err)
3249 }
3250 out, _, err := prg.Eval(tc.in)
3251 if err != nil && err.Error() != tc.out {
3252 t.Errorf("prg.Eval() got %v, wanted %v", err, tc.out)
3253 }
3254 want := adapter.NativeToValue(tc.out)
3255 if err == nil && out.Equal(want) != types.True {
3256 t.Errorf("prg.Eval() got %v, wanted %v", out, want)
3257 }
3258 })
3259 }
3260 }
3261
3262 func TestEnableErrorOnBadPresenceTest(t *testing.T) {
3263 env := testEnv(t,
3264 OptionalTypes(),
3265 EnableErrorOnBadPresenceTest(true),
3266 )
3267 adapter := env.TypeAdapter()
3268 tests := []struct {
3269 expr string
3270 in map[string]any
3271 out any
3272 }{
3273 {
3274 expr: `{}.?invalid`,
3275 out: types.OptionalNone,
3276 },
3277 {
3278 expr: `{'null_field': dyn(null)}.?null_field`,
3279 out: types.OptionalOf(types.NullValue),
3280 },
3281 {
3282 expr: `{'null_field': dyn(null)}.?null_field.?nested`,
3283 out: "no such key: nested",
3284 },
3285 {
3286 expr: `{'zero_field': dyn(0)}.?zero_field.?invalid`,
3287 out: "no such key: invalid",
3288 },
3289 {
3290 expr: `{0: dyn(0)}[?0].?invalid`,
3291 out: "no such key: invalid",
3292 },
3293 {
3294 expr: `{true: dyn(0)}[?false].?invalid`,
3295 out: types.OptionalNone,
3296 },
3297 {
3298 expr: `{true: dyn(0)}[?true].?invalid`,
3299 out: "no such key: invalid",
3300 },
3301 }
3302
3303 for i, tst := range tests {
3304 tc := tst
3305 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
3306 ast, iss := env.Compile(tc.expr)
3307 if iss.Err() != nil {
3308 t.Fatalf("%v failed: %v", tc.expr, iss.Err())
3309 }
3310 prg, err := env.Program(ast)
3311 if err != nil {
3312 t.Errorf("env.Program() failed: %v", err)
3313 }
3314 out, _, err := prg.Eval(tc.in)
3315 if err != nil && err.Error() != tc.out {
3316 t.Errorf("prg.Eval() got %v, wanted %v", err, tc.out)
3317 }
3318 want := adapter.NativeToValue(tc.out)
3319 if err == nil && out.Equal(want) != types.True {
3320 t.Errorf("prg.Eval() got %v, wanted %v", out, want)
3321 }
3322 })
3323 }
3324
3325 }
3326
3327 func TestOptionalMacroError(t *testing.T) {
3328 env := testEnv(t,
3329 OptionalTypes(),
3330 // Test variables.
3331 Variable("x", OptionalType(IntType)),
3332 )
3333 _, iss := env.Compile("x.optMap(y.z, y.z + 1)")
3334 if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "variable name must be a simple identifier") {
3335 t.Errorf("optMap() got an unexpected result: %v", iss.Err())
3336 }
3337 _, iss = env.Compile("x.optFlatMap(y.z, y.z + 1)")
3338 if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "variable name must be a simple identifier") {
3339 t.Errorf("optFlatMap() got an unexpected result: %v", iss.Err())
3340 }
3341 env = testEnv(t,
3342 OptionalTypes(OptionalTypesVersion(0)),
3343 // Test variables.
3344 Variable("x", OptionalType(IntType)),
3345 )
3346 _, iss = env.Compile("x.optFlatMap(y, y.z + 1)")
3347 if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "undeclared reference to 'optFlatMap'") {
3348 t.Errorf("optFlatMap() got an unexpected result: %v", iss.Err())
3349 }
3350 }
3351
3352 func TestParserExpressionSizeLimit(t *testing.T) {
3353 env := testEnv(t, ParserExpressionSizeLimit(10))
3354 _, iss := env.Parse("'greeting'")
3355 if iss.Err() != nil {
3356 t.Errorf("Parse('greeting') failed: %v", iss.Err())
3357 }
3358 _, iss = env.Parse("'greetings'")
3359 if !strings.Contains(iss.Err().Error(), "size exceeds limit") {
3360 t.Errorf("Parse('greetings') got unexpected error: %v", iss.Err())
3361 }
3362 }
3363
3364 func BenchmarkOptionalValues(b *testing.B) {
3365 env := testEnv(b,
3366 OptionalTypes(),
3367 Variable("x", OptionalType(IntType)),
3368 Variable("y", OptionalType(IntType)),
3369 Variable("z", IntType),
3370 )
3371 ast, iss := env.Compile("x.or(y).orValue(z)")
3372 if iss.Err() != nil {
3373 b.Fatalf("env.Compile(x.or(y).orValue(z)) failed: %v", iss.Err())
3374 }
3375 prg, err := env.Program(ast, EvalOptions(OptOptimize))
3376 if err != nil {
3377 b.Errorf("env.Program() failed: %v", err)
3378 }
3379 input := map[string]any{
3380 "x": types.OptionalNone,
3381 "y": types.OptionalNone,
3382 "z": 42,
3383 }
3384 for i := 0; i < b.N; i++ {
3385 prg.Eval(input)
3386 }
3387 }
3388
3389 func BenchmarkDynamicDispatch(b *testing.B) {
3390 env := testEnv(b,
3391 HomogeneousAggregateLiterals(),
3392 Function("first",
3393 MemberOverload("first_list_int", []*Type{ListType(IntType)}, IntType,
3394 UnaryBinding(func(list ref.Val) ref.Val {
3395 l := list.(traits.Lister)
3396 if l.Size() == types.IntZero {
3397 return types.IntZero
3398 }
3399 return l.Get(types.IntZero)
3400 }),
3401 ),
3402 MemberOverload("first_list_double", []*Type{ListType(DoubleType)}, DoubleType,
3403 UnaryBinding(func(list ref.Val) ref.Val {
3404 l := list.(traits.Lister)
3405 if l.Size() == types.IntZero {
3406 return types.Double(0.0)
3407 }
3408 return l.Get(types.IntZero)
3409 }),
3410 ),
3411 MemberOverload("first_list_string", []*Type{ListType(StringType)}, StringType,
3412 UnaryBinding(func(list ref.Val) ref.Val {
3413 l := list.(traits.Lister)
3414 if l.Size() == types.IntZero {
3415 return types.String("")
3416 }
3417 return l.Get(types.IntZero)
3418 }),
3419 ),
3420 MemberOverload("first_list_list_string", []*Type{ListType(ListType(StringType))}, ListType(StringType),
3421 UnaryBinding(func(list ref.Val) ref.Val {
3422 l := list.(traits.Lister)
3423 if l.Size() == types.IntZero {
3424 return types.DefaultTypeAdapter.NativeToValue([]string{})
3425 }
3426 return l.Get(types.IntZero)
3427 }),
3428 ),
3429 ),
3430 )
3431 prg := compile(b, env, `
3432 [].first() == 0
3433 && [1, 2].first() == 1
3434 && [1.0, 2.0].first() == 1.0
3435 && ["hello", "world"].first() == "hello"
3436 && [["hello"], ["world", "!"]].first().first() == "hello"`)
3437 prgDyn := compile(b, env, `
3438 dyn([]).first() == 0
3439 && dyn([1, 2]).first() == 1
3440 && dyn([1.0, 2.0]).first() == 1.0
3441 && dyn(["hello", "world"]).first() == "hello"
3442 && dyn([["hello"], ["world", "!"]]).first().first() == "hello"`)
3443 b.ResetTimer()
3444 b.Run("DirectDispatch", func(b *testing.B) {
3445 for i := 0; i < b.N; i++ {
3446 prg.Eval(NoVars())
3447 }
3448 })
3449 b.ResetTimer()
3450 b.Run("DynamicDispatch", func(b *testing.B) {
3451 for i := 0; i < b.N; i++ {
3452 prgDyn.Eval(NoVars())
3453 }
3454 })
3455 }
3456
3457 func TestAstProgramNilValue(t *testing.T) {
3458 var ast *Ast = nil
3459 env := testEnv(t)
3460 prg, err := env.Program(ast)
3461 if err == nil || !strings.Contains(err.Error(), "unsupported expr") {
3462 t.Errorf("env.Program() got (%v,%v) wanted unsupported expr error", prg, err)
3463 }
3464 }
3465
3466 // TODO: ideally testCostEstimator and testRuntimeCostEstimator would be shared in a test fixtures package
3467 type testCostEstimator struct {
3468 hints map[string]uint64
3469 }
3470
3471 func (tc testCostEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate {
3472 if l, ok := tc.hints[strings.Join(element.Path(), ".")]; ok {
3473 return &checker.SizeEstimate{Min: 0, Max: l}
3474 }
3475 return nil
3476 }
3477
3478 func (tc testCostEstimator) EstimateCallCost(function, overloadID string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
3479 return nil
3480 }
3481
3482 func estimateTimestampToYear(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
3483 return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 7, Max: 7}}
3484 }
3485
3486 type testRuntimeCostEstimator struct{}
3487
3488 var timeToYearCost uint64 = 7
3489
3490 func (e testRuntimeCostEstimator) CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 {
3491 argsSize := make([]uint64, len(args))
3492 for i, arg := range args {
3493 reflectV := reflect.ValueOf(arg.Value())
3494 switch reflectV.Kind() {
3495 // Note that the CEL bytes type is implemented with Go byte slices, therefore also supported by the following
3496 // code.
3497 case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
3498 argsSize[i] = uint64(reflectV.Len())
3499 default:
3500 argsSize[i] = 1
3501 }
3502 }
3503 return nil
3504 }
3505
3506 func trackTimestampToYear(args []ref.Val, result ref.Val) *uint64 {
3507 return &timeToYearCost
3508 }
3509
3510 func testEnv(t testing.TB, opts ...EnvOption) *Env {
3511 t.Helper()
3512 e, err := NewEnv(opts...)
3513 if err != nil {
3514 t.Fatalf("NewEnv() failed: %v", err)
3515 }
3516 return e
3517 }
3518
3519 func compile(t testing.TB, env *Env, expr string) Program {
3520 t.Helper()
3521 prg, err := compileOrError(t, env, expr)
3522 if err != nil {
3523 t.Fatal(err)
3524 }
3525 return prg
3526 }
3527
3528 func compileOrError(t testing.TB, env *Env, expr string) (Program, error) {
3529 t.Helper()
3530 ast, iss := env.Compile(expr)
3531 if iss.Err() != nil {
3532 return nil, fmt.Errorf("env.Compile(%s) failed: %v", expr, iss.Err())
3533 }
3534 prg, err := env.Program(ast, EvalOptions(OptOptimize))
3535 if err != nil {
3536 return nil, fmt.Errorf("env.Program() failed: %v", err)
3537 }
3538 return prg, nil
3539 }
3540
3541 func interpret(t testing.TB, env *Env, expr string, vars any) (ref.Val, error) {
3542 t.Helper()
3543 prg, err := compileOrError(t, env, expr)
3544 if err != nil {
3545 return nil, err
3546 }
3547 out, _, err := prg.Eval(vars)
3548 if err != nil {
3549 return nil, fmt.Errorf("prg.Eval(%v) failed: %v", vars, err)
3550 }
3551 return out, nil
3552 }