Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/cel/optimizer.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 cel
16
17 import (
18 "fmt"
19 "sort"
20
21 "github.com/google/cel-go/common"
22 "github.com/google/cel-go/common/ast"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 )
26
27 // StaticOptimizer contains a sequence of ASTOptimizer instances which will be applied in order.
28 //
29 // The static optimizer normalizes expression ids and type-checking run between optimization
30 // passes to ensure that the final optimized output is a valid expression with metadata consistent
31 // with what would have been generated from a parsed and checked expression.
32 //
33 // Note: source position information is best-effort and incomplete, but optimized expressions
34 // should be suitable for calls to parser.Unparse.
35 type StaticOptimizer struct {
36 optimizers []ASTOptimizer
37 // If set, Optimize() will use this Source instead of the one from the AST.
38 sourceOverride *Source
39 }
40
41 type OptimizerOption func(*StaticOptimizer) (*StaticOptimizer, error)
42
43 // NewStaticOptimizer creates a StaticOptimizer with a sequence of ASTOptimizer's to be applied
44 // to a checked expression.
45 func NewStaticOptimizer(options ...any) (*StaticOptimizer, error) {
46 so := &StaticOptimizer{}
47 var err error
48 for _, opt := range options {
49 switch v := opt.(type) {
50 case ASTOptimizer:
51 so.optimizers = append(so.optimizers, v)
52 case OptimizerOption:
53 so, err = v(so)
54 if err != nil {
55 return nil, err
56 }
57 default:
58 return nil, fmt.Errorf("unsupported option: %v", v)
59 }
60 }
61 return so, nil
62 }
63
64 // OptimizeWithSource overrides the source used by the optimizer.
65 // Note this will cause the source info from the AST passed to Optimize() to be discarded.
66 func OptimizeWithSource(source Source) OptimizerOption {
67 return func(so *StaticOptimizer) (*StaticOptimizer, error) {
68 so.sourceOverride = &source
69 return so, nil
70 }
71 }
72
73 // Optimize applies a sequence of optimizations to an Ast within a given environment.
74 //
75 // If issues are encountered, the Issues.Err() return value will be non-nil.
76 func (opt *StaticOptimizer) Optimize(env *Env, a *Ast) (*Ast, *Issues) {
77 // Make a copy of the AST to be optimized.
78 optimized := ast.Copy(a.NativeRep())
79 source := a.Source()
80 sourceInfo := optimized.SourceInfo()
81 if opt.sourceOverride != nil {
82 source = *opt.sourceOverride
83 sourceInfo = ast.NewSourceInfo(*opt.sourceOverride)
84 }
85 ids := newIDGenerator(ast.MaxID(a.NativeRep()))
86
87 // Create the optimizer context, could be pooled in the future.
88 issues := NewIssues(common.NewErrors(source))
89 baseFac := ast.NewExprFactory()
90 exprFac := &optimizerExprFactory{
91 idGenerator: ids,
92 fac: baseFac,
93 sourceInfo: sourceInfo,
94 }
95 ctx := &OptimizerContext{
96 optimizerExprFactory: exprFac,
97 Env: env,
98 Issues: issues,
99 }
100
101 // Apply the optimizations sequentially.
102 for _, o := range opt.optimizers {
103 optimized = o.Optimize(ctx, optimized)
104 if issues.Err() != nil {
105 return nil, issues
106 }
107 // Normalize expression id metadata including coordination with macro call metadata.
108 freshIDGen := newIDGenerator(0)
109 info := optimized.SourceInfo()
110 expr := optimized.Expr()
111 normalizeIDs(freshIDGen.renumberStable, expr, info)
112 cleanupMacroRefs(expr, info)
113
114 // Recheck the updated expression for any possible type-agreement or validation errors.
115 parsed := &Ast{
116 source: source,
117 impl: ast.NewAST(expr, info)}
118 checked, iss := ctx.Check(parsed)
119 if iss.Err() != nil {
120 return nil, iss
121 }
122 optimized = checked.NativeRep()
123 }
124
125 // Return the optimized result.
126 return &Ast{
127 source: source,
128 impl: optimized,
129 }, nil
130 }
131
132 // normalizeIDs ensures that the metadata present with an AST is reset in a manner such
133 // that the ids within the expression correspond to the ids within macros.
134 func normalizeIDs(idGen ast.IDGenerator, optimized ast.Expr, info *ast.SourceInfo) {
135 optimized.RenumberIDs(idGen)
136 info.RenumberIDs(idGen)
137
138 if len(info.MacroCalls()) == 0 {
139 return
140 }
141
142 // Sort the macro ids to make sure that the renumbering of macro-specific variables
143 // is stable across normalization calls.
144 sortedMacroIDs := []int64{}
145 for id := range info.MacroCalls() {
146 sortedMacroIDs = append(sortedMacroIDs, id)
147 }
148 sort.Slice(sortedMacroIDs, func(i, j int) bool { return sortedMacroIDs[i] < sortedMacroIDs[j] })
149
150 // First, update the macro call ids themselves.
151 callIDMap := map[int64]int64{}
152 for _, id := range sortedMacroIDs {
153 callIDMap[id] = idGen(id)
154 }
155 // Then update the macro call definitions which refer to these ids, but
156 // ensure that the updates don't collide and remove macro entries which haven't
157 // been visited / updated yet.
158 type macroUpdate struct {
159 id int64
160 call ast.Expr
161 }
162 macroUpdates := []macroUpdate{}
163 for _, oldID := range sortedMacroIDs {
164 newID := callIDMap[oldID]
165 call, found := info.GetMacroCall(oldID)
166 if !found {
167 continue
168 }
169 call.RenumberIDs(idGen)
170 macroUpdates = append(macroUpdates, macroUpdate{id: newID, call: call})
171 info.ClearMacroCall(oldID)
172 }
173 for _, u := range macroUpdates {
174 info.SetMacroCall(u.id, u.call)
175 }
176 }
177
178 func cleanupMacroRefs(expr ast.Expr, info *ast.SourceInfo) {
179 if len(info.MacroCalls()) == 0 {
180 return
181 }
182
183 // Sanitize the macro call references once the optimized expression has been computed
184 // and the ids normalized between the expression and the macros.
185 exprRefMap := make(map[int64]struct{})
186 ast.PostOrderVisit(expr, ast.NewExprVisitor(func(e ast.Expr) {
187 if e.ID() == 0 {
188 return
189 }
190 exprRefMap[e.ID()] = struct{}{}
191 }))
192 // Update the macro call id references to ensure that macro pointers are
193 // updated consistently across macros.
194 for _, call := range info.MacroCalls() {
195 ast.PostOrderVisit(call, ast.NewExprVisitor(func(e ast.Expr) {
196 if e.ID() == 0 {
197 return
198 }
199 exprRefMap[e.ID()] = struct{}{}
200 }))
201 }
202 for id := range info.MacroCalls() {
203 if _, found := exprRefMap[id]; !found {
204 info.ClearMacroCall(id)
205 }
206 }
207 }
208
209 // newIDGenerator ensures that new ids are only created the first time they are encountered.
210 func newIDGenerator(seed int64) *idGenerator {
211 return &idGenerator{
212 idMap: make(map[int64]int64),
213 seed: seed,
214 }
215 }
216
217 type idGenerator struct {
218 idMap map[int64]int64
219 seed int64
220 }
221
222 func (gen *idGenerator) nextID() int64 {
223 gen.seed++
224 return gen.seed
225 }
226
227 func (gen *idGenerator) renumberStable(id int64) int64 {
228 if id == 0 {
229 return 0
230 }
231 if newID, found := gen.idMap[id]; found {
232 return newID
233 }
234 nextID := gen.nextID()
235 gen.idMap[id] = nextID
236 return nextID
237 }
238
239 // OptimizerContext embeds Env and Issues instances to make it easy to type-check and evaluate
240 // subexpressions and report any errors encountered along the way. The context also embeds the
241 // optimizerExprFactory which can be used to generate new sub-expressions with expression ids
242 // consistent with the expectations of a parsed expression.
243 type OptimizerContext struct {
244 *Env
245 *optimizerExprFactory
246 *Issues
247 }
248
249 // ExtendEnv auguments the context's environment with the additional options.
250 func (opt *OptimizerContext) ExtendEnv(opts ...EnvOption) error {
251 e, err := opt.Env.Extend(opts...)
252 if err != nil {
253 return err
254 }
255 opt.Env = e
256 return nil
257 }
258
259 // ASTOptimizer applies an optimization over an AST and returns the optimized result.
260 type ASTOptimizer interface {
261 // Optimize optimizes a type-checked AST within an Environment and accumulates any issues.
262 Optimize(*OptimizerContext, *ast.AST) *ast.AST
263 }
264
265 type optimizerExprFactory struct {
266 *idGenerator
267 fac ast.ExprFactory
268 sourceInfo *ast.SourceInfo
269 }
270
271 // NewAST creates an AST from the current expression using the tracked source info which
272 // is modified and managed by the OptimizerContext.
273 func (opt *optimizerExprFactory) NewAST(expr ast.Expr) *ast.AST {
274 return ast.NewAST(expr, opt.sourceInfo)
275 }
276
277 // CopyAST creates a renumbered copy of `Expr` and `SourceInfo` values of the input AST, where the
278 // renumbering uses the same scheme as the core optimizer logic ensuring there are no collisions
279 // between copies.
280 //
281 // Use this method before attempting to merge the expression from AST into another.
282 func (opt *optimizerExprFactory) CopyAST(a *ast.AST) (ast.Expr, *ast.SourceInfo) {
283 idGen := newIDGenerator(opt.nextID())
284 defer func() { opt.seed = idGen.nextID() }()
285 copyExpr := opt.fac.CopyExpr(a.Expr())
286 copyInfo := ast.CopySourceInfo(a.SourceInfo())
287 normalizeIDs(idGen.renumberStable, copyExpr, copyInfo)
288 return copyExpr, copyInfo
289 }
290
291 // CopyASTAndMetadata copies the input AST and propagates the macro metadata into the AST being
292 // optimized.
293 func (opt *optimizerExprFactory) CopyASTAndMetadata(a *ast.AST) ast.Expr {
294 copyExpr, copyInfo := opt.CopyAST(a)
295 for macroID, call := range copyInfo.MacroCalls() {
296 opt.SetMacroCall(macroID, call)
297 }
298 for id, offset := range copyInfo.OffsetRanges() {
299 opt.sourceInfo.SetOffsetRange(id, offset)
300 }
301 return copyExpr
302 }
303
304 // ClearMacroCall clears the macro at the given expression id.
305 func (opt *optimizerExprFactory) ClearMacroCall(id int64) {
306 opt.sourceInfo.ClearMacroCall(id)
307 }
308
309 // SetMacroCall sets the macro call metadata for the given macro id within the tracked source info
310 // metadata.
311 func (opt *optimizerExprFactory) SetMacroCall(id int64, expr ast.Expr) {
312 opt.sourceInfo.SetMacroCall(id, expr)
313 }
314
315 // MacroCalls returns the map of macro calls currently in the context.
316 func (opt *optimizerExprFactory) MacroCalls() map[int64]ast.Expr {
317 return opt.sourceInfo.MacroCalls()
318 }
319
320 // NewBindMacro creates an AST expression representing the expanded bind() macro, and a macro expression
321 // representing the unexpanded call signature to be inserted into the source info macro call metadata.
322 func (opt *optimizerExprFactory) NewBindMacro(macroID int64, varName string, varInit, remaining ast.Expr) (astExpr, macroExpr ast.Expr) {
323 varID := opt.nextID()
324 remainingID := opt.nextID()
325 remaining = opt.fac.CopyExpr(remaining)
326 remaining.RenumberIDs(func(id int64) int64 {
327 if id == macroID {
328 return remainingID
329 }
330 return id
331 })
332 if call, exists := opt.sourceInfo.GetMacroCall(macroID); exists {
333 opt.SetMacroCall(remainingID, opt.fac.CopyExpr(call))
334 }
335
336 astExpr = opt.fac.NewComprehension(macroID,
337 opt.fac.NewList(opt.nextID(), []ast.Expr{}, []int32{}),
338 "#unused",
339 varName,
340 opt.fac.CopyExpr(varInit),
341 opt.fac.NewLiteral(opt.nextID(), types.False),
342 opt.fac.NewIdent(varID, varName),
343 remaining)
344
345 macroExpr = opt.fac.NewMemberCall(0, "bind",
346 opt.fac.NewIdent(opt.nextID(), "cel"),
347 opt.fac.NewIdent(varID, varName),
348 opt.fac.CopyExpr(varInit),
349 opt.fac.CopyExpr(remaining))
350 opt.sanitizeMacro(macroID, macroExpr)
351 return
352 }
353
354 // NewCall creates a global function call invocation expression.
355 //
356 // Example:
357 //
358 // countByField(list, fieldName)
359 // - function: countByField
360 // - args: [list, fieldName]
361 func (opt *optimizerExprFactory) NewCall(function string, args ...ast.Expr) ast.Expr {
362 return opt.fac.NewCall(opt.nextID(), function, args...)
363 }
364
365 // NewMemberCall creates a member function call invocation expression where 'target' is the receiver of the call.
366 //
367 // Example:
368 //
369 // list.countByField(fieldName)
370 // - function: countByField
371 // - target: list
372 // - args: [fieldName]
373 func (opt *optimizerExprFactory) NewMemberCall(function string, target ast.Expr, args ...ast.Expr) ast.Expr {
374 return opt.fac.NewMemberCall(opt.nextID(), function, target, args...)
375 }
376
377 // NewIdent creates a new identifier expression.
378 //
379 // Examples:
380 //
381 // - simple_var_name
382 // - qualified.subpackage.var_name
383 func (opt *optimizerExprFactory) NewIdent(name string) ast.Expr {
384 return opt.fac.NewIdent(opt.nextID(), name)
385 }
386
387 // NewLiteral creates a new literal expression value.
388 //
389 // The range of valid values for a literal generated during optimization is different than for expressions
390 // generated via parsing / type-checking, as the ref.Val may be _any_ CEL value so long as the value can
391 // be converted back to a literal-like form.
392 func (opt *optimizerExprFactory) NewLiteral(value ref.Val) ast.Expr {
393 return opt.fac.NewLiteral(opt.nextID(), value)
394 }
395
396 // NewList creates a list expression with a set of optional indices.
397 //
398 // Examples:
399 //
400 // [a, b]
401 // - elems: [a, b]
402 // - optIndices: []
403 //
404 // [a, ?b, ?c]
405 // - elems: [a, b, c]
406 // - optIndices: [1, 2]
407 func (opt *optimizerExprFactory) NewList(elems []ast.Expr, optIndices []int32) ast.Expr {
408 return opt.fac.NewList(opt.nextID(), elems, optIndices)
409 }
410
411 // NewMap creates a map from a set of entry expressions which contain a key and value expression.
412 func (opt *optimizerExprFactory) NewMap(entries []ast.EntryExpr) ast.Expr {
413 return opt.fac.NewMap(opt.nextID(), entries)
414 }
415
416 // NewMapEntry creates a map entry with a key and value expression and a flag to indicate whether the
417 // entry is optional.
418 //
419 // Examples:
420 //
421 // {a: b}
422 // - key: a
423 // - value: b
424 // - optional: false
425 //
426 // {?a: ?b}
427 // - key: a
428 // - value: b
429 // - optional: true
430 func (opt *optimizerExprFactory) NewMapEntry(key, value ast.Expr, isOptional bool) ast.EntryExpr {
431 return opt.fac.NewMapEntry(opt.nextID(), key, value, isOptional)
432 }
433
434 // NewHasMacro generates a test-only select expression to be included within an AST and an unexpanded
435 // has() macro call signature to be inserted into the source info macro call metadata.
436 func (opt *optimizerExprFactory) NewHasMacro(macroID int64, s ast.Expr) (astExpr, macroExpr ast.Expr) {
437 sel := s.AsSelect()
438 astExpr = opt.fac.NewPresenceTest(macroID, sel.Operand(), sel.FieldName())
439 macroExpr = opt.fac.NewCall(0, "has",
440 opt.NewSelect(opt.fac.CopyExpr(sel.Operand()), sel.FieldName()))
441 opt.sanitizeMacro(macroID, macroExpr)
442 return
443 }
444
445 // NewSelect creates a select expression where a field value is selected from an operand.
446 //
447 // Example:
448 //
449 // msg.field_name
450 // - operand: msg
451 // - field: field_name
452 func (opt *optimizerExprFactory) NewSelect(operand ast.Expr, field string) ast.Expr {
453 return opt.fac.NewSelect(opt.nextID(), operand, field)
454 }
455
456 // NewStruct creates a new typed struct value with an set of field initializations.
457 //
458 // Example:
459 //
460 // pkg.TypeName{field: value}
461 // - typeName: pkg.TypeName
462 // - fields: [{field: value}]
463 func (opt *optimizerExprFactory) NewStruct(typeName string, fields []ast.EntryExpr) ast.Expr {
464 return opt.fac.NewStruct(opt.nextID(), typeName, fields)
465 }
466
467 // NewStructField creates a struct field initialization.
468 //
469 // Examples:
470 //
471 // {count: 3u}
472 // - field: count
473 // - value: 3u
474 // - optional: false
475 //
476 // {?count: x}
477 // - field: count
478 // - value: x
479 // - optional: true
480 func (opt *optimizerExprFactory) NewStructField(field string, value ast.Expr, isOptional bool) ast.EntryExpr {
481 return opt.fac.NewStructField(opt.nextID(), field, value, isOptional)
482 }
483
484 // UpdateExpr updates the target expression with the updated content while preserving macro metadata.
485 //
486 // There are four scenarios during the update to consider:
487 // 1. target is not macro, updated is not macro
488 // 2. target is macro, updated is not macro
489 // 3. target is macro, updated is macro
490 // 4. target is not macro, updated is macro
491 //
492 // When the target is a macro already, it may either be updated to a new macro function
493 // body if the update is also a macro, or it may be removed altogether if the update is
494 // a macro.
495 //
496 // When the update is a macro, then the target references within other macros must be
497 // updated to point to the new updated macro. Otherwise, other macros which pointed to
498 // the target body must be replaced with copies of the updated expression body.
499 func (opt *optimizerExprFactory) UpdateExpr(target, updated ast.Expr) {
500 // Update the expression
501 target.SetKindCase(updated)
502
503 // Early return if there's no macros present sa the source info reflects the
504 // macro set from the target and updated expressions.
505 if len(opt.sourceInfo.MacroCalls()) == 0 {
506 return
507 }
508 // Determine whether the target expression was a macro.
509 _, targetIsMacro := opt.sourceInfo.GetMacroCall(target.ID())
510
511 // Determine whether the updated expression was a macro.
512 updatedMacro, updatedIsMacro := opt.sourceInfo.GetMacroCall(updated.ID())
513
514 if updatedIsMacro {
515 // If the updated call was a macro, then updated id maps to target id,
516 // and the updated macro moves into the target id slot.
517 opt.sourceInfo.ClearMacroCall(updated.ID())
518 opt.sourceInfo.SetMacroCall(target.ID(), updatedMacro)
519 } else if targetIsMacro {
520 // Otherwise if the target expr was a macro, but is no longer, clear
521 // the macro reference.
522 opt.sourceInfo.ClearMacroCall(target.ID())
523 }
524
525 // Punch holes in the updated value where macros references exist.
526 macroExpr := opt.fac.CopyExpr(target)
527 macroRefVisitor := ast.NewExprVisitor(func(e ast.Expr) {
528 if _, exists := opt.sourceInfo.GetMacroCall(e.ID()); exists {
529 e.SetKindCase(nil)
530 }
531 })
532 ast.PostOrderVisit(macroExpr, macroRefVisitor)
533
534 // Update any references to the expression within a macro
535 macroVisitor := ast.NewExprVisitor(func(call ast.Expr) {
536 // Update the target expression to point to the macro expression which
537 // will be empty if the updated expression was a macro.
538 if call.ID() == target.ID() {
539 call.SetKindCase(opt.fac.CopyExpr(macroExpr))
540 }
541 // Update the macro call expression if it refers to the updated expression
542 // id which has since been remapped to the target id.
543 if call.ID() == updated.ID() {
544 // Either ensure the expression is a macro reference or a populated with
545 // the relevant sub-expression if the updated expr was not a macro.
546 if updatedIsMacro {
547 call.SetKindCase(nil)
548 } else {
549 call.SetKindCase(opt.fac.CopyExpr(macroExpr))
550 }
551 // Since SetKindCase does not renumber the id, ensure the references to
552 // the old 'updated' id are mapped to the target id.
553 call.RenumberIDs(func(id int64) int64 {
554 if id == updated.ID() {
555 return target.ID()
556 }
557 return id
558 })
559 }
560 })
561 for _, call := range opt.sourceInfo.MacroCalls() {
562 ast.PostOrderVisit(call, macroVisitor)
563 }
564 }
565
566 func (opt *optimizerExprFactory) sanitizeMacro(macroID int64, macroExpr ast.Expr) {
567 macroRefVisitor := ast.NewExprVisitor(func(e ast.Expr) {
568 if _, exists := opt.sourceInfo.GetMacroCall(e.ID()); exists && e.ID() != macroID {
569 e.SetKindCase(nil)
570 }
571 })
572 ast.PostOrderVisit(macroExpr, macroRefVisitor)
573 }