| 1 | // Copyright 2022 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // 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 | |
| 20 | "github.com/google/cel-go/common/ast" |
| 21 | "github.com/google/cel-go/common/decls" |
| 22 | "github.com/google/cel-go/common/functions" |
| 23 | "github.com/google/cel-go/common/types" |
| 24 | "github.com/google/cel-go/common/types/ref" |
| 25 | |
| 26 | celpb "cel.dev/expr" |
| 27 | exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 28 | ) |
| 29 | |
| 30 | // Kind indicates a CEL type's kind which is used to differentiate quickly between simple and complex types. |
| 31 | type Kind = types.Kind |
| 32 | |
| 33 | const ( |
| 34 | // DynKind represents a dynamic type. This kind only exists at type-check time. |
| 35 | DynKind Kind = types.DynKind |
| 36 | |
| 37 | // AnyKind represents a google.protobuf.Any type. This kind only exists at type-check time. |
| 38 | AnyKind = types.AnyKind |
| 39 | |
| 40 | // BoolKind represents a boolean type. |
| 41 | BoolKind = types.BoolKind |
| 42 | |
| 43 | // BytesKind represents a bytes type. |
| 44 | BytesKind = types.BytesKind |
| 45 | |
| 46 | // DoubleKind represents a double type. |
| 47 | DoubleKind = types.DoubleKind |
| 48 | |
| 49 | // DurationKind represents a CEL duration type. |
| 50 | DurationKind = types.DurationKind |
| 51 | |
| 52 | // IntKind represents an integer type. |
| 53 | IntKind = types.IntKind |
| 54 | |
| 55 | // ListKind represents a list type. |
| 56 | ListKind = types.ListKind |
| 57 | |
| 58 | // MapKind represents a map type. |
| 59 | MapKind = types.MapKind |
| 60 | |
| 61 | // NullTypeKind represents a null type. |
| 62 | NullTypeKind = types.NullTypeKind |
| 63 | |
| 64 | // OpaqueKind represents an abstract type which has no accessible fields. |
| 65 | OpaqueKind = types.OpaqueKind |
| 66 | |
| 67 | // StringKind represents a string type. |
| 68 | StringKind = types.StringKind |
| 69 | |
| 70 | // StructKind represents a structured object with typed fields. |
| 71 | StructKind = types.StructKind |
| 72 | |
| 73 | // TimestampKind represents a a CEL time type. |
| 74 | TimestampKind = types.TimestampKind |
| 75 | |
| 76 | // TypeKind represents the CEL type. |
| 77 | TypeKind = types.TypeKind |
| 78 | |
| 79 | // TypeParamKind represents a parameterized type whose type name will be resolved at type-check time, if possible. |
| 80 | TypeParamKind = types.TypeParamKind |
| 81 | |
| 82 | // UintKind represents a uint type. |
| 83 | UintKind = types.UintKind |
| 84 | ) |
| 85 | |
| 86 | var ( |
| 87 | // AnyType represents the google.protobuf.Any type. |
| 88 | AnyType = types.AnyType |
| 89 | // BoolType represents the bool type. |
| 90 | BoolType = types.BoolType |
| 91 | // BytesType represents the bytes type. |
| 92 | BytesType = types.BytesType |
| 93 | // DoubleType represents the double type. |
| 94 | DoubleType = types.DoubleType |
| 95 | // DurationType represents the CEL duration type. |
| 96 | DurationType = types.DurationType |
| 97 | // DynType represents a dynamic CEL type whose type will be determined at runtime from context. |
| 98 | DynType = types.DynType |
| 99 | // IntType represents the int type. |
| 100 | IntType = types.IntType |
| 101 | // NullType represents the type of a null value. |
| 102 | NullType = types.NullType |
| 103 | // StringType represents the string type. |
| 104 | StringType = types.StringType |
| 105 | // TimestampType represents the time type. |
| 106 | TimestampType = types.TimestampType |
| 107 | // TypeType represents a CEL type |
| 108 | TypeType = types.TypeType |
| 109 | // UintType represents a uint type. |
| 110 | UintType = types.UintType |
| 111 | |
| 112 | // function references for instantiating new types. |
| 113 | |
| 114 | // ListType creates an instances of a list type value with the provided element type. |
| 115 | ListType = types.NewListType |
| 116 | // MapType creates an instance of a map type value with the provided key and value types. |
| 117 | MapType = types.NewMapType |
| 118 | // NullableType creates an instance of a nullable type with the provided wrapped type. |
| 119 | // |
| 120 | // Note: only primitive types are supported as wrapped types. |
| 121 | NullableType = types.NewNullableType |
| 122 | // OptionalType creates an abstract parameterized type instance corresponding to CEL's notion of optional. |
| 123 | OptionalType = types.NewOptionalType |
| 124 | // OpaqueType creates an abstract parameterized type with a given name. |
| 125 | OpaqueType = types.NewOpaqueType |
| 126 | // ObjectType creates a type references to an externally defined type, e.g. a protobuf message type. |
| 127 | ObjectType = types.NewObjectType |
| 128 | // TypeParamType creates a parameterized type instance. |
| 129 | TypeParamType = types.NewTypeParamType |
| 130 | ) |
| 131 | |
| 132 | // Type holds a reference to a runtime type with an optional type-checked set of type parameters. |
| 133 | type Type = types.Type |
| 134 | |
| 135 | // Constant creates an instances of an identifier declaration with a variable name, type, and value. |
| 136 | func Constant(name string, t *Type, v ref.Val) EnvOption { |
| 137 | return func(e *Env) (*Env, error) { |
| 138 | e.variables = append(e.variables, decls.NewConstant(name, t, v)) |
| 139 | return e, nil |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // Variable creates an instance of a variable declaration with a variable name and type. |
| 144 | func Variable(name string, t *Type) EnvOption { |
| 145 | return VariableWithDoc(name, t, "") |
| 146 | } |
| 147 | |
| 148 | // VariableWithDoc creates an instance of a variable declaration with a variable name, type, and doc string. |
| 149 | func VariableWithDoc(name string, t *Type, doc string) EnvOption { |
| 150 | return func(e *Env) (*Env, error) { |
| 151 | e.variables = append(e.variables, decls.NewVariableWithDoc(name, t, doc)) |
| 152 | return e, nil |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // VariableDecls configures a set of fully defined cel.VariableDecl instances in the environment. |
| 157 | func VariableDecls(vars ...*decls.VariableDecl) EnvOption { |
| 158 | return func(e *Env) (*Env, error) { |
| 159 | for _, v := range vars { |
| 160 | e.variables = append(e.variables, v) |
| 161 | } |
| 162 | return e, nil |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | // Function defines a function and overloads with optional singleton or per-overload bindings. |
| 167 | // |
| 168 | // Using Function is roughly equivalent to calling Declarations() to declare the function signatures |
| 169 | // and Functions() to define the function bindings, if they have been defined. Specifying the |
| 170 | // same function name more than once will result in the aggregation of the function overloads. If any |
| 171 | // signatures conflict between the existing and new function definition an error will be raised. |
| 172 | // However, if the signatures are identical and the overload ids are the same, the redefinition will |
| 173 | // be considered a no-op. |
| 174 | // |
| 175 | // One key difference with using Function() is that each FunctionDecl provided will handle dynamic |
| 176 | // dispatch based on the type-signatures of the overloads provided which means overload resolution at |
| 177 | // runtime is handled out of the box rather than via a custom binding for overload resolution via |
| 178 | // Functions(): |
| 179 | // |
| 180 | // - Overloads are searched in the order they are declared |
| 181 | // - Dynamic dispatch for lists and maps is limited by inspection of the list and map contents |
| 182 | // |
| 183 | // at runtime. Empty lists and maps will result in a 'default dispatch' |
| 184 | // |
| 185 | // - In the event that a default dispatch occurs, the first overload provided is the one invoked |
| 186 | // |
| 187 | // If you intend to use overloads which differentiate based on the key or element type of a list or |
| 188 | // map, consider using a generic function instead: e.g. func(list(T)) or func(map(K, V)) as this |
| 189 | // will allow your implementation to determine how best to handle dispatch and the default behavior |
| 190 | // for empty lists and maps whose contents cannot be inspected. |
| 191 | // |
| 192 | // For functions which use parameterized opaque types (abstract types), consider using a singleton |
| 193 | // function which is capable of inspecting the contents of the type and resolving the appropriate |
| 194 | // overload as CEL can only make inferences by type-name regarding such types. |
| 195 | func Function(name string, opts ...FunctionOpt) EnvOption { |
| 196 | return func(e *Env) (*Env, error) { |
| 197 | fn, err := decls.NewFunction(name, opts...) |
| 198 | if err != nil { |
| 199 | return nil, err |
| 200 | } |
| 201 | return FunctionDecls(fn)(e) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | // OverloadSelector selects an overload associated with a given function when it returns true. |
| 206 | // |
| 207 | // Used in combination with the FunctionDecl.Subset method. |
| 208 | type OverloadSelector = decls.OverloadSelector |
| 209 | |
| 210 | // IncludeOverloads defines an OverloadSelector which allow-lists a set of overloads by their ids. |
| 211 | func IncludeOverloads(overloadIDs ...string) OverloadSelector { |
| 212 | return decls.IncludeOverloads(overloadIDs...) |
| 213 | } |
| 214 | |
| 215 | // ExcludeOverloads defines an OverloadSelector which deny-lists a set of overloads by their ids. |
| 216 | func ExcludeOverloads(overloadIDs ...string) OverloadSelector { |
| 217 | return decls.ExcludeOverloads(overloadIDs...) |
| 218 | } |
| 219 | |
| 220 | // FunctionDecls provides one or more fully formed function declarations to be added to the environment. |
| 221 | func FunctionDecls(funcs ...*decls.FunctionDecl) EnvOption { |
| 222 | return func(e *Env) (*Env, error) { |
| 223 | var err error |
| 224 | for _, fn := range funcs { |
| 225 | if existing, found := e.functions[fn.Name()]; found { |
| 226 | fn, err = existing.Merge(fn) |
| 227 | if err != nil { |
| 228 | return nil, err |
| 229 | } |
| 230 | } |
| 231 | e.functions[fn.Name()] = fn |
| 232 | } |
| 233 | return e, nil |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // FunctionOpt defines a functional option for configuring a function declaration. |
| 238 | type FunctionOpt = decls.FunctionOpt |
| 239 | |
| 240 | // FunctionDocs provides a general usage documentation for the function. |
| 241 | // |
| 242 | // Use OverloadExamples to provide example usage instructions for specific overloads. |
| 243 | func FunctionDocs(docs ...string) FunctionOpt { |
| 244 | return decls.FunctionDocs(docs...) |
| 245 | } |
| 246 | |
| 247 | // SingletonUnaryBinding creates a singleton function definition to be used for all function overloads. |
| 248 | // |
| 249 | // Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 250 | // e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 251 | func SingletonUnaryBinding(fn functions.UnaryOp, traits ...int) FunctionOpt { |
| 252 | return decls.SingletonUnaryBinding(fn, traits...) |
| 253 | } |
| 254 | |
| 255 | // SingletonBinaryImpl creates a singleton function definition to be used with all function overloads. |
| 256 | // |
| 257 | // Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 258 | // e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 259 | // |
| 260 | // Deprecated: use SingletonBinaryBinding |
| 261 | func SingletonBinaryImpl(fn functions.BinaryOp, traits ...int) FunctionOpt { |
| 262 | return decls.SingletonBinaryBinding(fn, traits...) |
| 263 | } |
| 264 | |
| 265 | // SingletonBinaryBinding creates a singleton function definition to be used with all function overloads. |
| 266 | // |
| 267 | // Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 268 | // e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 269 | func SingletonBinaryBinding(fn functions.BinaryOp, traits ...int) FunctionOpt { |
| 270 | return decls.SingletonBinaryBinding(fn, traits...) |
| 271 | } |
| 272 | |
| 273 | // SingletonFunctionImpl creates a singleton function definition to be used with all function overloads. |
| 274 | // |
| 275 | // Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 276 | // e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 277 | // |
| 278 | // Deprecated: use SingletonFunctionBinding |
| 279 | func SingletonFunctionImpl(fn functions.FunctionOp, traits ...int) FunctionOpt { |
| 280 | return decls.SingletonFunctionBinding(fn, traits...) |
| 281 | } |
| 282 | |
| 283 | // SingletonFunctionBinding creates a singleton function definition to be used with all function overloads. |
| 284 | // |
| 285 | // Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 286 | // e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 287 | func SingletonFunctionBinding(fn functions.FunctionOp, traits ...int) FunctionOpt { |
| 288 | return decls.SingletonFunctionBinding(fn, traits...) |
| 289 | } |
| 290 | |
| 291 | // DisableDeclaration disables the function signatures, effectively removing them from the type-check |
| 292 | // environment while preserving the runtime bindings. |
| 293 | func DisableDeclaration(value bool) FunctionOpt { |
| 294 | return decls.DisableDeclaration(value) |
| 295 | } |
| 296 | |
| 297 | // Overload defines a new global overload with an overload id, argument types, and result type. Through the |
| 298 | // use of OverloadOpt options, the overload may also be configured with a binding, an operand trait, and to |
| 299 | // be non-strict. |
| 300 | // |
| 301 | // Note: function bindings should be commonly configured with Overload instances whereas operand traits and |
| 302 | // strict-ness should be rare occurrences. |
| 303 | func Overload(overloadID string, args []*Type, resultType *Type, opts ...OverloadOpt) FunctionOpt { |
| 304 | return decls.Overload(overloadID, args, resultType, opts...) |
| 305 | } |
| 306 | |
| 307 | // MemberOverload defines a new receiver-style overload (or member function) with an overload id, argument types, |
| 308 | // and result type. Through the use of OverloadOpt options, the overload may also be configured with a binding, |
| 309 | // an operand trait, and to be non-strict. |
| 310 | // |
| 311 | // Note: function bindings should be commonly configured with Overload instances whereas operand traits and |
| 312 | // strict-ness should be rare occurrences. |
| 313 | func MemberOverload(overloadID string, args []*Type, resultType *Type, opts ...OverloadOpt) FunctionOpt { |
| 314 | return decls.MemberOverload(overloadID, args, resultType, opts...) |
| 315 | } |
| 316 | |
| 317 | // OverloadOpt is a functional option for configuring a function overload. |
| 318 | type OverloadOpt = decls.OverloadOpt |
| 319 | |
| 320 | // OverloadExamples configures an example of how to invoke the overload. |
| 321 | func OverloadExamples(docs ...string) OverloadOpt { |
| 322 | return decls.OverloadExamples(docs...) |
| 323 | } |
| 324 | |
| 325 | // UnaryBinding provides the implementation of a unary overload. The provided function is protected by a runtime |
| 326 | // type-guard which ensures runtime type agreement between the overload signature and runtime argument types. |
| 327 | func UnaryBinding(binding functions.UnaryOp) OverloadOpt { |
| 328 | return decls.UnaryBinding(binding) |
| 329 | } |
| 330 | |
| 331 | // BinaryBinding provides the implementation of a binary overload. The provided function is protected by a runtime |
| 332 | // type-guard which ensures runtime type agreement between the overload signature and runtime argument types. |
| 333 | func BinaryBinding(binding functions.BinaryOp) OverloadOpt { |
| 334 | return decls.BinaryBinding(binding) |
| 335 | } |
| 336 | |
| 337 | // FunctionBinding provides the implementation of a variadic overload. The provided function is protected by a runtime |
| 338 | // type-guard which ensures runtime type agreement between the overload signature and runtime argument types. |
| 339 | func FunctionBinding(binding functions.FunctionOp) OverloadOpt { |
| 340 | return decls.FunctionBinding(binding) |
| 341 | } |
| 342 | |
| 343 | // LateFunctionBinding indicates that the function has a binding which is not known at compile time. |
| 344 | // This is useful for functions which have side-effects or are not deterministically computable. |
| 345 | func LateFunctionBinding() OverloadOpt { |
| 346 | return decls.LateFunctionBinding() |
| 347 | } |
| 348 | |
| 349 | // OverloadIsNonStrict enables the function to be called with error and unknown argument values. |
| 350 | // |
| 351 | // Note: do not use this option unless absoluately necessary as it should be an uncommon feature. |
| 352 | func OverloadIsNonStrict() OverloadOpt { |
| 353 | return decls.OverloadIsNonStrict() |
| 354 | } |
| 355 | |
| 356 | // OverloadOperandTrait configures a set of traits which the first argument to the overload must implement in order to be |
| 357 | // successfully invoked. |
| 358 | func OverloadOperandTrait(trait int) OverloadOpt { |
| 359 | return decls.OverloadOperandTrait(trait) |
| 360 | } |
| 361 | |
| 362 | // TypeToExprType converts a CEL-native type representation to a protobuf CEL Type representation. |
| 363 | func TypeToExprType(t *Type) (*exprpb.Type, error) { |
| 364 | return types.TypeToExprType(t) |
| 365 | } |
| 366 | |
| 367 | // ExprTypeToType converts a protobuf CEL type representation to a CEL-native type representation. |
| 368 | func ExprTypeToType(t *exprpb.Type) (*Type, error) { |
| 369 | return types.ExprTypeToType(t) |
| 370 | } |
| 371 | |
| 372 | // ExprDeclToDeclaration converts a protobuf CEL declaration to a CEL-native declaration, either a Variable or Function. |
| 373 | func ExprDeclToDeclaration(d *exprpb.Decl) (EnvOption, error) { |
| 374 | return AlphaProtoAsDeclaration(d) |
| 375 | } |
| 376 | |
| 377 | // AlphaProtoAsDeclaration converts a v1alpha1.Decl value describing a variable or function into an EnvOption. |
| 378 | func AlphaProtoAsDeclaration(d *exprpb.Decl) (EnvOption, error) { |
| 379 | canonical := &celpb.Decl{} |
| 380 | if err := convertProto(d, canonical); err != nil { |
| 381 | return nil, err |
| 382 | } |
| 383 | return ProtoAsDeclaration(canonical) |
| 384 | } |
| 385 | |
| 386 | // ProtoAsDeclaration converts a canonical celpb.Decl value describing a variable or function into an EnvOption. |
| 387 | func ProtoAsDeclaration(d *celpb.Decl) (EnvOption, error) { |
| 388 | switch d.GetDeclKind().(type) { |
| 389 | case *celpb.Decl_Function: |
| 390 | overloads := d.GetFunction().GetOverloads() |
| 391 | opts := make([]FunctionOpt, len(overloads)) |
| 392 | for i, o := range overloads { |
| 393 | args := make([]*Type, len(o.GetParams())) |
| 394 | for j, p := range o.GetParams() { |
| 395 | a, err := types.ProtoAsType(p) |
| 396 | if err != nil { |
| 397 | return nil, err |
| 398 | } |
| 399 | args[j] = a |
| 400 | } |
| 401 | res, err := types.ProtoAsType(o.GetResultType()) |
| 402 | if err != nil { |
| 403 | return nil, err |
| 404 | } |
| 405 | if o.IsInstanceFunction { |
| 406 | opts[i] = decls.MemberOverload(o.GetOverloadId(), args, res) |
| 407 | } else { |
| 408 | opts[i] = decls.Overload(o.GetOverloadId(), args, res) |
| 409 | } |
| 410 | } |
| 411 | return Function(d.GetName(), opts...), nil |
| 412 | case *celpb.Decl_Ident: |
| 413 | t, err := types.ProtoAsType(d.GetIdent().GetType()) |
| 414 | if err != nil { |
| 415 | return nil, err |
| 416 | } |
| 417 | if d.GetIdent().GetValue() == nil { |
| 418 | return Variable(d.GetName(), t), nil |
| 419 | } |
| 420 | val, err := ast.ProtoConstantAsVal(d.GetIdent().GetValue()) |
| 421 | if err != nil { |
| 422 | return nil, err |
| 423 | } |
| 424 | return Constant(d.GetName(), t, val), nil |
| 425 | default: |
| 426 | return nil, fmt.Errorf("unsupported decl: %v", d) |
| 427 | } |
| 428 | } |