| 1 | // Copyright 2020 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package cel |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "math" |
| 20 | |
| 21 | "github.com/google/cel-go/common" |
| 22 | "github.com/google/cel-go/common/ast" |
| 23 | "github.com/google/cel-go/common/decls" |
| 24 | "github.com/google/cel-go/common/env" |
| 25 | "github.com/google/cel-go/common/operators" |
| 26 | "github.com/google/cel-go/common/overloads" |
| 27 | "github.com/google/cel-go/common/stdlib" |
| 28 | "github.com/google/cel-go/common/types" |
| 29 | "github.com/google/cel-go/common/types/ref" |
| 30 | "github.com/google/cel-go/common/types/traits" |
| 31 | "github.com/google/cel-go/interpreter" |
| 32 | "github.com/google/cel-go/parser" |
| 33 | ) |
| 34 | |
| 35 | const ( |
| 36 | optMapMacro = "optMap" |
| 37 | optFlatMapMacro = "optFlatMap" |
| 38 | hasValueFunc = "hasValue" |
| 39 | unwrapOptFunc = "unwrapOpt" |
| 40 | optionalNoneFunc = "optional.none" |
| 41 | optionalOfFunc = "optional.of" |
| 42 | optionalOfNonZeroValueFunc = "optional.ofNonZeroValue" |
| 43 | optionalUnwrapFunc = "optional.unwrap" |
| 44 | valueFunc = "value" |
| 45 | unusedIterVar = "#unused" |
| 46 | ) |
| 47 | |
| 48 | // Library provides a collection of EnvOption and ProgramOption values used to configure a CEL |
| 49 | // environment for a particular use case or with a related set of functionality. |
| 50 | // |
| 51 | // Note, the ProgramOption values provided by a library are expected to be static and not vary |
| 52 | // between calls to Env.Program(). If there is a need for such dynamic configuration, prefer to |
| 53 | // configure these options outside the Library and within the Env.Program() call directly. |
| 54 | type Library interface { |
| 55 | // CompileOptions returns a collection of functional options for configuring the Parse / Check |
| 56 | // environment. |
| 57 | CompileOptions() []EnvOption |
| 58 | |
| 59 | // ProgramOptions returns a collection of functional options which should be included in every |
| 60 | // Program generated from the Env.Program() call. |
| 61 | ProgramOptions() []ProgramOption |
| 62 | } |
| 63 | |
| 64 | // SingletonLibrary refines the Library interface to ensure that libraries in this format are only |
| 65 | // configured once within the environment. |
| 66 | type SingletonLibrary interface { |
| 67 | Library |
| 68 | |
| 69 | // LibraryName provides a namespaced name which is used to check whether the library has already |
| 70 | // been configured in the environment. |
| 71 | LibraryName() string |
| 72 | } |
| 73 | |
| 74 | // LibraryAliaser generates a simple named alias for the library, for use during environment serialization. |
| 75 | type LibraryAliaser interface { |
| 76 | LibraryAlias() string |
| 77 | } |
| 78 | |
| 79 | // LibrarySubsetter provides the subset description associated with the library, nil if not subset. |
| 80 | type LibrarySubsetter interface { |
| 81 | LibrarySubset() *env.LibrarySubset |
| 82 | } |
| 83 | |
| 84 | // LibraryVersioner provides a version number for the library. |
| 85 | // |
| 86 | // If not implemented, the library version will be flagged as 'latest' during environment serialization. |
| 87 | type LibraryVersioner interface { |
| 88 | LibraryVersion() uint32 |
| 89 | } |
| 90 | |
| 91 | // Lib creates an EnvOption out of a Library, allowing libraries to be provided as functional args, |
| 92 | // and to be linked to each other. |
| 93 | func Lib(l Library) EnvOption { |
| 94 | singleton, isSingleton := l.(SingletonLibrary) |
| 95 | return func(e *Env) (*Env, error) { |
| 96 | if isSingleton { |
| 97 | if e.HasLibrary(singleton.LibraryName()) { |
| 98 | return e, nil |
| 99 | } |
| 100 | e.libraries[singleton.LibraryName()] = singleton |
| 101 | } |
| 102 | var err error |
| 103 | for _, opt := range l.CompileOptions() { |
| 104 | e, err = opt(e) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | } |
| 109 | e.progOpts = append(e.progOpts, l.ProgramOptions()...) |
| 110 | return e, nil |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // StdLibOption specifies a functional option for configuring the standard CEL library. |
| 115 | type StdLibOption func(*stdLibrary) *stdLibrary |
| 116 | |
| 117 | // StdLibSubset configures the standard library to use a subset of its functions and macros. |
| 118 | // |
| 119 | // Since the StdLib is a singleton library, only the first instance of the StdLib() environment options |
| 120 | // will be configured on the environment which means only the StdLibSubset() initially configured with |
| 121 | // the library will be used. |
| 122 | func StdLibSubset(subset *env.LibrarySubset) StdLibOption { |
| 123 | return func(lib *stdLibrary) *stdLibrary { |
| 124 | lib.subset = subset |
| 125 | return lib |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // StdLib returns an EnvOption for the standard library of CEL functions and macros. |
| 130 | func StdLib(opts ...StdLibOption) EnvOption { |
| 131 | lib := &stdLibrary{} |
| 132 | for _, o := range opts { |
| 133 | lib = o(lib) |
| 134 | } |
| 135 | return Lib(lib) |
| 136 | } |
| 137 | |
| 138 | // stdLibrary implements the Library interface and provides functional options for the core CEL |
| 139 | // features documented in the specification. |
| 140 | type stdLibrary struct { |
| 141 | subset *env.LibrarySubset |
| 142 | } |
| 143 | |
| 144 | // LibraryName implements the SingletonLibrary interface method. |
| 145 | func (*stdLibrary) LibraryName() string { |
| 146 | return "cel.lib.std" |
| 147 | } |
| 148 | |
| 149 | // LibraryAlias returns the simple name of the library. |
| 150 | func (*stdLibrary) LibraryAlias() string { |
| 151 | return "stdlib" |
| 152 | } |
| 153 | |
| 154 | // LibrarySubset returns the env.LibrarySubset definition associated with the CEL Library. |
| 155 | func (lib *stdLibrary) LibrarySubset() *env.LibrarySubset { |
| 156 | return lib.subset |
| 157 | } |
| 158 | |
| 159 | // CompileOptions returns options for the standard CEL function declarations and macros. |
| 160 | func (lib *stdLibrary) CompileOptions() []EnvOption { |
| 161 | funcs := stdlib.Functions() |
| 162 | macros := StandardMacros |
| 163 | if lib.subset != nil { |
| 164 | subMacros := []Macro{} |
| 165 | for _, m := range macros { |
| 166 | if lib.subset.SubsetMacro(m.Function()) { |
| 167 | subMacros = append(subMacros, m) |
| 168 | } |
| 169 | } |
| 170 | macros = subMacros |
| 171 | subFuncs := []*decls.FunctionDecl{} |
| 172 | for _, fn := range funcs { |
| 173 | if f, include := lib.subset.SubsetFunction(fn); include { |
| 174 | subFuncs = append(subFuncs, f) |
| 175 | } |
| 176 | } |
| 177 | funcs = subFuncs |
| 178 | } |
| 179 | return []EnvOption{ |
| 180 | func(e *Env) (*Env, error) { |
| 181 | var err error |
| 182 | if err = lib.subset.Validate(); err != nil { |
| 183 | return nil, err |
| 184 | } |
| 185 | for _, fn := range funcs { |
| 186 | existing, found := e.functions[fn.Name()] |
| 187 | if found { |
| 188 | fn, err = existing.Merge(fn) |
| 189 | if err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | } |
| 193 | e.functions[fn.Name()] = fn |
| 194 | } |
| 195 | return e, nil |
| 196 | }, |
| 197 | Macros(macros...), |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // ProgramOptions returns function implementations for the standard CEL functions. |
| 202 | func (*stdLibrary) ProgramOptions() []ProgramOption { |
| 203 | return []ProgramOption{} |
| 204 | } |
| 205 | |
| 206 | // OptionalTypes enable support for optional syntax and types in CEL. |
| 207 | // |
| 208 | // The optional value type makes it possible to express whether variables have |
| 209 | // been provided, whether a result has been computed, and in the future whether |
| 210 | // an object field path, map key value, or list index has a value. |
| 211 | // |
| 212 | // # Syntax Changes |
| 213 | // |
| 214 | // OptionalTypes are unlike other CEL extensions because they modify the CEL |
| 215 | // syntax itself, notably through the use of a `?` preceding a field name or |
| 216 | // index value. |
| 217 | // |
| 218 | // ## Field Selection |
| 219 | // |
| 220 | // The optional syntax in field selection is denoted as `obj.?field`. In other |
| 221 | // words, if a field is set, return `optional.of(obj.field)“, else |
| 222 | // `optional.none()`. The optional field selection is viral in the sense that |
| 223 | // after the first optional selection all subsequent selections or indices |
| 224 | // are treated as optional, i.e. the following expressions are equivalent: |
| 225 | // |
| 226 | // obj.?field.subfield |
| 227 | // obj.?field.?subfield |
| 228 | // |
| 229 | // ## Indexing |
| 230 | // |
| 231 | // Similar to field selection, the optional syntax can be used in index |
| 232 | // expressions on maps and lists: |
| 233 | // |
| 234 | // list[?0] |
| 235 | // map[?key] |
| 236 | // |
| 237 | // ## Optional Field Setting |
| 238 | // |
| 239 | // When creating map or message literals, if a field may be optionally set |
| 240 | // based on its presence, then placing a `?` before the field name or key |
| 241 | // will ensure the type on the right-hand side must be optional(T) where T |
| 242 | // is the type of the field or key-value. |
| 243 | // |
| 244 | // The following returns a map with the key expression set only if the |
| 245 | // subfield is present, otherwise an empty map is created: |
| 246 | // |
| 247 | // {?key: obj.?field.subfield} |
| 248 | // |
| 249 | // ## Optional Element Setting |
| 250 | // |
| 251 | // When creating list literals, an element in the list may be optionally added |
| 252 | // when the element expression is preceded by a `?`: |
| 253 | // |
| 254 | // [a, ?b, ?c] // return a list with either [a], [a, b], [a, b, c], or [a, c] |
| 255 | // |
| 256 | // # Optional.Of |
| 257 | // |
| 258 | // Create an optional(T) value of a given value with type T. |
| 259 | // |
| 260 | // optional.of(10) |
| 261 | // |
| 262 | // # Optional.OfNonZeroValue |
| 263 | // |
| 264 | // Create an optional(T) value of a given value with type T if it is not a |
| 265 | // zero-value. A zero-value the default empty value for any given CEL type, |
| 266 | // including empty protobuf message types. If the value is empty, the result |
| 267 | // of this call will be optional.none(). |
| 268 | // |
| 269 | // optional.ofNonZeroValue([1, 2, 3]) // optional(list(int)) |
| 270 | // optional.ofNonZeroValue([]) // optional.none() |
| 271 | // optional.ofNonZeroValue(0) // optional.none() |
| 272 | // optional.ofNonZeroValue("") // optional.none() |
| 273 | // |
| 274 | // # Optional.None |
| 275 | // |
| 276 | // Create an empty optional value. |
| 277 | // |
| 278 | // # HasValue |
| 279 | // |
| 280 | // Determine whether the optional contains a value. |
| 281 | // |
| 282 | // optional.of(b'hello').hasValue() // true |
| 283 | // optional.ofNonZeroValue({}).hasValue() // false |
| 284 | // |
| 285 | // # Value |
| 286 | // |
| 287 | // Get the value contained by the optional. If the optional does not have a |
| 288 | // value, the result will be a CEL error. |
| 289 | // |
| 290 | // optional.of(b'hello').value() // b'hello' |
| 291 | // optional.ofNonZeroValue({}).value() // error |
| 292 | // |
| 293 | // # Or |
| 294 | // |
| 295 | // If the value on the left-hand side is optional.none(), the optional value |
| 296 | // on the right hand side is returned. If the value on the left-hand set is |
| 297 | // valued, then it is returned. This operation is short-circuiting and will |
| 298 | // only evaluate as many links in the `or` chain as are needed to return a |
| 299 | // non-empty optional value. |
| 300 | // |
| 301 | // obj.?field.or(m[?key]) |
| 302 | // l[?index].or(obj.?field.subfield).or(obj.?other) |
| 303 | // |
| 304 | // # OrValue |
| 305 | // |
| 306 | // Either return the value contained within the optional on the left-hand side |
| 307 | // or return the alternative value on the right hand side. |
| 308 | // |
| 309 | // m[?key].orValue("none") |
| 310 | // |
| 311 | // # OptMap |
| 312 | // |
| 313 | // Apply a transformation to the optional's underlying value if it is not empty |
| 314 | // and return an optional typed result based on the transformation. The |
| 315 | // transformation expression type must return a type T which is wrapped into |
| 316 | // an optional. |
| 317 | // |
| 318 | // msg.?elements.optMap(e, e.size()).orValue(0) |
| 319 | // |
| 320 | // # OptFlatMap |
| 321 | // |
| 322 | // Introduced in version: 1 |
| 323 | // |
| 324 | // Apply a transformation to the optional's underlying value if it is not empty |
| 325 | // and return the result. The transform expression must return an optional(T) |
| 326 | // rather than type T. This can be useful when dealing with zero values and |
| 327 | // conditionally generating an empty or non-empty result in ways which cannot |
| 328 | // be expressed with `optMap`. |
| 329 | // |
| 330 | // msg.?elements.optFlatMap(e, e[?0]) // return the first element if present. |
| 331 | // |
| 332 | // # First |
| 333 | // |
| 334 | // Introduced in version: 2 |
| 335 | // |
| 336 | // Returns an optional with the first value from the right hand list, or |
| 337 | // optional.None. |
| 338 | // |
| 339 | // [1, 2, 3].first().value() == 1 |
| 340 | // |
| 341 | // # Last |
| 342 | // |
| 343 | // Introduced in version: 2 |
| 344 | // |
| 345 | // Returns an optional with the last value from the right hand list, or |
| 346 | // optional.None. |
| 347 | // |
| 348 | // [1, 2, 3].last().value() == 3 |
| 349 | // |
| 350 | // This is syntactic sugar for msg.elements[msg.elements.size()-1]. |
| 351 | // |
| 352 | // # Unwrap / UnwrapOpt |
| 353 | // |
| 354 | // Introduced in version: 2 |
| 355 | // |
| 356 | // Returns a list of all the values that are not none in the input list of optional values. |
| 357 | // Can be used as optional.unwrap(List[T]) or with postfix notation: List[T].unwrapOpt() |
| 358 | // |
| 359 | // optional.unwrap([optional.of(42), optional.none()]) == [42] |
| 360 | // [optional.of(42), optional.none()].unwrapOpt() == [42] |
| 361 | func OptionalTypes(opts ...OptionalTypesOption) EnvOption { |
| 362 | lib := &optionalLib{version: math.MaxUint32} |
| 363 | for _, opt := range opts { |
| 364 | lib = opt(lib) |
| 365 | } |
| 366 | return Lib(lib) |
| 367 | } |
| 368 | |
| 369 | type optionalLib struct { |
| 370 | version uint32 |
| 371 | } |
| 372 | |
| 373 | // OptionalTypesOption is a functional interface for configuring the strings library. |
| 374 | type OptionalTypesOption func(*optionalLib) *optionalLib |
| 375 | |
| 376 | // OptionalTypesVersion configures the version of the optional type library. |
| 377 | // |
| 378 | // The version limits which functions are available. Only functions introduced |
| 379 | // below or equal to the given version included in the library. If this option |
| 380 | // is not set, all functions are available. |
| 381 | // |
| 382 | // See the library documentation to determine which version a function was introduced. |
| 383 | // If the documentation does not state which version a function was introduced, it can |
| 384 | // be assumed to be introduced at version 0, when the library was first created. |
| 385 | func OptionalTypesVersion(version uint32) OptionalTypesOption { |
| 386 | return func(lib *optionalLib) *optionalLib { |
| 387 | lib.version = version |
| 388 | return lib |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | // LibraryName implements the SingletonLibrary interface method. |
| 393 | func (*optionalLib) LibraryName() string { |
| 394 | return "cel.lib.optional" |
| 395 | } |
| 396 | |
| 397 | // LibraryAlias returns the simple name of the library. |
| 398 | func (*optionalLib) LibraryAlias() string { |
| 399 | return "optional" |
| 400 | } |
| 401 | |
| 402 | // LibraryVersion returns the version of the library. |
| 403 | func (lib *optionalLib) LibraryVersion() uint32 { |
| 404 | return lib.version |
| 405 | } |
| 406 | |
| 407 | // CompileOptions implements the Library interface method. |
| 408 | func (lib *optionalLib) CompileOptions() []EnvOption { |
| 409 | paramTypeK := TypeParamType("K") |
| 410 | paramTypeV := TypeParamType("V") |
| 411 | optionalTypeV := OptionalType(paramTypeV) |
| 412 | listTypeV := ListType(paramTypeV) |
| 413 | mapTypeKV := MapType(paramTypeK, paramTypeV) |
| 414 | listOptionalTypeV := ListType(optionalTypeV) |
| 415 | |
| 416 | opts := []EnvOption{ |
| 417 | // Enable the optional syntax in the parser. |
| 418 | enableOptionalSyntax(), |
| 419 | |
| 420 | // Introduce the optional type. |
| 421 | Types(types.OptionalType), |
| 422 | |
| 423 | // Configure the optMap and optFlatMap macros. |
| 424 | Macros(ReceiverMacro(optMapMacro, 2, optMap, |
| 425 | MacroDocs(`perform computation on the value if present and return the result as an optional`), |
| 426 | MacroExamples( |
| 427 | common.MultilineDescription( |
| 428 | `// sub with the prefix 'dev.cel' or optional.none()`, |
| 429 | `request.auth.tokens.?sub.optMap(id, 'dev.cel.' + id)`), |
| 430 | `optional.none().optMap(i, i * 2) // optional.none()`))), |
| 431 | |
| 432 | // Global and member functions for working with optional values. |
| 433 | Function(optionalOfFunc, |
| 434 | FunctionDocs(`create a new optional_type(T) with a value where any value is considered valid`), |
| 435 | Overload("optional_of", []*Type{paramTypeV}, optionalTypeV, |
| 436 | OverloadExamples(`optional.of(1) // optional(1)`), |
| 437 | UnaryBinding(func(value ref.Val) ref.Val { |
| 438 | return types.OptionalOf(value) |
| 439 | }))), |
| 440 | Function(optionalOfNonZeroValueFunc, |
| 441 | FunctionDocs(`create a new optional_type(T) with a value, if the value is not a zero or empty value`), |
| 442 | Overload("optional_ofNonZeroValue", []*Type{paramTypeV}, optionalTypeV, |
| 443 | OverloadExamples( |
| 444 | `optional.ofNonZeroValue(null) // optional.none()`, |
| 445 | `optional.ofNonZeroValue("") // optional.none()`, |
| 446 | `optional.ofNonZeroValue("hello") // optional.of('hello')`), |
| 447 | UnaryBinding(func(value ref.Val) ref.Val { |
| 448 | v, isZeroer := value.(traits.Zeroer) |
| 449 | if !isZeroer || !v.IsZeroValue() { |
| 450 | return types.OptionalOf(value) |
| 451 | } |
| 452 | return types.OptionalNone |
| 453 | }))), |
| 454 | Function(optionalNoneFunc, |
| 455 | FunctionDocs(`singleton value representing an optional without a value`), |
| 456 | Overload("optional_none", []*Type{}, optionalTypeV, |
| 457 | OverloadExamples(`optional.none()`), |
| 458 | FunctionBinding(func(values ...ref.Val) ref.Val { |
| 459 | return types.OptionalNone |
| 460 | }))), |
| 461 | Function(valueFunc, |
| 462 | FunctionDocs(`obtain the value contained by the optional, error if optional.none()`), |
| 463 | MemberOverload("optional_value", []*Type{optionalTypeV}, paramTypeV, |
| 464 | OverloadExamples( |
| 465 | `optional.of(1).value() // 1`, |
| 466 | `optional.none().value() // error`), |
| 467 | UnaryBinding(func(value ref.Val) ref.Val { |
| 468 | opt := value.(*types.Optional) |
| 469 | return opt.GetValue() |
| 470 | }))), |
| 471 | Function(hasValueFunc, |
| 472 | FunctionDocs(`determine whether the optional contains a value`), |
| 473 | MemberOverload("optional_hasValue", []*Type{optionalTypeV}, BoolType, |
| 474 | OverloadExamples(`optional.of({1: 2}).hasValue() // true`), |
| 475 | UnaryBinding(func(value ref.Val) ref.Val { |
| 476 | opt := value.(*types.Optional) |
| 477 | return types.Bool(opt.HasValue()) |
| 478 | }))), |
| 479 | |
| 480 | // Implementation of 'or' and 'orValue' are special-cased to support short-circuiting in the |
| 481 | // evaluation chain. |
| 482 | Function("or", |
| 483 | FunctionDocs(`chain optional expressions together, picking the first valued optional expression`), |
| 484 | MemberOverload("optional_or_optional", []*Type{optionalTypeV, optionalTypeV}, optionalTypeV, |
| 485 | OverloadExamples( |
| 486 | `optional.none().or(optional.of(1)) // optional.of(1)`, |
| 487 | common.MultilineDescription( |
| 488 | `// either a value from the first list, a value from the second, or optional.none()`, |
| 489 | `[1, 2, 3][?x].or([3, 4, 5][?y])`)))), |
| 490 | Function("orValue", |
| 491 | FunctionDocs(`chain optional expressions together picking the first valued optional or the default value`), |
| 492 | MemberOverload("optional_orValue_value", []*Type{optionalTypeV, paramTypeV}, paramTypeV, |
| 493 | OverloadExamples( |
| 494 | common.MultilineDescription( |
| 495 | `// pick the value for the given key if the key exists, otherwise return 'you'`, |
| 496 | `{'hello': 'world', 'goodbye': 'cruel world'}[?greeting].orValue('you')`)))), |
| 497 | |
| 498 | // OptSelect is handled specially by the type-checker, so the receiver's field type is used to determine the |
| 499 | // optput type. |
| 500 | Function(operators.OptSelect, |
| 501 | FunctionDocs(`if the field is present create an optional of the field value, otherwise return optional.none()`), |
| 502 | Overload("select_optional_field", []*Type{DynType, StringType}, optionalTypeV, |
| 503 | OverloadExamples( |
| 504 | `msg.?field // optional.of(field) if non-empty, otherwise optional.none()`, |
| 505 | `msg.?field.?nested_field // optional.of(nested_field) if both field and nested_field are non-empty.`))), |
| 506 | |
| 507 | // OptIndex is handled mostly like any other indexing operation on a list or map, so the type-checker can use |
| 508 | // these signatures to determine type-agreement without any special handling. |
| 509 | Function(operators.OptIndex, |
| 510 | FunctionDocs(`if the index is present create an optional of the field value, otherwise return optional.none()`), |
| 511 | Overload("list_optindex_optional_int", []*Type{listTypeV, IntType}, optionalTypeV, |
| 512 | OverloadExamples(`[1, 2, 3][?x] // element value if x is in the list size, else optional.none()`)), |
| 513 | Overload("optional_list_optindex_optional_int", []*Type{OptionalType(listTypeV), IntType}, optionalTypeV), |
| 514 | Overload("map_optindex_optional_value", []*Type{mapTypeKV, paramTypeK}, optionalTypeV, |
| 515 | OverloadExamples( |
| 516 | `map_value[?key] // value at the key if present, else optional.none()`, |
| 517 | common.MultilineDescription( |
| 518 | `// map key-value if index is a valid map key, else optional.none()`, |
| 519 | `{0: 2, 2: 4, 6: 8}[?index]`))), |
| 520 | Overload("optional_map_optindex_optional_value", []*Type{OptionalType(mapTypeKV), paramTypeK}, optionalTypeV)), |
| 521 | |
| 522 | // Index overloads to accommodate using an optional value as the operand. |
| 523 | Function(operators.Index, |
| 524 | Overload("optional_list_index_int", []*Type{OptionalType(listTypeV), IntType}, optionalTypeV), |
| 525 | Overload("optional_map_index_value", []*Type{OptionalType(mapTypeKV), paramTypeK}, optionalTypeV)), |
| 526 | } |
| 527 | if lib.version >= 1 { |
| 528 | opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMap, |
| 529 | MacroDocs(`perform computation on the value if present and produce an optional value within the computation`), |
| 530 | MacroExamples( |
| 531 | common.MultilineDescription( |
| 532 | `// m = {'key': {}}`, |
| 533 | `m.?key.optFlatMap(k, k.?subkey) // optional.none()`), |
| 534 | common.MultilineDescription( |
| 535 | `// m = {'key': {'subkey': 'value'}}`, |
| 536 | `m.?key.optFlatMap(k, k.?subkey) // optional.of('value')`), |
| 537 | )))) |
| 538 | } |
| 539 | |
| 540 | if lib.version >= 2 { |
| 541 | opts = append(opts, Function("last", |
| 542 | FunctionDocs(`return the last value in a list if present, otherwise optional.none()`), |
| 543 | MemberOverload("list_last", []*Type{listTypeV}, optionalTypeV, |
| 544 | OverloadExamples( |
| 545 | `[].last() // optional.none()`, |
| 546 | `[1, 2, 3].last() ? optional.of(3)`), |
| 547 | UnaryBinding(func(v ref.Val) ref.Val { |
| 548 | list := v.(traits.Lister) |
| 549 | sz := list.Size().(types.Int) |
| 550 | if sz == types.IntZero { |
| 551 | return types.OptionalNone |
| 552 | } |
| 553 | return types.OptionalOf(list.Get(types.Int(sz - 1))) |
| 554 | }), |
| 555 | ), |
| 556 | )) |
| 557 | |
| 558 | opts = append(opts, Function("first", |
| 559 | FunctionDocs(`return the first value in a list if present, otherwise optional.none()`), |
| 560 | MemberOverload("list_first", []*Type{listTypeV}, optionalTypeV, |
| 561 | OverloadExamples( |
| 562 | `[].first() // optional.none()`, |
| 563 | `[1, 2, 3].first() ? optional.of(1)`), |
| 564 | UnaryBinding(func(v ref.Val) ref.Val { |
| 565 | list := v.(traits.Lister) |
| 566 | sz := list.Size().(types.Int) |
| 567 | if sz == types.IntZero { |
| 568 | return types.OptionalNone |
| 569 | } |
| 570 | return types.OptionalOf(list.Get(types.Int(0))) |
| 571 | }), |
| 572 | ), |
| 573 | )) |
| 574 | |
| 575 | opts = append(opts, Function(optionalUnwrapFunc, |
| 576 | FunctionDocs(`convert a list of optional values to a list containing only value which are not optional.none()`), |
| 577 | Overload("optional_unwrap", []*Type{listOptionalTypeV}, listTypeV, |
| 578 | OverloadExamples(`optional.unwrap([optional.of(1), optional.none()]) // [1]`), |
| 579 | UnaryBinding(optUnwrap)))) |
| 580 | opts = append(opts, Function(unwrapOptFunc, |
| 581 | FunctionDocs(`convert a list of optional values to a list containing only value which are not optional.none()`), |
| 582 | MemberOverload("optional_unwrapOpt", []*Type{listOptionalTypeV}, listTypeV, |
| 583 | OverloadExamples(`[optional.of(1), optional.none()].unwrapOpt() // [1]`), |
| 584 | UnaryBinding(optUnwrap)))) |
| 585 | } |
| 586 | |
| 587 | return opts |
| 588 | } |
| 589 | |
| 590 | // ProgramOptions implements the Library interface method. |
| 591 | func (lib *optionalLib) ProgramOptions() []ProgramOption { |
| 592 | return []ProgramOption{ |
| 593 | CustomDecorator(decorateOptionalOr), |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | // Version returns the current version of the library. |
| 598 | func (lib *optionalLib) Version() uint32 { |
| 599 | return lib.version |
| 600 | } |
| 601 | |
| 602 | func optMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { |
| 603 | varIdent := args[0] |
| 604 | varName := "" |
| 605 | switch varIdent.Kind() { |
| 606 | case ast.IdentKind: |
| 607 | varName = varIdent.AsIdent() |
| 608 | default: |
| 609 | return nil, meh.NewError(varIdent.ID(), "optMap() variable name must be a simple identifier") |
| 610 | } |
| 611 | mapExpr := args[1] |
| 612 | return meh.NewCall( |
| 613 | operators.Conditional, |
| 614 | meh.NewMemberCall(hasValueFunc, target), |
| 615 | meh.NewCall(optionalOfFunc, |
| 616 | meh.NewComprehension( |
| 617 | meh.NewList(), |
| 618 | unusedIterVar, |
| 619 | varName, |
| 620 | meh.NewMemberCall(valueFunc, meh.Copy(target)), |
| 621 | meh.NewLiteral(types.False), |
| 622 | meh.NewIdent(varName), |
| 623 | mapExpr, |
| 624 | ), |
| 625 | ), |
| 626 | meh.NewCall(optionalNoneFunc), |
| 627 | ), nil |
| 628 | } |
| 629 | |
| 630 | func optFlatMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) { |
| 631 | varIdent := args[0] |
| 632 | varName := "" |
| 633 | switch varIdent.Kind() { |
| 634 | case ast.IdentKind: |
| 635 | varName = varIdent.AsIdent() |
| 636 | default: |
| 637 | return nil, meh.NewError(varIdent.ID(), "optFlatMap() variable name must be a simple identifier") |
| 638 | } |
| 639 | mapExpr := args[1] |
| 640 | return meh.NewCall( |
| 641 | operators.Conditional, |
| 642 | meh.NewMemberCall(hasValueFunc, target), |
| 643 | meh.NewComprehension( |
| 644 | meh.NewList(), |
| 645 | unusedIterVar, |
| 646 | varName, |
| 647 | meh.NewMemberCall(valueFunc, meh.Copy(target)), |
| 648 | meh.NewLiteral(types.False), |
| 649 | meh.NewIdent(varName), |
| 650 | mapExpr, |
| 651 | ), |
| 652 | meh.NewCall(optionalNoneFunc), |
| 653 | ), nil |
| 654 | } |
| 655 | |
| 656 | func optUnwrap(value ref.Val) ref.Val { |
| 657 | list := value.(traits.Lister) |
| 658 | var unwrappedList []ref.Val |
| 659 | iter := list.Iterator() |
| 660 | for iter.HasNext() == types.True { |
| 661 | val := iter.Next() |
| 662 | opt, isOpt := val.(*types.Optional) |
| 663 | if !isOpt { |
| 664 | return types.WrapErr(fmt.Errorf("value %v is not optional", val)) |
| 665 | } |
| 666 | if opt.HasValue() { |
| 667 | unwrappedList = append(unwrappedList, opt.GetValue()) |
| 668 | } |
| 669 | } |
| 670 | return types.DefaultTypeAdapter.NativeToValue(unwrappedList) |
| 671 | } |
| 672 | |
| 673 | func enableOptionalSyntax() EnvOption { |
| 674 | return func(e *Env) (*Env, error) { |
| 675 | e.prsrOpts = append(e.prsrOpts, parser.EnableOptionalSyntax(true)) |
| 676 | return e, nil |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | // EnableErrorOnBadPresenceTest enables error generation when a presence test or optional field |
| 681 | // selection is performed on a primitive type. |
| 682 | func EnableErrorOnBadPresenceTest(value bool) EnvOption { |
| 683 | return features(featureEnableErrorOnBadPresenceTest, value) |
| 684 | } |
| 685 | |
| 686 | func decorateOptionalOr(i interpreter.Interpretable) (interpreter.Interpretable, error) { |
| 687 | call, ok := i.(interpreter.InterpretableCall) |
| 688 | if !ok { |
| 689 | return i, nil |
| 690 | } |
| 691 | args := call.Args() |
| 692 | if len(args) != 2 { |
| 693 | return i, nil |
| 694 | } |
| 695 | switch call.Function() { |
| 696 | case "or": |
| 697 | if call.OverloadID() != "" && call.OverloadID() != "optional_or_optional" { |
| 698 | return i, nil |
| 699 | } |
| 700 | return &evalOptionalOr{ |
| 701 | id: call.ID(), |
| 702 | lhs: args[0], |
| 703 | rhs: args[1], |
| 704 | }, nil |
| 705 | case "orValue": |
| 706 | if call.OverloadID() != "" && call.OverloadID() != "optional_orValue_value" { |
| 707 | return i, nil |
| 708 | } |
| 709 | return &evalOptionalOrValue{ |
| 710 | id: call.ID(), |
| 711 | lhs: args[0], |
| 712 | rhs: args[1], |
| 713 | }, nil |
| 714 | default: |
| 715 | return i, nil |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | // evalOptionalOr selects between two optional values, either the first if it has a value, or |
| 720 | // the second optional expression is evaluated and returned. |
| 721 | type evalOptionalOr struct { |
| 722 | id int64 |
| 723 | lhs interpreter.Interpretable |
| 724 | rhs interpreter.Interpretable |
| 725 | } |
| 726 | |
| 727 | // ID implements the Interpretable interface method. |
| 728 | func (opt *evalOptionalOr) ID() int64 { |
| 729 | return opt.id |
| 730 | } |
| 731 | |
| 732 | // Eval evaluates the left-hand side optional to determine whether it contains a value, else |
| 733 | // proceeds with the right-hand side evaluation. |
| 734 | func (opt *evalOptionalOr) Eval(ctx interpreter.Activation) ref.Val { |
| 735 | // short-circuit lhs. |
| 736 | optLHS := opt.lhs.Eval(ctx) |
| 737 | optVal, ok := optLHS.(*types.Optional) |
| 738 | if !ok { |
| 739 | return optLHS |
| 740 | } |
| 741 | if optVal.HasValue() { |
| 742 | return optVal |
| 743 | } |
| 744 | return opt.rhs.Eval(ctx) |
| 745 | } |
| 746 | |
| 747 | // evalOptionalOrValue selects between an optional or a concrete value. If the optional has a value, |
| 748 | // its value is returned, otherwise the alternative value expression is evaluated and returned. |
| 749 | type evalOptionalOrValue struct { |
| 750 | id int64 |
| 751 | lhs interpreter.Interpretable |
| 752 | rhs interpreter.Interpretable |
| 753 | } |
| 754 | |
| 755 | // ID implements the Interpretable interface method. |
| 756 | func (opt *evalOptionalOrValue) ID() int64 { |
| 757 | return opt.id |
| 758 | } |
| 759 | |
| 760 | // Eval evaluates the left-hand side optional to determine whether it contains a value, else |
| 761 | // proceeds with the right-hand side evaluation. |
| 762 | func (opt *evalOptionalOrValue) Eval(ctx interpreter.Activation) ref.Val { |
| 763 | // short-circuit lhs. |
| 764 | optLHS := opt.lhs.Eval(ctx) |
| 765 | optVal, ok := optLHS.(*types.Optional) |
| 766 | if !ok { |
| 767 | return optLHS |
| 768 | } |
| 769 | if optVal.HasValue() { |
| 770 | return optVal.GetValue() |
| 771 | } |
| 772 | return opt.rhs.Eval(ctx) |
| 773 | } |
| 774 | |
| 775 | type timeLegacyLibrary struct{} |
| 776 | |
| 777 | func (timeLegacyLibrary) CompileOptions() []EnvOption { |
| 778 | return timeOverloadDeclarations |
| 779 | } |
| 780 | |
| 781 | func (timeLegacyLibrary) ProgramOptions() []ProgramOption { |
| 782 | return []ProgramOption{} |
| 783 | } |
| 784 | |
| 785 | // Declarations and functions which enable using UTC on time.Time inputs when the timezone is unspecified |
| 786 | // in the CEL expression. |
| 787 | var ( |
| 788 | timeOverloadDeclarations = []EnvOption{ |
| 789 | Function(overloads.TimeGetFullYear, |
| 790 | MemberOverload(overloads.TimestampToYear, []*Type{TimestampType}, IntType, |
| 791 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 792 | t := ts.(types.Timestamp) |
| 793 | return t.Receive(overloads.TimeGetFullYear, overloads.TimestampToYear, []ref.Val{}) |
| 794 | }), |
| 795 | ), |
| 796 | ), |
| 797 | Function(overloads.TimeGetMonth, |
| 798 | MemberOverload(overloads.TimestampToMonth, []*Type{TimestampType}, IntType, |
| 799 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 800 | t := ts.(types.Timestamp) |
| 801 | return t.Receive(overloads.TimeGetMonth, overloads.TimestampToMonth, []ref.Val{}) |
| 802 | }), |
| 803 | ), |
| 804 | ), |
| 805 | Function(overloads.TimeGetDayOfYear, |
| 806 | MemberOverload(overloads.TimestampToDayOfYear, []*Type{TimestampType}, IntType, |
| 807 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 808 | t := ts.(types.Timestamp) |
| 809 | return t.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYear, []ref.Val{}) |
| 810 | }), |
| 811 | ), |
| 812 | ), |
| 813 | Function(overloads.TimeGetDayOfMonth, |
| 814 | MemberOverload(overloads.TimestampToDayOfMonthZeroBased, []*Type{TimestampType}, IntType, |
| 815 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 816 | t := ts.(types.Timestamp) |
| 817 | return t.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBased, []ref.Val{}) |
| 818 | }), |
| 819 | ), |
| 820 | ), |
| 821 | Function(overloads.TimeGetDate, |
| 822 | MemberOverload(overloads.TimestampToDayOfMonthOneBased, []*Type{TimestampType}, IntType, |
| 823 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 824 | t := ts.(types.Timestamp) |
| 825 | return t.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBased, []ref.Val{}) |
| 826 | }), |
| 827 | ), |
| 828 | ), |
| 829 | Function(overloads.TimeGetDayOfWeek, |
| 830 | MemberOverload(overloads.TimestampToDayOfWeek, []*Type{TimestampType}, IntType, |
| 831 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 832 | t := ts.(types.Timestamp) |
| 833 | return t.Receive(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeek, []ref.Val{}) |
| 834 | }), |
| 835 | ), |
| 836 | ), |
| 837 | Function(overloads.TimeGetHours, |
| 838 | MemberOverload(overloads.TimestampToHours, []*Type{TimestampType}, IntType, |
| 839 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 840 | t := ts.(types.Timestamp) |
| 841 | return t.Receive(overloads.TimeGetHours, overloads.TimestampToHours, []ref.Val{}) |
| 842 | }), |
| 843 | ), |
| 844 | ), |
| 845 | Function(overloads.TimeGetMinutes, |
| 846 | MemberOverload(overloads.TimestampToMinutes, []*Type{TimestampType}, IntType, |
| 847 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 848 | t := ts.(types.Timestamp) |
| 849 | return t.Receive(overloads.TimeGetMinutes, overloads.TimestampToMinutes, []ref.Val{}) |
| 850 | }), |
| 851 | ), |
| 852 | ), |
| 853 | Function(overloads.TimeGetSeconds, |
| 854 | MemberOverload(overloads.TimestampToSeconds, []*Type{TimestampType}, IntType, |
| 855 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 856 | t := ts.(types.Timestamp) |
| 857 | return t.Receive(overloads.TimeGetSeconds, overloads.TimestampToSeconds, []ref.Val{}) |
| 858 | }), |
| 859 | ), |
| 860 | ), |
| 861 | Function(overloads.TimeGetMilliseconds, |
| 862 | MemberOverload(overloads.TimestampToMilliseconds, []*Type{TimestampType}, IntType, |
| 863 | UnaryBinding(func(ts ref.Val) ref.Val { |
| 864 | t := ts.(types.Timestamp) |
| 865 | return t.Receive(overloads.TimeGetMilliseconds, overloads.TimestampToMilliseconds, []ref.Val{}) |
| 866 | }), |
| 867 | ), |
| 868 | ), |
| 869 | } |
| 870 | ) |