Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/interpreter/prune.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 "github.com/google/cel-go/common/ast"
19 "github.com/google/cel-go/common/operators"
20 "github.com/google/cel-go/common/overloads"
21 "github.com/google/cel-go/common/types"
22 "github.com/google/cel-go/common/types/ref"
23 "github.com/google/cel-go/common/types/traits"
24 )
25
26 type astPruner struct {
27 ast.ExprFactory
28 expr ast.Expr
29 macroCalls map[int64]ast.Expr
30 state EvalState
31 nextExprID int64
32 }
33
34 // TODO Consider having a separate walk of the AST that finds common
35 // subexpressions. This can be called before or after constant folding to find
36 // common subexpressions.
37
38 // PruneAst prunes the given AST based on the given EvalState and generates a new AST.
39 // Given AST is copied on write and a new AST is returned.
40 // Couple of typical use cases this interface would be:
41 //
42 // A)
43 // 1) Evaluate expr with some unknowns,
44 // 2) If result is unknown:
45 //
46 // a) PruneAst
47 // b) Goto 1
48 //
49 // Functional call results which are known would be effectively cached across
50 // iterations.
51 //
52 // B)
53 // 1) Compile the expression (maybe via a service and maybe after checking a
54 //
55 // compiled expression does not exists in local cache)
56 //
57 // 2) Prepare the environment and the interpreter. Activation might be empty.
58 // 3) Eval the expression. This might return unknown or error or a concrete
59 //
60 // value.
61 //
62 // 4) PruneAst
63 // 4) Maybe cache the expression
64 // This is effectively constant folding the expression. How the environment is
65 // prepared in step 2 is flexible. For example, If the caller caches the
66 // compiled and constant folded expressions, but is not willing to constant
67 // fold(and thus cache results of) some external calls, then they can prepare
68 // the overloads accordingly.
69 func PruneAst(expr ast.Expr, macroCalls map[int64]ast.Expr, state EvalState) *ast.AST {
70 pruneState := NewEvalState()
71 for _, id := range state.IDs() {
72 v, _ := state.Value(id)
73 pruneState.SetValue(id, v)
74 }
75 pruner := &astPruner{
76 ExprFactory: ast.NewExprFactory(),
77 expr: expr,
78 macroCalls: macroCalls,
79 state: pruneState,
80 nextExprID: getMaxID(expr)}
81 newExpr, _ := pruner.maybePrune(expr)
82 newInfo := ast.NewSourceInfo(nil)
83 for id, call := range pruner.macroCalls {
84 newInfo.SetMacroCall(id, call)
85 }
86 return ast.NewAST(newExpr, newInfo)
87 }
88
89 func (p *astPruner) maybeCreateLiteral(id int64, val ref.Val) (ast.Expr, bool) {
90 switch v := val.(type) {
91 case types.Bool, types.Bytes, types.Double, types.Int, types.Null, types.String, types.Uint, *types.Optional:
92 p.state.SetValue(id, val)
93 return p.NewLiteral(id, val), true
94 case types.Duration:
95 p.state.SetValue(id, val)
96 durationString := v.ConvertToType(types.StringType).(types.String)
97 return p.NewCall(id, overloads.TypeConvertDuration, p.NewLiteral(p.nextID(), durationString)), true
98 case types.Timestamp:
99 timestampString := v.ConvertToType(types.StringType).(types.String)
100 return p.NewCall(id, overloads.TypeConvertTimestamp, p.NewLiteral(p.nextID(), timestampString)), true
101 }
102
103 // Attempt to build a list literal.
104 if list, isList := val.(traits.Lister); isList {
105 sz := list.Size().(types.Int)
106 elemExprs := make([]ast.Expr, sz)
107 for i := types.Int(0); i < sz; i++ {
108 elem := list.Get(i)
109 if types.IsUnknownOrError(elem) {
110 return nil, false
111 }
112 elemExpr, ok := p.maybeCreateLiteral(p.nextID(), elem)
113 if !ok {
114 return nil, false
115 }
116 elemExprs[i] = elemExpr
117 }
118 p.state.SetValue(id, val)
119 return p.NewList(id, elemExprs, []int32{}), true
120 }
121
122 // Create a map literal if possible.
123 if mp, isMap := val.(traits.Mapper); isMap {
124 it := mp.Iterator()
125 entries := make([]ast.EntryExpr, mp.Size().(types.Int))
126 i := 0
127 for it.HasNext() != types.False {
128 key := it.Next()
129 val := mp.Get(key)
130 if types.IsUnknownOrError(key) || types.IsUnknownOrError(val) {
131 return nil, false
132 }
133 keyExpr, ok := p.maybeCreateLiteral(p.nextID(), key)
134 if !ok {
135 return nil, false
136 }
137 valExpr, ok := p.maybeCreateLiteral(p.nextID(), val)
138 if !ok {
139 return nil, false
140 }
141 entry := p.NewMapEntry(p.nextID(), keyExpr, valExpr, false)
142 entries[i] = entry
143 i++
144 }
145 p.state.SetValue(id, val)
146 return p.NewMap(id, entries), true
147 }
148
149 // TODO(issues/377) To construct message literals, the type provider will need to support
150 // the enumeration the fields for a given message.
151 return nil, false
152 }
153
154 func (p *astPruner) maybePruneOptional(elem ast.Expr) (ast.Expr, bool) {
155 elemVal, found := p.value(elem.ID())
156 if found && elemVal.Type() == types.OptionalType {
157 opt := elemVal.(*types.Optional)
158 if !opt.HasValue() {
159 return nil, true
160 }
161 if newElem, pruned := p.maybeCreateLiteral(elem.ID(), opt.GetValue()); pruned {
162 return newElem, true
163 }
164 }
165 return elem, false
166 }
167
168 func (p *astPruner) maybePruneIn(node ast.Expr) (ast.Expr, bool) {
169 // elem in list
170 call := node.AsCall()
171 val, exists := p.maybeValue(call.Args()[1].ID())
172 if !exists {
173 return nil, false
174 }
175 if sz, ok := val.(traits.Sizer); ok && sz.Size() == types.IntZero {
176 return p.maybeCreateLiteral(node.ID(), types.False)
177 }
178 return nil, false
179 }
180
181 func (p *astPruner) maybePruneLogicalNot(node ast.Expr) (ast.Expr, bool) {
182 call := node.AsCall()
183 arg := call.Args()[0]
184 val, exists := p.maybeValue(arg.ID())
185 if !exists {
186 return nil, false
187 }
188 if b, ok := val.(types.Bool); ok {
189 return p.maybeCreateLiteral(node.ID(), !b)
190 }
191 return nil, false
192 }
193
194 func (p *astPruner) maybePruneOr(node ast.Expr) (ast.Expr, bool) {
195 call := node.AsCall()
196 // We know result is unknown, so we have at least one unknown arg
197 // and if one side is a known value, we know we can ignore it.
198 if v, exists := p.maybeValue(call.Args()[0].ID()); exists {
199 if v == types.True {
200 return p.maybeCreateLiteral(node.ID(), types.True)
201 }
202 return call.Args()[1], true
203 }
204 if v, exists := p.maybeValue(call.Args()[1].ID()); exists {
205 if v == types.True {
206 return p.maybeCreateLiteral(node.ID(), types.True)
207 }
208 return call.Args()[0], true
209 }
210 return nil, false
211 }
212
213 func (p *astPruner) maybePruneAnd(node ast.Expr) (ast.Expr, bool) {
214 call := node.AsCall()
215 // We know result is unknown, so we have at least one unknown arg
216 // and if one side is a known value, we know we can ignore it.
217 if v, exists := p.maybeValue(call.Args()[0].ID()); exists {
218 if v == types.False {
219 return p.maybeCreateLiteral(node.ID(), types.False)
220 }
221 return call.Args()[1], true
222 }
223 if v, exists := p.maybeValue(call.Args()[1].ID()); exists {
224 if v == types.False {
225 return p.maybeCreateLiteral(node.ID(), types.False)
226 }
227 return call.Args()[0], true
228 }
229 return nil, false
230 }
231
232 func (p *astPruner) maybePruneConditional(node ast.Expr) (ast.Expr, bool) {
233 call := node.AsCall()
234 cond, exists := p.maybeValue(call.Args()[0].ID())
235 if !exists {
236 return nil, false
237 }
238 if cond.Value().(bool) {
239 return call.Args()[1], true
240 }
241 return call.Args()[2], true
242 }
243
244 func (p *astPruner) maybePruneFunction(node ast.Expr) (ast.Expr, bool) {
245 if _, exists := p.value(node.ID()); !exists {
246 return nil, false
247 }
248 call := node.AsCall()
249 if call.FunctionName() == operators.LogicalOr {
250 return p.maybePruneOr(node)
251 }
252 if call.FunctionName() == operators.LogicalAnd {
253 return p.maybePruneAnd(node)
254 }
255 if call.FunctionName() == operators.Conditional {
256 return p.maybePruneConditional(node)
257 }
258 if call.FunctionName() == operators.In {
259 return p.maybePruneIn(node)
260 }
261 if call.FunctionName() == operators.LogicalNot {
262 return p.maybePruneLogicalNot(node)
263 }
264 return nil, false
265 }
266
267 func (p *astPruner) maybePrune(node ast.Expr) (ast.Expr, bool) {
268 return p.prune(node)
269 }
270
271 func (p *astPruner) prune(node ast.Expr) (ast.Expr, bool) {
272 if node == nil {
273 return node, false
274 }
275 val, valueExists := p.maybeValue(node.ID())
276 if valueExists {
277 if newNode, ok := p.maybeCreateLiteral(node.ID(), val); ok {
278 delete(p.macroCalls, node.ID())
279 return newNode, true
280 }
281 }
282 if macro, found := p.macroCalls[node.ID()]; found {
283 // Ensure that intermediate values for the comprehension are cleared during pruning
284 pruneMacroCall := node.Kind() != ast.UnspecifiedExprKind
285 if node.Kind() == ast.ComprehensionKind {
286 // Only prune cel.bind() calls since the variables of the comprehension are all
287 // visible to the user, so there's no chance of an incorrect value being observed
288 // as a result of looking at intermediate computations within a comprehension.
289 pruneMacroCall = isCelBindMacro(macro)
290 }
291 if pruneMacroCall {
292 // prune the expression in terms of the macro call instead of the expanded form when
293 // dealing with macro call tracking references.
294 if newMacro, pruned := p.prune(macro); pruned {
295 p.macroCalls[node.ID()] = newMacro
296 }
297 } else {
298 // Otherwise just prune the macro target in keeping with the pruning behavior of the
299 // comprehensions later in the call graph.
300 macroCall := macro.AsCall()
301 if macroCall.Target() != nil {
302 if newTarget, pruned := p.prune(macroCall.Target()); pruned {
303 macro = p.NewMemberCall(macro.ID(), macroCall.FunctionName(), newTarget, macroCall.Args()...)
304 p.macroCalls[node.ID()] = macro
305 }
306 }
307 }
308 }
309
310 // We have either an unknown/error value, or something we don't want to
311 // transform, or expression was not evaluated. If possible, drill down
312 // more.
313 switch node.Kind() {
314 case ast.SelectKind:
315 sel := node.AsSelect()
316 if operand, isPruned := p.maybePrune(sel.Operand()); isPruned {
317 if sel.IsTestOnly() {
318 return p.NewPresenceTest(node.ID(), operand, sel.FieldName()), true
319 }
320 return p.NewSelect(node.ID(), operand, sel.FieldName()), true
321 }
322 case ast.CallKind:
323 argsPruned := false
324 call := node.AsCall()
325 args := call.Args()
326 newArgs := make([]ast.Expr, len(args))
327 for i, a := range args {
328 newArgs[i] = a
329 if arg, isPruned := p.maybePrune(a); isPruned {
330 argsPruned = true
331 newArgs[i] = arg
332 }
333 }
334 if !call.IsMemberFunction() {
335 newCall := p.NewCall(node.ID(), call.FunctionName(), newArgs...)
336 if prunedCall, isPruned := p.maybePruneFunction(newCall); isPruned {
337 return prunedCall, true
338 }
339 return newCall, argsPruned
340 }
341 newTarget := call.Target()
342 targetPruned := false
343 if prunedTarget, isPruned := p.maybePrune(call.Target()); isPruned {
344 targetPruned = true
345 newTarget = prunedTarget
346 }
347 newCall := p.NewMemberCall(node.ID(), call.FunctionName(), newTarget, newArgs...)
348 if prunedCall, isPruned := p.maybePruneFunction(newCall); isPruned {
349 return prunedCall, true
350 }
351 return newCall, targetPruned || argsPruned
352 case ast.ListKind:
353 l := node.AsList()
354 elems := l.Elements()
355 optIndices := l.OptionalIndices()
356 optIndexMap := map[int32]bool{}
357 for _, i := range optIndices {
358 optIndexMap[i] = true
359 }
360 newOptIndexMap := make(map[int32]bool, len(optIndexMap))
361 newElems := make([]ast.Expr, 0, len(elems))
362 var listPruned bool
363 prunedIdx := 0
364 for i, elem := range elems {
365 _, isOpt := optIndexMap[int32(i)]
366 if isOpt {
367 newElem, pruned := p.maybePruneOptional(elem)
368 if pruned {
369 listPruned = true
370 if newElem != nil {
371 newElems = append(newElems, newElem)
372 prunedIdx++
373 }
374 continue
375 }
376 newOptIndexMap[int32(prunedIdx)] = true
377 }
378 if newElem, prunedElem := p.maybePrune(elem); prunedElem {
379 newElems = append(newElems, newElem)
380 listPruned = true
381 } else {
382 newElems = append(newElems, elem)
383 }
384 prunedIdx++
385 }
386 optIndices = make([]int32, len(newOptIndexMap))
387 idx := 0
388 for i := range newOptIndexMap {
389 optIndices[idx] = i
390 idx++
391 }
392 if listPruned {
393 return p.NewList(node.ID(), newElems, optIndices), true
394 }
395 case ast.MapKind:
396 var mapPruned bool
397 m := node.AsMap()
398 entries := m.Entries()
399 newEntries := make([]ast.EntryExpr, len(entries))
400 for i, entry := range entries {
401 newEntries[i] = entry
402 e := entry.AsMapEntry()
403 newKey, keyPruned := p.maybePrune(e.Key())
404 newValue, valuePruned := p.maybePrune(e.Value())
405 if !keyPruned && !valuePruned {
406 continue
407 }
408 mapPruned = true
409 newEntry := p.NewMapEntry(entry.ID(), newKey, newValue, e.IsOptional())
410 newEntries[i] = newEntry
411 }
412 if mapPruned {
413 return p.NewMap(node.ID(), newEntries), true
414 }
415 case ast.StructKind:
416 var structPruned bool
417 obj := node.AsStruct()
418 fields := obj.Fields()
419 newFields := make([]ast.EntryExpr, len(fields))
420 for i, field := range fields {
421 newFields[i] = field
422 f := field.AsStructField()
423 newValue, prunedValue := p.maybePrune(f.Value())
424 if !prunedValue {
425 continue
426 }
427 structPruned = true
428 newEntry := p.NewStructField(field.ID(), f.Name(), newValue, f.IsOptional())
429 newFields[i] = newEntry
430 }
431 if structPruned {
432 return p.NewStruct(node.ID(), obj.TypeName(), newFields), true
433 }
434 case ast.ComprehensionKind:
435 compre := node.AsComprehension()
436 // Only the range of the comprehension is pruned since the state tracking only records
437 // the last iteration of the comprehension and not each step in the evaluation which
438 // means that the any residuals computed in between might be inaccurate.
439 if newRange, pruned := p.maybePrune(compre.IterRange()); pruned {
440 if compre.HasIterVar2() {
441 return p.NewComprehensionTwoVar(
442 node.ID(),
443 newRange,
444 compre.IterVar(),
445 compre.IterVar2(),
446 compre.AccuVar(),
447 compre.AccuInit(),
448 compre.LoopCondition(),
449 compre.LoopStep(),
450 compre.Result(),
451 ), true
452 }
453 return p.NewComprehension(
454 node.ID(),
455 newRange,
456 compre.IterVar(),
457 compre.AccuVar(),
458 compre.AccuInit(),
459 compre.LoopCondition(),
460 compre.LoopStep(),
461 compre.Result(),
462 ), true
463 }
464 }
465 return node, false
466 }
467
468 func (p *astPruner) value(id int64) (ref.Val, bool) {
469 val, found := p.state.Value(id)
470 return val, (found && val != nil)
471 }
472
473 func (p *astPruner) maybeValue(id int64) (ref.Val, bool) {
474 val, found := p.value(id)
475 if !found || types.IsUnknownOrError(val) {
476 return nil, false
477 }
478 return val, true
479 }
480
481 func (p *astPruner) nextID() int64 {
482 next := p.nextExprID
483 p.nextExprID++
484 return next
485 }
486
487 type astVisitor struct {
488 // visitEntry is called on every expr node, including those within a map/struct entry.
489 visitExpr func(expr ast.Expr)
490 // visitEntry is called before entering the key, value of a map/struct entry.
491 visitEntry func(entry ast.EntryExpr)
492 }
493
494 func getMaxID(expr ast.Expr) int64 {
495 maxID := int64(1)
496 visit(expr, maxIDVisitor(&maxID))
497 return maxID
498 }
499
500 func maxIDVisitor(maxID *int64) astVisitor {
501 return astVisitor{
502 visitExpr: func(e ast.Expr) {
503 if e.ID() >= *maxID {
504 *maxID = e.ID() + 1
505 }
506 },
507 visitEntry: func(e ast.EntryExpr) {
508 if e.ID() >= *maxID {
509 *maxID = e.ID() + 1
510 }
511 },
512 }
513 }
514
515 func visit(expr ast.Expr, visitor astVisitor) {
516 exprs := []ast.Expr{expr}
517 for len(exprs) != 0 {
518 e := exprs[0]
519 if visitor.visitExpr != nil {
520 visitor.visitExpr(e)
521 }
522 exprs = exprs[1:]
523 switch e.Kind() {
524 case ast.SelectKind:
525 exprs = append(exprs, e.AsSelect().Operand())
526 case ast.CallKind:
527 call := e.AsCall()
528 if call.Target() != nil {
529 exprs = append(exprs, call.Target())
530 }
531 exprs = append(exprs, call.Args()...)
532 case ast.ComprehensionKind:
533 compre := e.AsComprehension()
534 exprs = append(exprs,
535 compre.IterRange(),
536 compre.AccuInit(),
537 compre.LoopCondition(),
538 compre.LoopStep(),
539 compre.Result())
540 case ast.ListKind:
541 list := e.AsList()
542 exprs = append(exprs, list.Elements()...)
543 case ast.MapKind:
544 for _, entry := range e.AsMap().Entries() {
545 e := entry.AsMapEntry()
546 if visitor.visitEntry != nil {
547 visitor.visitEntry(entry)
548 }
549 exprs = append(exprs, e.Key())
550 exprs = append(exprs, e.Value())
551 }
552 case ast.StructKind:
553 for _, entry := range e.AsStruct().Fields() {
554 f := entry.AsStructField()
555 if visitor.visitEntry != nil {
556 visitor.visitEntry(entry)
557 }
558 exprs = append(exprs, f.Value())
559 }
560 }
561 }
562 }
563
564 func isCelBindMacro(macro ast.Expr) bool {
565 if macro.Kind() != ast.CallKind {
566 return false
567 }
568 macroCall := macro.AsCall()
569 target := macroCall.Target()
570 return macroCall.FunctionName() == "bind" &&
571 macroCall.IsMemberFunction() &&
572 target.Kind() == ast.IdentKind &&
573 target.AsIdent() == "cel"
574 }