Debian Codegraph @

repl/evaluator.go

raw symbols SCIP
1 // Copyright 2022 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 // https://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 repl defines a set of utilities for working with command line processing of CEL.
16 package repl
17
18 import (
19 "errors"
20 "fmt"
21 "os"
22 "regexp"
23 "sort"
24 "strings"
25
26 "github.com/google/cel-go/cel"
27 "github.com/google/cel-go/checker/decls"
28 "github.com/google/cel-go/common/env"
29 "github.com/google/cel-go/common/functions"
30 "github.com/google/cel-go/common/types"
31 "github.com/google/cel-go/common/types/ref"
32 "github.com/google/cel-go/ext"
33
34 "google.golang.org/protobuf/encoding/prototext"
35 "google.golang.org/protobuf/proto"
36 "google.golang.org/protobuf/reflect/protodesc"
37 "google.golang.org/protobuf/reflect/protoreflect"
38
39 "go.yaml.in/yaml/v3"
40
41 test2pb "cel.dev/expr/conformance/proto2"
42 test3pb "cel.dev/expr/conformance/proto3"
43 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
44 attrpb "google.golang.org/genproto/googleapis/rpc/context/attribute_context"
45 descpb "google.golang.org/protobuf/types/descriptorpb"
46 )
47
48 var (
49 extensionMap = map[string]cel.EnvOption{
50 "optional": cel.OptionalTypes(),
51 "bindings": ext.Bindings(),
52 "strings": ext.Strings(),
53 "protos": ext.Protos(),
54 "math": ext.Math(),
55 "encoders": ext.Encoders(),
56 "sets": ext.Sets(),
57 "lists": ext.Lists(),
58 "two_var_comprehensions": ext.TwoVarComprehensions(),
59 }
60 )
61
62 // letVariable let variable representation
63 type letVariable struct {
64 identifier string
65 src string
66 typeHint *exprpb.Type
67
68 // memoized results from building the expression AST and program
69 resultType *exprpb.Type
70 env *cel.Env
71 ast *cel.Ast
72 prog cel.Program
73 }
74
75 type letFunctionParam struct {
76 identifier string
77 typeHint *exprpb.Type
78 }
79
80 // letFunction coordinates let function data (type definition and CEL function implementation).
81 type letFunction struct {
82 identifier string
83 src string
84 resultType *exprpb.Type
85 params []letFunctionParam
86 receiver *exprpb.Type // if not nil indicates an instance function
87
88 // memoized results from building the expression AST and program
89 env *cel.Env // the context env for repl evaluation
90 fnEnv *cel.Env // the env for implementing the extension fn
91 prog cel.Program
92 impl functions.FunctionOp
93 }
94
95 func typeAssignable(rtType ref.Type, declType *exprpb.Type) bool {
96 // TODO(issue/535): add better type agreement support
97 return UnparseType(declType) == rtType.TypeName()
98 }
99
100 func checkArgsMatch(params []letFunctionParam, args []ref.Val) error {
101 if len(params) != len(args) {
102 return fmt.Errorf("got %d args, expected %d", len(args), len(params))
103 }
104 for i, arg := range args {
105 if !typeAssignable(arg.Type(), params[i].typeHint) {
106 return fmt.Errorf("got %s, expected %s for argument %d", arg.Type().TypeName(), UnparseType(params[i].typeHint), i)
107 }
108 }
109 return nil
110 }
111
112 func (l *letFunction) updateImpl(env *cel.Env, deps []*functions.Overload) error {
113 var paramVars []*exprpb.Decl
114
115 if l.receiver != nil {
116 paramVars = append(paramVars, decls.NewVar("this", l.receiver))
117 }
118
119 for _, p := range l.params {
120 paramVars = append(paramVars, decls.NewVar(p.identifier, p.typeHint))
121 }
122
123 var err error
124 l.fnEnv, err = env.Extend(cel.Declarations(paramVars...))
125 if err != nil {
126 return err
127 }
128
129 ast, iss := l.fnEnv.Compile(l.src)
130
131 if iss != nil {
132 return iss.Err()
133 }
134
135 if !proto.Equal(ast.ResultType(), l.resultType) {
136 return fmt.Errorf("got result type %s for %s", UnparseType(ast.ResultType()), l)
137 }
138
139 l.prog, err = l.fnEnv.Program(ast, cel.Functions(deps...))
140
141 if err != nil {
142 return err
143 }
144
145 l.impl = func(args ...ref.Val) ref.Val {
146 var err error
147 var instance ref.Val
148 if l.receiver != nil {
149 instance = args[0]
150 args = args[1:]
151 }
152 err = checkArgsMatch(l.params, args)
153 if err != nil {
154 return types.NewErr("error evaluating %s: %v", l, err)
155 }
156
157 activation := make(map[string]any)
158 for i, param := range l.params {
159 activation[param.identifier] = args[i]
160 }
161
162 if instance != nil {
163 if !typeAssignable(instance.Type(), l.receiver) {
164 return types.NewErr("error evaluating %s: got receiver type: %s wanted %s", l, instance.Type().TypeName(), UnparseType(l.receiver))
165 }
166 activation["this"] = instance
167 }
168
169 val, _, err := l.prog.Eval(activation)
170
171 if err != nil {
172 return types.NewErr("error evaluating %s: %v", l, err)
173 }
174
175 return val
176 }
177 return nil
178 }
179
180 func (l *letFunction) update(env *cel.Env, deps []*functions.Overload) error {
181 var err error
182 if l.src != "" {
183 err = l.updateImpl(env, deps)
184 if err != nil {
185 return err
186 }
187 }
188
189 paramTypes := make([]*exprpb.Type, len(l.params))
190 for i, p := range l.params {
191 paramTypes[i] = p.typeHint
192 }
193
194 var opt cel.EnvOption
195 if l.receiver != nil {
196 paramTypes = append([]*exprpb.Type{l.receiver}, paramTypes...)
197 opt = cel.Declarations(
198 decls.NewFunction(l.identifier,
199 decls.NewInstanceOverload(
200 l.identifier,
201 paramTypes,
202 l.resultType,
203 )))
204 } else {
205 opt = cel.Declarations(
206 decls.NewFunction(
207 l.identifier,
208 decls.NewOverload(l.identifier,
209 paramTypes,
210 l.resultType)))
211 }
212
213 l.env, err = env.Extend(opt)
214 if err != nil {
215 return err
216 }
217
218 return nil
219 }
220
221 func (l letVariable) String() string {
222 return fmt.Sprintf("%s = %s", l.identifier, l.src)
223 }
224
225 func formatParams(params []letFunctionParam) string {
226 fmtParams := make([]string, len(params))
227
228 for i, p := range params {
229 fmtParams[i] = fmt.Sprintf("%s: %s", p.identifier, UnparseType(p.typeHint))
230 }
231
232 return fmt.Sprintf("(%s)", strings.Join(fmtParams, ", "))
233 }
234
235 func (l letFunction) String() string {
236 receiverFmt := ""
237 if l.receiver != nil {
238 receiverFmt = fmt.Sprintf("%s.", UnparseType(l.receiver))
239 }
240
241 return fmt.Sprintf("%s%s%s : %s -> %s", receiverFmt, l.identifier, formatParams(l.params), UnparseType(l.resultType), l.src)
242 }
243
244 func (l *letFunction) generateFunction() *functions.Overload {
245 argLen := len(l.params)
246 if l.receiver != nil {
247 argLen++
248 }
249 switch argLen {
250 case 1:
251 return &functions.Overload{
252 Operator: l.identifier,
253 Unary: func(v ref.Val) ref.Val { return l.impl(v) },
254 }
255 case 2:
256 return &functions.Overload{
257 Operator: l.identifier,
258 Binary: func(lhs ref.Val, rhs ref.Val) ref.Val { return l.impl(lhs, rhs) },
259 }
260 default:
261 return &functions.Overload{
262 Operator: l.identifier,
263 Function: l.impl,
264 }
265 }
266 }
267
268 // Reset plan if we need to recompile based on a dependency change.
269 func (l *letVariable) clearPlan() {
270 l.resultType = nil
271 l.env = nil
272 l.ast = nil
273 l.prog = nil
274 }
275
276 // Optioner interface represents an option set on the base CEL environment used by
277 // the evaluator.
278 type Optioner interface {
279 // Option returns the cel.EnvOption that should be applied to the
280 // environment.
281 Option() cel.EnvOption
282 }
283
284 type contextOption struct {
285 opt Optioner
286 // True if the option is captured by a yaml config.
287 yaml bool
288 }
289
290 type genericOption struct {
291 envOpt cel.EnvOption
292 }
293
294 func (o *genericOption) String() string {
295 return "// unsupported %configure option. see:\n" +
296 "// %status --yaml"
297 }
298
299 func (o *genericOption) Option() cel.EnvOption {
300 return o.envOpt
301 }
302
303 // EvaluationContext context for the repl.
304 // Handles maintaining state for multiple let expressions.
305 type EvaluationContext struct {
306 letVars []letVariable
307 letFns []letFunction
308 options []contextOption
309 enablePartialEval bool
310 }
311
312 func (ctx *EvaluationContext) indexLetVar(name string) int {
313 for idx, el := range ctx.letVars {
314 if el.identifier == name {
315 return idx
316 }
317 }
318 return -1
319 }
320
321 func (ctx *EvaluationContext) getEffectiveEnv(env *cel.Env) *cel.Env {
322 if len(ctx.letVars) > 0 {
323 env = ctx.letVars[len(ctx.letVars)-1].env
324 } else if len(ctx.letFns) > 0 {
325 env = ctx.letFns[len(ctx.letFns)-1].env
326 } else if len(ctx.options) > 0 {
327 for _, opt := range ctx.options {
328 env, _ = env.Extend(opt.opt.Option())
329 }
330 }
331
332 return env
333 }
334
335 func (ctx *EvaluationContext) indexLetFn(name string) int {
336 for idx, el := range ctx.letFns {
337 if el.identifier == name {
338 return idx
339 }
340 }
341 return -1
342 }
343
344 func (ctx *EvaluationContext) copy() *EvaluationContext {
345 var cpy EvaluationContext
346 cpy.options = make([]contextOption, len(ctx.options))
347 copy(cpy.options, ctx.options)
348 cpy.letVars = make([]letVariable, len(ctx.letVars))
349 copy(cpy.letVars, ctx.letVars)
350 cpy.letFns = make([]letFunction, len(ctx.letFns))
351 copy(cpy.letFns, ctx.letFns)
352 cpy.enablePartialEval = ctx.enablePartialEval
353 return &cpy
354 }
355
356 func (ctx *EvaluationContext) delLetVar(name string) {
357 idx := ctx.indexLetVar(name)
358 if idx < 0 {
359 // no-op if deleting something that's not defined
360 return
361 }
362
363 ctx.letVars = append(ctx.letVars[:idx], ctx.letVars[idx+1:]...)
364
365 for i := idx; i < len(ctx.letVars); i++ {
366 ctx.letVars[i].clearPlan()
367 }
368 }
369
370 func (ctx *EvaluationContext) delLetFn(name string) {
371 idx := ctx.indexLetFn(name)
372 if idx < 0 {
373 // no-op if deleting something that's not defined
374 return
375 }
376
377 ctx.letFns = append(ctx.letFns[:idx], ctx.letFns[idx+1:]...)
378
379 for i := range ctx.letVars {
380 ctx.letVars[i].clearPlan()
381 }
382 }
383
384 // Add or update an existing let then invalidate any computed plans.
385 func (ctx *EvaluationContext) addLetVar(name string, expr string, typeHint *exprpb.Type) {
386 idx := ctx.indexLetVar(name)
387 newVar := letVariable{identifier: name, src: expr, typeHint: typeHint}
388 if idx < 0 {
389 ctx.letVars = append(ctx.letVars, newVar)
390 } else {
391 ctx.letVars[idx] = newVar
392 for i := idx + 1; i < len(ctx.letVars); i++ {
393 // invalidate dependant let exprs
394 ctx.letVars[i].clearPlan()
395 }
396 }
397 }
398
399 // Try to normalize a defined function name as either a namespaced function or a receiver call.
400 func (ctx *EvaluationContext) resolveFn(name string) (string, *exprpb.Type) {
401 leadingDot := ""
402 id := name
403 if strings.HasPrefix(name, ".") {
404 id = strings.TrimLeft(name, ".")
405 leadingDot = "."
406 }
407 qualifiers := strings.Split(id, ".")
408 if len(qualifiers) == 1 {
409 return qualifiers[0], nil
410 }
411
412 namespace := strings.Join(qualifiers[:len(qualifiers)-1], ".")
413 id = qualifiers[len(qualifiers)-1]
414
415 maybeType, err := ParseType(leadingDot + namespace)
416 if err != nil {
417 return name, nil
418 }
419
420 switch maybeType.TypeKind.(type) {
421 // unsupported type assume it's just namespaced
422 case *exprpb.Type_AbstractType_:
423 case *exprpb.Type_MessageType:
424 case *exprpb.Type_Error:
425 case *exprpb.Type_Function:
426 default:
427 return id, maybeType
428 }
429
430 return name, nil
431 }
432
433 // Add or update an existing let then invalidate any computed plans.
434 func (ctx *EvaluationContext) addLetFn(name string, params []letFunctionParam, resultType *exprpb.Type, expr string) {
435 name, receiver := ctx.resolveFn(name)
436 idx := ctx.indexLetFn(name)
437 newFn := letFunction{identifier: name, params: params, receiver: receiver, resultType: resultType, src: expr}
438 if idx < 0 {
439 ctx.letFns = append(ctx.letFns, newFn)
440 } else {
441 ctx.letFns[idx] = newFn
442 }
443
444 for i := 0; i < len(ctx.letVars); i++ {
445 // invalidate dependant let exprs
446 ctx.letVars[i].clearPlan()
447 }
448 }
449
450 func (ctx *EvaluationContext) addOption(opt Optioner, isYAML bool) {
451 ctx.options = append(ctx.options,
452 contextOption{opt: opt, yaml: isYAML})
453
454 for i := 0; i < len(ctx.letVars); i++ {
455 // invalidate dependant let exprs
456 ctx.letVars[i].clearPlan()
457 }
458 }
459
460 // programOptions generates the program options for planning.
461 // Assumes context has been planned.
462 func (ctx *EvaluationContext) programOptions() []cel.ProgramOption {
463 var fns = make([]*functions.Overload, len(ctx.letFns))
464 for i, fn := range ctx.letFns {
465 fns[i] = fn.generateFunction()
466 }
467 result := []cel.ProgramOption{cel.Functions(fns...)}
468 if ctx.enablePartialEval {
469 result = append(result, cel.EvalOptions(cel.OptPartialEval))
470 }
471 return result
472 }
473
474 // Evaluator provides basic environment for evaluating an expression with
475 // applied context.
476 type Evaluator struct {
477 env *cel.Env
478 ctx EvaluationContext
479 }
480
481 // NewEvaluator returns an inialized evaluator
482 func NewEvaluator() (*Evaluator, error) {
483 env, err := cel.NewEnv(cel.EnableMacroCallTracking())
484 if err != nil {
485 return nil, err
486 }
487
488 return &Evaluator{env: env}, nil
489 }
490
491 // Attempt to update context in place after an update.
492 // This is done eagerly to help avoid introducing an invalid 'let' expression.
493 // The planned expressions are evaluated as needed when evaluating a (non-let) CEL expression.
494 // Return an error if any of the updates fail.
495 func updateContextPlans(ctx *EvaluationContext, env *cel.Env) error {
496 for _, opt := range ctx.options {
497 var err error
498 env, err = env.Extend(opt.opt.Option())
499 if err != nil {
500 return err
501 }
502 }
503 overloads := make([]*functions.Overload, 0)
504 for i := range ctx.letFns {
505 letFn := &ctx.letFns[i]
506 err := letFn.update(env, overloads)
507 if err != nil {
508 return fmt.Errorf("error updating %s: %w", letFn, err)
509 }
510 env = letFn.env
511 // if no src, this is declared but not defined.
512 if letFn.src != "" {
513 overloads = append(overloads, letFn.generateFunction())
514 }
515
516 }
517 for i := range ctx.letVars {
518 el := &ctx.letVars[i]
519 // Check if the let variable has a definition and needs to be re-planned
520 if el.prog == nil && el.src != "" {
521 ast, iss := env.Compile(el.src)
522 if iss != nil {
523 return fmt.Errorf("error updating %v\n%w", el, iss.Err())
524 }
525
526 if el.typeHint != nil && !proto.Equal(ast.ResultType(), el.typeHint) {
527 return fmt.Errorf("error updating %v\ntype mismatch got %v expected %v",
528 el,
529 UnparseType(ast.ResultType()),
530 UnparseType(el.typeHint))
531 }
532
533 el.ast = ast
534 el.resultType = ast.ResultType()
535
536 plan, err := env.Program(ast, ctx.programOptions()...)
537 if err != nil {
538 return err
539 }
540 el.prog = plan
541 } else if el.src == "" {
542 // Variable is declared but not defined, just update the type checking environment
543 el.resultType = el.typeHint
544 }
545 if el.env == nil {
546 env, err := env.Extend(cel.Declarations(decls.NewVar(el.identifier, el.resultType)))
547 if err != nil {
548 return err
549 }
550 el.env = env
551 }
552 env = el.env
553 }
554 return nil
555 }
556
557 // AddLetVar adds a let variable to the evaluation context.
558 // The expression is planned but evaluated lazily.
559 func (e *Evaluator) AddLetVar(name string, expr string, typeHint *exprpb.Type) error {
560 // copy the current context and attempt to update dependant expressions.
561 // if successful, swap the current context with the updated copy.
562 ctx := e.ctx.copy()
563 ctx.addLetVar(name, expr, typeHint)
564 err := updateContextPlans(ctx, e.env)
565 if err != nil {
566 return err
567 }
568 e.ctx = *ctx
569 return nil
570 }
571
572 // AddLetFn adds a let function to the evaluation context.
573 func (e *Evaluator) AddLetFn(name string, params []letFunctionParam, resultType *exprpb.Type, expr string) error {
574 // copy the current context and attempt to update dependant expressions.
575 // if successful, swap the current context with the updated copy.
576 cpy := e.ctx.copy()
577 cpy.addLetFn(name, params, resultType, expr)
578 err := updateContextPlans(cpy, e.env)
579 if err != nil {
580 return err
581 }
582 e.ctx = *cpy
583 return nil
584 }
585
586 // AddDeclVar declares a variable in the environment but doesn't register an expr with it.
587 // This allows planning to succeed, but with no value for the variable at runtime.
588 func (e *Evaluator) AddDeclVar(name string, typeHint *exprpb.Type) error {
589 ctx := e.ctx.copy()
590 ctx.addLetVar(name, "", typeHint)
591 err := updateContextPlans(ctx, e.env)
592 if err != nil {
593 return err
594 }
595 e.ctx = *ctx
596 return nil
597 }
598
599 // AddDeclFn declares a function in the environment but doesn't register an expr with it.
600 // This allows planning to succeed, but with no value for the function at runtime.
601 func (e *Evaluator) AddDeclFn(name string, params []letFunctionParam, typeHint *exprpb.Type) error {
602 ctx := e.ctx.copy()
603 ctx.addLetFn(name, params, typeHint, "")
604 err := updateContextPlans(ctx, e.env)
605 if err != nil {
606 return err
607 }
608 e.ctx = *ctx
609 return nil
610 }
611
612 // AddOption adds an option to the basic environment.
613 // Options are applied before evaluating any of the let statements.
614 // Returns an error if setting the option prevents planning any of the defined let expressions.
615 func (e *Evaluator) AddOption(opt Optioner) error {
616 cpy := e.ctx.copy()
617 cpy.addOption(opt, false)
618 err := updateContextPlans(cpy, e.env)
619 if err != nil {
620 return err
621 }
622 e.ctx = *cpy
623 return nil
624 }
625
626 // AddSerializableOption adds an option to the basic environment that is flagged as YAML compatible.
627 func (e *Evaluator) AddSerializableOption(opt Optioner) error {
628 cpy := e.ctx.copy()
629 cpy.addOption(opt, true)
630 err := updateContextPlans(cpy, e.env)
631 if err != nil {
632 return err
633 }
634 e.ctx = *cpy
635 return nil
636 }
637
638 // EnablePartialEval enables the option to allow partial evaluations.
639 func (e *Evaluator) EnablePartialEval() error {
640 cpy := e.ctx.copy()
641 cpy.enablePartialEval = true
642 err := updateContextPlans(cpy, e.env)
643 if err != nil {
644 return err
645 }
646 e.ctx = *cpy
647 return nil
648 }
649
650 // DelLetVar removes a variable from the evaluation context.
651 // If deleting the variable breaks a later expression, this function will return an error without modifying the context.
652 func (e *Evaluator) DelLetVar(name string) error {
653 ctx := e.ctx.copy()
654 ctx.delLetVar(name)
655 err := updateContextPlans(ctx, e.env)
656 if err != nil {
657 return err
658 }
659 e.ctx = *ctx
660 return nil
661 }
662
663 // DelLetFn removes a function from the evaluation context.
664 // If deleting the function breaks a later expression, this function will return an error without modifying the context.
665 func (e *Evaluator) DelLetFn(name string) error {
666 ctx := e.ctx.copy()
667 ctx.delLetFn(name)
668 err := updateContextPlans(ctx, e.env)
669 if err != nil {
670 return err
671 }
672 e.ctx = *ctx
673 return nil
674 }
675
676 type statusFormat int
677
678 const (
679 statusFormatREPL statusFormat = iota
680 statusFormatYAML
681 statusFomatUnspecfied
682 )
683
684 func (e *Evaluator) handleStatus(args []string) (string, error) {
685 format := statusFormatREPL
686 for _, a := range args {
687 switch a {
688 case "--yaml":
689 format = statusFormatYAML
690 case "--repl":
691 format = statusFormatREPL
692 default:
693 return "", fmt.Errorf("status: unsupported option: '%s'", a)
694 }
695 }
696
697 switch format {
698 case statusFormatREPL:
699 return e.REPLConfig(), nil
700 case statusFormatYAML:
701 return e.YAMLConfig()
702 }
703
704 return "", errors.New("status: unsupported status format requested")
705 }
706
707 func (e *Evaluator) handleConfig(args []string) (string, error) {
708 format := statusFormatREPL
709 var fromFile bool
710 var configRef string
711 for _, a := range args {
712 switch a {
713 case "--yaml":
714 format = statusFormatYAML
715 case "--repl":
716 format = statusFormatREPL
717 case "--file":
718 fromFile = true
719 default:
720 configRef = a
721 }
722 }
723
724 if configRef == "" {
725 return "", errors.New("config: no config provided")
726 }
727 src := []byte(configRef)
728 if fromFile {
729 tmp, err := os.ReadFile(configRef)
730 if err != nil {
731 return "", fmt.Errorf("configure: %w", err)
732 }
733 src = tmp
734 }
735
736 switch format {
737 case statusFormatYAML:
738 return e.parseYAMLConfig(src)
739 }
740
741 return "", fmt.Errorf("configure: not yet implemented %v %v %v ", format, fromFile, configRef)
742 }
743
744 // REPLConfig returns a stringified view of the current evaluator state in terms of REPL Commands.
745 func (e *Evaluator) REPLConfig() string {
746 var status strings.Builder
747
748 if len(e.ctx.options) > 0 {
749 status.WriteString("// Options\n")
750 for _, opt := range e.ctx.options {
751 status.WriteString(fmt.Sprintf("%s\n", opt.opt))
752 }
753 status.WriteString("\n")
754 }
755
756 if len(e.ctx.letFns) > 0 {
757 status.WriteString("// Functions\n")
758 for _, fn := range e.ctx.letFns {
759 cmd := "let"
760 if fn.src == "" {
761 cmd = "declare"
762 }
763 status.WriteString(fmt.Sprintf("%%%s %s\n", cmd, fn))
764 }
765 status.WriteString("\n")
766 }
767
768 if len(e.ctx.letVars) > 0 {
769 status.WriteString("// Variables\n")
770 for _, lVar := range e.ctx.letVars {
771 cmd := "let"
772 if lVar.src == "" {
773 cmd = "declare"
774 }
775 status.WriteString(fmt.Sprintf("%%%s %s\n", cmd, lVar))
776 }
777 status.WriteString("\n")
778 }
779 return status.String()
780 }
781
782 func pruneDuplicateDecls(conf *env.Config) {
783 // Duplicate variables are allowed when they have an equivalent type. The way the REPL handles
784 // bindings ends up with a declaration in the config and a repeat when the "%let" operation is
785 // applied. Filter here to keep the config clear.
786 filtered := make([]*env.Variable, 0, len(conf.Variables))
787 seen := make(map[string]bool)
788 for _, v := range conf.Variables {
789 if seen[v.Name] {
790 continue
791 }
792 seen[v.Name] = true
793 filtered = append(filtered, v)
794 }
795 conf.Variables = filtered
796 }
797
798 // YAMLConfig returns a yaml-based CEL environment representing the current evaluator state.
799 func (e *Evaluator) YAMLConfig() (string, error) {
800 var status strings.Builder
801 status.WriteString("# CEL environment YAML\n")
802 conf, err := e.getEffectiveEnv().ToConfig("repl-session")
803 if err != nil {
804 return "", fmt.Errorf("status: REPL env broken: %w", err)
805 }
806 pruneDuplicateDecls(conf)
807 data, err := yaml.Marshal(conf)
808 if err != nil {
809 return "", fmt.Errorf("status: unserializable YAML environment: %w", err)
810 }
811 status.Write(data)
812 status.WriteString("\n\n# REPL Bindings: \n")
813
814 for _, opt := range e.ctx.options {
815 if !opt.yaml {
816 status.WriteString(fmt.Sprintf("# %s\n", opt.opt))
817 }
818 }
819
820 for _, lFn := range e.ctx.letFns {
821 if lFn.src == "" {
822 // Declaration handled in the standard YAML
823 continue
824 }
825 lines := strings.Split(lFn.String(), "\n")
826 for i, l := range lines {
827 if i == 0 {
828 status.WriteString("# %let ")
829 } else {
830 status.WriteString("# ")
831 }
832 status.WriteString(l)
833 if i < len(lines)-1 {
834 status.WriteString("\\\n")
835 }
836 }
837 status.WriteString("\n#\n")
838 }
839
840 for _, lVar := range e.ctx.letVars {
841 if lVar.src == "" {
842 continue
843 }
844 lines := strings.Split(lVar.String(), "\n")
845 for i, l := range lines {
846 if i == 0 {
847 status.WriteString("# %let ")
848 } else {
849 status.WriteString("# ")
850 }
851 status.WriteString(l)
852 if i < len(lines)-1 {
853 status.WriteString("\\\n")
854 }
855 }
856 status.WriteString("\n#\n")
857 }
858
859 return status.String(), nil
860 }
861
862 var trailerRegexp = regexp.MustCompile("# REPL Bindings:")
863
864 func (e *Evaluator) parseYAMLConfig(conf []byte) (string, error) {
865 yamlSrc := conf
866 var replSrc []byte
867
868 pos := trailerRegexp.FindIndex(conf)
869 if len(pos) == 2 {
870 yamlSrc = conf[0:pos[0]]
871 replSrc = conf[pos[1]:]
872 }
873
874 var c env.Config
875 if err := yaml.Unmarshal(yamlSrc, &c); err != nil {
876 return "", fmt.Errorf("configure (yaml): %w", err)
877 }
878
879 s := string(replSrc)
880
881 lines := strings.Split(s, "\n")
882
883 // A little unfortunate, but we need to apply option commands manually
884 // before the yaml environment. This is mainly because the yaml doesn't
885 // describe how to lookup extension types (e.g. load_descriptors).
886 updated, _ := NewEvaluator()
887
888 var cmds []Cmder
889 var sb strings.Builder
890 for _, line := range lines {
891 if !strings.HasPrefix(line, "# ") {
892 continue
893 }
894 norm := strings.TrimPrefix(line, "# ")
895 if strings.HasSuffix(norm, "\\") {
896 norm = strings.TrimSuffix(norm, "\\")
897 sb.WriteString(norm)
898 sb.WriteString("\n")
899 continue
900 }
901 sb.WriteString(norm)
902 cmd := sb.String()
903 sb.Reset()
904 pCmd, err := Parse(cmd)
905 if err != nil {
906 return "", fmt.Errorf("configure: invalid REPL command: %w", err)
907 }
908 switch pCmd.(type) {
909 case *letFnCmd, *letVarCmd:
910 cmds = append(cmds, pCmd)
911 continue
912 }
913 _, exit, err := updated.Process(pCmd)
914
915 if exit {
916 return "", errors.New("configure: config triggered an exit")
917 }
918 if err != nil {
919 return "", fmt.Errorf("configure: failed to process option %w", err)
920 }
921 }
922
923 if len(updated.ctx.letFns) > 0 || len(updated.ctx.letVars) > 0 {
924 return "", errors.New("configure: unsupported REPL config. Option defines variables")
925 }
926
927 err := updated.AddSerializableOption(&genericOption{envOpt: cel.FromConfig(&c, ext.ExtensionOptionFactory)})
928
929 if err != nil {
930 return "", fmt.Errorf("configure: failed to apply yaml: %w", err)
931 }
932
933 // Apply bindings now.
934 for _, cmd := range cmds {
935 _, exit, err := updated.Process(cmd)
936
937 if exit {
938 return "", errors.New("configure: config triggered an exit")
939 }
940 if err != nil {
941 return "", fmt.Errorf("configure: failed to apply let: %w", err)
942 }
943 }
944
945 *e, *updated = *updated, *e
946 return "<loaded config>", nil
947 }
948
949 func (e *Evaluator) getEffectiveEnv() *cel.Env {
950 env := e.ctx.getEffectiveEnv(e.env)
951 return env
952 }
953
954 // applyContext evaluates the let expressions in the context to build an activation for the given expression.
955 // returns the environment for compiling and planning the top level CEL expression and an activation with the
956 // values of the let expressions.
957 func (e *Evaluator) applyContext() (*cel.Env, cel.Activation, error) {
958 var vars = make(map[string]any)
959
960 for _, el := range e.ctx.letVars {
961 if el.prog == nil {
962 // Declared but not defined variable so nothing to evaluate
963 continue
964 }
965
966 val, _, err := el.prog.Eval(vars)
967 if val != nil {
968 vars[el.identifier] = val
969 } else if err != nil {
970 return nil, nil, err
971 }
972 }
973
974 act, err := cel.NewActivation(vars)
975 if err != nil {
976 return nil, nil, err
977 }
978
979 return e.getEffectiveEnv(), act, nil
980 }
981
982 // typeOption implements optioner for loading a set of types defined by a protobuf file descriptor set.
983 type typeOption struct {
984 path string
985 fds *descpb.FileDescriptorSet
986 isPkg bool
987 }
988
989 func (o *typeOption) String() string {
990 flags := ""
991 if o.isPkg {
992 flags = "--pkg"
993 }
994 return fmt.Sprintf("%%load_descriptors %s '%s'", flags, o.path)
995 }
996
997 type backtickOpt struct {
998 enabled bool
999 }
1000
1001 func (o *backtickOpt) Option() cel.EnvOption {
1002 if o.enabled {
1003 return cel.EnableIdentifierEscapeSyntax()
1004 }
1005 return func(e *cel.Env) (*cel.Env, error) { return e, nil }
1006 }
1007
1008 func (o *backtickOpt) String() string {
1009 return "%option --enable_escaped_fields"
1010 }
1011
1012 func (o *typeOption) Option() cel.EnvOption {
1013 return cel.TypeDescs(o.fds)
1014 }
1015
1016 type containerOption struct {
1017 container string
1018 }
1019
1020 func (o *containerOption) String() string {
1021 return fmt.Sprintf("%%option --container '%s'", o.container)
1022 }
1023
1024 func (o *containerOption) Option() cel.EnvOption {
1025 return cel.Container(o.container)
1026 }
1027
1028 // extensionOption implements optional for loading a specific extension into the environment (String, Math, Proto, Encoder)
1029 type extensionOption struct {
1030 extensionType string
1031 option cel.EnvOption
1032 }
1033
1034 func (o *extensionOption) String() string {
1035 return fmt.Sprintf("%%option --extension '%s'", o.extensionType)
1036 }
1037
1038 func (o extensionOption) Option() cel.EnvOption {
1039 return o.option
1040 }
1041
1042 func newExtensionOption(extType string) (*extensionOption, error) {
1043 extType = strings.ToLower(extType)
1044 if extOption, found := extensionMap[extType]; found {
1045 return &extensionOption{extensionType: extType, option: extOption}, nil
1046 } else {
1047 keys := make([]string, 0)
1048 for k := range extensionMap {
1049 keys = append(keys, k)
1050 }
1051 sort.Strings(keys)
1052 extKeyName := make([]string, 0, len(keys))
1053 for _, k := range keys {
1054 extKeyName = append(extKeyName, "'"+k+"'")
1055 }
1056 joinedOptions := "['all', " + strings.Join(extKeyName, ", ") + "]"
1057 return nil, fmt.Errorf("unknown option: %s. Available options are: %s", extType, joinedOptions)
1058 }
1059 }
1060
1061 // setOption sets a number of options on the environment. returns an error if
1062 // any of them fail.
1063 func (e *Evaluator) setOption(args []string) error {
1064 var issues []string
1065 for idx := 0; idx < len(args); {
1066 arg := args[idx]
1067 idx++
1068 switch arg {
1069 case "--container":
1070 err := e.loadContainerOption(idx, args)
1071 idx++
1072 if err != nil {
1073 issues = append(issues, fmt.Sprintf("container: %v", err))
1074 }
1075 case "--extension":
1076 err := e.loadExtensionOption(idx, args)
1077 idx++
1078 if err != nil {
1079 issues = append(issues, fmt.Sprintf("extension: %v", err))
1080 }
1081 case "--enable_escaped_fields":
1082 err := e.AddSerializableOption(&backtickOpt{enabled: true})
1083 if err != nil {
1084 issues = append(issues, fmt.Sprintf("enable_escaped_fields: %v", err))
1085 }
1086 case "--enable_partial_eval":
1087 err := e.EnablePartialEval()
1088 if err != nil {
1089 issues = append(issues, fmt.Sprintf("enable_partial_eval: %v", err))
1090 }
1091 default:
1092 issues = append(issues, fmt.Sprintf("unsupported option '%s'", arg))
1093 }
1094 }
1095 if len(issues) > 0 {
1096 return errors.New(strings.Join(issues, "\n"))
1097 }
1098 return nil
1099 }
1100
1101 func checkOptionArgs(idx int, args []string) error {
1102 if idx >= len(args) {
1103 return fmt.Errorf("not enough arguments")
1104 }
1105 return nil
1106 }
1107
1108 func (e *Evaluator) loadContainerOption(idx int, args []string) error {
1109 err := checkOptionArgs(idx, args)
1110 if err != nil {
1111 return err
1112 }
1113
1114 container := args[idx]
1115 idx++
1116 err = e.AddSerializableOption(&containerOption{container: container})
1117 if err != nil {
1118 return err
1119 }
1120 return nil
1121 }
1122
1123 func (e *Evaluator) loadExtensionOption(idx int, args []string) error {
1124 err := checkOptionArgs(idx, args)
1125 if err != nil {
1126 return err
1127 }
1128
1129 argExtType := args[idx]
1130 if argExtType == "all" {
1131 // Load all extension types as a convenience
1132 for val := range extensionMap {
1133 err := e.loadExtensionOptionType(val)
1134 if err != nil {
1135 return err
1136 }
1137 }
1138 return nil
1139 }
1140 return e.loadExtensionOptionType(argExtType)
1141 }
1142
1143 func (e *Evaluator) loadExtensionOptionType(extType string) error {
1144 extensionOption, err := newExtensionOption(extType)
1145 if err != nil {
1146 return err
1147 }
1148
1149 err = e.AddSerializableOption(extensionOption)
1150 if err != nil {
1151 return err
1152 }
1153
1154 return nil
1155
1156 }
1157
1158 func loadFileDescriptorSet(path string, textfmt bool) (*descpb.FileDescriptorSet, error) {
1159 data, err := os.ReadFile(path)
1160 if err != nil {
1161 return nil, err
1162 }
1163
1164 var fds descpb.FileDescriptorSet
1165
1166 if textfmt {
1167 err = prototext.Unmarshal(data, &fds)
1168 } else {
1169 // binary pb
1170 err = proto.Unmarshal(data, &fds)
1171 }
1172 if err != nil {
1173 return nil, err
1174 }
1175
1176 return &fds, nil
1177 }
1178
1179 func deps(d protoreflect.FileDescriptor) []*descpb.FileDescriptorProto {
1180 var descriptorProtos []*descpb.FileDescriptorProto
1181
1182 for i := 0; i < d.Imports().Len(); i++ {
1183 descriptorProtos = append(descriptorProtos,
1184 protodesc.ToFileDescriptorProto(d.Imports().Get(i)))
1185 }
1186
1187 return descriptorProtos
1188 }
1189
1190 func (e *Evaluator) loadDescriptorFromPackage(pkg string) error {
1191 switch pkg {
1192 case "cel-spec-test-types":
1193 fdp := (&test2pb.TestAllTypes{}).ProtoReflect().Type().Descriptor().ParentFile()
1194 fdp2 := (&test3pb.TestAllTypes{}).ProtoReflect().Type().Descriptor().ParentFile()
1195
1196 descriptorProtos := deps(fdp)
1197
1198 descriptorProtos = append(descriptorProtos,
1199 protodesc.ToFileDescriptorProto(fdp),
1200 protodesc.ToFileDescriptorProto(fdp2))
1201
1202 fds := descpb.FileDescriptorSet{
1203 File: descriptorProtos,
1204 }
1205
1206 return e.AddOption(&typeOption{pkg, &fds, true})
1207 case "google-rpc":
1208 fdp := (&attrpb.AttributeContext{}).ProtoReflect().Type().Descriptor().ParentFile()
1209
1210 descriptorProtos := append(deps(fdp),
1211 protodesc.ToFileDescriptorProto(fdp))
1212
1213 fds := descpb.FileDescriptorSet{
1214 File: descriptorProtos,
1215 }
1216
1217 return e.AddOption(&typeOption{pkg, &fds, true})
1218 }
1219
1220 return fmt.Errorf("unknown type package: '%s'", pkg)
1221 }
1222
1223 func (e *Evaluator) loadDescriptorFromFile(p string, textfmt bool) error {
1224 fds, err := loadFileDescriptorSet(p, textfmt)
1225 if err != nil {
1226 return fmt.Errorf("error loading file: %v", err)
1227 }
1228
1229 return e.AddOption(&typeOption{path: p, fds: fds})
1230 }
1231
1232 func (e *Evaluator) loadDescriptors(args []string) error {
1233 if len(args) < 1 {
1234 return errors.New("expected args for load descriptors")
1235 }
1236
1237 textfmt := true
1238
1239 var paths []string
1240 var pkgs []string
1241 nextIsPkg := false
1242 for _, flag := range args {
1243 switch flag {
1244 case "--binarypb":
1245 {
1246 textfmt = false
1247 }
1248 case "--pkg":
1249 {
1250 nextIsPkg = true
1251 }
1252 default:
1253 {
1254 if nextIsPkg {
1255 pkgs = append(pkgs, flag)
1256 nextIsPkg = false
1257 } else {
1258 paths = append(paths, flag)
1259 }
1260 }
1261 }
1262 }
1263
1264 for _, p := range paths {
1265 err := e.loadDescriptorFromFile(p, textfmt)
1266 if err != nil {
1267 return err
1268 }
1269 }
1270
1271 for _, p := range pkgs {
1272 err := e.loadDescriptorFromPackage(p)
1273 if err != nil {
1274 return err
1275 }
1276 }
1277
1278 return nil
1279 }
1280
1281 // Process processes the command provided.
1282 func (e *Evaluator) Process(cmd Cmder) (string, bool, error) {
1283 switch cmd := cmd.(type) {
1284 case *compileCmd:
1285 ast, err := e.Compile(cmd.expr)
1286 if err != nil {
1287 return "", false, fmt.Errorf("compile failed:\n%v", err)
1288 }
1289 cAST, err := cel.AstToCheckedExpr(ast)
1290 if err != nil {
1291 return "", false, fmt.Errorf("compile failed:\n%v", err)
1292 }
1293 return prototext.Format(cAST), false, nil
1294 case *parseCmd:
1295 ast, err := e.Parse(cmd.expr)
1296 if err != nil {
1297 return "", false, fmt.Errorf("parse failed:\n%v", err)
1298 }
1299 pAST, err := cel.AstToParsedExpr(ast)
1300 if err != nil {
1301 return "", false, fmt.Errorf("parse failed:\n%v", err)
1302 }
1303 return prototext.Format(pAST), false, nil
1304 case *evalCmd:
1305 var (
1306 val ref.Val
1307 resultT *exprpb.Type
1308 err error
1309 )
1310 if cmd.parseOnly {
1311 val, resultT, err = e.EvaluateParseOnly(cmd.expr)
1312 } else {
1313 val, resultT, err = e.Evaluate(cmd.expr)
1314 }
1315 if err != nil {
1316 return "", false, fmt.Errorf("expr failed:\n%v", err)
1317 }
1318 if val != nil {
1319 unknown, ok := val.Value().(*types.Unknown)
1320 if ok {
1321 return fmt.Sprintf("Unknown %v", unknown), false, nil
1322 }
1323 if cmd.parseOnly {
1324 return fmt.Sprintf("%s", types.Format(val)), false, nil
1325 }
1326 t := UnparseType(resultT)
1327 return fmt.Sprintf("%s : %s", types.Format(val), t), false, nil
1328 }
1329 case *letVarCmd:
1330 var err error
1331 if cmd.src != "" {
1332 err = e.AddLetVar(cmd.identifier, cmd.src, cmd.typeHint)
1333 } else {
1334 // declare only
1335 err = e.AddDeclVar(cmd.identifier, cmd.typeHint)
1336 }
1337 if err != nil {
1338 return "", false, fmt.Errorf("adding variable failed:\n%v", err)
1339 }
1340 case *letFnCmd:
1341 err := errors.New("declare not yet implemented")
1342 if cmd.src != "" {
1343 err = e.AddLetFn(cmd.identifier, cmd.params, cmd.resultType, cmd.src)
1344 }
1345 if err != nil {
1346 return "", false, fmt.Errorf("adding function failed:\n%v", err)
1347 }
1348 case *delCmd:
1349 err := e.DelLetVar(cmd.identifier)
1350 if err != nil {
1351 return "", false, fmt.Errorf("deleting declaration failed:\n%v", err)
1352 }
1353 err = e.DelLetFn(cmd.identifier)
1354 if err != nil {
1355 return "", false, fmt.Errorf("deleting declaration failed:\n%v", err)
1356 }
1357
1358 case *simpleCmd:
1359 switch cmd.Cmd() {
1360 case "exit":
1361 return "", true, nil
1362 case "null":
1363 return "", false, nil
1364 case "configure":
1365 out, err := e.handleConfig(cmd.args)
1366 return out, false, err
1367 case "status":
1368 out, err := e.handleStatus(cmd.args)
1369 return out, false, err
1370 case "load_descriptors":
1371 return "", false, e.loadDescriptors(cmd.args)
1372 case "option":
1373 return "", false, e.setOption(cmd.args)
1374 case "reset":
1375 e.ctx = EvaluationContext{}
1376 return "", false, nil
1377 default:
1378 return "", false, fmt.Errorf("unsupported command: %v", cmd.Cmd())
1379 }
1380 default:
1381 return "", false, fmt.Errorf("unsupported command: %v", cmd.Cmd())
1382 }
1383 return "", false, nil
1384 }
1385
1386 // Evaluate sets up a CEL evaluation using the current REPL context.
1387 func (e *Evaluator) Evaluate(expr string) (ref.Val, *exprpb.Type, error) {
1388 env, act, err := e.applyContext()
1389 if err != nil {
1390 return nil, nil, err
1391 }
1392
1393 ast, iss := env.Compile(expr)
1394 if iss.Err() != nil {
1395 return nil, nil, iss.Err()
1396 }
1397
1398 p, err := env.Program(ast, e.ctx.programOptions()...)
1399 if err != nil {
1400 return nil, nil, err
1401 }
1402
1403 act, _ = env.PartialVars(act)
1404 val, _, err := p.Eval(act)
1405 // expression can be well-formed and result in an error
1406 return val, ast.ResultType(), err
1407 }
1408
1409 // EvaluateParseOnly evalutes the CEL expression using the current REPL context without type checking.
1410 func (e *Evaluator) EvaluateParseOnly(expr string) (ref.Val, *exprpb.Type, error) {
1411 env, act, err := e.applyContext()
1412 if err != nil {
1413 return nil, nil, err
1414 }
1415
1416 ast, iss := env.Parse(expr)
1417 if iss.Err() != nil {
1418 return nil, nil, iss.Err()
1419 }
1420
1421 p, err := env.Program(ast, e.ctx.programOptions()...)
1422 if err != nil {
1423 return nil, nil, err
1424 }
1425
1426 act, _ = env.PartialVars(act)
1427 val, _, err := p.Eval(act)
1428 // expression can be well-formed and result in an error
1429 return val, ast.ResultType(), err
1430 }
1431
1432 // Compile compiles the input expression using the current REPL context.
1433 func (e *Evaluator) Compile(expr string) (*cel.Ast, error) {
1434 env, _, err := e.applyContext()
1435 if err != nil {
1436 return nil, err
1437 }
1438 ast, iss := env.Compile(expr)
1439 if iss.Err() != nil {
1440 return nil, iss.Err()
1441 }
1442 return ast, nil
1443 }
1444
1445 // Parse parses the input expression using the current REPL context.
1446 func (e *Evaluator) Parse(expr string) (*cel.Ast, error) {
1447 env, _, err := e.applyContext()
1448 if err != nil {
1449 return nil, err
1450 }
1451 ast, iss := env.Parse(expr)
1452 if iss.Err() != nil {
1453 return nil, iss.Err()
1454 }
1455 return ast, nil
1456 }