Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/common/ast/navigable.go

raw symbols SCIP
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
16
17 import (
18 "github.com/google/cel-go/common/types"
19 "github.com/google/cel-go/common/types/ref"
20 )
21
22 // NavigableExpr represents the base navigable expression value with methods to inspect the
23 // parent and child expressions.
24 type NavigableExpr interface {
25 Expr
26
27 // Type of the expression.
28 //
29 // If the expression is type-checked, the type check metadata is returned. If the expression
30 // has not been type-checked, the types.DynType value is returned.
31 Type() *types.Type
32
33 // Parent returns the parent expression node, if one exists.
34 Parent() (NavigableExpr, bool)
35
36 // Children returns a list of child expression nodes.
37 Children() []NavigableExpr
38
39 // Depth indicates the depth in the expression tree.
40 //
41 // The root expression has depth 0.
42 Depth() int
43 }
44
45 // NavigateAST converts an AST to a NavigableExpr
46 func NavigateAST(ast *AST) NavigableExpr {
47 return NavigateExpr(ast, ast.Expr())
48 }
49
50 // NavigateExpr creates a NavigableExpr whose type information is backed by the input AST.
51 //
52 // If the expression is already a NavigableExpr, the parent and depth information will be
53 // propagated on the new NavigableExpr value; otherwise, the expr value will be treated
54 // as though it is the root of the expression graph with a depth of 0.
55 func NavigateExpr(ast *AST, expr Expr) NavigableExpr {
56 depth := 0
57 var parent NavigableExpr = nil
58 if nav, ok := expr.(NavigableExpr); ok {
59 depth = nav.Depth()
60 parent, _ = nav.Parent()
61 }
62 return newNavigableExpr(ast, parent, expr, depth)
63 }
64
65 // ExprMatcher takes a NavigableExpr in and indicates whether the value is a match.
66 //
67 // This function type should be use with the `Match` and `MatchList` calls.
68 type ExprMatcher func(NavigableExpr) bool
69
70 // ConstantValueMatcher returns an ExprMatcher which will return true if the input NavigableExpr
71 // is comprised of all constant values, such as a simple literal or even list and map literal.
72 func ConstantValueMatcher() ExprMatcher {
73 return matchIsConstantValue
74 }
75
76 // KindMatcher returns an ExprMatcher which will return true if the input NavigableExpr.Kind() matches
77 // the specified `kind`.
78 func KindMatcher(kind ExprKind) ExprMatcher {
79 return func(e NavigableExpr) bool {
80 return e.Kind() == kind
81 }
82 }
83
84 // FunctionMatcher returns an ExprMatcher which will match NavigableExpr nodes of CallKind type whose
85 // function name is equal to `funcName`.
86 func FunctionMatcher(funcName string) ExprMatcher {
87 return func(e NavigableExpr) bool {
88 if e.Kind() != CallKind {
89 return false
90 }
91 return e.AsCall().FunctionName() == funcName
92 }
93 }
94
95 // AllMatcher returns true for all descendants of a NavigableExpr, effectively flattening them into a list.
96 //
97 // Such a result would work well with subsequent MatchList calls.
98 func AllMatcher() ExprMatcher {
99 return func(NavigableExpr) bool {
100 return true
101 }
102 }
103
104 // MatchDescendants takes a NavigableExpr and ExprMatcher and produces a list of NavigableExpr values
105 // matching the input criteria in post-order (bottom up).
106 func MatchDescendants(expr NavigableExpr, matcher ExprMatcher) []NavigableExpr {
107 matches := []NavigableExpr{}
108 navVisitor := &baseVisitor{
109 visitExpr: func(e Expr) {
110 nav := e.(NavigableExpr)
111 if matcher(nav) {
112 matches = append(matches, nav)
113 }
114 },
115 }
116 visit(expr, navVisitor, postOrder, 0, 0)
117 return matches
118 }
119
120 // MatchSubset applies an ExprMatcher to a list of NavigableExpr values and their descendants, producing a
121 // subset of NavigableExpr values which match.
122 func MatchSubset(exprs []NavigableExpr, matcher ExprMatcher) []NavigableExpr {
123 matches := []NavigableExpr{}
124 navVisitor := &baseVisitor{
125 visitExpr: func(e Expr) {
126 nav := e.(NavigableExpr)
127 if matcher(nav) {
128 matches = append(matches, nav)
129 }
130 },
131 }
132 for _, expr := range exprs {
133 visit(expr, navVisitor, postOrder, 0, 1)
134 }
135 return matches
136 }
137
138 // Visitor defines an object for visiting Expr and EntryExpr nodes within an expression graph.
139 type Visitor interface {
140 // VisitExpr visits the input expression.
141 VisitExpr(Expr)
142
143 // VisitEntryExpr visits the input entry expression, i.e. a struct field or map entry.
144 VisitEntryExpr(EntryExpr)
145 }
146
147 type baseVisitor struct {
148 visitExpr func(Expr)
149 visitEntryExpr func(EntryExpr)
150 }
151
152 // VisitExpr visits the Expr if the internal expr visitor has been configured.
153 func (v *baseVisitor) VisitExpr(e Expr) {
154 if v.visitExpr != nil {
155 v.visitExpr(e)
156 }
157 }
158
159 // VisitEntryExpr visits the entry if the internal expr entry visitor has been configured.
160 func (v *baseVisitor) VisitEntryExpr(e EntryExpr) {
161 if v.visitEntryExpr != nil {
162 v.visitEntryExpr(e)
163 }
164 }
165
166 // NewExprVisitor creates a visitor which only visits expression nodes.
167 func NewExprVisitor(v func(Expr)) Visitor {
168 return &baseVisitor{
169 visitExpr: v,
170 visitEntryExpr: nil,
171 }
172 }
173
174 // PostOrderVisit walks the expression graph and calls the visitor in post-order (bottom-up).
175 func PostOrderVisit(expr Expr, visitor Visitor) {
176 visit(expr, visitor, postOrder, 0, 0)
177 }
178
179 // PreOrderVisit walks the expression graph and calls the visitor in pre-order (top-down).
180 func PreOrderVisit(expr Expr, visitor Visitor) {
181 visit(expr, visitor, preOrder, 0, 0)
182 }
183
184 type visitOrder int
185
186 const (
187 preOrder = iota + 1
188 postOrder
189 )
190
191 // TODO: consider exposing a way to configure a limit for the max visit depth.
192 // It's possible that we could want to configure this on the NewExprVisitor()
193 // and through MatchDescendents() / MaxID().
194 func visit(expr Expr, visitor Visitor, order visitOrder, depth, maxDepth int) {
195 if maxDepth > 0 && depth == maxDepth {
196 return
197 }
198 if order == preOrder {
199 visitor.VisitExpr(expr)
200 }
201 switch expr.Kind() {
202 case CallKind:
203 c := expr.AsCall()
204 if c.IsMemberFunction() {
205 visit(c.Target(), visitor, order, depth+1, maxDepth)
206 }
207 for _, arg := range c.Args() {
208 visit(arg, visitor, order, depth+1, maxDepth)
209 }
210 case ComprehensionKind:
211 c := expr.AsComprehension()
212 visit(c.IterRange(), visitor, order, depth+1, maxDepth)
213 visit(c.AccuInit(), visitor, order, depth+1, maxDepth)
214 visit(c.LoopCondition(), visitor, order, depth+1, maxDepth)
215 visit(c.LoopStep(), visitor, order, depth+1, maxDepth)
216 visit(c.Result(), visitor, order, depth+1, maxDepth)
217 case ListKind:
218 l := expr.AsList()
219 for _, elem := range l.Elements() {
220 visit(elem, visitor, order, depth+1, maxDepth)
221 }
222 case MapKind:
223 m := expr.AsMap()
224 for _, e := range m.Entries() {
225 if order == preOrder {
226 visitor.VisitEntryExpr(e)
227 }
228 entry := e.AsMapEntry()
229 visit(entry.Key(), visitor, order, depth+1, maxDepth)
230 visit(entry.Value(), visitor, order, depth+1, maxDepth)
231 if order == postOrder {
232 visitor.VisitEntryExpr(e)
233 }
234 }
235 case SelectKind:
236 visit(expr.AsSelect().Operand(), visitor, order, depth+1, maxDepth)
237 case StructKind:
238 s := expr.AsStruct()
239 for _, f := range s.Fields() {
240 if order == preOrder {
241 visitor.VisitEntryExpr(f)
242 }
243 visit(f.AsStructField().Value(), visitor, order, depth+1, maxDepth)
244 if order == postOrder {
245 visitor.VisitEntryExpr(f)
246 }
247 }
248 }
249 if order == postOrder {
250 visitor.VisitExpr(expr)
251 }
252 }
253
254 func matchIsConstantValue(e NavigableExpr) bool {
255 if e.Kind() == LiteralKind {
256 return true
257 }
258 if e.Kind() == StructKind || e.Kind() == MapKind || e.Kind() == ListKind {
259 for _, child := range e.Children() {
260 if !matchIsConstantValue(child) {
261 return false
262 }
263 }
264 return true
265 }
266 return false
267 }
268
269 func newNavigableExpr(ast *AST, parent NavigableExpr, expr Expr, depth int) NavigableExpr {
270 // Reduce navigable expression nesting by unwrapping the embedded Expr value.
271 if nav, ok := expr.(*navigableExprImpl); ok {
272 expr = nav.Expr
273 }
274 nav := &navigableExprImpl{
275 Expr: expr,
276 depth: depth,
277 ast: ast,
278 parent: parent,
279 createChildren: getChildFactory(expr),
280 }
281 return nav
282 }
283
284 type navigableExprImpl struct {
285 Expr
286 depth int
287 ast *AST
288 parent NavigableExpr
289 createChildren childFactory
290 }
291
292 func (nav *navigableExprImpl) Parent() (NavigableExpr, bool) {
293 if nav.parent != nil {
294 return nav.parent, true
295 }
296 return nil, false
297 }
298
299 func (nav *navigableExprImpl) ID() int64 {
300 return nav.Expr.ID()
301 }
302
303 func (nav *navigableExprImpl) Kind() ExprKind {
304 return nav.Expr.Kind()
305 }
306
307 func (nav *navigableExprImpl) Type() *types.Type {
308 return nav.ast.GetType(nav.ID())
309 }
310
311 func (nav *navigableExprImpl) Children() []NavigableExpr {
312 return nav.createChildren(nav)
313 }
314
315 func (nav *navigableExprImpl) Depth() int {
316 return nav.depth
317 }
318
319 func (nav *navigableExprImpl) AsCall() CallExpr {
320 return navigableCallImpl{navigableExprImpl: nav}
321 }
322
323 func (nav *navigableExprImpl) AsComprehension() ComprehensionExpr {
324 return navigableComprehensionImpl{navigableExprImpl: nav}
325 }
326
327 func (nav *navigableExprImpl) AsIdent() string {
328 return nav.Expr.AsIdent()
329 }
330
331 func (nav *navigableExprImpl) AsList() ListExpr {
332 return navigableListImpl{navigableExprImpl: nav}
333 }
334
335 func (nav *navigableExprImpl) AsLiteral() ref.Val {
336 return nav.Expr.AsLiteral()
337 }
338
339 func (nav *navigableExprImpl) AsMap() MapExpr {
340 return navigableMapImpl{navigableExprImpl: nav}
341 }
342
343 func (nav *navigableExprImpl) AsSelect() SelectExpr {
344 return navigableSelectImpl{navigableExprImpl: nav}
345 }
346
347 func (nav *navigableExprImpl) AsStruct() StructExpr {
348 return navigableStructImpl{navigableExprImpl: nav}
349 }
350
351 func (nav *navigableExprImpl) createChild(e Expr) NavigableExpr {
352 return newNavigableExpr(nav.ast, nav, e, nav.depth+1)
353 }
354
355 func (nav *navigableExprImpl) isExpr() {}
356
357 type navigableCallImpl struct {
358 *navigableExprImpl
359 }
360
361 func (call navigableCallImpl) FunctionName() string {
362 return call.Expr.AsCall().FunctionName()
363 }
364
365 func (call navigableCallImpl) IsMemberFunction() bool {
366 return call.Expr.AsCall().IsMemberFunction()
367 }
368
369 func (call navigableCallImpl) Target() Expr {
370 t := call.Expr.AsCall().Target()
371 if t != nil {
372 return call.createChild(t)
373 }
374 return nil
375 }
376
377 func (call navigableCallImpl) Args() []Expr {
378 args := call.Expr.AsCall().Args()
379 navArgs := make([]Expr, len(args))
380 for i, a := range args {
381 navArgs[i] = call.createChild(a)
382 }
383 return navArgs
384 }
385
386 type navigableComprehensionImpl struct {
387 *navigableExprImpl
388 }
389
390 func (comp navigableComprehensionImpl) IterRange() Expr {
391 return comp.createChild(comp.Expr.AsComprehension().IterRange())
392 }
393
394 func (comp navigableComprehensionImpl) IterVar() string {
395 return comp.Expr.AsComprehension().IterVar()
396 }
397
398 func (comp navigableComprehensionImpl) IterVar2() string {
399 return comp.Expr.AsComprehension().IterVar2()
400 }
401
402 func (comp navigableComprehensionImpl) HasIterVar2() bool {
403 return comp.Expr.AsComprehension().HasIterVar2()
404 }
405
406 func (comp navigableComprehensionImpl) AccuVar() string {
407 return comp.Expr.AsComprehension().AccuVar()
408 }
409
410 func (comp navigableComprehensionImpl) AccuInit() Expr {
411 return comp.createChild(comp.Expr.AsComprehension().AccuInit())
412 }
413
414 func (comp navigableComprehensionImpl) LoopCondition() Expr {
415 return comp.createChild(comp.Expr.AsComprehension().LoopCondition())
416 }
417
418 func (comp navigableComprehensionImpl) LoopStep() Expr {
419 return comp.createChild(comp.Expr.AsComprehension().LoopStep())
420 }
421
422 func (comp navigableComprehensionImpl) Result() Expr {
423 return comp.createChild(comp.Expr.AsComprehension().Result())
424 }
425
426 type navigableListImpl struct {
427 *navigableExprImpl
428 }
429
430 func (l navigableListImpl) Elements() []Expr {
431 pbElems := l.Expr.AsList().Elements()
432 elems := make([]Expr, len(pbElems))
433 for i := 0; i < len(pbElems); i++ {
434 elems[i] = l.createChild(pbElems[i])
435 }
436 return elems
437 }
438
439 func (l navigableListImpl) IsOptional(index int32) bool {
440 return l.Expr.AsList().IsOptional(index)
441 }
442
443 func (l navigableListImpl) OptionalIndices() []int32 {
444 return l.Expr.AsList().OptionalIndices()
445 }
446
447 func (l navigableListImpl) Size() int {
448 return l.Expr.AsList().Size()
449 }
450
451 type navigableMapImpl struct {
452 *navigableExprImpl
453 }
454
455 func (m navigableMapImpl) Entries() []EntryExpr {
456 mapExpr := m.Expr.AsMap()
457 entries := make([]EntryExpr, len(mapExpr.Entries()))
458 for i, e := range mapExpr.Entries() {
459 entry := e.AsMapEntry()
460 entries[i] = &entryExpr{
461 id: e.ID(),
462 entryExprKindCase: navigableEntryImpl{
463 key: m.createChild(entry.Key()),
464 val: m.createChild(entry.Value()),
465 isOpt: entry.IsOptional(),
466 },
467 }
468 }
469 return entries
470 }
471
472 func (m navigableMapImpl) Size() int {
473 return m.Expr.AsMap().Size()
474 }
475
476 type navigableEntryImpl struct {
477 key NavigableExpr
478 val NavigableExpr
479 isOpt bool
480 }
481
482 func (e navigableEntryImpl) Kind() EntryExprKind {
483 return MapEntryKind
484 }
485
486 func (e navigableEntryImpl) Key() Expr {
487 return e.key
488 }
489
490 func (e navigableEntryImpl) Value() Expr {
491 return e.val
492 }
493
494 func (e navigableEntryImpl) IsOptional() bool {
495 return e.isOpt
496 }
497
498 func (e navigableEntryImpl) renumberIDs(IDGenerator) {}
499
500 func (e navigableEntryImpl) isEntryExpr() {}
501
502 type navigableSelectImpl struct {
503 *navigableExprImpl
504 }
505
506 func (sel navigableSelectImpl) FieldName() string {
507 return sel.Expr.AsSelect().FieldName()
508 }
509
510 func (sel navigableSelectImpl) IsTestOnly() bool {
511 return sel.Expr.AsSelect().IsTestOnly()
512 }
513
514 func (sel navigableSelectImpl) Operand() Expr {
515 return sel.createChild(sel.Expr.AsSelect().Operand())
516 }
517
518 type navigableStructImpl struct {
519 *navigableExprImpl
520 }
521
522 func (s navigableStructImpl) TypeName() string {
523 return s.Expr.AsStruct().TypeName()
524 }
525
526 func (s navigableStructImpl) Fields() []EntryExpr {
527 fieldInits := s.Expr.AsStruct().Fields()
528 fields := make([]EntryExpr, len(fieldInits))
529 for i, f := range fieldInits {
530 field := f.AsStructField()
531 fields[i] = &entryExpr{
532 id: f.ID(),
533 entryExprKindCase: navigableFieldImpl{
534 name: field.Name(),
535 val: s.createChild(field.Value()),
536 isOpt: field.IsOptional(),
537 },
538 }
539 }
540 return fields
541 }
542
543 type navigableFieldImpl struct {
544 name string
545 val NavigableExpr
546 isOpt bool
547 }
548
549 func (f navigableFieldImpl) Kind() EntryExprKind {
550 return StructFieldKind
551 }
552
553 func (f navigableFieldImpl) Name() string {
554 return f.name
555 }
556
557 func (f navigableFieldImpl) Value() Expr {
558 return f.val
559 }
560
561 func (f navigableFieldImpl) IsOptional() bool {
562 return f.isOpt
563 }
564
565 func (f navigableFieldImpl) renumberIDs(IDGenerator) {}
566
567 func (f navigableFieldImpl) isEntryExpr() {}
568
569 func getChildFactory(expr Expr) childFactory {
570 if expr == nil {
571 return noopFactory
572 }
573 switch expr.Kind() {
574 case LiteralKind:
575 return noopFactory
576 case IdentKind:
577 return noopFactory
578 case SelectKind:
579 return selectFactory
580 case CallKind:
581 return callArgFactory
582 case ListKind:
583 return listElemFactory
584 case MapKind:
585 return mapEntryFactory
586 case StructKind:
587 return structEntryFactory
588 case ComprehensionKind:
589 return comprehensionFactory
590 default:
591 return noopFactory
592 }
593 }
594
595 type childFactory func(*navigableExprImpl) []NavigableExpr
596
597 func noopFactory(*navigableExprImpl) []NavigableExpr {
598 return nil
599 }
600
601 func selectFactory(nav *navigableExprImpl) []NavigableExpr {
602 return []NavigableExpr{nav.createChild(nav.AsSelect().Operand())}
603 }
604
605 func callArgFactory(nav *navigableExprImpl) []NavigableExpr {
606 call := nav.Expr.AsCall()
607 argCount := len(call.Args())
608 if call.IsMemberFunction() {
609 argCount++
610 }
611 navExprs := make([]NavigableExpr, argCount)
612 i := 0
613 if call.IsMemberFunction() {
614 navExprs[i] = nav.createChild(call.Target())
615 i++
616 }
617 for _, arg := range call.Args() {
618 navExprs[i] = nav.createChild(arg)
619 i++
620 }
621 return navExprs
622 }
623
624 func listElemFactory(nav *navigableExprImpl) []NavigableExpr {
625 l := nav.Expr.AsList()
626 navExprs := make([]NavigableExpr, len(l.Elements()))
627 for i, e := range l.Elements() {
628 navExprs[i] = nav.createChild(e)
629 }
630 return navExprs
631 }
632
633 func structEntryFactory(nav *navigableExprImpl) []NavigableExpr {
634 s := nav.Expr.AsStruct()
635 entries := make([]NavigableExpr, len(s.Fields()))
636 for i, e := range s.Fields() {
637 f := e.AsStructField()
638 entries[i] = nav.createChild(f.Value())
639 }
640 return entries
641 }
642
643 func mapEntryFactory(nav *navigableExprImpl) []NavigableExpr {
644 m := nav.Expr.AsMap()
645 entries := make([]NavigableExpr, len(m.Entries())*2)
646 j := 0
647 for _, e := range m.Entries() {
648 mapEntry := e.AsMapEntry()
649 entries[j] = nav.createChild(mapEntry.Key())
650 entries[j+1] = nav.createChild(mapEntry.Value())
651 j += 2
652 }
653 return entries
654 }
655
656 func comprehensionFactory(nav *navigableExprImpl) []NavigableExpr {
657 compre := nav.Expr.AsComprehension()
658 return []NavigableExpr{
659 nav.createChild(compre.IterRange()),
660 nav.createChild(compre.AccuInit()),
661 nav.createChild(compre.LoopCondition()),
662 nav.createChild(compre.LoopStep()),
663 nav.createChild(compre.Result()),
664 }
665 }