Debian Codegraph @

ext/bindings.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 ext
16
17 import (
18 "errors"
19 "fmt"
20 "math"
21 "strconv"
22 "strings"
23 "sync"
24
25 "github.com/google/cel-go/cel"
26 "github.com/google/cel-go/common/ast"
27 "github.com/google/cel-go/common/types"
28 "github.com/google/cel-go/common/types/ref"
29 "github.com/google/cel-go/common/types/traits"
30 "github.com/google/cel-go/interpreter"
31 )
32
33 // Bindings returns a cel.EnvOption to configure support for local variable
34 // bindings in expressions.
35 //
36 // # Cel.Bind
37 //
38 // Binds a simple identifier to an initialization expression which may be used
39 // in a subsequenct result expression. Bindings may also be nested within each
40 // other.
41 //
42 // cel.bind(<varName>, <initExpr>, <resultExpr>)
43 //
44 // Examples:
45 //
46 // cel.bind(a, 'hello',
47 // cel.bind(b, 'world', a + b + b + a)) // "helloworldworldhello"
48 //
49 // // Avoid a list allocation within the exists comprehension.
50 // cel.bind(valid_values, [a, b, c],
51 // [d, e, f].exists(elem, elem in valid_values))
52 //
53 // Local bindings are not guaranteed to be evaluated before use.
54 func Bindings(options ...BindingsOption) cel.EnvOption {
55 b := &celBindings{version: math.MaxUint32}
56 for _, o := range options {
57 b = o(b)
58 }
59 return cel.Lib(b)
60 }
61
62 const (
63 celNamespace = "cel"
64 bindMacro = "bind"
65 blockFunc = "@block"
66 unusedIterVar = "#unused"
67 )
68
69 // BindingsOption declares a functional operator for configuring the Bindings library behavior.
70 type BindingsOption func(*celBindings) *celBindings
71
72 // BindingsVersion sets the version of the bindings library to an explicit version.
73 func BindingsVersion(version uint32) BindingsOption {
74 return func(lib *celBindings) *celBindings {
75 lib.version = version
76 return lib
77 }
78 }
79
80 type celBindings struct {
81 version uint32
82 }
83
84 func (*celBindings) LibraryName() string {
85 return "cel.lib.ext.cel.bindings"
86 }
87
88 func (lib *celBindings) CompileOptions() []cel.EnvOption {
89 opts := []cel.EnvOption{
90 cel.Macros(
91 // cel.bind(var, <init>, <expr>)
92 cel.ReceiverMacro(bindMacro, 3, celBind),
93 ),
94 }
95 if lib.version >= 1 {
96 // The cel.@block signature takes a list of subexpressions and a typed expression which is
97 // used as the output type.
98 paramType := cel.TypeParamType("T")
99 opts = append(opts,
100 cel.Function("cel.@block",
101 cel.Overload("cel_block_list",
102 []*cel.Type{cel.ListType(cel.DynType), paramType}, paramType)),
103 )
104 opts = append(opts, cel.ASTValidators(blockValidationExemption{}))
105 }
106 return opts
107 }
108
109 func (lib *celBindings) ProgramOptions() []cel.ProgramOption {
110 if lib.version >= 1 {
111 celBlockPlan := func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
112 call, ok := i.(interpreter.InterpretableCall)
113 if !ok {
114 return i, nil
115 }
116 switch call.Function() {
117 case "cel.@block":
118 args := call.Args()
119 if len(args) != 2 {
120 return nil, fmt.Errorf("cel.@block expects two arguments, but got %d", len(args))
121 }
122 expr := args[1]
123 // Non-empty block
124 if block, ok := args[0].(interpreter.InterpretableConstructor); ok {
125 slotExprs := block.InitVals()
126 return newDynamicBlock(slotExprs, expr), nil
127 }
128 // Constant valued block which can happen during runtime optimization.
129 if cons, ok := args[0].(interpreter.InterpretableConst); ok {
130 if cons.Value().Type() == types.ListType {
131 l := cons.Value().(traits.Lister)
132 if l.Size().Equal(types.IntZero) == types.True {
133 return args[1], nil
134 }
135 return newConstantBlock(l, expr), nil
136 }
137 }
138 return nil, errors.New("cel.@block expects a list constructor as the first argument")
139 default:
140 return i, nil
141 }
142 }
143 return []cel.ProgramOption{cel.CustomDecorator(celBlockPlan)}
144 }
145 return []cel.ProgramOption{}
146 }
147
148 type blockValidationExemption struct{}
149
150 // Name returns the name of the validator.
151 func (blockValidationExemption) Name() string {
152 return "cel.validator.cel_block"
153 }
154
155 // Configure implements the ASTValidatorConfigurer interface and augments the list of functions to skip
156 // during homogeneous aggregate literal type-checks.
157 func (blockValidationExemption) Configure(config cel.MutableValidatorConfig) error {
158 functions := config.GetOrDefault(cel.HomogeneousAggregateLiteralExemptFunctions, []string{}).([]string)
159 functions = append(functions, "cel.@block")
160 return config.Set(cel.HomogeneousAggregateLiteralExemptFunctions, functions)
161 }
162
163 // Validate is a no-op as the intent is to simply disable strong type-checks for list literals during
164 // when they occur within cel.@block calls as the arg types have already been validated.
165 func (blockValidationExemption) Validate(env *cel.Env, _ cel.ValidatorConfig, a *ast.AST, iss *cel.Issues) {
166 }
167
168 func celBind(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) {
169 if !macroTargetMatchesNamespace(celNamespace, target) {
170 return nil, nil
171 }
172 varIdent := args[0]
173 varName := ""
174 switch varIdent.Kind() {
175 case ast.IdentKind:
176 varName = varIdent.AsIdent()
177 default:
178 return nil, mef.NewError(varIdent.ID(), "cel.bind() variable names must be simple identifiers")
179 }
180 varInit := args[1]
181 resultExpr := args[2]
182 return mef.NewComprehension(
183 mef.NewList(),
184 unusedIterVar,
185 varName,
186 varInit,
187 mef.NewLiteral(types.False),
188 mef.NewIdent(varName),
189 resultExpr,
190 ), nil
191 }
192
193 func newDynamicBlock(slotExprs []interpreter.Interpretable, expr interpreter.Interpretable) interpreter.Interpretable {
194 bs := &dynamicBlock{
195 slotExprs: slotExprs,
196 expr: expr,
197 }
198 bs.slotActivationPool = &sync.Pool{
199 New: func() any {
200 slotCount := len(slotExprs)
201 sa := &dynamicSlotActivation{
202 slotExprs: slotExprs,
203 slotCount: slotCount,
204 slotVals: make([]*slotVal, slotCount),
205 }
206 for i := 0; i < slotCount; i++ {
207 sa.slotVals[i] = &slotVal{}
208 }
209 return sa
210 },
211 }
212 return bs
213 }
214
215 type dynamicBlock struct {
216 slotExprs []interpreter.Interpretable
217 expr interpreter.Interpretable
218 slotActivationPool *sync.Pool
219 }
220
221 // ID implements the Interpretable interface method.
222 func (b *dynamicBlock) ID() int64 {
223 return b.expr.ID()
224 }
225
226 // Eval implements the Interpretable interface method.
227 func (b *dynamicBlock) Eval(activation cel.Activation) ref.Val {
228 sa := b.slotActivationPool.Get().(*dynamicSlotActivation)
229 sa.Activation = activation
230 defer b.clearSlots(sa)
231 return b.expr.Eval(sa)
232 }
233
234 func (b *dynamicBlock) clearSlots(sa *dynamicSlotActivation) {
235 sa.reset()
236 b.slotActivationPool.Put(sa)
237 }
238
239 type slotVal struct {
240 value *ref.Val
241 visited bool
242 }
243
244 type dynamicSlotActivation struct {
245 cel.Activation
246 slotExprs []interpreter.Interpretable
247 slotCount int
248 slotVals []*slotVal
249 }
250
251 // Unwrap returns the underlying activation.
252 func (sa *dynamicSlotActivation) Unwrap() cel.Activation {
253 return sa.Activation
254 }
255
256 // ResolveName implements the Activation interface method but handles variables prefixed with `@index`
257 // as special variables which exist within the slot-based memory of the cel.@block() where each slot
258 // refers to an expression which must be computed only once.
259 func (sa *dynamicSlotActivation) ResolveName(name string) (any, bool) {
260 if idx, found := matchSlot(name, sa.slotCount); found {
261 v := sa.slotVals[idx]
262 if v.visited {
263 // Return not found if the index expression refers to itself
264 if v.value == nil {
265 return nil, false
266 }
267 return *v.value, true
268 }
269 v.visited = true
270 val := sa.slotExprs[idx].Eval(sa)
271 v.value = &val
272 return val, true
273 }
274 return sa.Activation.ResolveName(name)
275 }
276
277 func (sa *dynamicSlotActivation) reset() {
278 sa.Activation = nil
279 for _, sv := range sa.slotVals {
280 sv.visited = false
281 sv.value = nil
282 }
283 }
284
285 func newConstantBlock(slots traits.Lister, expr interpreter.Interpretable) interpreter.Interpretable {
286 count := slots.Size().(types.Int)
287 return &constantBlock{slots: slots, slotCount: int(count), expr: expr}
288 }
289
290 type constantBlock struct {
291 slots traits.Lister
292 slotCount int
293 expr interpreter.Interpretable
294 }
295
296 // ID implements the interpreter.Interpretable interface method.
297 func (b *constantBlock) ID() int64 {
298 return b.expr.ID()
299 }
300
301 // Eval implements the interpreter.Interpretable interface method, and will proxy @index prefixed variable
302 // lookups into a set of constant slots determined from the plan step.
303 func (b *constantBlock) Eval(activation cel.Activation) ref.Val {
304 vars := constantSlotActivation{Activation: activation, slots: b.slots, slotCount: b.slotCount}
305 return b.expr.Eval(vars)
306 }
307
308 type constantSlotActivation struct {
309 cel.Activation
310 slots traits.Lister
311 slotCount int
312 }
313
314 // Unwrap returns the underlying activation.
315 func (sa *constantSlotActivation) Unwrap() cel.Activation {
316 return sa.Activation
317 }
318
319 // ResolveName implements Activation interface method and proxies @index prefixed lookups into the slot
320 // activation associated with the block scope.
321 func (sa constantSlotActivation) ResolveName(name string) (any, bool) {
322 if idx, found := matchSlot(name, sa.slotCount); found {
323 return sa.slots.Get(types.Int(idx)), true
324 }
325 return sa.Activation.ResolveName(name)
326 }
327
328 func matchSlot(name string, slotCount int) (int, bool) {
329 if idx, found := strings.CutPrefix(name, indexPrefix); found {
330 idx, err := strconv.Atoi(idx)
331 // Return not found if the index is not numeric
332 if err != nil {
333 return -1, false
334 }
335 // Return not found if the index is not a valid slot
336 if idx < 0 || idx >= slotCount {
337 return -1, false
338 }
339 return idx, true
340 }
341 return -1, false
342 }
343
344 var (
345 indexPrefix = "@index"
346 )