| 1 | // Copyright 2018 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 interpreter provides functions to evaluate parsed expressions with |
| 16 | // the option to augment the evaluation with inputs and functions supplied at |
| 17 | // evaluation time. |
| 18 | package interpreter |
| 19 | |
| 20 | import ( |
| 21 | "errors" |
| 22 | |
| 23 | "github.com/google/cel-go/common/ast" |
| 24 | "github.com/google/cel-go/common/containers" |
| 25 | "github.com/google/cel-go/common/types" |
| 26 | "github.com/google/cel-go/common/types/ref" |
| 27 | ) |
| 28 | |
| 29 | // PlannerOption configures the program plan options during interpretable setup. |
| 30 | type PlannerOption func(*planner) (*planner, error) |
| 31 | |
| 32 | // Interpreter generates a new Interpretable from a checked or unchecked expression. |
| 33 | type Interpreter interface { |
| 34 | // NewInterpretable creates an Interpretable from a checked expression and an |
| 35 | // optional list of PlannerOption values. |
| 36 | NewInterpretable(exprAST *ast.AST, opts ...PlannerOption) (Interpretable, error) |
| 37 | } |
| 38 | |
| 39 | // EvalObserver is a functional interface that accepts an expression id and an observed value. |
| 40 | // The id identifies the expression that was evaluated, the programStep is the Interpretable or Qualifier that |
| 41 | // was evaluated and value is the result of the evaluation. |
| 42 | type EvalObserver func(vars Activation, id int64, programStep any, value ref.Val) |
| 43 | |
| 44 | // StatefulObserver observes evaluation while tracking or utilizing stateful behavior. |
| 45 | type StatefulObserver interface { |
| 46 | // InitState configures stateful metadata on the activation. |
| 47 | InitState(Activation) (Activation, error) |
| 48 | |
| 49 | // GetState retrieves the stateful metadata from the activation. |
| 50 | GetState(Activation) any |
| 51 | |
| 52 | // Observe passes the activation and relevant evaluation metadata to the observer. |
| 53 | // The observe method is expected to do the equivalent of GetState(vars) in order |
| 54 | // to find the metadata that needs to be updated upon invocation. |
| 55 | Observe(vars Activation, id int64, programStep any, value ref.Val) |
| 56 | } |
| 57 | |
| 58 | // EvalCancelledError represents a cancelled program evaluation operation. |
| 59 | type EvalCancelledError struct { |
| 60 | Message string |
| 61 | // Type identifies the cause of the cancellation. |
| 62 | Cause CancellationCause |
| 63 | } |
| 64 | |
| 65 | func (e EvalCancelledError) Error() string { |
| 66 | return e.Message |
| 67 | } |
| 68 | |
| 69 | // CancellationCause enumerates the ways a program evaluation operation can be cancelled. |
| 70 | type CancellationCause int |
| 71 | |
| 72 | const ( |
| 73 | // ContextCancelled indicates that the operation was cancelled in response to a Golang context cancellation. |
| 74 | ContextCancelled CancellationCause = iota |
| 75 | |
| 76 | // CostLimitExceeded indicates that the operation was cancelled in response to the actual cost limit being |
| 77 | // exceeded. |
| 78 | CostLimitExceeded |
| 79 | ) |
| 80 | |
| 81 | // evalStateOption configures the evalStateFactory behavior. |
| 82 | type evalStateOption func(*evalStateFactory) *evalStateFactory |
| 83 | |
| 84 | // EvalStateFactory configures the EvalState generator to be used by the EvalStateObserver. |
| 85 | func EvalStateFactory(factory func() EvalState) evalStateOption { |
| 86 | return func(fac *evalStateFactory) *evalStateFactory { |
| 87 | fac.factory = factory |
| 88 | return fac |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | // EvalStateObserver provides an observer which records the value associated with the given expression id. |
| 93 | // EvalState must be provided to the observer. |
| 94 | func EvalStateObserver(opts ...evalStateOption) PlannerOption { |
| 95 | et := &evalStateFactory{factory: NewEvalState} |
| 96 | for _, o := range opts { |
| 97 | et = o(et) |
| 98 | } |
| 99 | return func(p *planner) (*planner, error) { |
| 100 | if et.factory == nil { |
| 101 | return nil, errors.New("eval state factory not configured") |
| 102 | } |
| 103 | p.observers = append(p.observers, et) |
| 104 | p.decorators = append(p.decorators, decObserveEval(et.Observe)) |
| 105 | return p, nil |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // evalStateConverter identifies an object which is convertible to an EvalState instance. |
| 110 | type evalStateConverter interface { |
| 111 | asEvalState() EvalState |
| 112 | } |
| 113 | |
| 114 | // evalStateActivation hides state in the Activation in a manner not accessible to expressions. |
| 115 | type evalStateActivation struct { |
| 116 | vars Activation |
| 117 | state EvalState |
| 118 | } |
| 119 | |
| 120 | // ResolveName proxies variable lookups to the backing activation. |
| 121 | func (esa evalStateActivation) ResolveName(name string) (any, bool) { |
| 122 | return esa.vars.ResolveName(name) |
| 123 | } |
| 124 | |
| 125 | // Parent proxies parent lookups to the backing activation. |
| 126 | func (esa evalStateActivation) Parent() Activation { |
| 127 | return esa.vars |
| 128 | } |
| 129 | |
| 130 | // AsPartialActivation supports conversion to a partial activation in order to detect unknown attributes. |
| 131 | func (esa evalStateActivation) AsPartialActivation() (PartialActivation, bool) { |
| 132 | return AsPartialActivation(esa.vars) |
| 133 | } |
| 134 | |
| 135 | // asEvalState implements the evalStateConverter method. |
| 136 | func (esa evalStateActivation) asEvalState() EvalState { |
| 137 | return esa.state |
| 138 | } |
| 139 | |
| 140 | // activationWrapper identifies an object carrying local variables which should not be exposed to the user |
| 141 | // Activations used for such purposes can be unwrapped to return the activation which omits local state. |
| 142 | type activationWrapper interface { |
| 143 | // Unwrap returns the Activation which omits local state. |
| 144 | Unwrap() Activation |
| 145 | } |
| 146 | |
| 147 | // asEvalState walks the Activation hierarchy and returns the first EvalState found, if present. |
| 148 | func asEvalState(vars Activation) (EvalState, bool) { |
| 149 | if conv, ok := vars.(evalStateConverter); ok { |
| 150 | return conv.asEvalState(), true |
| 151 | } |
| 152 | // Check if the current activation wraps another activation. This is used to support |
| 153 | // wrappers such as the @block() activation which may be composed of a dynamicSlotActivation or a |
| 154 | // constantSlotActivation. In this case, the underlying activation is the portion which interacts |
| 155 | // with the EvalState. |
| 156 | if wrapper, ok := vars.(activationWrapper); ok { |
| 157 | unwrapped := wrapper.Unwrap() |
| 158 | // Recursively call asEvalState on the unwrapped activation. This will check the unwrapped value and its parents. |
| 159 | return asEvalState(unwrapped) |
| 160 | } |
| 161 | if vars.Parent() != nil { |
| 162 | return asEvalState(vars.Parent()) |
| 163 | } |
| 164 | return nil, false |
| 165 | } |
| 166 | |
| 167 | // evalStateFactory holds a reference to a factory function that produces an EvalState instance. |
| 168 | type evalStateFactory struct { |
| 169 | factory func() EvalState |
| 170 | } |
| 171 | |
| 172 | // InitState produces an EvalState instance and bundles it into the Activation in a way which is |
| 173 | // not visible to expression evaluation. |
| 174 | func (et *evalStateFactory) InitState(vars Activation) (Activation, error) { |
| 175 | state := et.factory() |
| 176 | return evalStateActivation{vars: vars, state: state}, nil |
| 177 | } |
| 178 | |
| 179 | // GetState extracts the EvalState from the Activation. |
| 180 | func (et *evalStateFactory) GetState(vars Activation) any { |
| 181 | if state, found := asEvalState(vars); found { |
| 182 | return state |
| 183 | } |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | // Observe records the evaluation state for a given expression node and program step. |
| 188 | func (et *evalStateFactory) Observe(vars Activation, id int64, programStep any, val ref.Val) { |
| 189 | state, found := asEvalState(vars) |
| 190 | if !found { |
| 191 | return |
| 192 | } |
| 193 | state.SetValue(id, val) |
| 194 | } |
| 195 | |
| 196 | // CustomDecorator configures a custom interpretable decorator for the program. |
| 197 | func CustomDecorator(dec InterpretableDecorator) PlannerOption { |
| 198 | return func(p *planner) (*planner, error) { |
| 199 | p.decorators = append(p.decorators, dec) |
| 200 | return p, nil |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // ExhaustiveEval replaces operations that short-circuit with versions that evaluate |
| 205 | // expressions and couples this behavior with the TrackState() decorator to provide |
| 206 | // insight into the evaluation state of the entire expression. EvalState must be |
| 207 | // provided to the decorator. This decorator is not thread-safe, and the EvalState |
| 208 | // must be reset between Eval() calls. |
| 209 | func ExhaustiveEval() PlannerOption { |
| 210 | return CustomDecorator(decDisableShortcircuits()) |
| 211 | } |
| 212 | |
| 213 | // InterruptableEval annotates comprehension loops with information that indicates they |
| 214 | // should check the `#interrupted` state within a custom Activation. |
| 215 | // |
| 216 | // The custom activation is currently managed higher up in the stack within the 'cel' package |
| 217 | // and should not require any custom support on behalf of callers. |
| 218 | func InterruptableEval() PlannerOption { |
| 219 | return CustomDecorator(decInterruptFolds()) |
| 220 | } |
| 221 | |
| 222 | // Optimize will pre-compute operations such as list and map construction and optimize |
| 223 | // call arguments to set membership tests. The set of optimizations will increase over time. |
| 224 | func Optimize() PlannerOption { |
| 225 | return CustomDecorator(decOptimize()) |
| 226 | } |
| 227 | |
| 228 | // RegexOptimization provides a way to replace an InterpretableCall for a regex function when the |
| 229 | // RegexIndex argument is a string constant. Typically, the Factory would compile the regex pattern at |
| 230 | // RegexIndex and report any errors (at program creation time) and then use the compiled regex for |
| 231 | // all regex function invocations. |
| 232 | type RegexOptimization struct { |
| 233 | // Function is the name of the function to optimize. |
| 234 | Function string |
| 235 | // OverloadID is the ID of the overload to optimize. |
| 236 | OverloadID string |
| 237 | // RegexIndex is the index position of the regex pattern argument. Only calls to the function where this argument is |
| 238 | // a string constant will be delegated to this optimizer. |
| 239 | RegexIndex int |
| 240 | // Factory constructs a replacement InterpretableCall node that optimizes the regex function call. Factory is |
| 241 | // provided with the unoptimized regex call and the string constant at the RegexIndex argument. |
| 242 | // The Factory may compile the regex for use across all invocations of the call, return any errors and |
| 243 | // return an interpreter.NewCall with the desired regex optimized function impl. |
| 244 | Factory func(call InterpretableCall, regexPattern string) (InterpretableCall, error) |
| 245 | } |
| 246 | |
| 247 | // CompileRegexConstants compiles regex pattern string constants at program creation time and reports any regex pattern |
| 248 | // compile errors. |
| 249 | func CompileRegexConstants(regexOptimizations ...*RegexOptimization) PlannerOption { |
| 250 | return CustomDecorator(decRegexOptimizer(regexOptimizations...)) |
| 251 | } |
| 252 | |
| 253 | type exprInterpreter struct { |
| 254 | dispatcher Dispatcher |
| 255 | container *containers.Container |
| 256 | provider types.Provider |
| 257 | adapter types.Adapter |
| 258 | attrFactory AttributeFactory |
| 259 | } |
| 260 | |
| 261 | // NewInterpreter builds an Interpreter from a Dispatcher and TypeProvider which will be used |
| 262 | // throughout the Eval of all Interpretable instances generated from it. |
| 263 | func NewInterpreter(dispatcher Dispatcher, |
| 264 | container *containers.Container, |
| 265 | provider types.Provider, |
| 266 | adapter types.Adapter, |
| 267 | attrFactory AttributeFactory) Interpreter { |
| 268 | return &exprInterpreter{ |
| 269 | dispatcher: dispatcher, |
| 270 | container: container, |
| 271 | provider: provider, |
| 272 | adapter: adapter, |
| 273 | attrFactory: attrFactory} |
| 274 | } |
| 275 | |
| 276 | // NewIntepretable implements the Interpreter interface method. |
| 277 | func (i *exprInterpreter) NewInterpretable( |
| 278 | checked *ast.AST, |
| 279 | opts ...PlannerOption) (Interpretable, error) { |
| 280 | p := newPlanner(i.dispatcher, i.provider, i.adapter, i.attrFactory, i.container, checked) |
| 281 | var err error |
| 282 | for _, o := range opts { |
| 283 | p, err = o(p) |
| 284 | if err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | } |
| 288 | return p.Plan(checked.Expr()) |
| 289 | } |