| 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 |
"github.com/google/cel-go/common/ast" |
| 19 |
"github.com/google/cel-go/common/containers" |
| 20 |
"github.com/google/cel-go/common/operators" |
| 21 |
"github.com/google/cel-go/common/overloads" |
| 22 |
"github.com/google/cel-go/common/types" |
| 23 |
"github.com/google/cel-go/common/types/traits" |
| 24 |
) |
| 25 |
|
| 26 |
// InlineVariable holds a variable name to be matched and an AST representing |
| 27 |
// the expression graph which should be used to replace it. |
| 28 |
type InlineVariable struct { |
| 29 |
name string |
| 30 |
alias string |
| 31 |
def *ast.AST |
| 32 |
} |
| 33 |
|
| 34 |
// Name returns the qualified variable or field selection to replace. |
| 35 |
func (v *InlineVariable) Name() string { |
| 36 |
return v.name |
| 37 |
} |
| 38 |
|
| 39 |
// Alias returns the alias to use when performing cel.bind() calls during inlining. |
| 40 |
func (v *InlineVariable) Alias() string { |
| 41 |
return v.alias |
| 42 |
} |
| 43 |
|
| 44 |
// Expr returns the inlined expression value. |
| 45 |
func (v *InlineVariable) Expr() ast.Expr { |
| 46 |
return v.def.Expr() |
| 47 |
} |
| 48 |
|
| 49 |
// Type indicates the inlined expression type. |
| 50 |
func (v *InlineVariable) Type() *Type { |
| 51 |
return v.def.GetType(v.def.Expr().ID()) |
| 52 |
} |
| 53 |
|
| 54 |
// NewInlineVariable declares a variable name to be replaced by a checked expression. |
| 55 |
func NewInlineVariable(name string, definition *Ast) *InlineVariable { |
| 56 |
return NewInlineVariableWithAlias(name, name, definition) |
| 57 |
} |
| 58 |
|
| 59 |
// NewInlineVariableWithAlias declares a variable name to be replaced by a checked expression. |
| 60 |
// If the variable occurs more than once, the provided alias will be used to replace the expressions |
| 61 |
// where the variable name occurs. |
| 62 |
func NewInlineVariableWithAlias(name, alias string, definition *Ast) *InlineVariable { |
| 63 |
return &InlineVariable{name: name, alias: alias, def: definition.NativeRep()} |
| 64 |
} |
| 65 |
|
| 66 |
// NewInliningOptimizer creates and optimizer which replaces variables with expression definitions. |
| 67 |
// |
| 68 |
// If a variable occurs one time, the variable is replaced by the inline definition. If the |
| 69 |
// variable occurs more than once, the variable occurences are replaced by a cel.bind() call. |
| 70 |
func NewInliningOptimizer(inlineVars ...*InlineVariable) ASTOptimizer { |
| 71 |
return &inliningOptimizer{variables: inlineVars} |
| 72 |
} |
| 73 |
|
| 74 |
type inliningOptimizer struct { |
| 75 |
variables []*InlineVariable |
| 76 |
} |
| 77 |
|
| 78 |
func (opt *inliningOptimizer) Optimize(ctx *OptimizerContext, a *ast.AST) *ast.AST { |
| 79 |
root := ast.NavigateAST(a) |
| 80 |
for _, inlineVar := range opt.variables { |
| 81 |
matches := ast.MatchDescendants(root, opt.matchVariable(inlineVar.Name())) |
| 82 |
// Skip cases where the variable isn't in the expression graph |
| 83 |
if len(matches) == 0 { |
| 84 |
continue |
| 85 |
} |
| 86 |
|
| 87 |
// For a single match, do a direct replacement of the expression sub-graph. |
| 88 |
if len(matches) == 1 || !isBindable(matches, inlineVar.Expr(), inlineVar.Type()) { |
| 89 |
for _, match := range matches { |
| 90 |
// Copy the inlined AST expr and source info. |
| 91 |
copyExpr := ctx.CopyASTAndMetadata(inlineVar.def) |
| 92 |
opt.inlineExpr(ctx, match, copyExpr, inlineVar.Type()) |
| 93 |
} |
| 94 |
continue |
| 95 |
} |
| 96 |
|
| 97 |
// For multiple matches, find the least common ancestor (lca) and insert the |
| 98 |
// variable as a cel.bind() macro. |
| 99 |
var lca ast.NavigableExpr = root |
| 100 |
lcaAncestorCount := 0 |
| 101 |
ancestors := map[int64]int{} |
| 102 |
for _, match := range matches { |
| 103 |
// Update the identifier matches with the provided alias. |
| 104 |
parent, found := match, true |
| 105 |
for found { |
| 106 |
ancestorCount, hasAncestor := ancestors[parent.ID()] |
| 107 |
if !hasAncestor { |
| 108 |
ancestors[parent.ID()] = 1 |
| 109 |
parent, found = parent.Parent() |
| 110 |
continue |
| 111 |
} |
| 112 |
if lcaAncestorCount < ancestorCount || (lcaAncestorCount == ancestorCount && lca.Depth() < parent.Depth()) { |
| 113 |
lca = parent |
| 114 |
lcaAncestorCount = ancestorCount |
| 115 |
} |
| 116 |
ancestors[parent.ID()] = ancestorCount + 1 |
| 117 |
parent, found = parent.Parent() |
| 118 |
} |
| 119 |
aliasExpr := ctx.NewIdent(inlineVar.Alias()) |
| 120 |
opt.inlineExpr(ctx, match, aliasExpr, inlineVar.Type()) |
| 121 |
} |
| 122 |
|
| 123 |
// Copy the inlined AST expr and source info. |
| 124 |
copyExpr := ctx.CopyASTAndMetadata(inlineVar.def) |
| 125 |
// Update the least common ancestor by inserting a cel.bind() call to the alias. |
| 126 |
inlined, bindMacro := ctx.NewBindMacro(lca.ID(), inlineVar.Alias(), copyExpr, lca) |
| 127 |
opt.inlineExpr(ctx, lca, inlined, inlineVar.Type()) |
| 128 |
ctx.SetMacroCall(lca.ID(), bindMacro) |
| 129 |
} |
| 130 |
return a |
| 131 |
} |
| 132 |
|
| 133 |
// inlineExpr replaces the current expression with the inlined one, unless the location of the inlining |
| 134 |
// happens within a presence test, e.g. has(a.b.c) -> inline alpha for a.b.c in which case an attempt is |
| 135 |
// made to determine whether the inlined value can be presence or existence tested. |
| 136 |
func (opt *inliningOptimizer) inlineExpr(ctx *OptimizerContext, prev ast.NavigableExpr, inlined ast.Expr, inlinedType *Type) { |
| 137 |
switch prev.Kind() { |
| 138 |
case ast.SelectKind: |
| 139 |
sel := prev.AsSelect() |
| 140 |
if !sel.IsTestOnly() { |
| 141 |
ctx.UpdateExpr(prev, inlined) |
| 142 |
return |
| 143 |
} |
| 144 |
opt.rewritePresenceExpr(ctx, prev, inlined, inlinedType) |
| 145 |
default: |
| 146 |
ctx.UpdateExpr(prev, inlined) |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
// rewritePresenceExpr converts the inlined expression, when it occurs within a has() macro, to type-safe |
| 151 |
// expression appropriate for the inlined type, if possible. |
| 152 |
// |
| 153 |
// If the rewrite is not possible an error is reported at the inline expression site. |
| 154 |
func (opt *inliningOptimizer) rewritePresenceExpr(ctx *OptimizerContext, prev, inlined ast.Expr, inlinedType *Type) { |
| 155 |
// If the input inlined expression is not a select expression it won't work with the has() |
| 156 |
// macro. Attempt to rewrite the presence test in terms of the typed input, otherwise error. |
| 157 |
if inlined.Kind() == ast.SelectKind { |
| 158 |
presenceTest, hasMacro := ctx.NewHasMacro(prev.ID(), inlined) |
| 159 |
ctx.UpdateExpr(prev, presenceTest) |
| 160 |
ctx.SetMacroCall(prev.ID(), hasMacro) |
| 161 |
return |
| 162 |
} |
| 163 |
|
| 164 |
ctx.ClearMacroCall(prev.ID()) |
| 165 |
if inlinedType.IsAssignableType(NullType) { |
| 166 |
ctx.UpdateExpr(prev, |
| 167 |
ctx.NewCall(operators.NotEquals, |
| 168 |
inlined, |
| 169 |
ctx.NewLiteral(types.NullValue), |
| 170 |
)) |
| 171 |
return |
| 172 |
} |
| 173 |
if inlinedType.HasTrait(traits.SizerType) { |
| 174 |
ctx.UpdateExpr(prev, |
| 175 |
ctx.NewCall(operators.NotEquals, |
| 176 |
ctx.NewMemberCall(overloads.Size, inlined), |
| 177 |
ctx.NewLiteral(types.IntZero), |
| 178 |
)) |
| 179 |
return |
| 180 |
} |
| 181 |
ctx.ReportErrorAtID(prev.ID(), "unable to inline expression type %v into presence test", inlinedType) |
| 182 |
} |
| 183 |
|
| 184 |
// isBindable indicates whether the inlined type can be used within a cel.bind() if the expression |
| 185 |
// being replaced occurs within a presence test. Value types with a size() method or field selection |
| 186 |
// support can be bound. |
| 187 |
// |
| 188 |
// In future iterations, support may also be added for indexer types which can be rewritten as an `in` |
| 189 |
// expression; however, this would imply a rewrite of the inlined expression that may not be necessary |
| 190 |
// in most cases. |
| 191 |
func isBindable(matches []ast.NavigableExpr, inlined ast.Expr, inlinedType *Type) bool { |
| 192 |
if inlinedType.IsAssignableType(NullType) || |
| 193 |
inlinedType.HasTrait(traits.SizerType) { |
| 194 |
return true |
| 195 |
} |
| 196 |
for _, m := range matches { |
| 197 |
if m.Kind() != ast.SelectKind { |
| 198 |
continue |
| 199 |
} |
| 200 |
sel := m.AsSelect() |
| 201 |
if sel.IsTestOnly() { |
| 202 |
return false |
| 203 |
} |
| 204 |
} |
| 205 |
return true |
| 206 |
} |
| 207 |
|
| 208 |
// matchVariable matches simple identifiers, select expressions, and presence test expressions |
| 209 |
// which match the (potentially) qualified variable name provided as input. |
| 210 |
// |
| 211 |
// Note, this function does not support inlining against select expressions which includes optional |
| 212 |
// field selection. This may be a future refinement. |
| 213 |
func (opt *inliningOptimizer) matchVariable(varName string) ast.ExprMatcher { |
| 214 |
return func(e ast.NavigableExpr) bool { |
| 215 |
if e.Kind() == ast.IdentKind && e.AsIdent() == varName { |
| 216 |
return true |
| 217 |
} |
| 218 |
if e.Kind() == ast.SelectKind { |
| 219 |
sel := e.AsSelect() |
| 220 |
// While the `ToQualifiedName` call could take the select directly, this |
| 221 |
// would skip presence tests from possible matches, which we would like |
| 222 |
// to include. |
| 223 |
qualName, found := containers.ToQualifiedName(sel.Operand()) |
| 224 |
return found && qualName+"."+sel.FieldName() == varName |
| 225 |
} |
| 226 |
return false |
| 227 |
} |
| 228 |
} |