Debian Codegraph @

cel/folding.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 cel
16
17 import (
18 "fmt"
19
20 "github.com/google/cel-go/common/ast"
21 "github.com/google/cel-go/common/operators"
22 "github.com/google/cel-go/common/overloads"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 "github.com/google/cel-go/common/types/traits"
26 )
27
28 // ConstantFoldingOption defines a functional option for configuring constant folding.
29 type ConstantFoldingOption func(opt *constantFoldingOptimizer) (*constantFoldingOptimizer, error)
30
31 // MaxConstantFoldIterations limits the number of times literals may be folding during optimization.
32 //
33 // Defaults to 100 if not set.
34 func MaxConstantFoldIterations(limit int) ConstantFoldingOption {
35 return func(opt *constantFoldingOptimizer) (*constantFoldingOptimizer, error) {
36 opt.maxFoldIterations = limit
37 return opt, nil
38 }
39 }
40
41 // FoldKnownValues adds an Activation which provides known values for the folding evaluator
42 //
43 // Any values the activation provides will be used by the constant folder and turned into
44 // literals in the AST.
45 //
46 // Defaults to the NoVars() Activation
47 func FoldKnownValues(knownValues Activation) ConstantFoldingOption {
48 return func(opt *constantFoldingOptimizer) (*constantFoldingOptimizer, error) {
49 if knownValues != nil {
50 opt.knownValues = knownValues
51 } else {
52 opt.knownValues = NoVars()
53 }
54 return opt, nil
55 }
56 }
57
58 // NewConstantFoldingOptimizer creates an optimizer which inlines constant scalar an aggregate
59 // literal values within function calls and select statements with their evaluated result.
60 func NewConstantFoldingOptimizer(opts ...ConstantFoldingOption) (ASTOptimizer, error) {
61 folder := &constantFoldingOptimizer{
62 maxFoldIterations: defaultMaxConstantFoldIterations,
63 }
64 var err error
65 for _, o := range opts {
66 folder, err = o(folder)
67 if err != nil {
68 return nil, err
69 }
70 }
71 return folder, nil
72 }
73
74 type constantFoldingOptimizer struct {
75 maxFoldIterations int
76 knownValues Activation
77 }
78
79 // Optimize queries the expression graph for scalar and aggregate literal expressions within call and
80 // select statements and then evaluates them and replaces the call site with the literal result.
81 //
82 // Note: only values which can be represented as literals in CEL syntax are supported.
83 func (opt *constantFoldingOptimizer) Optimize(ctx *OptimizerContext, a *ast.AST) *ast.AST {
84 root := ast.NavigateAST(a)
85
86 // Walk the list of foldable expression and continue to fold until there are no more folds left.
87 // All of the fold candidates returned by the constantExprMatcher should succeed unless there's
88 // a logic bug with the selection of expressions.
89 constantExprMatcherCapture := func(e ast.NavigableExpr) bool { return opt.constantExprMatcher(ctx, a, e) }
90 foldableExprs := ast.MatchDescendants(root, constantExprMatcherCapture)
91 foldCount := 0
92 for len(foldableExprs) != 0 && foldCount < opt.maxFoldIterations {
93 for _, fold := range foldableExprs {
94 // If the expression could be folded because it's a non-strict call, and the
95 // branches are pruned, continue to the next fold.
96 if fold.Kind() == ast.CallKind && maybePruneBranches(ctx, fold) {
97 continue
98 }
99 // Late-bound function calls cannot be folded.
100 if fold.Kind() == ast.CallKind && isLateBoundFunctionCall(ctx, a, fold) {
101 continue
102 }
103 // Otherwise, assume all context is needed to evaluate the expression.
104 err := opt.tryFold(ctx, a, fold)
105 // Ignore errors for identifiers, since there is no guarantee that the environment
106 // has a value for them.
107 if err != nil && fold.Kind() != ast.IdentKind {
108 ctx.ReportErrorAtID(fold.ID(), "constant-folding evaluation failed: %v", err.Error())
109 return a
110 }
111 }
112 foldCount++
113 foldableExprs = ast.MatchDescendants(root, constantExprMatcherCapture)
114 }
115 // Once all of the constants have been folded, try to run through the remaining comprehensions
116 // one last time. In this case, there's no guarantee they'll run, so we only update the
117 // target comprehension node with the literal value if the evaluation succeeds.
118 for _, compre := range ast.MatchDescendants(root, ast.KindMatcher(ast.ComprehensionKind)) {
119 opt.tryFold(ctx, a, compre)
120 }
121
122 // If the output is a list, map, or struct which contains optional entries, then prune it
123 // to make sure that the optionals, if resolved, do not surface in the output literal.
124 pruneOptionalElements(ctx, root)
125
126 // Ensure that all intermediate values in the folded expression can be represented as valid
127 // CEL literals within the AST structure. Use `PostOrderVisit` rather than `MatchDescendents`
128 // to avoid extra allocations during this final pass through the AST.
129 ast.PostOrderVisit(root, ast.NewExprVisitor(func(e ast.Expr) {
130 if e.Kind() != ast.LiteralKind {
131 return
132 }
133 val := e.AsLiteral()
134 adapted, err := adaptLiteral(ctx, val)
135 if err != nil {
136 ctx.ReportErrorAtID(root.ID(), "constant-folding evaluation failed: %v", err.Error())
137 return
138 }
139 ctx.UpdateExpr(e, adapted)
140 }))
141
142 return a
143 }
144
145 // tryFold attempts to evaluate a sub-expression to a literal.
146 //
147 // If the evaluation succeeds, the input expr value will be modified to become a literal, otherwise
148 // the method will return an error.
149 func (opt *constantFoldingOptimizer) tryFold(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) error {
150 // Assume all context is needed to evaluate the expression.
151 subAST := &Ast{
152 impl: ast.NewCheckedAST(ast.NewAST(expr, a.SourceInfo()), a.TypeMap(), a.ReferenceMap()),
153 }
154 prg, err := ctx.Program(subAST)
155 if err != nil {
156 return err
157 }
158 activation := opt.knownValues
159 if activation == nil {
160 activation = NoVars()
161 }
162 out, _, err := prg.Eval(activation)
163 if err != nil {
164 return err
165 }
166 // Update the fold expression to be a literal.
167 ctx.UpdateExpr(expr, ctx.NewLiteral(out))
168 return nil
169 }
170
171 func isLateBoundFunctionCall(ctx *OptimizerContext, a *ast.AST, expr ast.Expr) bool {
172 call := expr.AsCall()
173 function := ctx.Functions()[call.FunctionName()]
174 if function == nil {
175 return false
176 }
177 return function.HasLateBinding()
178 }
179
180 // maybePruneBranches inspects the non-strict call expression to determine whether
181 // a branch can be removed. Evaluation will naturally prune logical and / or calls,
182 // but conditional will not be pruned cleanly, so this is one small area where the
183 // constant folding step reimplements a portion of the evaluator.
184 func maybePruneBranches(ctx *OptimizerContext, expr ast.NavigableExpr) bool {
185 call := expr.AsCall()
186 args := call.Args()
187 switch call.FunctionName() {
188 case operators.LogicalAnd, operators.LogicalOr:
189 return maybeShortcircuitLogic(ctx, call.FunctionName(), args, expr)
190 case operators.Conditional:
191 cond := args[0]
192 truthy := args[1]
193 falsy := args[2]
194 if cond.Kind() != ast.LiteralKind {
195 return false
196 }
197 if cond.AsLiteral() == types.True {
198 ctx.UpdateExpr(expr, truthy)
199 } else {
200 ctx.UpdateExpr(expr, falsy)
201 }
202 return true
203 case operators.In:
204 haystack := args[1]
205 if haystack.Kind() == ast.ListKind && haystack.AsList().Size() == 0 {
206 ctx.UpdateExpr(expr, ctx.NewLiteral(types.False))
207 return true
208 }
209 needle := args[0]
210 if needle.Kind() == ast.LiteralKind && haystack.Kind() == ast.ListKind {
211 needleValue := needle.AsLiteral()
212 list := haystack.AsList()
213 for _, e := range list.Elements() {
214 if e.Kind() == ast.LiteralKind && e.AsLiteral().Equal(needleValue) == types.True {
215 ctx.UpdateExpr(expr, ctx.NewLiteral(types.True))
216 return true
217 }
218 }
219 }
220 }
221 return false
222 }
223
224 func maybeShortcircuitLogic(ctx *OptimizerContext, function string, args []ast.Expr, expr ast.NavigableExpr) bool {
225 shortcircuit := types.False
226 skip := types.True
227 if function == operators.LogicalOr {
228 shortcircuit = types.True
229 skip = types.False
230 }
231 newArgs := []ast.Expr{}
232 for _, arg := range args {
233 if arg.Kind() != ast.LiteralKind {
234 newArgs = append(newArgs, arg)
235 continue
236 }
237 if arg.AsLiteral() == skip {
238 continue
239 }
240 if arg.AsLiteral() == shortcircuit {
241 ctx.UpdateExpr(expr, arg)
242 return true
243 }
244 }
245 if len(newArgs) == 0 {
246 newArgs = append(newArgs, args[0])
247 ctx.UpdateExpr(expr, newArgs[0])
248 return true
249 }
250 if len(newArgs) == 1 {
251 ctx.UpdateExpr(expr, newArgs[0])
252 return true
253 }
254 ctx.UpdateExpr(expr, ctx.NewCall(function, newArgs...))
255 return true
256 }
257
258 // pruneOptionalElements works from the bottom up to resolve optional elements within
259 // aggregate literals.
260 //
261 // Note, many aggregate literals will be resolved as arguments to functions or select
262 // statements, so this method exists to handle the case where the literal could not be
263 // fully resolved or exists outside of a call, select, or comprehension context.
264 func pruneOptionalElements(ctx *OptimizerContext, root ast.NavigableExpr) {
265 aggregateLiterals := ast.MatchDescendants(root, aggregateLiteralMatcher)
266 for _, lit := range aggregateLiterals {
267 switch lit.Kind() {
268 case ast.ListKind:
269 pruneOptionalListElements(ctx, lit)
270 case ast.MapKind:
271 pruneOptionalMapEntries(ctx, lit)
272 case ast.StructKind:
273 pruneOptionalStructFields(ctx, lit)
274 }
275 }
276 }
277
278 func pruneOptionalListElements(ctx *OptimizerContext, e ast.Expr) {
279 l := e.AsList()
280 elems := l.Elements()
281 optIndices := l.OptionalIndices()
282 if len(optIndices) == 0 {
283 return
284 }
285 updatedElems := []ast.Expr{}
286 updatedIndices := []int32{}
287 newOptIndex := -1
288 for _, e := range elems {
289 newOptIndex++
290 if !l.IsOptional(int32(newOptIndex)) {
291 updatedElems = append(updatedElems, e)
292 continue
293 }
294 if e.Kind() != ast.LiteralKind {
295 updatedElems = append(updatedElems, e)
296 updatedIndices = append(updatedIndices, int32(newOptIndex))
297 continue
298 }
299 optElemVal, ok := e.AsLiteral().(*types.Optional)
300 if !ok {
301 updatedElems = append(updatedElems, e)
302 updatedIndices = append(updatedIndices, int32(newOptIndex))
303 continue
304 }
305 if !optElemVal.HasValue() {
306 newOptIndex-- // Skipping causes the list to get smaller.
307 continue
308 }
309 ctx.UpdateExpr(e, ctx.NewLiteral(optElemVal.GetValue()))
310 updatedElems = append(updatedElems, e)
311 }
312 ctx.UpdateExpr(e, ctx.NewList(updatedElems, updatedIndices))
313 }
314
315 func pruneOptionalMapEntries(ctx *OptimizerContext, e ast.Expr) {
316 m := e.AsMap()
317 entries := m.Entries()
318 updatedEntries := []ast.EntryExpr{}
319 modified := false
320 for _, e := range entries {
321 entry := e.AsMapEntry()
322 key := entry.Key()
323 val := entry.Value()
324 // If the entry is not optional, or the value-side of the optional hasn't
325 // been resolved to a literal, then preserve the entry as-is.
326 if !entry.IsOptional() || val.Kind() != ast.LiteralKind {
327 updatedEntries = append(updatedEntries, e)
328 continue
329 }
330 optElemVal, ok := val.AsLiteral().(*types.Optional)
331 if !ok {
332 updatedEntries = append(updatedEntries, e)
333 continue
334 }
335 // When the key is not a literal, but the value is, then it needs to be
336 // restored to an optional value.
337 if key.Kind() != ast.LiteralKind {
338 undoOptVal, err := adaptLiteral(ctx, optElemVal)
339 if err != nil {
340 ctx.ReportErrorAtID(val.ID(), "invalid map value literal %v: %v", optElemVal, err)
341 }
342 ctx.UpdateExpr(val, undoOptVal)
343 updatedEntries = append(updatedEntries, e)
344 continue
345 }
346 modified = true
347 if !optElemVal.HasValue() {
348 continue
349 }
350 ctx.UpdateExpr(val, ctx.NewLiteral(optElemVal.GetValue()))
351 updatedEntry := ctx.NewMapEntry(key, val, false)
352 updatedEntries = append(updatedEntries, updatedEntry)
353 }
354 if modified {
355 ctx.UpdateExpr(e, ctx.NewMap(updatedEntries))
356 }
357 }
358
359 func pruneOptionalStructFields(ctx *OptimizerContext, e ast.Expr) {
360 s := e.AsStruct()
361 fields := s.Fields()
362 updatedFields := []ast.EntryExpr{}
363 modified := false
364 for _, f := range fields {
365 field := f.AsStructField()
366 val := field.Value()
367 if !field.IsOptional() || val.Kind() != ast.LiteralKind {
368 updatedFields = append(updatedFields, f)
369 continue
370 }
371 optElemVal, ok := val.AsLiteral().(*types.Optional)
372 if !ok {
373 updatedFields = append(updatedFields, f)
374 continue
375 }
376 modified = true
377 if !optElemVal.HasValue() {
378 continue
379 }
380 ctx.UpdateExpr(val, ctx.NewLiteral(optElemVal.GetValue()))
381 updatedField := ctx.NewStructField(field.Name(), val, false)
382 updatedFields = append(updatedFields, updatedField)
383 }
384 if modified {
385 ctx.UpdateExpr(e, ctx.NewStruct(s.TypeName(), updatedFields))
386 }
387 }
388
389 // adaptLiteral converts a runtime CEL value to its equivalent literal expression.
390 //
391 // For strongly typed values, the type-provider will be used to reconstruct the fields
392 // which are present in the literal and their equivalent initialization values.
393 func adaptLiteral(ctx *OptimizerContext, val ref.Val) (ast.Expr, error) {
394 switch t := val.Type().(type) {
395 case *types.Type:
396 switch t {
397 case types.BoolType, types.BytesType, types.DoubleType, types.IntType,
398 types.NullType, types.StringType, types.UintType:
399 return ctx.NewLiteral(val), nil
400 case types.DurationType:
401 return ctx.NewCall(
402 overloads.TypeConvertDuration,
403 ctx.NewLiteral(val.ConvertToType(types.StringType)),
404 ), nil
405 case types.TimestampType:
406 return ctx.NewCall(
407 overloads.TypeConvertTimestamp,
408 ctx.NewLiteral(val.ConvertToType(types.StringType)),
409 ), nil
410 case types.OptionalType:
411 opt := val.(*types.Optional)
412 if !opt.HasValue() {
413 return ctx.NewCall("optional.none"), nil
414 }
415 target, err := adaptLiteral(ctx, opt.GetValue())
416 if err != nil {
417 return nil, err
418 }
419 return ctx.NewCall("optional.of", target), nil
420 case types.TypeType:
421 return ctx.NewIdent(val.(*types.Type).TypeName()), nil
422 case types.ListType:
423 l, ok := val.(traits.Lister)
424 if !ok {
425 return nil, fmt.Errorf("failed to adapt %v to literal", val)
426 }
427 elems := make([]ast.Expr, l.Size().(types.Int))
428 idx := 0
429 it := l.Iterator()
430 for it.HasNext() == types.True {
431 elemVal := it.Next()
432 elemExpr, err := adaptLiteral(ctx, elemVal)
433 if err != nil {
434 return nil, err
435 }
436 elems[idx] = elemExpr
437 idx++
438 }
439 return ctx.NewList(elems, []int32{}), nil
440 case types.MapType:
441 m, ok := val.(traits.Mapper)
442 if !ok {
443 return nil, fmt.Errorf("failed to adapt %v to literal", val)
444 }
445 entries := make([]ast.EntryExpr, m.Size().(types.Int))
446 idx := 0
447 it := m.Iterator()
448 for it.HasNext() == types.True {
449 keyVal := it.Next()
450 keyExpr, err := adaptLiteral(ctx, keyVal)
451 if err != nil {
452 return nil, err
453 }
454 valVal := m.Get(keyVal)
455 valExpr, err := adaptLiteral(ctx, valVal)
456 if err != nil {
457 return nil, err
458 }
459 entries[idx] = ctx.NewMapEntry(keyExpr, valExpr, false)
460 idx++
461 }
462 return ctx.NewMap(entries), nil
463 default:
464 provider := ctx.CELTypeProvider()
465 fields, found := provider.FindStructFieldNames(t.TypeName())
466 if !found {
467 return nil, fmt.Errorf("failed to adapt %v to literal", val)
468 }
469 tester := val.(traits.FieldTester)
470 indexer := val.(traits.Indexer)
471 fieldInits := []ast.EntryExpr{}
472 for _, f := range fields {
473 field := types.String(f)
474 if tester.IsSet(field) != types.True {
475 continue
476 }
477 fieldVal := indexer.Get(field)
478 fieldExpr, err := adaptLiteral(ctx, fieldVal)
479 if err != nil {
480 return nil, err
481 }
482 fieldInits = append(fieldInits, ctx.NewStructField(f, fieldExpr, false))
483 }
484 return ctx.NewStruct(t.TypeName(), fieldInits), nil
485 }
486 }
487 return nil, fmt.Errorf("failed to adapt %v to literal", val)
488 }
489
490 // constantExprMatcher matches calls, select statements, and comprehensions whose arguments
491 // are all constant scalar or aggregate literal values.
492 //
493 // Only comprehensions which are not nested are included as possible constant folds, and only
494 // if all variables referenced in the comprehension stack exist are only iteration or
495 // accumulation variables.
496 func (opt *constantFoldingOptimizer) constantExprMatcher(ctx *OptimizerContext, a *ast.AST, e ast.NavigableExpr) bool {
497 switch e.Kind() {
498 case ast.CallKind:
499 return constantCallMatcher(e)
500 case ast.SelectKind:
501 sel := e.AsSelect() // guaranteed to be a navigable value
502 return constantMatcher(sel.Operand().(ast.NavigableExpr))
503 case ast.IdentKind:
504 return opt.knownValues != nil && a.ReferenceMap()[e.ID()] != nil
505 case ast.ComprehensionKind:
506 if isNestedComprehension(e) {
507 return false
508 }
509 vars := map[string]bool{}
510 constantExprs := true
511 visitor := ast.NewExprVisitor(func(e ast.Expr) {
512 if e.Kind() == ast.ComprehensionKind {
513 nested := e.AsComprehension()
514 vars[nested.AccuVar()] = true
515 vars[nested.IterVar()] = true
516 }
517 if e.Kind() == ast.IdentKind && !vars[e.AsIdent()] {
518 constantExprs = false
519 }
520 // Late-bound function calls cannot be folded.
521 if e.Kind() == ast.CallKind && isLateBoundFunctionCall(ctx, a, e) {
522 constantExprs = false
523 }
524 })
525 ast.PreOrderVisit(e, visitor)
526 return constantExprs
527 default:
528 return false
529 }
530 }
531
532 // constantCallMatcher identifies strict and non-strict calls which can be folded.
533 func constantCallMatcher(e ast.NavigableExpr) bool {
534 call := e.AsCall()
535 children := e.Children()
536 fnName := call.FunctionName()
537 if fnName == operators.LogicalAnd {
538 for _, child := range children {
539 if child.Kind() == ast.LiteralKind {
540 return true
541 }
542 }
543 }
544 if fnName == operators.LogicalOr {
545 for _, child := range children {
546 if child.Kind() == ast.LiteralKind {
547 return true
548 }
549 }
550 }
551 if fnName == operators.Conditional {
552 cond := children[0]
553 if cond.Kind() == ast.LiteralKind && cond.AsLiteral().Type() == types.BoolType {
554 return true
555 }
556 }
557 if fnName == operators.In {
558 haystack := children[1]
559 if haystack.Kind() == ast.ListKind && haystack.AsList().Size() == 0 {
560 return true
561 }
562 needle := children[0]
563 if needle.Kind() == ast.LiteralKind && haystack.Kind() == ast.ListKind {
564 needleValue := needle.AsLiteral()
565 list := haystack.AsList()
566 for _, e := range list.Elements() {
567 if e.Kind() == ast.LiteralKind && e.AsLiteral().Equal(needleValue) == types.True {
568 return true
569 }
570 }
571 }
572 }
573 // convert all other calls with constant arguments
574 for _, child := range children {
575 if !constantMatcher(child) {
576 return false
577 }
578 }
579 return true
580 }
581
582 func isNestedComprehension(e ast.NavigableExpr) bool {
583 parent, found := e.Parent()
584 for found {
585 if parent.Kind() == ast.ComprehensionKind {
586 return true
587 }
588 parent, found = parent.Parent()
589 }
590 return false
591 }
592
593 func aggregateLiteralMatcher(e ast.NavigableExpr) bool {
594 return e.Kind() == ast.ListKind || e.Kind() == ast.MapKind || e.Kind() == ast.StructKind
595 }
596
597 var (
598 constantMatcher = ast.ConstantValueMatcher()
599 )
600
601 const (
602 defaultMaxConstantFoldIterations = 100
603 )