Debian Codegraph @

common/ast/conversion_test.go

raw
1 // Copyright 2023 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 ast_test
16
17 import (
18 "fmt"
19 "reflect"
20 "testing"
21 "time"
22
23 "google.golang.org/protobuf/encoding/prototext"
24 "google.golang.org/protobuf/proto"
25
26 chkdecls "github.com/google/cel-go/checker/decls"
27 "github.com/google/cel-go/common"
28 "github.com/google/cel-go/common/ast"
29 "github.com/google/cel-go/common/operators"
30 "github.com/google/cel-go/common/overloads"
31 "github.com/google/cel-go/common/types"
32 "github.com/google/cel-go/common/types/ref"
33 "github.com/google/cel-go/parser"
34
35 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
36 )
37
38 func TestConvertAST(t *testing.T) {
39 fac := ast.NewExprFactory()
40 tests := []struct {
41 goAST *ast.AST
42 pbAST *exprpb.CheckedExpr
43 }{
44 {
45 goAST: ast.NewCheckedAST(ast.NewAST(nil, nil),
46 map[int64]*types.Type{
47 1: types.BoolType,
48 2: types.DynType,
49 },
50 map[int64]*ast.ReferenceInfo{
51 1: ast.NewFunctionReference(overloads.LogicalNot),
52 2: ast.NewIdentReference("TRUE", types.True),
53 },
54 ),
55 pbAST: &exprpb.CheckedExpr{
56 Expr: &exprpb.Expr{},
57 SourceInfo: &exprpb.SourceInfo{},
58 TypeMap: map[int64]*exprpb.Type{
59 1: chkdecls.Bool,
60 2: chkdecls.Dyn,
61 },
62 ReferenceMap: map[int64]*exprpb.Reference{
63 1: {OverloadId: []string{overloads.LogicalNot}},
64 2: {
65 Name: "TRUE",
66 Value: &exprpb.Constant{
67 ConstantKind: &exprpb.Constant_BoolValue{BoolValue: true},
68 },
69 },
70 },
71 },
72 },
73 {
74 goAST: ast.NewAST(
75 fac.NewComprehensionTwoVar(1,
76 fac.NewIdent(2, "data"),
77 "i",
78 "v",
79 "__result__",
80 fac.NewList(3, []ast.Expr{}, []int32{}),
81 fac.NewLiteral(4, types.True),
82 fac.NewCall(8, operators.Add,
83 fac.NewAccuIdent(9),
84 fac.NewCall(5, operators.Add,
85 fac.NewIdent(6, "i"),
86 fac.NewIdent(7, "v"),
87 )),
88 fac.NewAccuIdent(10),
89 ), nil),
90 pbAST: &exprpb.CheckedExpr{
91 Expr: &exprpb.Expr{
92 Id: 1,
93 ExprKind: &exprpb.Expr_ComprehensionExpr{
94 ComprehensionExpr: &exprpb.Expr_Comprehension{
95 IterRange: &exprpb.Expr{
96 Id: 2,
97 ExprKind: &exprpb.Expr_IdentExpr{
98 IdentExpr: &exprpb.Expr_Ident{
99 Name: "data",
100 },
101 },
102 },
103 IterVar: "i",
104 IterVar2: "v",
105 AccuVar: "__result__",
106 AccuInit: &exprpb.Expr{
107 Id: 3,
108 ExprKind: &exprpb.Expr_ListExpr{
109 ListExpr: &exprpb.Expr_CreateList{},
110 },
111 },
112 LoopCondition: &exprpb.Expr{
113 Id: 4,
114 ExprKind: &exprpb.Expr_ConstExpr{
115 ConstExpr: &exprpb.Constant{
116 ConstantKind: &exprpb.Constant_BoolValue{
117 BoolValue: true,
118 },
119 },
120 },
121 },
122 LoopStep: &exprpb.Expr{
123 Id: 8,
124 ExprKind: &exprpb.Expr_CallExpr{
125 CallExpr: &exprpb.Expr_Call{
126 Function: operators.Add,
127 Args: []*exprpb.Expr{
128 {
129 Id: 9,
130 ExprKind: &exprpb.Expr_IdentExpr{
131 IdentExpr: &exprpb.Expr_Ident{
132 Name: "__result__",
133 },
134 },
135 },
136 {
137 Id: 5,
138 ExprKind: &exprpb.Expr_CallExpr{
139 CallExpr: &exprpb.Expr_Call{
140 Function: operators.Add,
141 Args: []*exprpb.Expr{
142 {
143 Id: 6,
144 ExprKind: &exprpb.Expr_IdentExpr{
145 IdentExpr: &exprpb.Expr_Ident{
146 Name: "i",
147 },
148 },
149 },
150 {
151 Id: 7,
152 ExprKind: &exprpb.Expr_IdentExpr{
153 IdentExpr: &exprpb.Expr_Ident{
154 Name: "v",
155 },
156 },
157 },
158 },
159 },
160 },
161 },
162 },
163 },
164 },
165 },
166 Result: &exprpb.Expr{
167 Id: 10,
168 ExprKind: &exprpb.Expr_IdentExpr{
169 IdentExpr: &exprpb.Expr_Ident{
170 Name: "__result__",
171 },
172 },
173 },
174 },
175 },
176 },
177 SourceInfo: &exprpb.SourceInfo{},
178 TypeMap: map[int64]*exprpb.Type{},
179 ReferenceMap: map[int64]*exprpb.Reference{},
180 },
181 },
182 }
183
184 for i, tst := range tests {
185 tc := tst
186 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
187 goAST := tc.goAST
188 pbAST := tc.pbAST
189 checkedAST, err := ast.ToAST(pbAST)
190 if err != nil {
191 t.Fatalf("ProtoToAST() failed: %v", err)
192 }
193 if !reflect.DeepEqual(checkedAST.ReferenceMap(), goAST.ReferenceMap()) ||
194 !reflect.DeepEqual(checkedAST.TypeMap(), goAST.TypeMap()) {
195 t.Errorf("conversion to AST did not produce identical results: got %v, wanted %v", checkedAST, goAST)
196 }
197 if len(checkedAST.ReferenceMap()) > 2 {
198 if !checkedAST.ReferenceMap()[1].Equals(goAST.ReferenceMap()[1]) ||
199 !checkedAST.ReferenceMap()[2].Equals(goAST.ReferenceMap()[2]) {
200 t.Error("converted reference info values not equal")
201 }
202 }
203 checkedExpr, err := ast.ToProto(checkedAST)
204 if err != nil {
205 t.Fatalf("ASTToProto() failed: %v", err)
206 }
207 if !proto.Equal(checkedExpr, pbAST) {
208 t.Errorf("conversion to protobuf did not produce identical results: got %v, wanted %v", checkedExpr, pbAST)
209 }
210 })
211 }
212 }
213
214 func TestConvertProtoToEntryExpr(t *testing.T) {
215 fac := ast.NewExprFactory()
216 tests := []struct {
217 goAST ast.EntryExpr
218 pbAST *exprpb.Expr_CreateStruct_Entry
219 }{
220 {
221 goAST: fac.NewMapEntry(1,
222 fac.NewIdent(2, "var_key"),
223 fac.NewLiteral(3, types.String("hello")),
224 true),
225 pbAST: &exprpb.Expr_CreateStruct_Entry{
226 Id: 1,
227 KeyKind: &exprpb.Expr_CreateStruct_Entry_MapKey{
228 MapKey: &exprpb.Expr{
229 Id: 2,
230 ExprKind: &exprpb.Expr_IdentExpr{
231 IdentExpr: &exprpb.Expr_Ident{
232 Name: "var_key",
233 },
234 },
235 },
236 },
237 Value: &exprpb.Expr{
238 Id: 3,
239 ExprKind: &exprpb.Expr_ConstExpr{
240 ConstExpr: &exprpb.Constant{
241 ConstantKind: &exprpb.Constant_StringValue{
242 StringValue: "hello",
243 },
244 },
245 },
246 },
247 OptionalEntry: true,
248 },
249 },
250 {
251 goAST: fac.NewStructField(1,
252 "field_name",
253 fac.NewLiteral(2, types.String("hello")),
254 false),
255 pbAST: &exprpb.Expr_CreateStruct_Entry{
256 Id: 1,
257 KeyKind: &exprpb.Expr_CreateStruct_Entry_FieldKey{
258 FieldKey: "field_name",
259 },
260 Value: &exprpb.Expr{
261 Id: 2,
262 ExprKind: &exprpb.Expr_ConstExpr{
263 ConstExpr: &exprpb.Constant{
264 ConstantKind: &exprpb.Constant_StringValue{
265 StringValue: "hello",
266 },
267 },
268 },
269 },
270 OptionalEntry: false,
271 },
272 },
273 }
274
275 for i, tst := range tests {
276 tc := tst
277 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
278 goAST := tc.goAST
279 pbAST := tc.pbAST
280 gotGoAST, err := ast.ProtoToEntryExpr(pbAST)
281 if err != nil {
282 t.Fatalf("ProtoToEntryExpr() failed: %v", err)
283 }
284 if !reflect.DeepEqual(goAST, gotGoAST) {
285 t.Errorf("conversion to go AST did not produce identical results: got %v, wanted %v", gotGoAST, goAST)
286 }
287 gotProtoAST, err := ast.EntryExprToProto(gotGoAST)
288 if err != nil {
289 t.Fatalf("EntryExprToProto() failed: %v", err)
290 }
291 if !proto.Equal(gotProtoAST, pbAST) {
292 t.Errorf("conversion to protobuf did not produce identical results: got %v, wanted %v", gotProtoAST, pbAST)
293 }
294 })
295 }
296 }
297
298 func TestConvertExpr(t *testing.T) {
299 fac := ast.NewExprFactory()
300 tests := []struct {
301 expr string
302 wantExpr ast.Expr
303 macroCalls map[int64]ast.Expr
304 }{
305 {
306 expr: `true`,
307 wantExpr: fac.NewLiteral(1, types.True),
308 },
309 {
310 expr: `a`,
311 wantExpr: fac.NewIdent(1, "a"),
312 },
313 {
314 expr: `a.b`,
315 wantExpr: fac.NewSelect(2, fac.NewIdent(1, "a"), "b"),
316 },
317 {
318 expr: `has(a.b)`,
319 wantExpr: fac.NewPresenceTest(4, fac.NewIdent(2, "a"), "b"),
320 macroCalls: map[int64]ast.Expr{
321 4: fac.NewCall(0, "has", fac.NewSelect(3, fac.NewIdent(2, "a"), "b")),
322 },
323 },
324 {
325 expr: `!a`,
326 wantExpr: fac.NewCall(1, "!_", fac.NewIdent(2, "a")),
327 },
328 {
329 expr: `a.size()`,
330 wantExpr: fac.NewMemberCall(2, "size", fac.NewIdent(1, "a")),
331 },
332 {
333 expr: `[a]`,
334 wantExpr: fac.NewList(1, []ast.Expr{fac.NewIdent(2, "a")}, []int32{}),
335 },
336 {
337 expr: `[?a]`,
338 wantExpr: fac.NewList(1, []ast.Expr{fac.NewIdent(2, "a")}, []int32{0}),
339 },
340 {
341 expr: `{'string': 42}`,
342 wantExpr: fac.NewMap(1, []ast.EntryExpr{
343 fac.NewMapEntry(2,
344 fac.NewLiteral(3, types.String("string")),
345 fac.NewLiteral(4, types.Int(42)),
346 false),
347 }),
348 },
349 {
350 expr: `{?'string': a.?b}`,
351 wantExpr: fac.NewMap(1, []ast.EntryExpr{
352 fac.NewMapEntry(2,
353 fac.NewLiteral(3, types.String("string")),
354 fac.NewCall(6, "_?._", fac.NewIdent(4, "a"), fac.NewLiteral(5, types.String("b"))),
355 true),
356 }),
357 },
358 {
359 expr: `custom.StructType{uint_field: 42u}`,
360 wantExpr: fac.NewStruct(1,
361 "custom.StructType",
362 []ast.EntryExpr{
363 fac.NewStructField(2,
364 "uint_field",
365 fac.NewLiteral(3, types.Uint(42)),
366 false),
367 }),
368 },
369 {
370 expr: `[].exists(i, i)`,
371 wantExpr: fac.NewComprehension(12,
372 fac.NewList(1, []ast.Expr{}, []int32{}),
373 "i",
374 fac.AccuIdentName(),
375 fac.NewLiteral(5, types.False),
376 fac.NewCall(8, "@not_strictly_false", fac.NewCall(7, "!_", fac.NewAccuIdent(6))),
377 fac.NewCall(10, "_||_", fac.NewAccuIdent(9), fac.NewIdent(4, "i")),
378 fac.NewAccuIdent(11),
379 ),
380 macroCalls: map[int64]ast.Expr{
381 12: fac.NewMemberCall(0, "exists",
382 fac.NewList(1, []ast.Expr{}, []int32{}),
383 fac.NewIdent(3, "i"),
384 fac.NewIdent(4, "i"),
385 ),
386 },
387 },
388 }
389 p, err := parser.NewParser(
390 parser.Macros(parser.AllMacros...),
391 parser.EnableOptionalSyntax(true),
392 parser.PopulateMacroCalls(true))
393 if err != nil {
394 t.Fatalf("parser.NewParser() failed: %v", err)
395 }
396 for _, tst := range tests {
397 tc := tst
398 t.Run(tc.expr, func(t *testing.T) {
399 parsed, errs := p.Parse(common.NewTextSource(tc.expr))
400 if len(errs.GetErrors()) != 0 {
401 t.Fatalf("Parse() failed: %s", errs.ToDisplayString())
402 }
403 gotPBExpr, err := ast.ExprToProto(parsed.Expr())
404 if err != nil {
405 t.Fatalf("ast.ExprToProto() failed: %v", err)
406 }
407 wantPBExpr, err := ast.ExprToProto(tc.wantExpr)
408 if err != nil {
409 t.Fatalf("ast.ExprToProto() failed: %v", err)
410 }
411 if !proto.Equal(gotPBExpr, wantPBExpr) {
412 t.Errorf("got %v\n, wanted %v",
413 prototext.Format(gotPBExpr), prototext.Format(wantPBExpr))
414 }
415 gotExpr := parsed.Expr()
416 if !reflect.DeepEqual(gotExpr, tc.wantExpr) {
417 t.Errorf("got %v, wanted %v", gotExpr, tc.wantExpr)
418 }
419 gotExprRoundtrip, err := ast.ProtoToExpr(gotPBExpr)
420 if err != nil {
421 t.Fatalf("ast.ProtoToExpr() failed: %v", err)
422 }
423 if !reflect.DeepEqual(parsed.Expr(), gotExprRoundtrip) {
424 t.Errorf("ast.ProtoToExpr() got %v, wanted %v", gotExprRoundtrip, parsed.Expr())
425 }
426 info := parsed.SourceInfo()
427 for id, wantCall := range tc.macroCalls {
428 call, found := info.GetMacroCall(id)
429 if !found {
430 t.Fatalf("GetMacroCall(%d) returned not found", id)
431 }
432 if !reflect.DeepEqual(call, wantCall) {
433 t.Errorf("macro call got %v, wanted %v", call, wantCall)
434 }
435 }
436 })
437 }
438 }
439
440 func TestSourceInfoToProto(t *testing.T) {
441 expr := `[{}, {'field': true}].exists(i, has(i.field))`
442 p, err := parser.NewParser(
443 parser.Macros(parser.AllMacros...),
444 parser.EnableOptionalSyntax(true),
445 parser.PopulateMacroCalls(true))
446 if err != nil {
447 t.Fatalf("parser.NewParser() failed: %v", err)
448 }
449 parsed, errs := p.Parse(common.NewTextSource(expr))
450 if len(errs.GetErrors()) != 0 {
451 t.Fatalf("Parse() failed: %s", errs.ToDisplayString())
452 }
453 pbInfo, err := ast.SourceInfoToProto(parsed.SourceInfo())
454 if err != nil {
455 t.Fatalf("SourceInfoToProto() failed: %v", err)
456 }
457 wantInfo := `
458 location: "<input>"
459 line_offsets: 46
460 positions: {
461 key: 1
462 value: 0
463 }
464 positions: {
465 key: 2
466 value: 1
467 }
468 positions: {
469 key: 3
470 value: 5
471 }
472 positions: {
473 key: 4
474 value: 13
475 }
476 positions: {
477 key: 5
478 value: 6
479 }
480 positions: {
481 key: 6
482 value: 15
483 }
484 positions: {
485 key: 8
486 value: 29
487 }
488 positions: {
489 key: 10
490 value: 36
491 }
492 positions: {
493 key: 11
494 value: 37
495 }
496 positions: {
497 key: 12
498 value: 35
499 }
500 positions: {
501 key: 13
502 value: 28
503 }
504 positions: {
505 key: 14
506 value: 28
507 }
508 positions: {
509 key: 15
510 value: 28
511 }
512 positions: {
513 key: 16
514 value: 28
515 }
516 positions: {
517 key: 17
518 value: 28
519 }
520 positions: {
521 key: 18
522 value: 28
523 }
524 positions: {
525 key: 19
526 value: 28
527 }
528 positions: {
529 key: 20
530 value: 28
531 }
532 macro_calls: {
533 key: 12
534 value: {
535 call_expr: {
536 function: "has"
537 args: {
538 id: 11
539 select_expr: {
540 operand: {
541 id: 10
542 ident_expr: {
543 name: "i"
544 }
545 }
546 field: "field"
547 }
548 }
549 }
550 }
551 }
552 macro_calls: {
553 key: 20
554 value: {
555 call_expr: {
556 target: {
557 id: 1
558 list_expr: {
559 elements: {
560 id: 2
561 struct_expr: {}
562 }
563 elements: {
564 id: 3
565 struct_expr: {
566 entries: {
567 id: 4
568 map_key: {
569 id: 5
570 const_expr: {
571 string_value: "field"
572 }
573 }
574 value: {
575 id: 6
576 const_expr: {
577 bool_value: true
578 }
579 }
580 }
581 }
582 }
583 }
584 }
585 function: "exists"
586 args: {
587 id: 8
588 ident_expr: {
589 name: "i"
590 }
591 }
592 args: {
593 id: 12
594 }
595 }
596 }
597 }`
598 wantPBInfo := &exprpb.SourceInfo{}
599 prototext.Unmarshal([]byte(wantInfo), wantPBInfo)
600 if !proto.Equal(pbInfo, wantPBInfo) {
601 t.Errorf("SourceInfoToProto() got %v, wanted %v",
602 prototext.Format(pbInfo), prototext.Format(wantPBInfo))
603 }
604 }
605
606 func TestReferenceInfoToProtoError(t *testing.T) {
607 out, err := ast.ReferenceInfoToProto(
608 ast.NewIdentReference("SECOND", types.Duration{Duration: time.Duration(1) * time.Second}))
609 if err == nil {
610 t.Errorf("ReferenceInfoToProto() got %v, wanted error", out)
611 }
612 }
613
614 func TestProtoToReferenceInfoError(t *testing.T) {
615 out, err := ast.ProtoToReferenceInfo(&exprpb.Reference{Value: &exprpb.Constant{}})
616 if err == nil {
617 t.Errorf("ProtoToReferenceInfo() got %v, wanted error", out)
618 }
619 }
620
621 func TestConvertVal(t *testing.T) {
622 tests := []ref.Val{
623 types.True,
624 types.Bytes("bytes"),
625 types.Double(3.2),
626 types.Int(-1),
627 types.NullValue,
628 types.String("string"),
629 types.Uint(27),
630 }
631 for _, tst := range tests {
632 c, err := ast.ValToConstant(tst)
633 if err != nil {
634 t.Errorf("ValToConstant(%v) failed: %v", tst, err)
635 }
636 v, err := ast.ConstantToVal(c)
637 if err != nil {
638 t.Errorf("ValToConstant(%v) failed: %v", c, err)
639 }
640 if tst.Equal(v) != types.True {
641 t.Errorf("roundtrip from %v to %v and back did not produce equal results, got %v, wanted %v", tst, c, v, tst)
642 }
643 }
644 }
645
646 func TestValToConstantError(t *testing.T) {
647 out, err := ast.ValToConstant(types.Duration{Duration: time.Duration(10)})
648 if err == nil {
649 t.Errorf("ValToConstant() got %v, wanted error", out)
650 }
651 }
652
653 func TestConstantToValError(t *testing.T) {
654 out, err := ast.ConstantToVal(&exprpb.Constant{})
655 if err == nil {
656 t.Errorf("ConstantToVal() got %v, wanted error", out)
657 }
658 }