Debian Codegraph @

interpreter/interpreter_test.go

raw symbols SCIP
1 // Copyright 2018 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 interpreter
16
17 import (
18 "context"
19 "encoding/base64"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "reflect"
24 "strings"
25 "testing"
26 "time"
27
28 "google.golang.org/protobuf/proto"
29
30 "github.com/google/cel-go/checker"
31 "github.com/google/cel-go/common"
32 "github.com/google/cel-go/common/ast"
33 "github.com/google/cel-go/common/containers"
34 "github.com/google/cel-go/common/decls"
35 "github.com/google/cel-go/common/functions"
36 "github.com/google/cel-go/common/operators"
37 "github.com/google/cel-go/common/stdlib"
38 "github.com/google/cel-go/common/types"
39 "github.com/google/cel-go/common/types/ref"
40 "github.com/google/cel-go/common/types/traits"
41 "github.com/google/cel-go/parser"
42
43 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
44 structpb "google.golang.org/protobuf/types/known/structpb"
45 tpb "google.golang.org/protobuf/types/known/timestamppb"
46 wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
47
48 proto2pb "github.com/google/cel-go/test/proto2pb"
49 proto3pb "github.com/google/cel-go/test/proto3pb"
50 )
51
52 type testCase struct {
53 name string
54 expr string
55 container string
56 abbrevs []string
57 types []proto.Message
58 vars []*decls.VariableDecl
59 funcs []*decls.FunctionDecl
60 attrs AttributeFactory
61 unchecked bool
62 extraOpts []PlannerOption
63
64 in any
65 out any
66 err string
67 progErr string
68 }
69
70 func testData(t testing.TB) []testCase {
71 return []testCase{
72 {
73 name: "double_ne_nan",
74 expr: `0.0/0.0 == 0.0/0.0`,
75 out: types.False,
76 },
77 {
78 name: "and_false_1st",
79 expr: `false && true`,
80 out: types.False,
81 },
82 {
83 name: "and_false_2nd",
84 expr: `true && false`,
85 out: types.False,
86 },
87 {
88 name: "and_error_1st_false",
89 expr: `1/0 != 0 && false`,
90 out: types.False,
91 },
92 {
93 name: "and_error_2nd_false",
94 expr: `false && 1/0 != 0`,
95 out: types.False,
96 },
97 {
98 name: "and_error_1st_error",
99 expr: `1/0 != 0 && true`,
100 err: "division by zero",
101 },
102 {
103 name: "and_error_2nd_error",
104 expr: `true && 1/0 != 0`,
105 err: "division by zero",
106 },
107 {
108 name: "call_no_args",
109 expr: `zero()`,
110 unchecked: true,
111 funcs: []*decls.FunctionDecl{
112 funcDecl(t, "zero",
113 decls.Overload("zero", []*types.Type{}, types.IntType),
114 decls.SingletonFunctionBinding(func(args ...ref.Val) ref.Val {
115 return types.IntZero
116 }),
117 )},
118 out: types.IntZero,
119 },
120 {
121 name: "call_one_arg",
122 expr: `neg(1)`,
123 unchecked: true,
124 funcs: []*decls.FunctionDecl{
125 funcDecl(t, "neg",
126 decls.Overload("neg_int", []*types.Type{types.IntType}, types.IntType,
127 decls.OverloadOperandTrait(traits.NegatorType),
128 decls.UnaryBinding(func(arg ref.Val) ref.Val {
129 return arg.(traits.Negater).Negate()
130 }),
131 ),
132 ),
133 },
134 out: types.IntNegOne,
135 },
136 {
137 name: "call_two_arg",
138 expr: `b'abc'.concat(b'def')`,
139 unchecked: true,
140 funcs: []*decls.FunctionDecl{
141 funcDecl(t, "concat",
142 decls.MemberOverload("bytes_concat_bytes", []*types.Type{types.BytesType, types.BytesType}, types.BytesType,
143 decls.OverloadOperandTrait(traits.AdderType),
144 decls.BinaryBinding(func(lhs, rhs ref.Val) ref.Val {
145 return lhs.(traits.Adder).Add(rhs)
146 }))),
147 },
148 out: []byte{'a', 'b', 'c', 'd', 'e', 'f'},
149 },
150 {
151 name: "call_four_args",
152 expr: `addall(a, b, c, d) == 10`,
153 unchecked: true,
154 funcs: []*decls.FunctionDecl{
155 funcDecl(t, "addall",
156 decls.Overload("addall_four",
157 []*types.Type{types.IntType, types.IntType, types.IntType, types.IntType},
158 types.IntType),
159 decls.DisableTypeGuards(true),
160 decls.SingletonFunctionBinding(func(args ...ref.Val) ref.Val {
161 val := types.Int(0)
162 for _, arg := range args {
163 val += arg.(types.Int)
164 }
165 return val
166 }, traits.AdderType)),
167 },
168 in: map[string]any{
169 "a": 1, "b": 2, "c": 3, "d": 4,
170 },
171 },
172 {
173 name: `call_ns_func`,
174 expr: `base64.encode('hello')`,
175 funcs: []*decls.FunctionDecl{
176 funcDecl(t, "base64.encode",
177 decls.Overload("base64_encode_string", []*types.Type{types.StringType}, types.StringType),
178 decls.SingletonUnaryBinding(base64Encode)),
179 },
180 out: "aGVsbG8=",
181 },
182 {
183 name: `call_ns_func_unchecked`,
184 expr: `base64.encode('hello')`,
185 unchecked: true,
186 funcs: []*decls.FunctionDecl{
187 funcDecl(t, "base64.encode",
188 decls.Overload("base64_encode_string", []*types.Type{types.StringType}, types.StringType),
189 decls.SingletonUnaryBinding(base64Encode)),
190 },
191 out: "aGVsbG8=",
192 },
193 {
194 name: `call_ns_func_in_pkg`,
195 container: `base64`,
196 expr: `encode('hello')`,
197 funcs: []*decls.FunctionDecl{
198 funcDecl(t, "base64.encode",
199 decls.Overload("base64_encode_string", []*types.Type{types.StringType}, types.StringType),
200 decls.SingletonUnaryBinding(base64Encode)),
201 },
202 out: "aGVsbG8=",
203 },
204 {
205 name: `call_ns_func_unchecked_in_pkg`,
206 expr: `encode('hello')`,
207 container: `base64`,
208 unchecked: true,
209 funcs: []*decls.FunctionDecl{
210 funcDecl(t, "base64.encode",
211 decls.Overload("base64_encode_string", []*types.Type{types.StringType}, types.StringType),
212 decls.SingletonUnaryBinding(base64Encode)),
213 },
214 out: "aGVsbG8=",
215 },
216 {
217 name: "complex",
218 expr: `
219 !(headers.ip in ["10.0.1.4", "10.0.1.5"]) &&
220 ((headers.path.startsWith("v1") && headers.token in ["v1", "v2", "admin"]) ||
221 (headers.path.startsWith("v2") && headers.token in ["v2", "admin"]) ||
222 (headers.path.startsWith("/admin") && headers.token == "admin" && headers.ip in ["10.0.1.2", "10.0.1.2", "10.0.1.2"]))
223 `,
224 vars: []*decls.VariableDecl{
225 decls.NewVariable("headers", types.NewMapType(types.StringType, types.StringType)),
226 },
227 in: map[string]any{
228 "headers": map[string]any{
229 "ip": "10.0.1.2",
230 "path": "/admin/edit",
231 "token": "admin",
232 },
233 },
234 },
235 {
236 name: "complex_qual_vars",
237 expr: `
238 !(headers.ip in ["10.0.1.4", "10.0.1.5"]) &&
239 ((headers.path.startsWith("v1") && headers.token in ["v1", "v2", "admin"]) ||
240 (headers.path.startsWith("v2") && headers.token in ["v2", "admin"]) ||
241 (headers.path.startsWith("/admin") && headers.token == "admin" && headers.ip in ["10.0.1.2", "10.0.1.2", "10.0.1.2"]))
242 `,
243 vars: []*decls.VariableDecl{
244 decls.NewVariable("headers.ip", types.StringType),
245 decls.NewVariable("headers.path", types.StringType),
246 decls.NewVariable("headers.token", types.StringType),
247 },
248 in: map[string]any{
249 "headers.ip": "10.0.1.2",
250 "headers.path": "/admin/edit",
251 "headers.token": "admin",
252 },
253 },
254 {
255 name: "cond",
256 expr: `a ? b < 1.2 : c == ['hello']`,
257 vars: []*decls.VariableDecl{
258 decls.NewVariable("a", types.BoolType),
259 decls.NewVariable("b", types.DoubleType),
260 decls.NewVariable("c", types.NewListType(types.StringType)),
261 },
262 in: map[string]any{
263 "a": true,
264 "b": 2.0,
265 "c": []string{"hello"},
266 },
267 out: types.False,
268 },
269 {
270 name: "cond_attr_out_of_bounds_error",
271 expr: `m[(x ? 0 : 1)] >= 0`,
272 vars: []*decls.VariableDecl{
273 decls.NewVariable("m", types.NewListType(types.IntType)),
274 decls.NewVariable("x", types.BoolType),
275 },
276 in: map[string]any{
277 "m": []int{-1},
278 "x": false,
279 },
280 err: "index out of bounds: 1",
281 },
282 {
283 name: "cond_attr_qualify_bad_type_error",
284 expr: `m[(x ? a : b)] >= 0`,
285 vars: []*decls.VariableDecl{
286 decls.NewVariable("m", types.NewListType(types.DynType)),
287 decls.NewVariable("a", types.DynType),
288 decls.NewVariable("b", types.DynType),
289 decls.NewVariable("x", types.BoolType),
290 },
291 in: map[string]any{
292 "m": []int{1},
293 "x": false,
294 "a": time.Millisecond,
295 "b": time.Millisecond,
296 },
297 err: "invalid qualifier type",
298 },
299 {
300 name: "cond_attr_qualify_bad_field_error",
301 expr: `m[(x ? a : b).c] >= 0`,
302 vars: []*decls.VariableDecl{
303 decls.NewVariable("m", types.NewListType(types.DynType)),
304 decls.NewVariable("a", types.DynType),
305 decls.NewVariable("b", types.DynType),
306 decls.NewVariable("x", types.BoolType),
307 },
308 in: map[string]any{
309 "m": []int{1},
310 "x": false,
311 "a": int32(1),
312 "b": int32(2),
313 },
314 err: "no such key: c",
315 },
316 {
317 name: "in_empty_list",
318 expr: `6 in []`,
319 out: types.False,
320 },
321 {
322 name: "in_constant_list",
323 expr: `6 in [2, 12, 6]`,
324 },
325 {
326 name: "bytes_in_constant_list",
327 expr: "b'hello' in [b'world', b'universe', b'hello']",
328 },
329 {
330 name: "list_in_constant_list",
331 expr: `[6] in [2, 12, [6]]`,
332 },
333 {
334 name: "in_constant_list_cross_type_uint_int",
335 expr: `dyn(12u) in [2, 12, 6]`,
336 },
337 {
338 name: "in_constant_list_cross_type_double_int",
339 expr: `dyn(6.0) in [2, 12, 6]`,
340 },
341 {
342 name: "in_constant_list_cross_type_int_double",
343 expr: `dyn(6) in [2.1, 12.0, 6.0]`,
344 },
345 {
346 name: "not_in_constant_list_cross_type_int_double",
347 expr: `dyn(2) in [2.1, 12.0, 6.0]`,
348 out: types.False,
349 },
350 {
351 name: "in_constant_list_cross_type_int_uint",
352 expr: `dyn(6) in [2u, 12u, 6u]`,
353 },
354 {
355 name: "in_constant_list_cross_type_negative_int_uint",
356 expr: `dyn(-6) in [2u, 12u, 6u]`,
357 out: types.False,
358 },
359 {
360 name: "in_constant_list_cross_type_negative_double_uint",
361 expr: `dyn(-6.1) in [2u, 12u, 6u]`,
362 out: types.False,
363 },
364 {
365 name: "in_var_list_int",
366 expr: `6 in [2, 12, x]`,
367 vars: []*decls.VariableDecl{
368 decls.NewVariable("x", types.DynType),
369 },
370 in: map[string]any{"x": 6},
371 },
372 {
373 name: "in_var_list_uint",
374 expr: `6 in [2, 12, x]`,
375 vars: []*decls.VariableDecl{
376 decls.NewVariable("x", types.DynType),
377 },
378 in: map[string]any{"x": uint64(6)},
379 },
380 {
381 name: "in_var_list_double",
382 expr: `6 in [2, 12, x]`,
383 vars: []*decls.VariableDecl{
384 decls.NewVariable("x", types.DynType),
385 },
386 in: map[string]any{"x": 6.0},
387 },
388 {
389 name: "in_var_list_double_double",
390 expr: `dyn(6.0) in [2, 12, x]`,
391 vars: []*decls.VariableDecl{
392 decls.NewVariable("x", types.IntType),
393 },
394 in: map[string]any{"x": 6},
395 },
396 {
397 name: "in_constant_map",
398 expr: `'other-key' in {'key': null, 'other-key': 42}`,
399 out: types.True,
400 },
401 {
402 name: "in_constant_map_cross_type_string_number",
403 expr: `'other-key' in {1: null, 2u: 42}`,
404 out: types.False,
405 },
406 {
407 name: "in_constant_map_cross_type_double_int",
408 expr: `2.0 in {1: null, 2u: 42}`,
409 },
410 {
411 name: "not_in_constant_map_cross_type_double_int",
412 expr: `2.1 in {1: null, 2u: 42}`,
413 out: types.False,
414 },
415 {
416 name: "in_constant_heterogeneous_map",
417 expr: `'hello' in {1: 'one', false: true, 'hello': 'world'}`,
418 out: types.True,
419 },
420 {
421 name: "not_in_constant_heterogeneous_map",
422 expr: `!('hello' in {1: 'one', false: true})`,
423 out: types.True,
424 },
425 {
426 name: "not_in_constant_heterogeneous_map_with_same_key_type",
427 expr: `!('hello' in {1: 'one', 'world': true})`,
428 out: types.True,
429 },
430 {
431 name: "in_var_key_map",
432 expr: `'other-key' in {x: null, y: 42}`,
433 out: types.True,
434 vars: []*decls.VariableDecl{
435 decls.NewVariable("x", types.StringType),
436 decls.NewVariable("y", types.IntType),
437 },
438 in: map[string]any{
439 "x": "other-key",
440 "y": 2,
441 },
442 },
443 {
444 name: "in_var_value_map",
445 expr: `'other-key' in {1: x, 2u: y}`,
446 out: types.False,
447 vars: []*decls.VariableDecl{
448 decls.NewVariable("x", types.StringType),
449 decls.NewVariable("y", types.IntType),
450 },
451 in: map[string]any{
452 "x": "other-value",
453 "y": 2,
454 },
455 },
456 {
457 name: "index",
458 expr: `m['key'][1] == 42u && m['null'] == null && m[string(0)] == 10`,
459 vars: []*decls.VariableDecl{
460 decls.NewVariable("m", types.NewMapType(types.StringType, types.DynType)),
461 },
462 in: map[string]any{
463 "m": map[string]any{
464 "key": []uint{21, 42},
465 "null": nil,
466 "0": 10,
467 },
468 },
469 },
470 {
471 name: "index_cross_type_float_uint",
472 expr: `{1: 'hello'}[x] == 'hello' && {2: 'world'}[y] == 'world'`,
473 vars: []*decls.VariableDecl{
474 decls.NewVariable("x", types.DynType),
475 decls.NewVariable("y", types.DynType),
476 },
477 in: map[string]any{
478 "x": float32(1.0),
479 "y": uint(2),
480 },
481 },
482 {
483 name: "no_index_cross_type_float_uint",
484 expr: `{1: 'hello'}[x] == 'hello' && ['world'][y] == 'world'`,
485 vars: []*decls.VariableDecl{
486 decls.NewVariable("x", types.DynType),
487 decls.NewVariable("y", types.DynType),
488 },
489 in: map[string]any{
490 "x": float32(2.0),
491 "y": uint(3),
492 },
493 err: "no such key: 2",
494 },
495 {
496 name: "index_cross_type_double",
497 expr: `{1: 'hello', 2: 'world'}[x] == 'hello'`,
498 vars: []*decls.VariableDecl{
499 decls.NewVariable("x", types.DynType),
500 },
501 in: map[string]any{
502 "x": 1.0,
503 },
504 },
505 {
506 name: "index_cross_type_double_const",
507 expr: `{1: 'hello', 2: 'world'}[dyn(2.0)] == 'world'`,
508 },
509 {
510 name: "index_cross_type_uint",
511 expr: `{1: 'hello', 2: 'world'}[dyn(2u)] == 'world'`,
512 },
513 {
514 name: "index_cross_type_bad_qualifier",
515 expr: `{1: 'hello', 2: 'world'}[x] == 'world'`,
516 vars: []*decls.VariableDecl{
517 decls.NewVariable("x", types.DynType),
518 },
519 in: map[string]any{
520 "x": time.Millisecond,
521 },
522 err: "invalid qualifier type",
523 },
524 {
525 name: "index_list_int_double_type_index",
526 expr: `[7, 8, 9][dyn(0.0)] == 7`,
527 },
528 {
529 name: "index_list_int_uint_type_index",
530 expr: `[7, 8, 9][dyn(0u)] == 7`,
531 },
532 {
533 name: "index_list_int_bad_double_type_index",
534 expr: `[7, 8, 9][dyn(0.1)] == 7`,
535 err: `unsupported index value`,
536 },
537 {
538 name: "index_relative",
539 expr: `([[[1]], [[2]], [[3]]][0][0] + [2, 3, {'four': {'five': 'six'}}])[3].four.five == 'six'`,
540 },
541 {
542 name: "list_eq_false_with_error",
543 expr: `['string', 1] == [2, 3]`,
544 out: types.False,
545 },
546 {
547 name: "list_eq_error",
548 expr: `['string', true] == [2, 3]`,
549 out: types.False,
550 },
551 {
552 name: "literal_bool_false",
553 expr: `false`,
554 out: types.False,
555 },
556 {
557 name: "literal_bool_true",
558 expr: `true`,
559 },
560 {
561 name: "literal_null",
562 expr: `null`,
563 out: types.NullValue,
564 },
565 {
566 name: "literal_list",
567 expr: `[1, 2, 3]`,
568 out: []int64{1, 2, 3},
569 },
570 {
571 name: "literal_map",
572 expr: `{'hi': 21, 'world': 42u}`,
573 out: map[string]any{
574 "hi": 21,
575 "world": uint(42),
576 },
577 },
578 {
579 name: "literal_equiv_string_bytes",
580 expr: `string(bytes("\303\277")) == '''\303\277'''`,
581 },
582 {
583 name: "literal_not_equiv_string_bytes",
584 expr: `string(b"\303\277") != '''\303\277'''`,
585 },
586 {
587 name: "literal_equiv_bytes_string",
588 expr: `string(b"\303\277") == 'ÿ'`,
589 },
590 {
591 name: "literal_bytes_string",
592 expr: `string(b'aaa"bbb')`,
593 out: `aaa"bbb`,
594 },
595 {
596 name: "literal_bytes_string2",
597 expr: `string(b"""Kim\t""")`,
598 out: `Kim `,
599 },
600 {
601 name: "literal_pb3_msg",
602 container: "google.api.expr",
603 types: []proto.Message{&exprpb.Expr{}},
604 expr: `v1alpha1.Expr{
605 id: 1,
606 const_expr: v1alpha1.Constant{
607 string_value: "oneof_test"
608 }
609 }`,
610 out: &exprpb.Expr{Id: 1,
611 ExprKind: &exprpb.Expr_ConstExpr{
612 ConstExpr: &exprpb.Constant{
613 ConstantKind: &exprpb.Constant_StringValue{
614 StringValue: "oneof_test"}}}},
615 },
616 {
617 name: "literal_pb_enum",
618 container: "google.expr.proto3.test",
619 types: []proto.Message{&proto3pb.TestAllTypes{}},
620 expr: `TestAllTypes{
621 repeated_nested_enum: [
622 0,
623 TestAllTypes.NestedEnum.BAZ,
624 TestAllTypes.NestedEnum.BAR],
625 repeated_int32: [
626 TestAllTypes.NestedEnum.FOO,
627 TestAllTypes.NestedEnum.BAZ]}`,
628 out: &proto3pb.TestAllTypes{
629 RepeatedNestedEnum: []proto3pb.TestAllTypes_NestedEnum{
630 proto3pb.TestAllTypes_FOO,
631 proto3pb.TestAllTypes_BAZ,
632 proto3pb.TestAllTypes_BAR,
633 },
634 RepeatedInt32: []int32{0, 2},
635 },
636 },
637 {
638 name: "literal_pb_wrapper_assign",
639 container: "google.expr.proto3.test",
640 types: []proto.Message{&proto3pb.TestAllTypes{}},
641 expr: `TestAllTypes{
642 single_int64_wrapper: 10,
643 single_int32_wrapper: TestAllTypes{}.single_int32_wrapper,
644 }`,
645 out: &proto3pb.TestAllTypes{
646 SingleInt64Wrapper: wrapperspb.Int64(10),
647 },
648 },
649 {
650 name: "literal_pb_wrapper_assign_roundtrip",
651 container: "google.expr.proto3.test",
652 types: []proto.Message{&proto3pb.TestAllTypes{}},
653 expr: `TestAllTypes{
654 single_int32_wrapper: TestAllTypes{}.single_int32_wrapper,
655 }.single_int32_wrapper == null`,
656 out: true,
657 },
658 {
659 name: "literal_pb_list_assign_null_wrapper",
660 container: "google.expr.proto3.test",
661 types: []proto.Message{&proto3pb.TestAllTypes{}},
662 expr: `TestAllTypes{
663 repeated_int32: [123, 456, TestAllTypes{}.single_int32_wrapper],
664 }`,
665 err: "field type conversion error",
666 },
667 {
668 name: "literal_pb_map_assign_null_entry_value",
669 container: "google.expr.proto3.test",
670 types: []proto.Message{&proto3pb.TestAllTypes{}},
671 expr: `TestAllTypes{
672 map_string_string: {
673 'hello': 'world',
674 'goodbye': TestAllTypes{}.single_string_wrapper,
675 },
676 }`,
677 err: "field type conversion error",
678 },
679 {
680 name: "unset_wrapper_access",
681 container: "google.expr.proto3.test",
682 types: []proto.Message{&proto3pb.TestAllTypes{}},
683 expr: `TestAllTypes{}.single_string_wrapper`,
684 out: types.NullValue,
685 },
686 {
687 name: "timestamp_eq_timestamp",
688 expr: `timestamp(0) == timestamp(0)`,
689 },
690 {
691 name: "timestamp_ne_timestamp",
692 expr: `timestamp(1) != timestamp(2)`,
693 },
694 {
695 name: "timestamp_lt_timestamp",
696 expr: `timestamp(0) < timestamp(1)`,
697 },
698 {
699 name: "timestamp_le_timestamp",
700 expr: `timestamp(2) <= timestamp(2)`,
701 },
702 {
703 name: "timestamp_gt_timestamp",
704 expr: `timestamp(1) > timestamp(0)`,
705 },
706 {
707 name: "timestamp_ge_timestamp",
708 expr: `timestamp(2) >= timestamp(2)`,
709 },
710 {
711 name: "timestamp_methods",
712 vars: []*decls.VariableDecl{
713 decls.NewVariable("x", types.TimestampType),
714 },
715 in: map[string]any{
716 "x": time.Unix(7506, 1000000).Local(),
717 },
718 expr: `
719 x.getFullYear() == 1970
720 && x.getMonth() == 0
721 && x.getDayOfYear() == 0
722 && x.getDayOfMonth() == 0
723 && x.getDate() == 1
724 && x.getDayOfWeek() == 4
725 && x.getHours() == 2
726 && x.getMinutes() == 5
727 && x.getSeconds() == 6
728 && x.getMilliseconds() == 1
729 && x.getFullYear('-07:30') == 1969
730 && x.getDayOfYear('-07:30') == 364
731 && x.getMonth('-07:30') == 11
732 && x.getDayOfMonth('-07:30') == 30
733 && x.getDate('-07:30') == 31
734 && x.getDayOfWeek('-07:30') == 3
735 && x.getHours('-07:30') == 18
736 && x.getMinutes('-07:30') == 35
737 && x.getSeconds('-07:30') == 6
738 && x.getMilliseconds('-07:30') == 1
739 && x.getFullYear('23:15') == 1970
740 && x.getDayOfYear('23:15') == 1
741 && x.getMonth('23:15') == 0
742 && x.getDayOfMonth('23:15') == 1
743 && x.getDate('23:15') == 2
744 && x.getDayOfWeek('23:15') == 5
745 && x.getHours('23:15') == 1
746 && x.getMinutes('23:15') == 20
747 && x.getSeconds('23:15') == 6
748 && x.getMilliseconds('23:15') == 1`,
749 },
750 {
751 name: "string_to_timestamp",
752 expr: `timestamp('1986-04-26T01:23:40Z')`,
753 out: &tpb.Timestamp{Seconds: 514862620},
754 },
755 {
756 name: "macro_all_non_strict",
757 expr: `![0, 2, 4].all(x, 4/x != 2 && 4/(4-x) != 2)`,
758 },
759 {
760 name: "macro_all_non_strict_var",
761 expr: `code == "111" && ["a", "b"].all(x, x in tags)
762 || code == "222" && ["a", "b"].all(x, x in tags)`,
763 vars: []*decls.VariableDecl{
764 decls.NewVariable("code", types.StringType),
765 decls.NewVariable("tags", types.NewListType(types.StringType)),
766 },
767 in: map[string]any{
768 "code": "222",
769 "tags": []string{"a", "b"},
770 },
771 },
772 {
773 name: "macro_exists_lit",
774 expr: `[1, 2, 3, 4, 5u, 1.0].exists(e, type(e) == uint)`,
775 },
776 {
777 name: "macro_exists_nonstrict",
778 expr: `[0, 2, 4].exists(x, 4/x == 2 && 4/(4-x) == 2)`,
779 },
780 {
781 name: "macro_exists_var",
782 expr: `elems.exists(e, type(e) == uint)`,
783 vars: []*decls.VariableDecl{
784 decls.NewVariable("elems", types.NewListType(types.DynType)),
785 },
786 in: map[string]any{
787 "elems": []any{0, 1, 2, 3, 4, uint(5), 6},
788 },
789 },
790 {
791 name: "macro_exists_one",
792 expr: `[1, 2, 3].exists_one(x, (x % 2) == 0)`,
793 },
794 {
795 name: "macro_filter",
796 expr: `[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3].filter(x, x > 0)`,
797 out: []int64{1, 2, 3},
798 },
799 {
800 name: "macro_has_map_key",
801 expr: `has({'a':1}.a) && !has({}.a)`,
802 },
803 {
804 name: "macro_has_pb2_field_undefined",
805 container: "google.expr.proto2.test",
806 types: []proto.Message{&proto2pb.TestAllTypes{}},
807 unchecked: true,
808 expr: `has(TestAllTypes{}.invalid_field)`,
809 err: "no such field 'invalid_field'",
810 },
811 {
812 name: "macro_has_pb2_field",
813 container: "google.expr.proto2.test",
814 types: []proto.Message{&proto2pb.TestAllTypes{}},
815 vars: []*decls.VariableDecl{
816 decls.NewVariable("pb2", types.NewObjectType("google.expr.proto2.test.TestAllTypes")),
817 },
818 in: map[string]any{
819 "pb2": &proto2pb.TestAllTypes{
820 RepeatedBool: []bool{false},
821 MapInt64NestedType: map[int64]*proto2pb.NestedTestAllTypes{
822 1: {},
823 },
824 MapStringString: map[string]string{},
825 },
826 },
827 expr: `has(TestAllTypes{standalone_enum: TestAllTypes.NestedEnum.BAR}.standalone_enum)
828 && has(TestAllTypes{standalone_enum: TestAllTypes.NestedEnum.FOO}.standalone_enum)
829 && !has(TestAllTypes{single_nested_enum: TestAllTypes.NestedEnum.FOO}.single_nested_message)
830 && has(TestAllTypes{single_nested_enum: TestAllTypes.NestedEnum.FOO}.single_nested_enum)
831 && !has(TestAllTypes{}.standalone_enum)
832 && !has(pb2.single_int64)
833 && has(pb2.repeated_bool)
834 && !has(pb2.repeated_int32)
835 && has(pb2.map_int64_nested_type)
836 && !has(pb2.map_string_string)`,
837 },
838 {
839 name: "macro_has_pb3_field",
840 types: []proto.Message{&proto3pb.TestAllTypes{}},
841 vars: []*decls.VariableDecl{
842 decls.NewVariable("pb3", types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
843 },
844 container: "google.expr.proto3.test",
845 in: map[string]any{
846 "pb3": &proto3pb.TestAllTypes{
847 RepeatedBool: []bool{false},
848 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
849 1: {},
850 },
851 MapStringString: map[string]string{},
852 },
853 },
854 expr: `has(TestAllTypes{standalone_enum: TestAllTypes.NestedEnum.BAR}.standalone_enum)
855 && !has(TestAllTypes{standalone_enum: TestAllTypes.NestedEnum.FOO}.standalone_enum)
856 && !has(TestAllTypes{single_nested_enum: TestAllTypes.NestedEnum.FOO}.single_nested_message)
857 && has(TestAllTypes{single_nested_enum: TestAllTypes.NestedEnum.FOO}.single_nested_enum)
858 && !has(TestAllTypes{}.single_nested_message)
859 && has(TestAllTypes{single_nested_message: TestAllTypes.NestedMessage{}}.single_nested_message)
860 && !has(TestAllTypes{}.standalone_enum)
861 && !has(pb3.single_int64)
862 && has(pb3.repeated_bool)
863 && !has(pb3.repeated_int32)
864 && has(pb3.map_int64_nested_type)
865 && !has(pb3.map_string_string)`,
866 },
867 {
868 name: "macro_map",
869 expr: `[1, 2, 3].map(x, x * 2) == [2, 4, 6]`,
870 },
871 {
872 name: "matches_global",
873 expr: `matches(input, 'k.*')`,
874 vars: []*decls.VariableDecl{
875 decls.NewVariable("input", types.StringType),
876 },
877 in: map[string]any{
878 "input": "kathmandu",
879 },
880 },
881 {
882 name: "matches_member",
883 expr: `input.matches('k.*')
884 && !'foo'.matches('k.*')
885 && !'bar'.matches('k.*')
886 && 'kilimanjaro'.matches('.*ro')`,
887 vars: []*decls.VariableDecl{
888 decls.NewVariable("input", types.StringType),
889 },
890 in: map[string]any{
891 "input": "kathmandu",
892 },
893 },
894 {
895 name: "matches_error",
896 expr: `input.matches(')k.*')`,
897 vars: []*decls.VariableDecl{
898 decls.NewVariable("input", types.StringType),
899 },
900 in: map[string]any{
901 "input": "kathmandu",
902 },
903 extraOpts: []PlannerOption{CompileRegexConstants(MatchesRegexOptimization)},
904 // unoptimized program should report a regex compile error at runtime
905 err: "unexpected ): `)k.*`",
906 // optimized program should report a regex compile at program creation time
907 progErr: "unexpected ): `)k.*`",
908 },
909 {
910 name: "nested_proto_field",
911 expr: `pb3.single_nested_message.bb`,
912 types: []proto.Message{&proto3pb.TestAllTypes{}},
913 vars: []*decls.VariableDecl{
914 decls.NewVariable("pb3",
915 types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
916 },
917 in: map[string]any{
918 "pb3": &proto3pb.TestAllTypes{
919 NestedType: &proto3pb.TestAllTypes_SingleNestedMessage{
920 SingleNestedMessage: &proto3pb.TestAllTypes_NestedMessage{
921 Bb: 1234,
922 },
923 },
924 },
925 },
926 out: types.Int(1234),
927 },
928 {
929 name: "nested_proto_field_with_index",
930 expr: `pb3.map_int64_nested_type[0].child.payload.single_int32 == 1`,
931 types: []proto.Message{&proto3pb.TestAllTypes{}},
932 vars: []*decls.VariableDecl{
933 decls.NewVariable("pb3",
934 types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
935 },
936 in: map[string]any{
937 "pb3": &proto3pb.TestAllTypes{
938 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
939 0: {
940 Child: &proto3pb.NestedTestAllTypes{
941 Payload: &proto3pb.TestAllTypes{
942 SingleInt32: 1,
943 },
944 },
945 },
946 },
947 },
948 },
949 },
950 {
951 name: "or_true_1st",
952 expr: `ai == 20 || ar["foo"] == "bar"`,
953 vars: []*decls.VariableDecl{
954 decls.NewVariable("ai", types.IntType),
955 decls.NewVariable("ar", types.NewMapType(types.StringType, types.StringType)),
956 },
957 in: map[string]any{
958 "ai": 20,
959 "ar": map[string]string{
960 "foo": "bar",
961 },
962 },
963 },
964 {
965 name: "or_true_2nd",
966 expr: `ai == 20 || ar["foo"] == "bar"`,
967 vars: []*decls.VariableDecl{
968 decls.NewVariable("ai", types.IntType),
969 decls.NewVariable("ar", types.NewMapType(types.StringType, types.StringType)),
970 },
971 in: map[string]any{
972 "ai": 2,
973 "ar": map[string]string{
974 "foo": "bar",
975 },
976 },
977 },
978 {
979 name: "or_false",
980 expr: `ai == 20 || ar["foo"] == "bar"`,
981 vars: []*decls.VariableDecl{
982 decls.NewVariable("ai", types.IntType),
983 decls.NewVariable("ar", types.NewMapType(types.StringType, types.StringType)),
984 },
985 in: map[string]any{
986 "ai": 2,
987 "ar": map[string]string{
988 "foo": "baz",
989 },
990 },
991 out: types.False,
992 },
993 {
994 name: "or_error_1st_error",
995 expr: `1/0 != 0 || false`,
996 err: "division by zero",
997 },
998 {
999 name: "or_error_2nd_error",
1000 expr: `false || 1/0 != 0`,
1001 err: "division by zero",
1002 },
1003 {
1004 name: "or_error_1st_true",
1005 expr: `1/0 != 0 || true`,
1006 out: types.True,
1007 },
1008 {
1009 name: "or_error_2nd_true",
1010 expr: `true || 1/0 != 0`,
1011 out: types.True,
1012 },
1013 {
1014 name: "pkg_qualified_id",
1015 expr: `b.c.d != 10`,
1016 container: "a.b",
1017 vars: []*decls.VariableDecl{
1018 decls.NewVariable("a.b.c.d", types.IntType),
1019 },
1020 in: map[string]any{
1021 "a.b.c.d": 9,
1022 },
1023 },
1024 {
1025 name: "pkg_qualified_id_unchecked",
1026 expr: `c.d != 10`,
1027 unchecked: true,
1028 container: "a.b",
1029 in: map[string]any{
1030 "a.c.d": 9,
1031 },
1032 },
1033 {
1034 name: "pkg_qualified_index_unchecked",
1035 expr: `b.c['d'] == 10`,
1036 unchecked: true,
1037 container: "a.b",
1038 in: map[string]any{
1039 "a.b.c": map[string]int{
1040 "d": 10,
1041 },
1042 },
1043 },
1044 {
1045 name: "type_dyn_equals_string",
1046 expr: `type(dyn('')) == string`,
1047 },
1048 {
1049 name: "type_override",
1050 expr: `type == 'string'`,
1051 vars: []*decls.VariableDecl{
1052 decls.NewVariable("type", types.StringType),
1053 },
1054 in: map[string]any{
1055 "type": "string",
1056 },
1057 },
1058 {
1059 name: "select_key",
1060 expr: `m.strMap['val'] == 'string'
1061 && m.floatMap['val'] == 1.5
1062 && m.doubleMap['val'] == -2.0
1063 && m.intMap['val'] == -3
1064 && m.int32Map['val'] == 4
1065 && m.int64Map['val'] == -5
1066 && m.uintMap['val'] == 6u
1067 && m.uint32Map['val'] == 7u
1068 && m.uint64Map['val'] == 8u
1069 && m.boolMap['val'] == true
1070 && m.boolMap['val'] != false`,
1071 vars: []*decls.VariableDecl{
1072 decls.NewVariable("m", types.NewMapType(types.StringType, types.DynType)),
1073 },
1074 in: map[string]any{
1075 "m": map[string]any{
1076 "strMap": map[string]string{"val": "string"},
1077 "floatMap": map[string]float32{"val": 1.5},
1078 "doubleMap": map[string]float64{"val": -2.0},
1079 "intMap": map[string]int{"val": -3},
1080 "int32Map": map[string]int32{"val": 4},
1081 "int64Map": map[string]int64{"val": -5},
1082 "uintMap": map[string]uint{"val": 6},
1083 "uint32Map": map[string]uint32{"val": 7},
1084 "uint64Map": map[string]uint64{"val": 8},
1085 "boolMap": map[string]bool{"val": true},
1086 },
1087 },
1088 },
1089 {
1090 name: "select_bool_key",
1091 expr: `m.boolStr[true] == 'string'
1092 && m.boolFloat32[true] == 1.5
1093 && m.boolFloat64[false] == -2.1
1094 && m.boolInt[false] == -3
1095 && m.boolInt32[false] == 0
1096 && m.boolInt64[true] == 4
1097 && m.boolUint[true] == 5u
1098 && m.boolUint32[true] == 6u
1099 && m.boolUint64[false] == 7u
1100 && m.boolBool[true]
1101 && m.boolIface[false] == true`,
1102 vars: []*decls.VariableDecl{
1103 decls.NewVariable("m", types.NewMapType(types.StringType, types.DynType)),
1104 },
1105 in: map[string]any{
1106 "m": map[string]any{
1107 "boolStr": map[bool]string{true: "string"},
1108 "boolFloat32": map[bool]float32{true: 1.5},
1109 "boolFloat64": map[bool]float64{false: -2.1},
1110 "boolInt": map[bool]int{false: -3},
1111 "boolInt32": map[bool]int32{false: 0},
1112 "boolInt64": map[bool]int64{true: 4},
1113 "boolUint": map[bool]uint{true: 5},
1114 "boolUint32": map[bool]uint32{true: 6},
1115 "boolUint64": map[bool]uint64{false: 7},
1116 "boolBool": map[bool]bool{true: true},
1117 "boolIface": map[bool]any{false: true},
1118 },
1119 },
1120 },
1121 {
1122 name: "select_uint_key",
1123 expr: `m.uintIface[1u] == 'string'
1124 && m.uint32Iface[2u] == 1.5
1125 && m.uint64Iface[3u] == -2.1
1126 && m.uint64String[4u] == 'three'`,
1127 vars: []*decls.VariableDecl{
1128 decls.NewVariable("m", types.NewMapType(types.StringType, types.DynType)),
1129 },
1130 in: map[string]any{
1131 "m": map[string]any{
1132 "uintIface": map[uint]any{1: "string"},
1133 "uint32Iface": map[uint32]any{2: 1.5},
1134 "uint64Iface": map[uint64]any{3: -2.1},
1135 "uint64String": map[uint64]string{4: "three"},
1136 },
1137 },
1138 },
1139 {
1140 name: "select_index",
1141 expr: `m.strList[0] == 'string'
1142 && m.floatList[0] == 1.5
1143 && m.doubleList[0] == -2.0
1144 && m.intList[0] == -3
1145 && m.int32List[0] == 4
1146 && m.int64List[0] == -5
1147 && m.uintList[0] == 6u
1148 && m.uint32List[0] == 7u
1149 && m.uint64List[0] == 8u
1150 && m.boolList[0] == true
1151 && m.boolList[1] != true
1152 && m.ifaceList[0] == {}`,
1153 vars: []*decls.VariableDecl{
1154 decls.NewVariable("m", types.NewMapType(types.StringType, types.DynType)),
1155 },
1156 in: map[string]any{
1157 "m": map[string]any{
1158 "strList": []string{"string"},
1159 "floatList": []float32{1.5},
1160 "doubleList": []float64{-2.0},
1161 "intList": []int{-3},
1162 "int32List": []int32{4},
1163 "int64List": []int64{-5},
1164 "uintList": []uint{6},
1165 "uint32List": []uint32{7},
1166 "uint64List": []uint64{8},
1167 "boolList": []bool{true, false},
1168 "ifaceList": []any{map[string]string{}},
1169 },
1170 },
1171 },
1172 {
1173 name: "select_field",
1174 expr: `a.b.c
1175 && pb3.repeated_nested_enum[0] == test.TestAllTypes.NestedEnum.BAR
1176 && json.list[0] == 'world'`,
1177 container: "google.expr.proto3",
1178 types: []proto.Message{&proto3pb.TestAllTypes{}},
1179 vars: []*decls.VariableDecl{
1180 decls.NewVariable("a.b", types.NewMapType(types.StringType, types.BoolType)),
1181 decls.NewVariable("pb3", types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
1182 decls.NewVariable("json", types.NewMapType(types.StringType, types.DynType)),
1183 },
1184 in: map[string]any{
1185 "a.b": map[string]bool{
1186 "c": true,
1187 },
1188 "pb3": &proto3pb.TestAllTypes{
1189 RepeatedNestedEnum: []proto3pb.TestAllTypes_NestedEnum{proto3pb.TestAllTypes_BAR},
1190 },
1191 "json": &structpb.Value{
1192 Kind: &structpb.Value_StructValue{
1193 StructValue: &structpb.Struct{
1194 Fields: map[string]*structpb.Value{
1195 "list": {Kind: &structpb.Value_ListValue{
1196 ListValue: &structpb.ListValue{
1197 Values: []*structpb.Value{
1198 structpb.NewStringValue("world"),
1199 },
1200 },
1201 }},
1202 },
1203 },
1204 },
1205 },
1206 },
1207 },
1208 // pb2 primitive fields may have default values set.
1209 {
1210 name: "select_pb2_primitive_fields",
1211 expr: `!has(a.single_int32)
1212 && a.single_int32 == -32
1213 && a.single_int64 == -64
1214 && a.single_uint32 == 32u
1215 && a.single_uint64 == 64u
1216 && a.single_float == 3.0
1217 && a.single_double == 6.4
1218 && a.single_bool
1219 && "empty" == a.single_string`,
1220 types: []proto.Message{&proto2pb.TestAllTypes{}},
1221 in: map[string]any{
1222 "a": &proto2pb.TestAllTypes{},
1223 },
1224 vars: []*decls.VariableDecl{
1225 decls.NewVariable("a", types.NewObjectType("google.expr.proto2.test.TestAllTypes")),
1226 },
1227 },
1228 // Wrapper type nil or value test.
1229 {
1230 name: "select_pb3_wrapper_fields",
1231 expr: `!has(a.single_int32_wrapper) && a.single_int32_wrapper == null
1232 && has(a.single_int64_wrapper) && a.single_int64_wrapper == 0
1233 && has(a.single_string_wrapper) && a.single_string_wrapper == "hello"
1234 && a.single_int64_wrapper == Int32Value{value: 0}`,
1235 types: []proto.Message{&proto3pb.TestAllTypes{}},
1236 abbrevs: []string{"google.protobuf.Int32Value"},
1237 vars: []*decls.VariableDecl{
1238 decls.NewVariable("a", types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
1239 },
1240 in: map[string]any{
1241 "a": &proto3pb.TestAllTypes{
1242 SingleInt64Wrapper: &wrapperspb.Int64Value{},
1243 SingleStringWrapper: wrapperspb.String("hello"),
1244 },
1245 },
1246 },
1247 {
1248 name: "select_pb3_compare",
1249 expr: `a.single_uint64 > 3u`,
1250 container: "google.expr.proto3.test",
1251 types: []proto.Message{&proto3pb.TestAllTypes{}},
1252 vars: []*decls.VariableDecl{
1253 decls.NewVariable("a", types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
1254 },
1255 in: map[string]any{
1256 "a": &proto3pb.TestAllTypes{
1257 SingleUint64: 10,
1258 },
1259 },
1260 out: types.True,
1261 },
1262 {
1263 name: "select_custom_pb3_compare",
1264 expr: `a.bb > 100`,
1265 container: "google.expr.proto3.test",
1266 types: []proto.Message{&proto3pb.TestAllTypes_NestedMessage{}},
1267 vars: []*decls.VariableDecl{
1268 decls.NewVariable("a",
1269 types.NewObjectType("google.expr.proto3.test.TestAllTypes.NestedMessage")),
1270 },
1271 attrs: &custAttrFactory{
1272 AttributeFactory: NewAttributeFactory(
1273 testContainer("google.expr.proto3.test"),
1274 newTestRegistry(t, &proto3pb.TestAllTypes_NestedMessage{}),
1275 newTestRegistry(t, &proto3pb.TestAllTypes_NestedMessage{}),
1276 ),
1277 },
1278 in: map[string]any{
1279 "a": &proto3pb.TestAllTypes_NestedMessage{
1280 Bb: 101,
1281 },
1282 },
1283 out: types.True,
1284 },
1285 {
1286 name: "select_custom_pb3_optional_field",
1287 expr: `a.?bb`,
1288 container: "google.expr.proto3.test",
1289 types: []proto.Message{&proto3pb.TestAllTypes_NestedMessage{}},
1290 vars: []*decls.VariableDecl{
1291 decls.NewVariable("a",
1292 types.NewObjectType("google.expr.proto3.test.TestAllTypes.NestedMessage")),
1293 },
1294 attrs: &custAttrFactory{
1295 AttributeFactory: NewAttributeFactory(
1296 testContainer("google.expr.proto3.test"),
1297 newTestRegistry(t, &proto3pb.TestAllTypes_NestedMessage{}),
1298 newTestRegistry(t, &proto3pb.TestAllTypes_NestedMessage{}),
1299 ),
1300 },
1301 in: map[string]any{
1302 "a": &proto3pb.TestAllTypes_NestedMessage{
1303 Bb: 101,
1304 },
1305 },
1306 out: types.OptionalOf(types.Int(101)),
1307 },
1308 {
1309 name: "select_relative",
1310 expr: `json('{"hi":"world"}').hi == 'world'`,
1311 funcs: []*decls.FunctionDecl{
1312 funcDecl(t, "json",
1313 decls.Overload("json_string", []*types.Type{types.StringType}, types.DynType,
1314 decls.UnaryBinding(func(val ref.Val) ref.Val {
1315 str, ok := val.(types.String)
1316 if !ok {
1317 return types.MaybeNoSuchOverloadErr(val)
1318 }
1319 m := make(map[string]any)
1320 err := json.Unmarshal([]byte(str), &m)
1321 if err != nil {
1322 return types.NewErr("invalid json: %v", err)
1323 }
1324 return types.DefaultTypeAdapter.NativeToValue(m)
1325 }),
1326 ),
1327 ),
1328 },
1329 },
1330 {
1331 name: "select_subsumed_field",
1332 expr: `a.b.c`,
1333 vars: []*decls.VariableDecl{
1334 decls.NewVariable("a.b.c", types.IntType),
1335 decls.NewVariable("a.b", types.NewMapType(types.StringType, types.StringType)),
1336 },
1337 in: map[string]any{
1338 "a.b.c": 10,
1339 "a.b": map[string]string{
1340 "c": "ten",
1341 },
1342 },
1343 out: types.Int(10),
1344 },
1345 {
1346 name: "select_empty_repeated_nested",
1347 expr: `TestAllTypes{}.repeated_nested_message.size() == 0`,
1348 types: []proto.Message{&proto3pb.TestAllTypes{}},
1349 container: "google.expr.proto3.test",
1350 out: types.True,
1351 },
1352 {
1353 name: "call_with_error_unary",
1354 expr: `try(0/0)`,
1355 unchecked: true,
1356 funcs: []*decls.FunctionDecl{
1357 funcDecl(t, "try",
1358 decls.Overload("try_dyn", []*types.Type{types.DynType}, types.DynType,
1359 decls.OverloadIsNonStrict(),
1360 decls.UnaryBinding(func(arg ref.Val) ref.Val {
1361 if types.IsError(arg) {
1362 return types.String(fmt.Sprintf("error: %s", arg))
1363 }
1364 return arg
1365 }),
1366 ),
1367 ),
1368 },
1369 out: types.String("error: division by zero"),
1370 },
1371 {
1372 name: "call_with_error_binary",
1373 expr: `try(0/0, 0)`,
1374 unchecked: true,
1375 funcs: []*decls.FunctionDecl{
1376 funcDecl(t, "try",
1377 decls.Overload("try_dyn",
1378 []*types.Type{types.DynType, types.DynType},
1379 types.NewListType(types.DynType),
1380 decls.OverloadIsNonStrict(),
1381 decls.BinaryBinding(func(arg0, arg1 ref.Val) ref.Val {
1382 if types.IsError(arg0) {
1383 return types.String(fmt.Sprintf("error: %s", arg0))
1384 }
1385 return types.NewDynamicList(types.DefaultTypeAdapter, []ref.Val{arg0, arg1})
1386 }),
1387 ),
1388 ),
1389 },
1390 out: types.String("error: division by zero"),
1391 },
1392 {
1393 name: "call_with_error_function",
1394 expr: `try(0/0, 0, 0)`,
1395 unchecked: true,
1396 funcs: []*decls.FunctionDecl{
1397 funcDecl(t, "try",
1398 decls.Overload("try_dyn",
1399 []*types.Type{types.DynType, types.DynType, types.DynType},
1400 types.NewListType(types.DynType),
1401 decls.OverloadIsNonStrict(),
1402 decls.FunctionBinding(func(args ...ref.Val) ref.Val {
1403 if types.IsError(args[0]) {
1404 return types.String(fmt.Sprintf("error: %s", args[0]))
1405 }
1406 return types.NewDynamicList(types.DefaultTypeAdapter, args)
1407 }),
1408 ),
1409 ),
1410 },
1411 out: types.String("error: division by zero"),
1412 },
1413 {
1414 name: "literal_map_optional_field",
1415 expr: `{?'hi': {}.?missing,
1416 ?'world': {'present': 42u}.?present}`,
1417 out: map[string]any{
1418 "world": uint(42),
1419 },
1420 },
1421 {
1422 name: "literal_map_optional_field_bad_init",
1423 expr: `{?'hi': 'world'}`,
1424 unchecked: true,
1425 err: `cannot initialize optional entry 'hi' from non-optional`,
1426 },
1427 {
1428 name: "literal_pb_optional_field",
1429 expr: `TestAllTypes{?single_int32: {'value': 1}.?value, ?single_string: {}.?missing}`,
1430 container: "google.expr.proto3.test",
1431 types: []proto.Message{&proto3pb.TestAllTypes{}},
1432 out: &proto3pb.TestAllTypes{
1433 SingleInt32: 1,
1434 },
1435 },
1436 {
1437 name: "literal_pb_optional_field_bad_init",
1438 expr: `TestAllTypes{?single_int32: 1}`,
1439 container: "google.expr.proto3.test",
1440 types: []proto.Message{&proto3pb.TestAllTypes{}},
1441 unchecked: true,
1442 err: `cannot initialize optional entry 'single_int32' from non-optional`,
1443 },
1444 {
1445 name: "literal_list_optional_element",
1446 expr: `[?{}.?missing, ?{'present': 42u}.?present]`,
1447 out: []uint64{42},
1448 },
1449 {
1450 name: "literal_list_optional_bad_element",
1451 expr: `[?123]`,
1452 unchecked: true,
1453 err: `cannot initialize optional list element from non-optional value 123`,
1454 },
1455 {
1456 name: "bad_argument_in_optimized_list",
1457 expr: `1/0 in [1, 2, 3]`,
1458 err: `division by zero`,
1459 },
1460 {
1461 name: "list_index_error",
1462 expr: `mylistundef[0]`,
1463 unchecked: true,
1464 err: `no such attribute(s): mylistundef`,
1465 },
1466 {
1467 name: "pkg_list_index_error",
1468 container: "goog",
1469 expr: `pkg.mylistundef[0]`,
1470 unchecked: true,
1471 err: `no such attribute(s): goog.pkg.mylistundef, pkg.mylistundef`,
1472 },
1473 {
1474 name: "unknown_attribute",
1475 expr: `a[0]`,
1476 vars: []*decls.VariableDecl{
1477 decls.NewVariable("a",
1478 types.NewMapType(types.IntType, types.BoolType)),
1479 },
1480 attrs: NewPartialAttributeFactory(testContainer(""), types.DefaultTypeAdapter, types.NewEmptyRegistry()),
1481 in: newTestPartialActivation(t, map[string]any{
1482 "a": map[int64]any{
1483 1: true,
1484 },
1485 }, NewAttributePattern("a").QualInt(0)),
1486 out: types.NewUnknown(2, types.QualifyAttribute[int64](types.NewAttributeTrail("a"), 0)),
1487 },
1488 {
1489 name: "unknown_attribute_mixed_qualifier",
1490 expr: `a[dyn(0u)]`,
1491 vars: []*decls.VariableDecl{
1492 decls.NewVariable("a",
1493 types.NewMapType(types.IntType, types.BoolType)),
1494 },
1495 attrs: NewPartialAttributeFactory(testContainer(""), types.DefaultTypeAdapter, types.NewEmptyRegistry()),
1496 in: newTestPartialActivation(t, map[string]any{
1497 "a": map[int64]any{
1498 1: true,
1499 },
1500 }, NewAttributePattern("a").QualInt(0)),
1501 out: types.NewUnknown(2, types.QualifyAttribute[uint64](types.NewAttributeTrail("a"), 0)),
1502 },
1503 {
1504 name: "invalid_presence_test_on_int_literal",
1505 expr: `has(dyn(1).invalid)`,
1506 err: "no such key: invalid",
1507 attrs: NewAttributeFactory(testContainer(""), types.DefaultTypeAdapter, types.NewEmptyRegistry(),
1508 EnableErrorOnBadPresenceTest(true)),
1509 },
1510 {
1511 name: "invalid_presence_test_on_list_literal",
1512 expr: `has(dyn([]).invalid)`,
1513 err: "unsupported index type 'string' in list",
1514 attrs: NewAttributeFactory(testContainer(""), types.DefaultTypeAdapter, types.NewEmptyRegistry(),
1515 EnableErrorOnBadPresenceTest(true)),
1516 },
1517
1518 {
1519 name: "optional_select_on_undefined",
1520 expr: `{}.?invalid`,
1521 out: types.OptionalNone,
1522 },
1523 {
1524 name: "optional_select_on_null_literal",
1525 expr: `{"invalid": dyn(null)}.?invalid.?nested`,
1526 out: types.OptionalNone,
1527 },
1528 {
1529 name: "local_shadow_identifier_in_select",
1530 expr: `[{'z': 0}].exists(y, y.z == 0)`,
1531 container: "cel.example",
1532 vars: []*decls.VariableDecl{
1533 decls.NewVariable("cel.example.y", types.IntType),
1534 },
1535 in: map[string]any{
1536 "cel.example.y": map[string]int{"z": 1},
1537 },
1538 out: types.True,
1539 },
1540 {
1541 name: "local_shadow_identifier_in_select_global_disambiguation",
1542 expr: `[{'z': 0}].exists(y, y.z == 0 && .y.z == 1)`,
1543 container: "y",
1544 vars: []*decls.VariableDecl{
1545 decls.NewVariable("y.z", types.IntType),
1546 },
1547 in: map[string]any{
1548 "y.z": 1,
1549 },
1550 out: types.True,
1551 },
1552 {
1553 name: "local_shadow_identifier_with_global_disambiguation",
1554 expr: `[0].exists(x, x == 0 && .x == 1)`,
1555 vars: []*decls.VariableDecl{
1556 decls.NewVariable("x", types.IntType),
1557 },
1558 in: map[string]any{
1559 "x": 1,
1560 },
1561 out: types.True,
1562 },
1563 {
1564 name: "local_double_shadow_identifier_with_global_disambiguation",
1565 expr: `[0].exists(x, [x+1].exists(x, x == .x))`,
1566 vars: []*decls.VariableDecl{
1567 decls.NewVariable("x", types.IntType),
1568 },
1569 in: map[string]any{
1570 "x": 1,
1571 },
1572 out: types.True,
1573 },
1574 {
1575 name: "unchecked_local_shadow_identifier_in_select",
1576 expr: `[{'z': 0}].exists(y, y.z == 0)`,
1577 unchecked: true,
1578 container: "cel.example",
1579 vars: []*decls.VariableDecl{
1580 decls.NewVariable("cel.example.y", types.IntType),
1581 },
1582 in: map[string]any{
1583 "cel.example.y": map[string]int{"z": 1},
1584 },
1585 out: types.True,
1586 },
1587 {
1588 name: "unchecked_local_shadow_identifier_in_select_global_disambiguation",
1589 expr: `[{'z': 0}].exists(y, y.z == 0 && .y.z == 1)`,
1590 container: "y",
1591 unchecked: true,
1592 vars: []*decls.VariableDecl{
1593 decls.NewVariable("y.z", types.IntType),
1594 },
1595 in: map[string]any{
1596 "y.z": 1,
1597 },
1598 out: types.True,
1599 },
1600 {
1601 name: "unchecked_local_shadow_identifier_with_global_disambiguation",
1602 expr: `[0].exists(x, x == 0 && .x == 1)`,
1603 unchecked: true,
1604 vars: []*decls.VariableDecl{
1605 decls.NewVariable("x", types.IntType),
1606 },
1607 in: map[string]any{
1608 "x": 1,
1609 },
1610 out: types.True,
1611 },
1612 {
1613 name: "unchecked_local_double_shadow_identifier_with_global_disambiguation",
1614 expr: `[0].exists(x, [x+1].exists(x, x == .x))`,
1615 unchecked: true,
1616 vars: []*decls.VariableDecl{
1617 decls.NewVariable("x", types.IntType),
1618 },
1619 in: map[string]any{
1620 "x": 1,
1621 },
1622 out: types.True,
1623 },
1624 }
1625 }
1626
1627 func BenchmarkInterpreter(b *testing.B) {
1628 for _, tst := range testData(b) {
1629 if tst.err != "" || tst.progErr != "" {
1630 continue
1631 }
1632 prg, vars, err := program(b, &tst, Optimize(), CompileRegexConstants(MatchesRegexOptimization))
1633 if err != nil {
1634 b.Fatal(err)
1635 }
1636 // Benchmark the eval.
1637 b.Run(tst.name, func(b *testing.B) {
1638 b.ResetTimer()
1639 b.ReportAllocs()
1640 for i := 0; i < b.N; i++ {
1641 prg.Eval(vars)
1642 }
1643 })
1644 }
1645 }
1646
1647 func BenchmarkInterpreterParallel(b *testing.B) {
1648 for _, tst := range testData(b) {
1649 prg, vars, err := program(b, &tst, Optimize(), CompileRegexConstants(MatchesRegexOptimization))
1650 if tst.err != "" || tst.progErr != "" {
1651 continue
1652 }
1653 if err != nil {
1654 b.Fatal(err)
1655 }
1656 b.ResetTimer()
1657 b.Run(tst.name,
1658 func(b *testing.B) {
1659 b.RunParallel(func(pb *testing.PB) {
1660 for pb.Next() {
1661 prg.Eval(vars)
1662 }
1663 })
1664 })
1665 }
1666 }
1667
1668 func TestInterpreter(t *testing.T) {
1669 for _, tst := range testData(t) {
1670 tc := tst
1671 prg, vars, err := program(t, &tc)
1672 if err != nil {
1673 t.Fatalf("%s: %v", tc.name, err)
1674 }
1675 t.Run(tc.name, func(t *testing.T) {
1676 t.Parallel()
1677
1678 var want ref.Val = types.True
1679 if tc.out != nil {
1680 want = tc.out.(ref.Val)
1681 }
1682 got := prg.Eval(vars)
1683 _, expectUnk := want.(*types.Unknown)
1684 if expectUnk {
1685 if !reflect.DeepEqual(got, want) {
1686 t.Fatalf("Got %v, wanted %v", got, want)
1687 }
1688 } else if tc.err != "" {
1689 if !types.IsError(got) || !strings.Contains(got.(*types.Err).String(), tc.err) {
1690 t.Fatalf("Got %v (%T), wanted error: %s", got, got, tc.err)
1691 }
1692 } else if got.Equal(want) != types.True {
1693 t.Fatalf("Got %v, wanted %v", got, want)
1694 }
1695
1696 state := NewEvalState()
1697 opts := map[string][]PlannerOption{
1698 "optimize": {Optimize()},
1699 "exhaustive": {ExhaustiveEval(),
1700 EvalStateObserver(EvalStateFactory(func() EvalState { return state }))},
1701 "track": {EvalStateObserver(EvalStateFactory(func() EvalState { return state }))},
1702 }
1703 for mode, opt := range opts {
1704 opts := opt
1705 if tc.extraOpts != nil {
1706 opts = append(opts, tc.extraOpts...)
1707 }
1708 prg, vars, err = program(t, &tc, opts...)
1709 if tc.progErr != "" {
1710 if !types.IsError(got) || !strings.Contains(got.(*types.Err).String(), tc.progErr) {
1711 t.Errorf("Got %v (%T), wanted error: %s", got, got, tc.progErr)
1712 }
1713 continue
1714 }
1715 if err != nil {
1716 t.Fatal(err)
1717 }
1718 t.Run(mode, func(t *testing.T) {
1719 got := prg.Eval(vars)
1720 _, expectUnk := want.(*types.Unknown)
1721 if expectUnk {
1722 if !reflect.DeepEqual(got, want) {
1723 t.Errorf("Got %v, wanted %v", got, want)
1724 }
1725 } else if tc.err != "" {
1726 if !types.IsError(got) || !strings.Contains(got.(*types.Err).String(), tc.err) {
1727 t.Errorf("Got %v (%T), wanted error: %s", got, got, tc.err)
1728 }
1729 type nodeIDer interface {
1730 NodeID() int64
1731 }
1732 nodeErr, ok := got.(nodeIDer)
1733 if !ok || nodeErr.NodeID() == 0 {
1734 t.Errorf("Did not get AST node ID from error: %#v", got)
1735 }
1736 } else if got.Equal(want) != types.True {
1737 t.Errorf("Got %v, wanted %v", got, want)
1738 }
1739 state.Reset()
1740 })
1741 }
1742 })
1743 }
1744 }
1745
1746 func TestInterpreter_ProtoAttributeOpt(t *testing.T) {
1747 inst, _, err := program(t, &testCase{
1748 name: "nested_proto_field_with_index",
1749 expr: `pb3.map_int64_nested_type[0].child.payload.single_int32`,
1750 types: []proto.Message{&proto3pb.TestAllTypes{}},
1751 vars: []*decls.VariableDecl{
1752 decls.NewVariable("pb3",
1753 types.NewObjectType("google.expr.proto3.test.TestAllTypes")),
1754 },
1755 in: map[string]any{
1756 "pb3": &proto3pb.TestAllTypes{
1757 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
1758 0: {
1759 Child: &proto3pb.NestedTestAllTypes{
1760 Payload: &proto3pb.TestAllTypes{
1761 SingleInt32: 1,
1762 },
1763 },
1764 },
1765 },
1766 },
1767 },
1768 }, Optimize())
1769 if err != nil {
1770 t.Fatal(err)
1771 }
1772 attr, ok := inst.(InterpretableAttribute)
1773 if !ok {
1774 t.Fatalf("got %v, expected attribute value", inst)
1775 }
1776 absAttr, ok := attr.Attr().(NamespacedAttribute)
1777 if !ok {
1778 t.Fatalf("got %v, expected global attribute", attr.Attr())
1779 }
1780 quals := absAttr.Qualifiers()
1781 if len(quals) != 5 {
1782 t.Errorf("got %d qualifiers, wanted 5", len(quals))
1783 }
1784 if !isFieldQual(quals[0], "map_int64_nested_type") ||
1785 !isConstQual(quals[1], types.IntZero) ||
1786 !isFieldQual(quals[2], "child") ||
1787 !isFieldQual(quals[3], "payload") ||
1788 !isFieldQual(quals[4], "single_int32") {
1789 t.Error("unoptimized qualifier types present in optimized attribute")
1790 }
1791 }
1792
1793 func TestInterpreter_LogicalAndMissingType(t *testing.T) {
1794 parsed := testMustParse(t, `a && TestProto{c: true}.c`)
1795 reg := newTestRegistry(t)
1796 cont := containers.DefaultContainer
1797 attrs := NewAttributeFactory(cont, reg, reg)
1798 intr := newStandardInterpreter(t, cont, reg, reg, attrs)
1799 i, err := intr.NewInterpretable(parsed)
1800 if err == nil {
1801 t.Errorf("Got '%v', wanted error", i)
1802 }
1803 }
1804
1805 func TestInterpreter_ExhaustiveConditionalExpr(t *testing.T) {
1806 parsed := testMustParse(t, `a ? b < 1.0 : c == ['hello']`)
1807 state := NewEvalState()
1808 cont := containers.DefaultContainer
1809 reg := newTestRegistry(t, &exprpb.ParsedExpr{})
1810 attrs := NewAttributeFactory(cont, reg, reg)
1811 intr := newStandardInterpreter(t, cont, reg, reg, attrs)
1812 interpretable, _ := intr.NewInterpretable(parsed, ExhaustiveEval(),
1813 EvalStateObserver(EvalStateFactory(func() EvalState { return state })))
1814 vars, _ := NewActivation(map[string]any{
1815 "a": types.True,
1816 "b": types.Double(0.999),
1817 "c": types.NewStringList(reg, []string{"hello"})})
1818 result := interpretable.Eval(vars)
1819 // Operator "_==_" is at Expr 7, should be evaluated in exhaustive mode
1820 // even though "a" is true
1821 ev, _ := state.Value(7)
1822 // "==" should be evaluated in exhaustive mode though unnecessary
1823 if ev != types.True {
1824 t.Errorf("Else expression expected to be true, got: %v", ev)
1825 }
1826 if result != types.True {
1827 t.Errorf("Expected true, got: %v", result)
1828 }
1829 }
1830
1831 func TestInterpreter_WrappedActivationEvalState(t *testing.T) {
1832 vars, _ := NewActivation(map[string]any{
1833 "a": types.True,
1834 "b": types.True,
1835 "c": types.False,
1836 "d": types.False,
1837 })
1838 state := NewEvalState()
1839 esa := &evalStateActivation{vars: vars, state: state}
1840 wrappedVars := &testActivationWrapper{esa, "test_activation_wrapper"}
1841 ac, _ := NewActivation(wrappedVars)
1842 es, found := asEvalState(ac)
1843 if !found {
1844 t.Errorf("asEvalState(%v) failed to find EvalState", ac)
1845 }
1846 if es != state {
1847 t.Errorf("asEvalState(%v) returned %v, wanted %v", ac, es, state)
1848 }
1849 }
1850
1851 func TestInterpreter_InterruptableEval(t *testing.T) {
1852 items := make([]int64, 5000)
1853 for i := int64(0); i < 5000; i++ {
1854 items[i] = i
1855 }
1856 tc := testCase{
1857 expr: `items.map(i, i).map(i, i).size() != 0`,
1858 vars: []*decls.VariableDecl{
1859 decls.NewVariable("items", types.NewListType(types.IntType)),
1860 },
1861 in: map[string]any{
1862 "items": items,
1863 },
1864 out: true,
1865 }
1866 prg, vars, err := program(t, &tc, InterruptableEval())
1867 if err != nil {
1868 t.Fatalf("program(%s) failed: %v", tc.expr, err)
1869 }
1870
1871 ctx := context.TODO()
1872 evalCtx, cancel := context.WithTimeout(ctx, 10*time.Microsecond)
1873 defer cancel()
1874
1875 ctxVars := &contextActivation{
1876 Activation: vars,
1877 interrupt: func() bool {
1878 select {
1879 case <-evalCtx.Done():
1880 return true
1881 default:
1882 return false
1883 }
1884 },
1885 }
1886 out := prg.Eval(ctxVars)
1887 if !types.IsError(out) || out.(*types.Err).String() != "operation interrupted" {
1888 t.Errorf("Got %v, wanted operation interrupted error", out)
1889 }
1890 }
1891
1892 type contextActivation struct {
1893 Activation
1894 interruptCount int
1895 interrupt func() bool
1896 }
1897
1898 func (ca *contextActivation) ResolveName(name string) (any, bool) {
1899 if name == "#interrupted" {
1900 ca.interruptCount++
1901 return ca.interruptCount%100 == 0 && ca.interrupt(), true
1902 }
1903 return ca.Activation.ResolveName(name)
1904 }
1905
1906 func TestInterpreter_ExhaustiveLogicalOrEquals(t *testing.T) {
1907 // a || b == "b"
1908 // Operator "==" is at Expr 4, should be evaluated though "a" is true
1909 parsed := testMustParse(t, `a || b == "b"`)
1910 state := NewEvalState()
1911 reg := newTestRegistry(t, &exprpb.Expr{})
1912 cont := testContainer("test")
1913 attrs := NewAttributeFactory(cont, reg, reg)
1914 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
1915 i, _ := interp.NewInterpretable(parsed, ExhaustiveEval(),
1916 EvalStateObserver(EvalStateFactory(func() EvalState { return state })))
1917 vars, _ := NewActivation(map[string]any{
1918 "a": true,
1919 "b": "b",
1920 })
1921 result := i.Eval(vars)
1922 rhv, _ := state.Value(3)
1923 // "==" should be evaluated in exhaustive mode though unnecessary
1924 if rhv != types.True {
1925 t.Errorf("Right hand side expression expected to be true, got: %v", rhv)
1926 }
1927 if result != types.True {
1928 t.Errorf("Expected true, got: %v", result)
1929 }
1930 }
1931
1932 func TestInterpreter_SetProto2PrimitiveFields(t *testing.T) {
1933 // Test the use of proto2 primitives within object construction.
1934 src := common.NewTextSource(
1935 `input == TestAllTypes{
1936 single_int32: 1,
1937 single_int64: 2,
1938 single_uint32: 3u,
1939 single_uint64: 4u,
1940 single_float: -3.3,
1941 single_double: -2.2,
1942 single_string: "hello world",
1943 single_bool: true
1944 }`)
1945 parsed := testMustParse(t, src)
1946 cont := testContainer("google.expr.proto2.test")
1947 reg := newTestRegistry(t, &proto2pb.TestAllTypes{})
1948 env := newTestEnv(t, cont, reg)
1949 env.AddIdents(
1950 decls.NewVariable("input",
1951 types.NewObjectType("google.expr.proto2.test.TestAllTypes")))
1952 checked, errors := checker.Check(parsed, src, env)
1953 if len(errors.GetErrors()) != 0 {
1954 t.Error(errors.ToDisplayString())
1955 }
1956
1957 attrs := NewAttributeFactory(cont, reg, reg)
1958 i := newStandardInterpreter(t, cont, reg, reg, attrs)
1959 eval, _ := i.NewInterpretable(checked)
1960 one := int32(1)
1961 two := int64(2)
1962 three := uint32(3)
1963 four := uint64(4)
1964 five := float32(-3.3)
1965 six := float64(-2.2)
1966 str := "hello world"
1967 truth := true
1968 input := &proto2pb.TestAllTypes{
1969 SingleInt32: &one,
1970 SingleInt64: &two,
1971 SingleUint32: &three,
1972 SingleUint64: &four,
1973 SingleFloat: &five,
1974 SingleDouble: &six,
1975 SingleString: &str,
1976 SingleBool: &truth,
1977 }
1978 vars, _ := NewActivation(map[string]any{
1979 "input": reg.NativeToValue(input),
1980 })
1981 result := eval.Eval(vars)
1982 got, ok := result.Value().(bool)
1983 if !ok {
1984 t.Fatalf("Got '%v', wanted 'true'.", result)
1985 }
1986 expected := true
1987 if !reflect.DeepEqual(got, expected) {
1988 t.Errorf("Could not build object properly. Got '%v', wanted '%v'",
1989 result.Value(),
1990 expected)
1991 }
1992 }
1993
1994 func TestInterpreter_MissingIdentInSelect(t *testing.T) {
1995 src := common.NewTextSource(`a.b.c`)
1996 parsed := testMustParse(t, src)
1997 cont := testContainer("test")
1998 reg := newTestRegistry(t)
1999 env := newTestEnv(t, cont, reg)
2000 env.AddIdents(decls.NewVariable("a.b", types.DynType))
2001 checked, errors := checker.Check(parsed, src, env)
2002 if len(errors.GetErrors()) != 0 {
2003 t.Fatal(errors.ToDisplayString())
2004 }
2005
2006 attrs := NewPartialAttributeFactory(cont, reg, reg)
2007 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
2008 i, _ := interp.NewInterpretable(checked)
2009 vars, _ := NewPartialActivation(
2010 map[string]any{
2011 "a.b": map[string]any{
2012 "d": "hello",
2013 },
2014 },
2015 NewAttributePattern("a.b").QualString("c"))
2016 result := i.Eval(vars)
2017 if !types.IsUnknown(result) {
2018 t.Errorf("Got %v, wanted unknown", result)
2019 }
2020
2021 result = i.Eval(EmptyActivation())
2022 if !types.IsError(result) {
2023 t.Errorf("Got %v, wanted error", result)
2024 }
2025 }
2026
2027 func TestInterpreter_TypeConversionOpt(t *testing.T) {
2028 tests := []struct {
2029 in string
2030 out ref.Val
2031 err bool
2032 }{
2033 {in: `bool('tru')`, err: true},
2034 {in: `bool("true")`, out: types.True},
2035 {in: `bytes("hello")`, out: types.Bytes("hello")},
2036 {in: `double("_123")`, err: true},
2037 {in: `double("123.0")`, out: types.Double(123.0)},
2038 {in: `duration('12hh3')`, err: true},
2039 {in: `duration('12s')`, out: types.Duration{Duration: time.Duration(12) * time.Second}},
2040 {in: `dyn(1u)`, out: types.Uint(1)},
2041 {in: `int('11l')`, err: true},
2042 {in: `int('11')`, out: types.Int(11)},
2043 {in: `string('11')`, out: types.String("11")},
2044 {in: `timestamp('123')`, err: true},
2045 {in: `timestamp(123)`, out: types.Timestamp{Time: time.Unix(123, 0).UTC()}},
2046 {in: `type(null)`, out: types.NullType},
2047 {in: `type(timestamp(int('123')))`, out: types.TimestampType},
2048 {in: `uint(-1)`, err: true},
2049 {in: `uint(1)`, out: types.Uint(1)},
2050 }
2051 for _, tc := range tests {
2052 src := common.NewTextSource(tc.in)
2053 parsed := testMustParse(t, src)
2054 cont := containers.DefaultContainer
2055 reg := newTestRegistry(t)
2056 env := newTestEnv(t, cont, reg)
2057 checked, errors := checker.Check(parsed, src, env)
2058 if len(errors.GetErrors()) != 0 {
2059 t.Fatal(errors.ToDisplayString())
2060 }
2061 attrs := NewAttributeFactory(cont, reg, reg)
2062 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
2063 // Show that program planning will now produce an error.
2064 i, err := interp.NewInterpretable(checked, Optimize())
2065 if tc.err && err == nil {
2066 t.Fatalf("got %v, expected error", i)
2067 }
2068 if tc.out != nil {
2069 if err != nil {
2070 t.Fatal(err)
2071 }
2072 ic, isConst := i.(InterpretableConst)
2073 if !isConst {
2074 t.Fatalf("got %v, expected constant", ic)
2075 }
2076 if tc.out.Equal(ic.Value()) != types.True {
2077 t.Errorf("got %v, wanted %v", ic.Value(), tc.out)
2078 }
2079 }
2080 // Show how the error returned during program planning is the same as the runtime
2081 // error which would be produced normally.
2082 if tc.err {
2083 i2, err2 := interp.NewInterpretable(checked)
2084 if err2 != nil {
2085 t.Fatalf("got error, wanted interpretable: %v", i2)
2086 }
2087 errVal := i2.Eval(EmptyActivation())
2088 errValStr := errVal.(*types.Err).Error()
2089 if errValStr != err.Error() {
2090 t.Errorf("got error %s, wanted error %s", errValStr, err.Error())
2091 }
2092 }
2093 }
2094 }
2095
2096 func TestInterpreter_PlanOptionalElements(t *testing.T) {
2097 fac := ast.NewExprFactory()
2098 // [?a] manipulated so the optional index is negative.
2099 badOptionalA := fac.NewList(1, []ast.Expr{fac.NewIdent(2, "a")}, []int32{-1})
2100 // [?b] manipulated so the optional index is out of range.
2101 badOptionalB := fac.NewList(1, []ast.Expr{fac.NewIdent(2, "b")}, []int32{24})
2102 cont := containers.DefaultContainer
2103 reg := newTestRegistry(t)
2104 attrs := NewAttributeFactory(cont, reg, reg)
2105 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
2106 _, err := interp.NewInterpretable(ast.NewAST(badOptionalA, nil), Optimize())
2107 if err == nil {
2108 t.Fatal("interp.NewInterpretable() should have failed with negative optional index: -1")
2109 }
2110 _, err = interp.NewInterpretable(ast.NewAST(badOptionalB, nil), Optimize())
2111 if err == nil {
2112 t.Fatal("interp.NewInterpretable() should have failed with out of range optional index: 24")
2113 }
2114 }
2115
2116 func TestInterpreter_PlanListComprehensionTwoVar(t *testing.T) {
2117 fac := ast.NewExprFactory()
2118 listTwoArgTuples := fac.NewComprehensionTwoVar(1,
2119 fac.NewList(2, []ast.Expr{
2120 fac.NewLiteral(3, types.Int(2)),
2121 fac.NewLiteral(4, types.Int(3)),
2122 }, []int32{}),
2123 "i",
2124 "v",
2125 fac.AccuIdentName(),
2126 fac.NewList(5, []ast.Expr{}, []int32{}),
2127 fac.NewLiteral(6, types.True),
2128 fac.NewCall(7, operators.Add, fac.NewAccuIdent(8),
2129 fac.NewList(9, []ast.Expr{fac.NewIdent(10, "i"), fac.NewIdent(11, "v")}, []int32{})),
2130 fac.NewAccuIdent(12),
2131 )
2132 cont := containers.DefaultContainer
2133 reg := newTestRegistry(t)
2134 attrs := NewAttributeFactory(cont, reg, reg)
2135 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
2136 expr, err := interp.NewInterpretable(ast.NewAST(listTwoArgTuples, nil), Optimize())
2137 if err != nil {
2138 t.Fatalf("interp.NewInterpretable() failed for two-variable comprehension: %v", err)
2139 }
2140 result := expr.Eval(EmptyActivation())
2141 if types.IsError(result) {
2142 t.Fatalf("expr.Eval() yielded error: %v", result)
2143 }
2144 want := []int64{0, 2, 1, 3}
2145 out, err := result.ConvertToNative(reflect.TypeOf(want))
2146 if err != nil {
2147 t.Fatalf("result.ConvertToNative() failed: %v", err)
2148 }
2149 if !reflect.DeepEqual(out, want) {
2150 t.Errorf("got %v, wanted %v", out, want)
2151 }
2152 }
2153
2154 func TestInterpreter_PlanMapComprehensionTwoVar(t *testing.T) {
2155 fac := ast.NewExprFactory()
2156 listTwoArgTuples := fac.NewComprehensionTwoVar(1,
2157 fac.NewMap(2, []ast.EntryExpr{
2158 fac.NewMapEntry(3, fac.NewLiteral(4, types.Int(0)), fac.NewLiteral(5, types.String("first")), false),
2159 fac.NewMapEntry(6, fac.NewLiteral(7, types.Int(1)), fac.NewLiteral(8, types.String("second")), false),
2160 }),
2161 "k",
2162 "v",
2163 fac.AccuIdentName(),
2164 fac.NewMap(9, []ast.EntryExpr{}),
2165 fac.NewLiteral(10, types.True),
2166 fac.NewCall(11, "cel.@mapInsert",
2167 fac.NewAccuIdent(12),
2168 fac.NewCall(13, operators.Add, fac.NewIdent(14, "k"), fac.NewLiteral(15, types.IntOne)),
2169 fac.NewIdent(16, "v"),
2170 ),
2171 fac.NewAccuIdent(17),
2172 )
2173 cont := containers.DefaultContainer
2174 reg := newTestRegistry(t)
2175 attrs := NewAttributeFactory(cont, reg, reg)
2176 interp := newStandardInterpreter(t, cont, reg, reg, attrs,
2177 funcDecl(t, "cel.@mapInsert",
2178 decls.Overload("cel.@mapInsert",
2179 []*types.Type{
2180 types.NewMapType(types.IntType, types.StringType),
2181 types.IntType,
2182 types.StringType,
2183 }, types.NewMapType(types.IntType, types.StringType)),
2184 decls.SingletonFunctionBinding(func(args ...ref.Val) ref.Val {
2185 m := args[0].(traits.Mapper)
2186 k := args[1]
2187 v := args[2]
2188 return types.InsertMapKeyValue(m, k, v)
2189 }),
2190 ))
2191 expr, err := interp.NewInterpretable(ast.NewAST(listTwoArgTuples, nil), Optimize())
2192 if err != nil {
2193 t.Fatalf("interp.NewInterpretable() failed for two-variable comprehension: %v", err)
2194 }
2195 result := expr.Eval(EmptyActivation())
2196 if types.IsError(result) {
2197 t.Fatalf("expr.Eval() yielded error: %v", result)
2198 }
2199 want := map[int64]string{1: "first", 2: "second"}
2200 out, err := result.ConvertToNative(reflect.TypeOf(want))
2201 if err != nil {
2202 t.Fatalf("result.ConvertToNative() failed: %v", err)
2203 }
2204 if !reflect.DeepEqual(out, want) {
2205 t.Errorf("got %v, wanted %v", out, want)
2206 }
2207 }
2208
2209 func testContainer(name string) *containers.Container {
2210 cont, _ := containers.NewContainer(containers.Name(name))
2211 return cont
2212 }
2213
2214 func program(t testing.TB, tst *testCase, opts ...PlannerOption) (Interpretable, Activation, error) {
2215 // Configure the package.
2216 cont := containers.DefaultContainer
2217 if tst.container != "" {
2218 cont = testContainer(tst.container)
2219 }
2220 var err error
2221 if tst.abbrevs != nil {
2222 cont, err = containers.NewContainer(
2223 containers.Name(cont.Name()),
2224 containers.Abbrevs(tst.abbrevs...))
2225 if err != nil {
2226 return nil, nil, err
2227 }
2228 }
2229 var reg *types.Registry
2230 var env *checker.Env
2231 reg = newTestRegistry(t)
2232 if tst.types != nil {
2233 reg = newTestRegistry(t, tst.types...)
2234 }
2235 env = newTestEnv(t, cont, reg)
2236 attrs := NewAttributeFactory(cont, reg, reg)
2237 if tst.attrs != nil {
2238 attrs = tst.attrs
2239 }
2240 if tst.vars != nil {
2241 err = env.AddIdents(tst.vars...)
2242 if err != nil {
2243 return nil, nil, fmt.Errorf("env.Add(%v) failed: %v", tst.vars, err)
2244 }
2245 }
2246 // Configure the program input.
2247 vars := EmptyActivation()
2248 if tst.in != nil {
2249 vars, err = NewActivation(tst.in)
2250 if err != nil {
2251 t.Fatalf("NewActivation(%v) failed: %v", tst.in, err)
2252 }
2253 }
2254 // Adapt the test output, if needed.
2255 if tst.out != nil {
2256 tst.out = reg.NativeToValue(tst.out)
2257 }
2258
2259 disp := NewDispatcher()
2260 addFunctionBindings(t, disp)
2261 if tst.funcs != nil {
2262 err = env.AddFunctions(tst.funcs...)
2263 if err != nil {
2264 return nil, nil, fmt.Errorf("env.Add(%v) failed: %v", tst.funcs, err)
2265 }
2266 disp.Add(funcBindings(t, tst.funcs...)...)
2267 }
2268 interp := NewInterpreter(disp, cont, reg, reg, attrs)
2269
2270 // Parse the expression.
2271 s := common.NewTextSource(tst.expr)
2272 p, err := parser.NewParser(
2273 parser.Macros(parser.AllMacros...),
2274 parser.EnableOptionalSyntax(true),
2275 parser.EnableVariadicOperatorASTs(true),
2276 )
2277 if err != nil {
2278 return nil, nil, err
2279 }
2280 parsed, errs := p.Parse(s)
2281 if len(errs.GetErrors()) != 0 {
2282 return nil, nil, errors.New(errs.ToDisplayString())
2283 }
2284 if tst.unchecked {
2285 // Build the program plan.
2286 prg, err := interp.NewInterpretable(parsed, opts...)
2287 if err != nil {
2288 return nil, nil, err
2289 }
2290 return prg, vars, nil
2291 }
2292 // Check the expression.
2293 checked, errs := checker.Check(parsed, s, env)
2294 if len(errs.GetErrors()) != 0 {
2295 return nil, nil, errors.New(errs.ToDisplayString())
2296 }
2297 // Build the program plan.
2298 prg, err := interp.NewInterpretable(checked, opts...)
2299 if err != nil {
2300 return nil, nil, err
2301 }
2302 return prg, vars, nil
2303 }
2304
2305 func base64Encode(val ref.Val) ref.Val {
2306 str, ok := val.(types.String)
2307 if !ok {
2308 return types.MaybeNoSuchOverloadErr(val)
2309 }
2310 return types.String(base64.StdEncoding.EncodeToString([]byte(str)))
2311 }
2312
2313 func isConstQual(q Qualifier, val ref.Val) bool {
2314 c, ok := q.(ConstantQualifier)
2315 if !ok {
2316 return false
2317 }
2318 return c.Value().Equal(val) == types.True
2319 }
2320
2321 func isFieldQual(q Qualifier, fieldName string) bool {
2322 f, ok := q.(*fieldQualifier)
2323 if !ok {
2324 return false
2325 }
2326 return f.Name == fieldName
2327 }
2328
2329 func testMustParse(t testing.TB, data any) *ast.AST {
2330 t.Helper()
2331 p, err := parser.NewParser()
2332 if err != nil {
2333 t.Fatalf("parser.NewParser() failed: %v", err)
2334 }
2335 var src common.Source
2336 switch d := data.(type) {
2337 case string:
2338 src = common.NewTextSource(d)
2339 case common.Source:
2340 src = d
2341 default:
2342 t.Fatalf("testMustParse() got invalid parse data: %v", data)
2343 }
2344 parsed, errors := p.Parse(src)
2345 if len(errors.GetErrors()) != 0 {
2346 t.Fatalf("Parse(%q) failed: %v", src.Content(), errors.ToDisplayString())
2347 }
2348 return parsed
2349 }
2350
2351 func newTestEnv(t testing.TB, cont *containers.Container, reg *types.Registry) *checker.Env {
2352 t.Helper()
2353 env, err := checker.NewEnv(cont, reg, checker.CrossTypeNumericComparisons(true))
2354 if err != nil {
2355 t.Fatalf("checker.NewEnv(%v, %v) failed: %v", cont, reg, err)
2356 }
2357 err = env.AddFunctions(stdlib.Functions()...)
2358 if err != nil {
2359 t.Fatalf("env.Add(stdlib.Functions()...) failed: %v", err)
2360 }
2361 return env
2362 }
2363
2364 func newTestRegistry(t testing.TB, msgs ...proto.Message) *types.Registry {
2365 t.Helper()
2366 reg, err := types.NewRegistry(msgs...)
2367 if err != nil {
2368 t.Fatalf("types.NewRegistry(%v) failed: %v", msgs, err)
2369 }
2370 return reg
2371 }
2372
2373 func newTestPartialActivation(t testing.TB, in any, unknowns ...*AttributePattern) any {
2374 t.Helper()
2375 vars, err := NewPartialActivation(in, unknowns...)
2376 if err != nil {
2377 t.Fatalf("NewPartialActivation(%v) failed: %v", in, err)
2378 }
2379 return vars
2380 }
2381
2382 // newStandardInterpreter builds a Dispatcher and TypeProvider with support for all of the CEL
2383 // builtins defined in the language definition.
2384 func newStandardInterpreter(t *testing.T,
2385 container *containers.Container,
2386 provider types.Provider,
2387 adapter types.Adapter,
2388 resolver AttributeFactory,
2389 optFuncs ...*decls.FunctionDecl) Interpreter {
2390 t.Helper()
2391 disp := NewDispatcher()
2392 addFunctionBindings(t, disp)
2393 for _, fn := range optFuncs {
2394 bindings, err := fn.Bindings()
2395 if err != nil {
2396 t.Fatalf("fn.Bindings() failed for function %v. error: %v", fn.Name(), err)
2397 }
2398 err = disp.Add(bindings...)
2399 if err != nil {
2400 t.Fatalf("dispatcher.Add() failed: %v", err)
2401 }
2402 }
2403 return NewInterpreter(disp, container, provider, adapter, resolver)
2404 }
2405
2406 func addFunctionBindings(t testing.TB, dispatcher Dispatcher) {
2407 funcs := stdlib.Functions()
2408 for _, fn := range funcs {
2409 bindings, err := fn.Bindings()
2410 if err != nil {
2411 t.Fatalf("fn.Bindings() failed for function %v. error: %v", fn.Name(), err)
2412 }
2413 err = dispatcher.Add(bindings...)
2414 if err != nil {
2415 t.Fatalf("dispatcher.Add() failed: %v", err)
2416 }
2417 }
2418 }
2419
2420 func funcDecl(t testing.TB, name string, opts ...decls.FunctionOpt) *decls.FunctionDecl {
2421 t.Helper()
2422 fn, err := decls.NewFunction(name, opts...)
2423 if err != nil {
2424 t.Fatalf("NewFunction(%v) failed: %v", name, err)
2425 }
2426 return fn
2427 }
2428
2429 func funcBindings(t testing.TB, funcs ...*decls.FunctionDecl) []*functions.Overload {
2430 t.Helper()
2431 bindings := []*functions.Overload{}
2432 for _, fn := range funcs {
2433 overloads, err := fn.Bindings()
2434 if err != nil {
2435 t.Fatalf("fn.Bindings() failed: %v", err)
2436 }
2437 bindings = append(bindings, overloads...)
2438 }
2439 return bindings
2440 }
2441
2442 type testActivationWrapper struct {
2443 Activation
2444 name string
2445 }
2446
2447 func (tw *testActivationWrapper) Unwrap() Activation {
2448 return tw.Activation
2449 }