| 1 | // Copyright 2019 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 |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "sync" |
| 20 | |
| 21 | "github.com/google/cel-go/common/functions" |
| 22 | "github.com/google/cel-go/common/operators" |
| 23 | "github.com/google/cel-go/common/overloads" |
| 24 | "github.com/google/cel-go/common/types" |
| 25 | "github.com/google/cel-go/common/types/ref" |
| 26 | "github.com/google/cel-go/common/types/traits" |
| 27 | ) |
| 28 | |
| 29 | // Interpretable can accept a given Activation and produce a value along with |
| 30 | // an accompanying EvalState which can be used to inspect whether additional |
| 31 | // data might be necessary to complete the evaluation. |
| 32 | type Interpretable interface { |
| 33 | // ID value corresponding to the expression node. |
| 34 | ID() int64 |
| 35 | |
| 36 | // Eval an Activation to produce an output. |
| 37 | Eval(activation Activation) ref.Val |
| 38 | } |
| 39 | |
| 40 | // InterpretableConst interface for tracking whether the Interpretable is a constant value. |
| 41 | type InterpretableConst interface { |
| 42 | Interpretable |
| 43 | |
| 44 | // Value returns the constant value of the instruction. |
| 45 | Value() ref.Val |
| 46 | } |
| 47 | |
| 48 | // InterpretableAttribute interface for tracking whether the Interpretable is an attribute. |
| 49 | type InterpretableAttribute interface { |
| 50 | Interpretable |
| 51 | |
| 52 | // Attr returns the Attribute value. |
| 53 | Attr() Attribute |
| 54 | |
| 55 | // Adapter returns the type adapter to be used for adapting resolved Attribute values. |
| 56 | Adapter() types.Adapter |
| 57 | |
| 58 | // AddQualifier proxies the Attribute.AddQualifier method. |
| 59 | // |
| 60 | // Note, this method may mutate the current attribute state. If the desire is to clone the |
| 61 | // Attribute, the Attribute should first be copied before adding the qualifier. Attributes |
| 62 | // are not copyable by default, so this is a capable that would need to be added to the |
| 63 | // AttributeFactory or specifically to the underlying Attribute implementation. |
| 64 | AddQualifier(Qualifier) (Attribute, error) |
| 65 | |
| 66 | // Qualify replicates the Attribute.Qualify method to permit extension and interception |
| 67 | // of object qualification. |
| 68 | Qualify(vars Activation, obj any) (any, error) |
| 69 | |
| 70 | // QualifyIfPresent qualifies the object if the qualifier is declared or defined on the object. |
| 71 | // The 'presenceOnly' flag indicates that the value is not necessary, just a boolean status as |
| 72 | // to whether the qualifier is present. |
| 73 | QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) |
| 74 | |
| 75 | // IsOptional indicates whether the resulting value is an optional type. |
| 76 | IsOptional() bool |
| 77 | |
| 78 | // Resolve returns the value of the Attribute given the current Activation. |
| 79 | Resolve(Activation) (any, error) |
| 80 | } |
| 81 | |
| 82 | // InterpretableCall interface for inspecting Interpretable instructions related to function calls. |
| 83 | type InterpretableCall interface { |
| 84 | Interpretable |
| 85 | |
| 86 | // Function returns the function name as it appears in text or mangled operator name as it |
| 87 | // appears in the operators.go file. |
| 88 | Function() string |
| 89 | |
| 90 | // OverloadID returns the overload id associated with the function specialization. |
| 91 | // Overload ids are stable across language boundaries and can be treated as synonymous with a |
| 92 | // unique function signature. |
| 93 | OverloadID() string |
| 94 | |
| 95 | // Args returns the normalized arguments to the function overload. |
| 96 | // For receiver-style functions, the receiver target is arg 0. |
| 97 | Args() []Interpretable |
| 98 | } |
| 99 | |
| 100 | // InterpretableConstructor interface for inspecting Interpretable instructions that initialize a list, map |
| 101 | // or struct. |
| 102 | type InterpretableConstructor interface { |
| 103 | Interpretable |
| 104 | |
| 105 | // InitVals returns all the list elements, map key and values or struct field values. |
| 106 | InitVals() []Interpretable |
| 107 | |
| 108 | // Type returns the type constructed. |
| 109 | Type() ref.Type |
| 110 | } |
| 111 | |
| 112 | // ObservableInterpretable is an Interpretable which supports stateful observation, such as tracing |
| 113 | // or cost-tracking. |
| 114 | type ObservableInterpretable struct { |
| 115 | Interpretable |
| 116 | observers []StatefulObserver |
| 117 | } |
| 118 | |
| 119 | // ID implements the Interpretable method to get the expression id associated with the step. |
| 120 | func (oi *ObservableInterpretable) ID() int64 { |
| 121 | return oi.Interpretable.ID() |
| 122 | } |
| 123 | |
| 124 | // Eval proxies to the ObserveEval method while invoking a no-op callback to report the observations. |
| 125 | func (oi *ObservableInterpretable) Eval(vars Activation) ref.Val { |
| 126 | return oi.ObserveEval(vars, func(any) {}) |
| 127 | } |
| 128 | |
| 129 | // ObserveEval evaluates an interpretable and performs per-evaluation state-tracking. |
| 130 | // |
| 131 | // This method is concurrency safe and the expectation is that the observer function will use |
| 132 | // a switch statement to determine the type of the state which has been reported back from the call. |
| 133 | func (oi *ObservableInterpretable) ObserveEval(vars Activation, observer func(any)) ref.Val { |
| 134 | var err error |
| 135 | // Initialize the state needed for the observers to function. |
| 136 | for _, obs := range oi.observers { |
| 137 | vars, err = obs.InitState(vars) |
| 138 | if err != nil { |
| 139 | return types.WrapErr(err) |
| 140 | } |
| 141 | // Provide an initial reference to the state to ensure state is available |
| 142 | // even in cases of interrupting errors generated during evaluation. |
| 143 | observer(obs.GetState(vars)) |
| 144 | } |
| 145 | result := oi.Interpretable.Eval(vars) |
| 146 | // Get the state which needs to be reported back as having been observed. |
| 147 | for _, obs := range oi.observers { |
| 148 | observer(obs.GetState(vars)) |
| 149 | } |
| 150 | return result |
| 151 | } |
| 152 | |
| 153 | // Core Interpretable implementations used during the program planning phase. |
| 154 | |
| 155 | type evalTestOnly struct { |
| 156 | id int64 |
| 157 | InterpretableAttribute |
| 158 | } |
| 159 | |
| 160 | // ID implements the Interpretable interface method. |
| 161 | func (test *evalTestOnly) ID() int64 { |
| 162 | return test.id |
| 163 | } |
| 164 | |
| 165 | // Eval implements the Interpretable interface method. |
| 166 | func (test *evalTestOnly) Eval(ctx Activation) ref.Val { |
| 167 | val, err := test.Resolve(ctx) |
| 168 | // Return an error if the resolve step fails |
| 169 | if err != nil { |
| 170 | return types.LabelErrNode(test.id, types.WrapErr(err)) |
| 171 | } |
| 172 | if optVal, isOpt := val.(*types.Optional); isOpt { |
| 173 | return types.Bool(optVal.HasValue()) |
| 174 | } |
| 175 | return test.Adapter().NativeToValue(val) |
| 176 | } |
| 177 | |
| 178 | // AddQualifier appends a qualifier that will always and only perform a presence test. |
| 179 | func (test *evalTestOnly) AddQualifier(q Qualifier) (Attribute, error) { |
| 180 | cq, ok := q.(ConstantQualifier) |
| 181 | if !ok { |
| 182 | return nil, fmt.Errorf("test only expressions must have constant qualifiers: %v", q) |
| 183 | } |
| 184 | return test.InterpretableAttribute.AddQualifier(&testOnlyQualifier{ConstantQualifier: cq}) |
| 185 | } |
| 186 | |
| 187 | type testOnlyQualifier struct { |
| 188 | ConstantQualifier |
| 189 | } |
| 190 | |
| 191 | // Qualify determines whether the test-only qualifier is present on the input object. |
| 192 | func (q *testOnlyQualifier) Qualify(vars Activation, obj any) (any, error) { |
| 193 | out, present, err := q.ConstantQualifier.QualifyIfPresent(vars, obj, true) |
| 194 | if err != nil { |
| 195 | return nil, err |
| 196 | } |
| 197 | if unk, isUnk := out.(types.Unknown); isUnk { |
| 198 | return unk, nil |
| 199 | } |
| 200 | return present, nil |
| 201 | } |
| 202 | |
| 203 | // QualifyIfPresent returns whether the target field in the test-only expression is present. |
| 204 | func (q *testOnlyQualifier) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { |
| 205 | // Only ever test for presence. |
| 206 | return q.ConstantQualifier.QualifyIfPresent(vars, obj, true) |
| 207 | } |
| 208 | |
| 209 | // QualifierValueEquals determines whether the test-only constant qualifier equals the input value. |
| 210 | func (q *testOnlyQualifier) QualifierValueEquals(value any) bool { |
| 211 | // The input qualifier will always be of type string |
| 212 | return q.ConstantQualifier.Value().Value() == value |
| 213 | } |
| 214 | |
| 215 | // NewConstValue creates a new constant valued Interpretable. |
| 216 | func NewConstValue(id int64, val ref.Val) InterpretableConst { |
| 217 | return &evalConst{ |
| 218 | id: id, |
| 219 | val: val, |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | type evalConst struct { |
| 224 | id int64 |
| 225 | val ref.Val |
| 226 | } |
| 227 | |
| 228 | // ID implements the Interpretable interface method. |
| 229 | func (cons *evalConst) ID() int64 { |
| 230 | return cons.id |
| 231 | } |
| 232 | |
| 233 | // Eval implements the Interpretable interface method. |
| 234 | func (cons *evalConst) Eval(ctx Activation) ref.Val { |
| 235 | return cons.val |
| 236 | } |
| 237 | |
| 238 | // Value implements the InterpretableConst interface method. |
| 239 | func (cons *evalConst) Value() ref.Val { |
| 240 | return cons.val |
| 241 | } |
| 242 | |
| 243 | type evalOr struct { |
| 244 | id int64 |
| 245 | terms []Interpretable |
| 246 | } |
| 247 | |
| 248 | // ID implements the Interpretable interface method. |
| 249 | func (or *evalOr) ID() int64 { |
| 250 | return or.id |
| 251 | } |
| 252 | |
| 253 | // Eval implements the Interpretable interface method. |
| 254 | func (or *evalOr) Eval(ctx Activation) ref.Val { |
| 255 | var err ref.Val = nil |
| 256 | var unk *types.Unknown |
| 257 | for _, term := range or.terms { |
| 258 | val := term.Eval(ctx) |
| 259 | boolVal, ok := val.(types.Bool) |
| 260 | // short-circuit on true. |
| 261 | if ok && boolVal == types.True { |
| 262 | return types.True |
| 263 | } |
| 264 | if !ok { |
| 265 | isUnk := false |
| 266 | unk, isUnk = types.MaybeMergeUnknowns(val, unk) |
| 267 | if !isUnk && err == nil { |
| 268 | if types.IsError(val) { |
| 269 | err = val |
| 270 | } else { |
| 271 | err = types.MaybeNoSuchOverloadErr(val) |
| 272 | } |
| 273 | err = types.LabelErrNode(or.id, err) |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | if unk != nil { |
| 278 | return unk |
| 279 | } |
| 280 | if err != nil { |
| 281 | return err |
| 282 | } |
| 283 | return types.False |
| 284 | } |
| 285 | |
| 286 | type evalAnd struct { |
| 287 | id int64 |
| 288 | terms []Interpretable |
| 289 | } |
| 290 | |
| 291 | // ID implements the Interpretable interface method. |
| 292 | func (and *evalAnd) ID() int64 { |
| 293 | return and.id |
| 294 | } |
| 295 | |
| 296 | // Eval implements the Interpretable interface method. |
| 297 | func (and *evalAnd) Eval(ctx Activation) ref.Val { |
| 298 | var err ref.Val = nil |
| 299 | var unk *types.Unknown |
| 300 | for _, term := range and.terms { |
| 301 | val := term.Eval(ctx) |
| 302 | boolVal, ok := val.(types.Bool) |
| 303 | // short-circuit on false. |
| 304 | if ok && boolVal == types.False { |
| 305 | return types.False |
| 306 | } |
| 307 | if !ok { |
| 308 | isUnk := false |
| 309 | unk, isUnk = types.MaybeMergeUnknowns(val, unk) |
| 310 | if !isUnk && err == nil { |
| 311 | if types.IsError(val) { |
| 312 | err = val |
| 313 | } else { |
| 314 | err = types.MaybeNoSuchOverloadErr(val) |
| 315 | } |
| 316 | err = types.LabelErrNode(and.id, err) |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | if unk != nil { |
| 321 | return unk |
| 322 | } |
| 323 | if err != nil { |
| 324 | return err |
| 325 | } |
| 326 | return types.True |
| 327 | } |
| 328 | |
| 329 | type evalEq struct { |
| 330 | id int64 |
| 331 | lhs Interpretable |
| 332 | rhs Interpretable |
| 333 | } |
| 334 | |
| 335 | // ID implements the Interpretable interface method. |
| 336 | func (eq *evalEq) ID() int64 { |
| 337 | return eq.id |
| 338 | } |
| 339 | |
| 340 | // Eval implements the Interpretable interface method. |
| 341 | func (eq *evalEq) Eval(ctx Activation) ref.Val { |
| 342 | lVal := eq.lhs.Eval(ctx) |
| 343 | rVal := eq.rhs.Eval(ctx) |
| 344 | if types.IsUnknownOrError(lVal) { |
| 345 | return lVal |
| 346 | } |
| 347 | if types.IsUnknownOrError(rVal) { |
| 348 | return rVal |
| 349 | } |
| 350 | return types.Equal(lVal, rVal) |
| 351 | } |
| 352 | |
| 353 | // Function implements the InterpretableCall interface method. |
| 354 | func (*evalEq) Function() string { |
| 355 | return operators.Equals |
| 356 | } |
| 357 | |
| 358 | // OverloadID implements the InterpretableCall interface method. |
| 359 | func (*evalEq) OverloadID() string { |
| 360 | return overloads.Equals |
| 361 | } |
| 362 | |
| 363 | // Args implements the InterpretableCall interface method. |
| 364 | func (eq *evalEq) Args() []Interpretable { |
| 365 | return []Interpretable{eq.lhs, eq.rhs} |
| 366 | } |
| 367 | |
| 368 | type evalNe struct { |
| 369 | id int64 |
| 370 | lhs Interpretable |
| 371 | rhs Interpretable |
| 372 | } |
| 373 | |
| 374 | // ID implements the Interpretable interface method. |
| 375 | func (ne *evalNe) ID() int64 { |
| 376 | return ne.id |
| 377 | } |
| 378 | |
| 379 | // Eval implements the Interpretable interface method. |
| 380 | func (ne *evalNe) Eval(ctx Activation) ref.Val { |
| 381 | lVal := ne.lhs.Eval(ctx) |
| 382 | rVal := ne.rhs.Eval(ctx) |
| 383 | if types.IsUnknownOrError(lVal) { |
| 384 | return lVal |
| 385 | } |
| 386 | if types.IsUnknownOrError(rVal) { |
| 387 | return rVal |
| 388 | } |
| 389 | return types.Bool(types.Equal(lVal, rVal) != types.True) |
| 390 | } |
| 391 | |
| 392 | // Function implements the InterpretableCall interface method. |
| 393 | func (*evalNe) Function() string { |
| 394 | return operators.NotEquals |
| 395 | } |
| 396 | |
| 397 | // OverloadID implements the InterpretableCall interface method. |
| 398 | func (*evalNe) OverloadID() string { |
| 399 | return overloads.NotEquals |
| 400 | } |
| 401 | |
| 402 | // Args implements the InterpretableCall interface method. |
| 403 | func (ne *evalNe) Args() []Interpretable { |
| 404 | return []Interpretable{ne.lhs, ne.rhs} |
| 405 | } |
| 406 | |
| 407 | type evalZeroArity struct { |
| 408 | id int64 |
| 409 | function string |
| 410 | overload string |
| 411 | impl functions.FunctionOp |
| 412 | } |
| 413 | |
| 414 | // ID implements the Interpretable interface method. |
| 415 | func (zero *evalZeroArity) ID() int64 { |
| 416 | return zero.id |
| 417 | } |
| 418 | |
| 419 | // Eval implements the Interpretable interface method. |
| 420 | func (zero *evalZeroArity) Eval(ctx Activation) ref.Val { |
| 421 | return types.LabelErrNode(zero.id, zero.impl()) |
| 422 | } |
| 423 | |
| 424 | // Function implements the InterpretableCall interface method. |
| 425 | func (zero *evalZeroArity) Function() string { |
| 426 | return zero.function |
| 427 | } |
| 428 | |
| 429 | // OverloadID implements the InterpretableCall interface method. |
| 430 | func (zero *evalZeroArity) OverloadID() string { |
| 431 | return zero.overload |
| 432 | } |
| 433 | |
| 434 | // Args returns the argument to the unary function. |
| 435 | func (zero *evalZeroArity) Args() []Interpretable { |
| 436 | return []Interpretable{} |
| 437 | } |
| 438 | |
| 439 | type evalUnary struct { |
| 440 | id int64 |
| 441 | function string |
| 442 | overload string |
| 443 | arg Interpretable |
| 444 | trait int |
| 445 | impl functions.UnaryOp |
| 446 | nonStrict bool |
| 447 | } |
| 448 | |
| 449 | // ID implements the Interpretable interface method. |
| 450 | func (un *evalUnary) ID() int64 { |
| 451 | return un.id |
| 452 | } |
| 453 | |
| 454 | // Eval implements the Interpretable interface method. |
| 455 | func (un *evalUnary) Eval(ctx Activation) ref.Val { |
| 456 | argVal := un.arg.Eval(ctx) |
| 457 | // Early return if the argument to the function is unknown or error. |
| 458 | strict := !un.nonStrict |
| 459 | if strict && types.IsUnknownOrError(argVal) { |
| 460 | return argVal |
| 461 | } |
| 462 | // If the implementation is bound and the argument value has the right traits required to |
| 463 | // invoke it, then call the implementation. |
| 464 | if un.impl != nil && (un.trait == 0 || (!strict && types.IsUnknownOrError(argVal)) || argVal.Type().HasTrait(un.trait)) { |
| 465 | return types.LabelErrNode(un.id, un.impl(argVal)) |
| 466 | } |
| 467 | // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the |
| 468 | // operand (arg0). |
| 469 | if argVal.Type().HasTrait(traits.ReceiverType) { |
| 470 | return types.LabelErrNode(un.id, argVal.(traits.Receiver).Receive(un.function, un.overload, []ref.Val{})) |
| 471 | } |
| 472 | return types.NewErrWithNodeID(un.id, "no such overload: %s", un.function) |
| 473 | } |
| 474 | |
| 475 | // Function implements the InterpretableCall interface method. |
| 476 | func (un *evalUnary) Function() string { |
| 477 | return un.function |
| 478 | } |
| 479 | |
| 480 | // OverloadID implements the InterpretableCall interface method. |
| 481 | func (un *evalUnary) OverloadID() string { |
| 482 | return un.overload |
| 483 | } |
| 484 | |
| 485 | // Args returns the argument to the unary function. |
| 486 | func (un *evalUnary) Args() []Interpretable { |
| 487 | return []Interpretable{un.arg} |
| 488 | } |
| 489 | |
| 490 | type evalBinary struct { |
| 491 | id int64 |
| 492 | function string |
| 493 | overload string |
| 494 | lhs Interpretable |
| 495 | rhs Interpretable |
| 496 | trait int |
| 497 | impl functions.BinaryOp |
| 498 | nonStrict bool |
| 499 | } |
| 500 | |
| 501 | // ID implements the Interpretable interface method. |
| 502 | func (bin *evalBinary) ID() int64 { |
| 503 | return bin.id |
| 504 | } |
| 505 | |
| 506 | // Eval implements the Interpretable interface method. |
| 507 | func (bin *evalBinary) Eval(ctx Activation) ref.Val { |
| 508 | lVal := bin.lhs.Eval(ctx) |
| 509 | rVal := bin.rhs.Eval(ctx) |
| 510 | // Early return if any argument to the function is unknown or error. |
| 511 | strict := !bin.nonStrict |
| 512 | if strict { |
| 513 | if types.IsUnknownOrError(lVal) { |
| 514 | return lVal |
| 515 | } |
| 516 | if types.IsUnknownOrError(rVal) { |
| 517 | return rVal |
| 518 | } |
| 519 | } |
| 520 | // If the implementation is bound and the argument value has the right traits required to |
| 521 | // invoke it, then call the implementation. |
| 522 | if bin.impl != nil && (bin.trait == 0 || (!strict && types.IsUnknownOrError(lVal)) || lVal.Type().HasTrait(bin.trait)) { |
| 523 | return types.LabelErrNode(bin.id, bin.impl(lVal, rVal)) |
| 524 | } |
| 525 | // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the |
| 526 | // operand (arg0). |
| 527 | if lVal.Type().HasTrait(traits.ReceiverType) { |
| 528 | return types.LabelErrNode(bin.id, lVal.(traits.Receiver).Receive(bin.function, bin.overload, []ref.Val{rVal})) |
| 529 | } |
| 530 | return types.NewErrWithNodeID(bin.id, "no such overload: %s", bin.function) |
| 531 | } |
| 532 | |
| 533 | // Function implements the InterpretableCall interface method. |
| 534 | func (bin *evalBinary) Function() string { |
| 535 | return bin.function |
| 536 | } |
| 537 | |
| 538 | // OverloadID implements the InterpretableCall interface method. |
| 539 | func (bin *evalBinary) OverloadID() string { |
| 540 | return bin.overload |
| 541 | } |
| 542 | |
| 543 | // Args returns the argument to the unary function. |
| 544 | func (bin *evalBinary) Args() []Interpretable { |
| 545 | return []Interpretable{bin.lhs, bin.rhs} |
| 546 | } |
| 547 | |
| 548 | type evalVarArgs struct { |
| 549 | id int64 |
| 550 | function string |
| 551 | overload string |
| 552 | args []Interpretable |
| 553 | trait int |
| 554 | impl functions.FunctionOp |
| 555 | nonStrict bool |
| 556 | } |
| 557 | |
| 558 | // NewCall creates a new call Interpretable. |
| 559 | func NewCall(id int64, function, overload string, args []Interpretable, impl functions.FunctionOp) InterpretableCall { |
| 560 | return &evalVarArgs{ |
| 561 | id: id, |
| 562 | function: function, |
| 563 | overload: overload, |
| 564 | args: args, |
| 565 | impl: impl, |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | // ID implements the Interpretable interface method. |
| 570 | func (fn *evalVarArgs) ID() int64 { |
| 571 | return fn.id |
| 572 | } |
| 573 | |
| 574 | // Eval implements the Interpretable interface method. |
| 575 | func (fn *evalVarArgs) Eval(ctx Activation) ref.Val { |
| 576 | argVals := make([]ref.Val, len(fn.args)) |
| 577 | // Early return if any argument to the function is unknown or error. |
| 578 | strict := !fn.nonStrict |
| 579 | for i, arg := range fn.args { |
| 580 | argVals[i] = arg.Eval(ctx) |
| 581 | if strict && types.IsUnknownOrError(argVals[i]) { |
| 582 | return argVals[i] |
| 583 | } |
| 584 | } |
| 585 | // If the implementation is bound and the argument value has the right traits required to |
| 586 | // invoke it, then call the implementation. |
| 587 | arg0 := argVals[0] |
| 588 | if fn.impl != nil && (fn.trait == 0 || (!strict && types.IsUnknownOrError(arg0)) || arg0.Type().HasTrait(fn.trait)) { |
| 589 | return types.LabelErrNode(fn.id, fn.impl(argVals...)) |
| 590 | } |
| 591 | // Otherwise, if the argument is a ReceiverType attempt to invoke the receiver method on the |
| 592 | // operand (arg0). |
| 593 | if arg0.Type().HasTrait(traits.ReceiverType) { |
| 594 | return types.LabelErrNode(fn.id, arg0.(traits.Receiver).Receive(fn.function, fn.overload, argVals[1:])) |
| 595 | } |
| 596 | return types.NewErrWithNodeID(fn.id, "no such overload: %s %d", fn.function, fn.id) |
| 597 | } |
| 598 | |
| 599 | // Function implements the InterpretableCall interface method. |
| 600 | func (fn *evalVarArgs) Function() string { |
| 601 | return fn.function |
| 602 | } |
| 603 | |
| 604 | // OverloadID implements the InterpretableCall interface method. |
| 605 | func (fn *evalVarArgs) OverloadID() string { |
| 606 | return fn.overload |
| 607 | } |
| 608 | |
| 609 | // Args returns the argument to the unary function. |
| 610 | func (fn *evalVarArgs) Args() []Interpretable { |
| 611 | return fn.args |
| 612 | } |
| 613 | |
| 614 | type evalList struct { |
| 615 | id int64 |
| 616 | elems []Interpretable |
| 617 | optionals []bool |
| 618 | hasOptionals bool |
| 619 | adapter types.Adapter |
| 620 | } |
| 621 | |
| 622 | // ID implements the Interpretable interface method. |
| 623 | func (l *evalList) ID() int64 { |
| 624 | return l.id |
| 625 | } |
| 626 | |
| 627 | // Eval implements the Interpretable interface method. |
| 628 | func (l *evalList) Eval(ctx Activation) ref.Val { |
| 629 | elemVals := make([]ref.Val, 0, len(l.elems)) |
| 630 | // If any argument is unknown or error early terminate. |
| 631 | for i, elem := range l.elems { |
| 632 | elemVal := elem.Eval(ctx) |
| 633 | if types.IsUnknownOrError(elemVal) { |
| 634 | return elemVal |
| 635 | } |
| 636 | if l.hasOptionals && l.optionals[i] { |
| 637 | optVal, ok := elemVal.(*types.Optional) |
| 638 | if !ok { |
| 639 | return types.LabelErrNode(l.id, invalidOptionalElementInit(elemVal)) |
| 640 | } |
| 641 | if !optVal.HasValue() { |
| 642 | continue |
| 643 | } |
| 644 | elemVal = optVal.GetValue() |
| 645 | } |
| 646 | elemVals = append(elemVals, elemVal) |
| 647 | } |
| 648 | return l.adapter.NativeToValue(elemVals) |
| 649 | } |
| 650 | |
| 651 | func (l *evalList) InitVals() []Interpretable { |
| 652 | return l.elems |
| 653 | } |
| 654 | |
| 655 | func (l *evalList) Type() ref.Type { |
| 656 | return types.ListType |
| 657 | } |
| 658 | |
| 659 | type evalMap struct { |
| 660 | id int64 |
| 661 | keys []Interpretable |
| 662 | vals []Interpretable |
| 663 | optionals []bool |
| 664 | hasOptionals bool |
| 665 | adapter types.Adapter |
| 666 | } |
| 667 | |
| 668 | // ID implements the Interpretable interface method. |
| 669 | func (m *evalMap) ID() int64 { |
| 670 | return m.id |
| 671 | } |
| 672 | |
| 673 | // Eval implements the Interpretable interface method. |
| 674 | func (m *evalMap) Eval(ctx Activation) ref.Val { |
| 675 | entries := make(map[ref.Val]ref.Val) |
| 676 | // If any argument is unknown or error early terminate. |
| 677 | for i, key := range m.keys { |
| 678 | keyVal := key.Eval(ctx) |
| 679 | if types.IsUnknownOrError(keyVal) { |
| 680 | return keyVal |
| 681 | } |
| 682 | valVal := m.vals[i].Eval(ctx) |
| 683 | if types.IsUnknownOrError(valVal) { |
| 684 | return valVal |
| 685 | } |
| 686 | if m.hasOptionals && m.optionals[i] { |
| 687 | optVal, ok := valVal.(*types.Optional) |
| 688 | if !ok { |
| 689 | return types.LabelErrNode(m.id, invalidOptionalEntryInit(keyVal, valVal)) |
| 690 | } |
| 691 | if !optVal.HasValue() { |
| 692 | delete(entries, keyVal) |
| 693 | continue |
| 694 | } |
| 695 | valVal = optVal.GetValue() |
| 696 | } |
| 697 | entries[keyVal] = valVal |
| 698 | } |
| 699 | return m.adapter.NativeToValue(entries) |
| 700 | } |
| 701 | |
| 702 | func (m *evalMap) InitVals() []Interpretable { |
| 703 | if len(m.keys) != len(m.vals) { |
| 704 | return nil |
| 705 | } |
| 706 | result := make([]Interpretable, len(m.keys)+len(m.vals)) |
| 707 | idx := 0 |
| 708 | for i, k := range m.keys { |
| 709 | v := m.vals[i] |
| 710 | result[idx] = k |
| 711 | idx++ |
| 712 | result[idx] = v |
| 713 | idx++ |
| 714 | } |
| 715 | return result |
| 716 | } |
| 717 | |
| 718 | func (m *evalMap) Type() ref.Type { |
| 719 | return types.MapType |
| 720 | } |
| 721 | |
| 722 | type evalObj struct { |
| 723 | id int64 |
| 724 | typeName string |
| 725 | fields []string |
| 726 | vals []Interpretable |
| 727 | optionals []bool |
| 728 | hasOptionals bool |
| 729 | provider types.Provider |
| 730 | } |
| 731 | |
| 732 | // ID implements the Interpretable interface method. |
| 733 | func (o *evalObj) ID() int64 { |
| 734 | return o.id |
| 735 | } |
| 736 | |
| 737 | // Eval implements the Interpretable interface method. |
| 738 | func (o *evalObj) Eval(ctx Activation) ref.Val { |
| 739 | fieldVals := make(map[string]ref.Val) |
| 740 | // If any argument is unknown or error early terminate. |
| 741 | for i, field := range o.fields { |
| 742 | val := o.vals[i].Eval(ctx) |
| 743 | if types.IsUnknownOrError(val) { |
| 744 | return val |
| 745 | } |
| 746 | if o.hasOptionals && o.optionals[i] { |
| 747 | optVal, ok := val.(*types.Optional) |
| 748 | if !ok { |
| 749 | return types.LabelErrNode(o.id, invalidOptionalEntryInit(field, val)) |
| 750 | } |
| 751 | if !optVal.HasValue() { |
| 752 | delete(fieldVals, field) |
| 753 | continue |
| 754 | } |
| 755 | val = optVal.GetValue() |
| 756 | } |
| 757 | fieldVals[field] = val |
| 758 | } |
| 759 | return types.LabelErrNode(o.id, o.provider.NewValue(o.typeName, fieldVals)) |
| 760 | } |
| 761 | |
| 762 | // InitVals implements the InterpretableConstructor interface method. |
| 763 | func (o *evalObj) InitVals() []Interpretable { |
| 764 | return o.vals |
| 765 | } |
| 766 | |
| 767 | // Type implements the InterpretableConstructor interface method. |
| 768 | func (o *evalObj) Type() ref.Type { |
| 769 | return types.NewObjectType(o.typeName) |
| 770 | } |
| 771 | |
| 772 | type evalFold struct { |
| 773 | id int64 |
| 774 | accuVar string |
| 775 | iterVar string |
| 776 | iterVar2 string |
| 777 | iterRange Interpretable |
| 778 | accu Interpretable |
| 779 | cond Interpretable |
| 780 | step Interpretable |
| 781 | result Interpretable |
| 782 | adapter types.Adapter |
| 783 | |
| 784 | // note an exhaustive fold will ensure that all branches are evaluated |
| 785 | // when using mutable values, these branches will mutate the final result |
| 786 | // rather than make a throw-away computation. |
| 787 | exhaustive bool |
| 788 | interruptable bool |
| 789 | } |
| 790 | |
| 791 | // ID implements the Interpretable interface method. |
| 792 | func (fold *evalFold) ID() int64 { |
| 793 | return fold.id |
| 794 | } |
| 795 | |
| 796 | // Eval implements the Interpretable interface method. |
| 797 | func (fold *evalFold) Eval(ctx Activation) ref.Val { |
| 798 | // Initialize the folder interface |
| 799 | f := newFolder(fold, ctx) |
| 800 | defer releaseFolder(f) |
| 801 | |
| 802 | foldRange := fold.iterRange.Eval(ctx) |
| 803 | if types.IsUnknownOrError(foldRange) { |
| 804 | return foldRange |
| 805 | } |
| 806 | if fold.iterVar2 != "" { |
| 807 | var foldable traits.Foldable |
| 808 | switch r := foldRange.(type) { |
| 809 | case traits.Mapper: |
| 810 | foldable = types.ToFoldableMap(r) |
| 811 | case traits.Lister: |
| 812 | foldable = types.ToFoldableList(r) |
| 813 | default: |
| 814 | return types.NewErrWithNodeID(fold.ID(), "unsupported comprehension range type: %T", foldRange) |
| 815 | } |
| 816 | foldable.Fold(f) |
| 817 | return f.evalResult() |
| 818 | } |
| 819 | |
| 820 | if !foldRange.Type().HasTrait(traits.IterableType) { |
| 821 | return types.ValOrErr(foldRange, "got '%T', expected iterable type", foldRange) |
| 822 | } |
| 823 | iterable := foldRange.(traits.Iterable) |
| 824 | return f.foldIterable(iterable) |
| 825 | } |
| 826 | |
| 827 | // Optional Interpretable implementations that specialize, subsume, or extend the core evaluation |
| 828 | // plan via decorators. |
| 829 | |
| 830 | // evalSetMembership is an Interpretable implementation which tests whether an input value |
| 831 | // exists within the set of map keys used to model a set. |
| 832 | type evalSetMembership struct { |
| 833 | inst Interpretable |
| 834 | arg Interpretable |
| 835 | valueSet map[ref.Val]ref.Val |
| 836 | } |
| 837 | |
| 838 | // ID implements the Interpretable interface method. |
| 839 | func (e *evalSetMembership) ID() int64 { |
| 840 | return e.inst.ID() |
| 841 | } |
| 842 | |
| 843 | // Eval implements the Interpretable interface method. |
| 844 | func (e *evalSetMembership) Eval(ctx Activation) ref.Val { |
| 845 | val := e.arg.Eval(ctx) |
| 846 | if types.IsUnknownOrError(val) { |
| 847 | return val |
| 848 | } |
| 849 | if ret, found := e.valueSet[val]; found { |
| 850 | return ret |
| 851 | } |
| 852 | return types.False |
| 853 | } |
| 854 | |
| 855 | // evalWatch is an Interpretable implementation that wraps the execution of a given |
| 856 | // expression so that it may observe the computed value and send it to an observer. |
| 857 | type evalWatch struct { |
| 858 | Interpretable |
| 859 | observer EvalObserver |
| 860 | } |
| 861 | |
| 862 | // Eval implements the Interpretable interface method. |
| 863 | func (e *evalWatch) Eval(vars Activation) ref.Val { |
| 864 | val := e.Interpretable.Eval(vars) |
| 865 | e.observer(vars, e.ID(), e.Interpretable, val) |
| 866 | return val |
| 867 | } |
| 868 | |
| 869 | // evalWatchAttr describes a watcher of an InterpretableAttribute Interpretable. |
| 870 | // |
| 871 | // Since the watcher may be selected against at a later stage in program planning, the watcher |
| 872 | // must implement the InterpretableAttribute interface by proxy. |
| 873 | type evalWatchAttr struct { |
| 874 | InterpretableAttribute |
| 875 | observer EvalObserver |
| 876 | } |
| 877 | |
| 878 | // AddQualifier creates a wrapper over the incoming qualifier which observes the qualification |
| 879 | // result. |
| 880 | func (e *evalWatchAttr) AddQualifier(q Qualifier) (Attribute, error) { |
| 881 | switch qual := q.(type) { |
| 882 | // By default, the qualifier is either a constant or an attribute |
| 883 | // There may be some custom cases where the attribute is neither. |
| 884 | case ConstantQualifier: |
| 885 | // Expose a method to test whether the qualifier matches the input pattern. |
| 886 | q = &evalWatchConstQual{ |
| 887 | ConstantQualifier: qual, |
| 888 | observer: e.observer, |
| 889 | adapter: e.Adapter(), |
| 890 | } |
| 891 | case *evalWatchAttr: |
| 892 | // Unwrap the evalWatchAttr since the observation will be applied during Qualify or |
| 893 | // QualifyIfPresent rather than Eval. |
| 894 | q = &evalWatchAttrQual{ |
| 895 | Attribute: qual.InterpretableAttribute, |
| 896 | observer: e.observer, |
| 897 | adapter: e.Adapter(), |
| 898 | } |
| 899 | case Attribute: |
| 900 | // Expose methods which intercept the qualification prior to being applied as a qualifier. |
| 901 | // Using this interface ensures that the qualifier is converted to a constant value one |
| 902 | // time during attribute pattern matching as the method embeds the Attribute interface |
| 903 | // needed to trip the conversion to a constant. |
| 904 | q = &evalWatchAttrQual{ |
| 905 | Attribute: qual, |
| 906 | observer: e.observer, |
| 907 | adapter: e.Adapter(), |
| 908 | } |
| 909 | default: |
| 910 | // This is likely a custom qualifier type. |
| 911 | q = &evalWatchQual{ |
| 912 | Qualifier: qual, |
| 913 | observer: e.observer, |
| 914 | adapter: e.Adapter(), |
| 915 | } |
| 916 | } |
| 917 | _, err := e.InterpretableAttribute.AddQualifier(q) |
| 918 | return e, err |
| 919 | } |
| 920 | |
| 921 | // Eval implements the Interpretable interface method. |
| 922 | func (e *evalWatchAttr) Eval(vars Activation) ref.Val { |
| 923 | val := e.InterpretableAttribute.Eval(vars) |
| 924 | e.observer(vars, e.ID(), e.InterpretableAttribute, val) |
| 925 | return val |
| 926 | } |
| 927 | |
| 928 | // evalWatchConstQual observes the qualification of an object using a constant boolean, int, |
| 929 | // string, or uint. |
| 930 | type evalWatchConstQual struct { |
| 931 | ConstantQualifier |
| 932 | observer EvalObserver |
| 933 | adapter types.Adapter |
| 934 | } |
| 935 | |
| 936 | // Qualify observes the qualification of a object via a constant boolean, int, string, or uint. |
| 937 | func (e *evalWatchConstQual) Qualify(vars Activation, obj any) (any, error) { |
| 938 | out, err := e.ConstantQualifier.Qualify(vars, obj) |
| 939 | var val ref.Val |
| 940 | if err != nil { |
| 941 | val = types.LabelErrNode(e.ID(), types.WrapErr(err)) |
| 942 | } else { |
| 943 | val = e.adapter.NativeToValue(out) |
| 944 | } |
| 945 | e.observer(vars, e.ID(), e.ConstantQualifier, val) |
| 946 | return out, err |
| 947 | } |
| 948 | |
| 949 | // QualifyIfPresent conditionally qualifies the variable and only records a value if one is present. |
| 950 | func (e *evalWatchConstQual) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { |
| 951 | out, present, err := e.ConstantQualifier.QualifyIfPresent(vars, obj, presenceOnly) |
| 952 | var val ref.Val |
| 953 | if err != nil { |
| 954 | val = types.LabelErrNode(e.ID(), types.WrapErr(err)) |
| 955 | } else if out != nil { |
| 956 | val = e.adapter.NativeToValue(out) |
| 957 | } else if presenceOnly { |
| 958 | val = types.Bool(present) |
| 959 | } |
| 960 | if present || presenceOnly { |
| 961 | e.observer(vars, e.ID(), e.ConstantQualifier, val) |
| 962 | } |
| 963 | return out, present, err |
| 964 | } |
| 965 | |
| 966 | // QualifierValueEquals tests whether the incoming value is equal to the qualifying constant. |
| 967 | func (e *evalWatchConstQual) QualifierValueEquals(value any) bool { |
| 968 | qve, ok := e.ConstantQualifier.(qualifierValueEquator) |
| 969 | return ok && qve.QualifierValueEquals(value) |
| 970 | } |
| 971 | |
| 972 | // evalWatchAttrQual observes the qualification of an object by a value computed at runtime. |
| 973 | type evalWatchAttrQual struct { |
| 974 | Attribute |
| 975 | observer EvalObserver |
| 976 | adapter ref.TypeAdapter |
| 977 | } |
| 978 | |
| 979 | // Qualify observes the qualification of a object via a value computed at runtime. |
| 980 | func (e *evalWatchAttrQual) Qualify(vars Activation, obj any) (any, error) { |
| 981 | out, err := e.Attribute.Qualify(vars, obj) |
| 982 | var val ref.Val |
| 983 | if err != nil { |
| 984 | val = types.LabelErrNode(e.ID(), types.WrapErr(err)) |
| 985 | } else { |
| 986 | val = e.adapter.NativeToValue(out) |
| 987 | } |
| 988 | e.observer(vars, e.ID(), e.Attribute, val) |
| 989 | return out, err |
| 990 | } |
| 991 | |
| 992 | // QualifyIfPresent conditionally qualifies the variable and only records a value if one is present. |
| 993 | func (e *evalWatchAttrQual) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { |
| 994 | out, present, err := e.Attribute.QualifyIfPresent(vars, obj, presenceOnly) |
| 995 | var val ref.Val |
| 996 | if err != nil { |
| 997 | val = types.LabelErrNode(e.ID(), types.WrapErr(err)) |
| 998 | } else if out != nil { |
| 999 | val = e.adapter.NativeToValue(out) |
| 1000 | } else if presenceOnly { |
| 1001 | val = types.Bool(present) |
| 1002 | } |
| 1003 | if present || presenceOnly { |
| 1004 | e.observer(vars, e.ID(), e.Attribute, val) |
| 1005 | } |
| 1006 | return out, present, err |
| 1007 | } |
| 1008 | |
| 1009 | // evalWatchQual observes the qualification of an object by a value computed at runtime. |
| 1010 | type evalWatchQual struct { |
| 1011 | Qualifier |
| 1012 | observer EvalObserver |
| 1013 | adapter types.Adapter |
| 1014 | } |
| 1015 | |
| 1016 | // Qualify observes the qualification of a object via a value computed at runtime. |
| 1017 | func (e *evalWatchQual) Qualify(vars Activation, obj any) (any, error) { |
| 1018 | out, err := e.Qualifier.Qualify(vars, obj) |
| 1019 | var val ref.Val |
| 1020 | if err != nil { |
| 1021 | val = types.LabelErrNode(e.ID(), types.WrapErr(err)) |
| 1022 | } else { |
| 1023 | val = e.adapter.NativeToValue(out) |
| 1024 | } |
| 1025 | e.observer(vars, e.ID(), e.Qualifier, val) |
| 1026 | return out, err |
| 1027 | } |
| 1028 | |
| 1029 | // QualifyIfPresent conditionally qualifies the variable and only records a value if one is present. |
| 1030 | func (e *evalWatchQual) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { |
| 1031 | out, present, err := e.Qualifier.QualifyIfPresent(vars, obj, presenceOnly) |
| 1032 | var val ref.Val |
| 1033 | if err != nil { |
| 1034 | val = types.LabelErrNode(e.ID(), types.WrapErr(err)) |
| 1035 | } else if out != nil { |
| 1036 | val = e.adapter.NativeToValue(out) |
| 1037 | } else if presenceOnly { |
| 1038 | val = types.Bool(present) |
| 1039 | } |
| 1040 | if present || presenceOnly { |
| 1041 | e.observer(vars, e.ID(), e.Qualifier, val) |
| 1042 | } |
| 1043 | return out, present, err |
| 1044 | } |
| 1045 | |
| 1046 | // evalWatchConst describes a watcher of an instConst Interpretable. |
| 1047 | type evalWatchConst struct { |
| 1048 | InterpretableConst |
| 1049 | observer EvalObserver |
| 1050 | } |
| 1051 | |
| 1052 | // Eval implements the Interpretable interface method. |
| 1053 | func (e *evalWatchConst) Eval(vars Activation) ref.Val { |
| 1054 | val := e.Value() |
| 1055 | e.observer(vars, e.ID(), e.InterpretableConst, val) |
| 1056 | return val |
| 1057 | } |
| 1058 | |
| 1059 | // evalExhaustiveOr is just like evalOr, but does not short-circuit argument evaluation. |
| 1060 | type evalExhaustiveOr struct { |
| 1061 | id int64 |
| 1062 | terms []Interpretable |
| 1063 | } |
| 1064 | |
| 1065 | // ID implements the Interpretable interface method. |
| 1066 | func (or *evalExhaustiveOr) ID() int64 { |
| 1067 | return or.id |
| 1068 | } |
| 1069 | |
| 1070 | // Eval implements the Interpretable interface method. |
| 1071 | func (or *evalExhaustiveOr) Eval(ctx Activation) ref.Val { |
| 1072 | var err ref.Val = nil |
| 1073 | var unk *types.Unknown |
| 1074 | isTrue := false |
| 1075 | for _, term := range or.terms { |
| 1076 | val := term.Eval(ctx) |
| 1077 | boolVal, ok := val.(types.Bool) |
| 1078 | // flag the result as true |
| 1079 | if ok && boolVal == types.True { |
| 1080 | isTrue = true |
| 1081 | } |
| 1082 | if !ok && !isTrue { |
| 1083 | isUnk := false |
| 1084 | unk, isUnk = types.MaybeMergeUnknowns(val, unk) |
| 1085 | if !isUnk && err == nil { |
| 1086 | if types.IsError(val) { |
| 1087 | err = val |
| 1088 | } else { |
| 1089 | err = types.MaybeNoSuchOverloadErr(val) |
| 1090 | } |
| 1091 | } |
| 1092 | } |
| 1093 | } |
| 1094 | if isTrue { |
| 1095 | return types.True |
| 1096 | } |
| 1097 | if unk != nil { |
| 1098 | return unk |
| 1099 | } |
| 1100 | if err != nil { |
| 1101 | return err |
| 1102 | } |
| 1103 | return types.False |
| 1104 | } |
| 1105 | |
| 1106 | // evalExhaustiveAnd is just like evalAnd, but does not short-circuit argument evaluation. |
| 1107 | type evalExhaustiveAnd struct { |
| 1108 | id int64 |
| 1109 | terms []Interpretable |
| 1110 | } |
| 1111 | |
| 1112 | // ID implements the Interpretable interface method. |
| 1113 | func (and *evalExhaustiveAnd) ID() int64 { |
| 1114 | return and.id |
| 1115 | } |
| 1116 | |
| 1117 | // Eval implements the Interpretable interface method. |
| 1118 | func (and *evalExhaustiveAnd) Eval(ctx Activation) ref.Val { |
| 1119 | var err ref.Val = nil |
| 1120 | var unk *types.Unknown |
| 1121 | isFalse := false |
| 1122 | for _, term := range and.terms { |
| 1123 | val := term.Eval(ctx) |
| 1124 | boolVal, ok := val.(types.Bool) |
| 1125 | // short-circuit on false. |
| 1126 | if ok && boolVal == types.False { |
| 1127 | isFalse = true |
| 1128 | } |
| 1129 | if !ok && !isFalse { |
| 1130 | isUnk := false |
| 1131 | unk, isUnk = types.MaybeMergeUnknowns(val, unk) |
| 1132 | if !isUnk && err == nil { |
| 1133 | if types.IsError(val) { |
| 1134 | err = val |
| 1135 | } else { |
| 1136 | err = types.MaybeNoSuchOverloadErr(val) |
| 1137 | } |
| 1138 | } |
| 1139 | } |
| 1140 | } |
| 1141 | if isFalse { |
| 1142 | return types.False |
| 1143 | } |
| 1144 | if unk != nil { |
| 1145 | return unk |
| 1146 | } |
| 1147 | if err != nil { |
| 1148 | return err |
| 1149 | } |
| 1150 | return types.True |
| 1151 | } |
| 1152 | |
| 1153 | // evalExhaustiveConditional is like evalConditional, but does not short-circuit argument |
| 1154 | // evaluation. |
| 1155 | type evalExhaustiveConditional struct { |
| 1156 | id int64 |
| 1157 | adapter types.Adapter |
| 1158 | attr *conditionalAttribute |
| 1159 | } |
| 1160 | |
| 1161 | // ID implements the Interpretable interface method. |
| 1162 | func (cond *evalExhaustiveConditional) ID() int64 { |
| 1163 | return cond.id |
| 1164 | } |
| 1165 | |
| 1166 | // Eval implements the Interpretable interface method. |
| 1167 | func (cond *evalExhaustiveConditional) Eval(ctx Activation) ref.Val { |
| 1168 | cVal := cond.attr.expr.Eval(ctx) |
| 1169 | tVal, tErr := cond.attr.truthy.Resolve(ctx) |
| 1170 | fVal, fErr := cond.attr.falsy.Resolve(ctx) |
| 1171 | cBool, ok := cVal.(types.Bool) |
| 1172 | if !ok { |
| 1173 | return types.ValOrErr(cVal, "no such overload") |
| 1174 | } |
| 1175 | if cBool { |
| 1176 | if tErr != nil { |
| 1177 | return types.LabelErrNode(cond.id, types.WrapErr(tErr)) |
| 1178 | } |
| 1179 | return cond.adapter.NativeToValue(tVal) |
| 1180 | } |
| 1181 | if fErr != nil { |
| 1182 | return types.LabelErrNode(cond.id, types.WrapErr(fErr)) |
| 1183 | } |
| 1184 | return cond.adapter.NativeToValue(fVal) |
| 1185 | } |
| 1186 | |
| 1187 | // evalAttr evaluates an Attribute value. |
| 1188 | type evalAttr struct { |
| 1189 | adapter types.Adapter |
| 1190 | attr Attribute |
| 1191 | optional bool |
| 1192 | } |
| 1193 | |
| 1194 | var _ InterpretableAttribute = &evalAttr{} |
| 1195 | |
| 1196 | // ID of the attribute instruction. |
| 1197 | func (a *evalAttr) ID() int64 { |
| 1198 | return a.attr.ID() |
| 1199 | } |
| 1200 | |
| 1201 | // AddQualifier implements the InterpretableAttribute interface method. |
| 1202 | func (a *evalAttr) AddQualifier(qual Qualifier) (Attribute, error) { |
| 1203 | attr, err := a.attr.AddQualifier(qual) |
| 1204 | a.attr = attr |
| 1205 | return attr, err |
| 1206 | } |
| 1207 | |
| 1208 | // Attr implements the InterpretableAttribute interface method. |
| 1209 | func (a *evalAttr) Attr() Attribute { |
| 1210 | return a.attr |
| 1211 | } |
| 1212 | |
| 1213 | // Adapter implements the InterpretableAttribute interface method. |
| 1214 | func (a *evalAttr) Adapter() types.Adapter { |
| 1215 | return a.adapter |
| 1216 | } |
| 1217 | |
| 1218 | // Eval implements the Interpretable interface method. |
| 1219 | func (a *evalAttr) Eval(ctx Activation) ref.Val { |
| 1220 | v, err := a.attr.Resolve(ctx) |
| 1221 | if err != nil { |
| 1222 | return types.LabelErrNode(a.ID(), types.WrapErr(err)) |
| 1223 | } |
| 1224 | return a.adapter.NativeToValue(v) |
| 1225 | } |
| 1226 | |
| 1227 | // Qualify proxies to the Attribute's Qualify method. |
| 1228 | func (a *evalAttr) Qualify(vars Activation, obj any) (any, error) { |
| 1229 | return a.attr.Qualify(vars, obj) |
| 1230 | } |
| 1231 | |
| 1232 | // QualifyIfPresent proxies to the Attribute's QualifyIfPresent method. |
| 1233 | func (a *evalAttr) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { |
| 1234 | return a.attr.QualifyIfPresent(vars, obj, presenceOnly) |
| 1235 | } |
| 1236 | |
| 1237 | func (a *evalAttr) IsOptional() bool { |
| 1238 | return a.optional |
| 1239 | } |
| 1240 | |
| 1241 | // Resolve proxies to the Attribute's Resolve method. |
| 1242 | func (a *evalAttr) Resolve(ctx Activation) (any, error) { |
| 1243 | return a.attr.Resolve(ctx) |
| 1244 | } |
| 1245 | |
| 1246 | type evalWatchConstructor struct { |
| 1247 | constructor InterpretableConstructor |
| 1248 | observer EvalObserver |
| 1249 | } |
| 1250 | |
| 1251 | // InitVals implements the InterpretableConstructor InitVals function. |
| 1252 | func (c *evalWatchConstructor) InitVals() []Interpretable { |
| 1253 | return c.constructor.InitVals() |
| 1254 | } |
| 1255 | |
| 1256 | // Type implements the InterpretableConstructor Type function. |
| 1257 | func (c *evalWatchConstructor) Type() ref.Type { |
| 1258 | return c.constructor.Type() |
| 1259 | } |
| 1260 | |
| 1261 | // ID implements the Interpretable ID function. |
| 1262 | func (c *evalWatchConstructor) ID() int64 { |
| 1263 | return c.constructor.ID() |
| 1264 | } |
| 1265 | |
| 1266 | // Eval implements the Interpretable Eval function. |
| 1267 | func (c *evalWatchConstructor) Eval(vars Activation) ref.Val { |
| 1268 | val := c.constructor.Eval(vars) |
| 1269 | c.observer(vars, c.ID(), c.constructor, val) |
| 1270 | return val |
| 1271 | } |
| 1272 | |
| 1273 | func invalidOptionalEntryInit(field any, value ref.Val) ref.Val { |
| 1274 | return types.NewErr("cannot initialize optional entry '%v' from non-optional value %v", field, value) |
| 1275 | } |
| 1276 | |
| 1277 | func invalidOptionalElementInit(value ref.Val) ref.Val { |
| 1278 | return types.NewErr("cannot initialize optional list element from non-optional value %v", value) |
| 1279 | } |
| 1280 | |
| 1281 | // newFolder creates or initializes a pooled folder instance. |
| 1282 | func newFolder(eval *evalFold, ctx Activation) *folder { |
| 1283 | f := folderPool.Get().(*folder) |
| 1284 | f.evalFold = eval |
| 1285 | f.activation = ctx |
| 1286 | return f |
| 1287 | } |
| 1288 | |
| 1289 | // releaseFolder resets and releases a pooled folder instance. |
| 1290 | func releaseFolder(f *folder) { |
| 1291 | f.reset() |
| 1292 | folderPool.Put(f) |
| 1293 | } |
| 1294 | |
| 1295 | // folder tracks the state associated with folding a list or map with a comprehension v2 style macro. |
| 1296 | // |
| 1297 | // The folder embeds an interpreter.Activation and Interpretable evalFold value as well as implements |
| 1298 | // the traits.Folder interface methods. |
| 1299 | // |
| 1300 | // Instances of a folder are intended to be pooled to minimize allocation overhead with this temporary |
| 1301 | // bookkeeping object which supports lazy evaluation of the accumulator init expression which is useful |
| 1302 | // in preserving evaluation order semantics which might otherwise be disrupted through the use of |
| 1303 | // cel.bind or cel.@block. |
| 1304 | type folder struct { |
| 1305 | *evalFold |
| 1306 | activation Activation |
| 1307 | |
| 1308 | // fold state objects. |
| 1309 | accuVal ref.Val |
| 1310 | iterVar1Val any |
| 1311 | iterVar2Val any |
| 1312 | |
| 1313 | // bookkeeping flags to modify Activation and fold behaviors. |
| 1314 | initialized bool |
| 1315 | mutableValue bool |
| 1316 | interrupted bool |
| 1317 | computeResult bool |
| 1318 | } |
| 1319 | |
| 1320 | func (f *folder) foldIterable(iterable traits.Iterable) ref.Val { |
| 1321 | it := iterable.Iterator() |
| 1322 | for it.HasNext() == types.True { |
| 1323 | f.iterVar1Val = it.Next() |
| 1324 | |
| 1325 | cond := f.cond.Eval(f) |
| 1326 | condBool, ok := cond.(types.Bool) |
| 1327 | if f.interrupted || (!f.exhaustive && ok && condBool != types.True) { |
| 1328 | return f.evalResult() |
| 1329 | } |
| 1330 | |
| 1331 | // Update the accumulation value and check for eval interuption. |
| 1332 | f.accuVal = f.step.Eval(f) |
| 1333 | f.initialized = true |
| 1334 | if f.interruptable && checkInterrupt(f.activation) { |
| 1335 | f.interrupted = true |
| 1336 | return f.evalResult() |
| 1337 | } |
| 1338 | } |
| 1339 | return f.evalResult() |
| 1340 | } |
| 1341 | |
| 1342 | // FoldEntry will either fold comprehension v1 style macros if iterVar2 is unset, or comprehension v2 style |
| 1343 | // macros if both the iterVar and iterVar2 are set to non-empty strings. |
| 1344 | func (f *folder) FoldEntry(key, val any) bool { |
| 1345 | // Default to referencing both values. |
| 1346 | f.iterVar1Val = key |
| 1347 | f.iterVar2Val = val |
| 1348 | |
| 1349 | // Terminate evaluation if evaluation is interrupted or the condition is not true and exhaustive |
| 1350 | // eval is not enabled. |
| 1351 | cond := f.cond.Eval(f) |
| 1352 | condBool, ok := cond.(types.Bool) |
| 1353 | if f.interrupted || (!f.exhaustive && ok && condBool != types.True) { |
| 1354 | return false |
| 1355 | } |
| 1356 | |
| 1357 | // Update the accumulation value and check for eval interuption. |
| 1358 | f.accuVal = f.step.Eval(f) |
| 1359 | f.initialized = true |
| 1360 | if f.interruptable && checkInterrupt(f.activation) { |
| 1361 | f.interrupted = true |
| 1362 | return false |
| 1363 | } |
| 1364 | return true |
| 1365 | } |
| 1366 | |
| 1367 | // ResolveName overrides the default Activation lookup to perform lazy initialization of the accumulator |
| 1368 | // and specialized lookups of iteration values with consideration for whether the final result is being |
| 1369 | // computed and the iteration variables should be ignored. |
| 1370 | func (f *folder) ResolveName(name string) (any, bool) { |
| 1371 | if name == f.accuVar { |
| 1372 | if !f.initialized { |
| 1373 | f.initialized = true |
| 1374 | initVal := f.accu.Eval(f.activation) |
| 1375 | if !f.exhaustive { |
| 1376 | if l, isList := initVal.(traits.Lister); isList && l.Size() == types.IntZero { |
| 1377 | initVal = types.NewMutableList(f.adapter) |
| 1378 | f.mutableValue = true |
| 1379 | } |
| 1380 | if m, isMap := initVal.(traits.Mapper); isMap && m.Size() == types.IntZero { |
| 1381 | initVal = types.NewMutableMap(f.adapter, map[ref.Val]ref.Val{}) |
| 1382 | f.mutableValue = true |
| 1383 | } |
| 1384 | } |
| 1385 | f.accuVal = initVal |
| 1386 | } |
| 1387 | return f.accuVal, true |
| 1388 | } |
| 1389 | if !f.computeResult { |
| 1390 | if name == f.iterVar { |
| 1391 | f.iterVar1Val = f.adapter.NativeToValue(f.iterVar1Val) |
| 1392 | return f.iterVar1Val, true |
| 1393 | } |
| 1394 | if name == f.iterVar2 { |
| 1395 | f.iterVar2Val = f.adapter.NativeToValue(f.iterVar2Val) |
| 1396 | return f.iterVar2Val, true |
| 1397 | } |
| 1398 | } |
| 1399 | return f.activation.ResolveName(name) |
| 1400 | } |
| 1401 | |
| 1402 | // Parent returns the activation embedded into the folder. |
| 1403 | func (f *folder) Parent() Activation { |
| 1404 | return f.activation |
| 1405 | } |
| 1406 | |
| 1407 | // Unwrap returns the parent activation, thus omitting access to local state |
| 1408 | func (f *folder) Unwrap() Activation { |
| 1409 | return f.activation |
| 1410 | } |
| 1411 | |
| 1412 | // UnknownAttributePatterns implements the PartialActivation interface returning the unknown patterns |
| 1413 | // if they were provided to the input activation, or an empty set if the proxied activation is not partial. |
| 1414 | func (f *folder) UnknownAttributePatterns() []*AttributePattern { |
| 1415 | if pv, ok := f.activation.(partialActivationConverter); ok { |
| 1416 | if partial, isPartial := pv.AsPartialActivation(); isPartial { |
| 1417 | return partial.UnknownAttributePatterns() |
| 1418 | } |
| 1419 | } |
| 1420 | return []*AttributePattern{} |
| 1421 | } |
| 1422 | |
| 1423 | func (f *folder) AsPartialActivation() (PartialActivation, bool) { |
| 1424 | if pv, ok := f.activation.(partialActivationConverter); ok { |
| 1425 | if _, isPartial := pv.AsPartialActivation(); isPartial { |
| 1426 | return f, true |
| 1427 | } |
| 1428 | } |
| 1429 | return nil, false |
| 1430 | } |
| 1431 | |
| 1432 | // evalResult computes the final result of the fold after all entries have been folded and accumulated. |
| 1433 | func (f *folder) evalResult() ref.Val { |
| 1434 | f.computeResult = true |
| 1435 | if f.interrupted { |
| 1436 | return types.NewErr("operation interrupted") |
| 1437 | } |
| 1438 | res := f.result.Eval(f) |
| 1439 | // Convert a mutable list or map to an immutable one if the comprehension has generated a list or |
| 1440 | // map as a result. |
| 1441 | if !types.IsUnknownOrError(res) && f.mutableValue { |
| 1442 | if _, ok := res.(traits.MutableLister); ok { |
| 1443 | res = res.(traits.MutableLister).ToImmutableList() |
| 1444 | } |
| 1445 | if _, ok := res.(traits.MutableMapper); ok { |
| 1446 | res = res.(traits.MutableMapper).ToImmutableMap() |
| 1447 | } |
| 1448 | } |
| 1449 | return res |
| 1450 | } |
| 1451 | |
| 1452 | // reset clears any state associated with folder evaluation. |
| 1453 | func (f *folder) reset() { |
| 1454 | f.evalFold = nil |
| 1455 | f.activation = nil |
| 1456 | f.accuVal = nil |
| 1457 | f.iterVar1Val = nil |
| 1458 | f.iterVar2Val = nil |
| 1459 | |
| 1460 | f.initialized = false |
| 1461 | f.mutableValue = false |
| 1462 | f.interrupted = false |
| 1463 | f.computeResult = false |
| 1464 | } |
| 1465 | |
| 1466 | func checkInterrupt(a Activation) bool { |
| 1467 | stop, found := a.ResolveName("#interrupted") |
| 1468 | return found && stop == true |
| 1469 | } |
| 1470 | |
| 1471 | var ( |
| 1472 | // pool of var folders to reduce allocations during folds. |
| 1473 | folderPool = &sync.Pool{ |
| 1474 | New: func() any { |
| 1475 | return &folder{} |
| 1476 | }, |
| 1477 | } |
| 1478 | ) |