| 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 | "math" |
| 20 | "reflect" |
| 21 | "strings" |
| 22 | "testing" |
| 23 | |
| 24 | chkdecls "github.com/google/cel-go/checker/decls" |
| 25 | "github.com/google/cel-go/common/decls" |
| 26 | "github.com/google/cel-go/common/functions" |
| 27 | "github.com/google/cel-go/common/operators" |
| 28 | "github.com/google/cel-go/common/overloads" |
| 29 | "github.com/google/cel-go/common/stdlib" |
| 30 | "github.com/google/cel-go/common/types" |
| 31 | "github.com/google/cel-go/common/types/ref" |
| 32 | "github.com/google/cel-go/common/types/traits" |
| 33 | |
| 34 | exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 35 | ) |
| 36 | |
| 37 | var dispatchTests = []struct { |
| 38 | expr string |
| 39 | out any |
| 40 | }{ |
| 41 | { |
| 42 | expr: "max(-1)", |
| 43 | out: types.IntNegOne, |
| 44 | }, |
| 45 | { |
| 46 | expr: "max(-1, 0)", |
| 47 | out: types.IntZero, |
| 48 | }, |
| 49 | { |
| 50 | expr: "max(-1, 0, 1)", |
| 51 | out: types.IntOne, |
| 52 | }, |
| 53 | { |
| 54 | expr: "max(dyn(1.2))", |
| 55 | out: fmt.Errorf("no such overload: max(double)"), |
| 56 | }, |
| 57 | |
| 58 | { |
| 59 | expr: "max(1, dyn(1.2))", |
| 60 | out: fmt.Errorf("no such overload: max(int, double)"), |
| 61 | }, |
| 62 | { |
| 63 | expr: "max(1, 2, dyn(1.2))", |
| 64 | out: fmt.Errorf("no such overload: max(int, int, double)"), |
| 65 | }, |
| 66 | { |
| 67 | expr: "max(err, 1)", |
| 68 | out: fmt.Errorf("error argument"), |
| 69 | }, |
| 70 | { |
| 71 | expr: "max(err, unk)", |
| 72 | out: fmt.Errorf("error argument"), |
| 73 | }, |
| 74 | { |
| 75 | expr: "max(unk, unk)", |
| 76 | out: types.NewUnknown(42, nil), |
| 77 | }, |
| 78 | { |
| 79 | expr: "max(unk, unk, unk)", |
| 80 | out: types.NewUnknown(42, nil), |
| 81 | }, |
| 82 | } |
| 83 | |
| 84 | func TestFunctionMerge(t *testing.T) { |
| 85 | size := Function("size", |
| 86 | Overload("size_map", []*Type{MapType(TypeParamType("K"), TypeParamType("V"))}, IntType), |
| 87 | Overload("size_list", []*Type{ListType(TypeParamType("V"))}, IntType), |
| 88 | Overload("size_string", []*Type{StringType}, IntType), |
| 89 | Overload("size_bytes", []*Type{BytesType}, IntType), |
| 90 | MemberOverload("map_size", []*Type{MapType(TypeParamType("K"), TypeParamType("V"))}, IntType), |
| 91 | MemberOverload("list_size", []*Type{ListType(TypeParamType("V"))}, IntType), |
| 92 | MemberOverload("string_size", []*Type{StringType}, IntType), |
| 93 | MemberOverload("bytes_size", []*Type{BytesType}, IntType), |
| 94 | SingletonUnaryBinding(func(arg ref.Val) ref.Val { |
| 95 | return arg.(traits.Sizer).Size() |
| 96 | }, traits.SizerType), |
| 97 | ) |
| 98 | // Note, the size() implementation is inherited from the singleton implementation for the size function. |
| 99 | // It is possible to redefine the singleton, but the singleton approach is incompatible with specialized |
| 100 | // overloads as the singleton is compatible with the parse-only approach and compiled approach; but |
| 101 | // a mix of singleton and specialized overloads might result in a singleton which does not encompass |
| 102 | // dynamic dispatch to all possible overloads. |
| 103 | sizeExt := Function("size", |
| 104 | Overload("size_vector", []*Type{OpaqueType("vector", TypeParamType("V"))}, IntType), |
| 105 | MemberOverload("vector_size", []*Type{OpaqueType("vector", TypeParamType("V"))}, IntType)) |
| 106 | |
| 107 | vectorExt := Function("vector", |
| 108 | Overload("vector_list", []*Type{ListType(TypeParamType("V"))}, OpaqueType("vector", TypeParamType("V")), |
| 109 | UnaryBinding(func(list ref.Val) ref.Val { |
| 110 | return list |
| 111 | }))) |
| 112 | |
| 113 | eq := Function(operators.Equals, |
| 114 | Overload(operators.Equals, []*Type{TypeParamType("T"), TypeParamType("T")}, BoolType, |
| 115 | BinaryBinding(func(lhs, rhs ref.Val) ref.Val { |
| 116 | return lhs.Equal(rhs) |
| 117 | }))) |
| 118 | |
| 119 | e, err := NewCustomEnv(size, sizeExt, vectorExt, eq) |
| 120 | if err != nil { |
| 121 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 122 | } |
| 123 | ast, iss := e.Compile(`[[0].size() == 1, |
| 124 | {'a': true, 'b': false}.size() == 2, |
| 125 | 'hello'.size() == 5, |
| 126 | b'hello'.size() == 5, |
| 127 | vector([1.2, 2.3, 3.4]).size() == 3]`) |
| 128 | if iss.Err() != nil { |
| 129 | t.Fatalf("Compile() errored: %v", iss.Err()) |
| 130 | } |
| 131 | if !reflect.DeepEqual(ast.OutputType(), ListType(BoolType)) { |
| 132 | t.Errorf("Compile() produced a %v, wanted bool", ast.OutputType()) |
| 133 | } |
| 134 | if ast.OutputType().String() != "list(bool)" { |
| 135 | t.Errorf("ast.OutputType().String() produced %s, wanted list(bool)", ast.OutputType()) |
| 136 | } |
| 137 | prg, err := e.Program(ast) |
| 138 | if err != nil { |
| 139 | t.Fatalf("e.Program(ast) failed: %v", err) |
| 140 | } |
| 141 | out, _, err := prg.Eval(NoVars()) |
| 142 | if err != nil { |
| 143 | t.Errorf("prg.Eval() errored: %v", err) |
| 144 | } |
| 145 | want := types.DefaultTypeAdapter.NativeToValue([]bool{true, true, true, true, true}) |
| 146 | if out.Equal(want) != types.True { |
| 147 | t.Errorf("prg.Eval() got %v, wanted %v", out, want) |
| 148 | } |
| 149 | |
| 150 | sizeBad := Function("size", |
| 151 | Overload("size_vector", []*Type{OpaqueType("vector", TypeParamType("V"))}, IntType), |
| 152 | MemberOverload("vector_size", []*Type{OpaqueType("vector", TypeParamType("V"))}, IntType), |
| 153 | SingletonBinaryBinding(func(lhs, rhs ref.Val) ref.Val { |
| 154 | return nil |
| 155 | })) |
| 156 | _, err = NewCustomEnv(size, sizeBad) |
| 157 | if err == nil || !strings.Contains(err.Error(), "already has a singleton binding") { |
| 158 | t.Errorf("NewCustomEnv(size, size) did not produce the expected error: %v", err) |
| 159 | } |
| 160 | e, err = NewCustomEnv(size, |
| 161 | Function("size", |
| 162 | Overload("size_int", []*Type{IntType}, IntType, |
| 163 | UnaryBinding(func(arg ref.Val) ref.Val { return types.Int(2) }), |
| 164 | ), |
| 165 | ), |
| 166 | ) |
| 167 | if err != nil { |
| 168 | t.Fatalf("NewCustomEnv(size, <custom>) failed: %v", err) |
| 169 | } |
| 170 | _, err = e.Program(ast) |
| 171 | if err == nil || !strings.Contains(err.Error(), "incompatible with specialized overloads") { |
| 172 | t.Errorf("NewCustomEnv(size, size_specialization) did not produce the expected error: %v", err) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | func TestFunctionMergeDuplicate(t *testing.T) { |
| 177 | maxFunc := Function("max", |
| 178 | Overload("max_int", []*Type{IntType}, IntType), |
| 179 | Overload("max_int", []*Type{IntType}, IntType), |
| 180 | ) |
| 181 | _, err := NewCustomEnv(maxFunc, maxFunc) |
| 182 | if err != nil { |
| 183 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | func TestFunctionMergeDeclarationAndDefinition(t *testing.T) { |
| 188 | idFuncDecl := Function("id", Overload("id", []*Type{TypeParamType("T")}, TypeParamType("T"), OverloadIsNonStrict())) |
| 189 | idFuncDef := Function("id", |
| 190 | Overload("id", []*Type{TypeParamType("T")}, TypeParamType("T"), OverloadIsNonStrict(), |
| 191 | UnaryBinding(func(arg ref.Val) ref.Val { |
| 192 | return arg |
| 193 | }), |
| 194 | ), |
| 195 | ) |
| 196 | env, err := NewCustomEnv(Variable("x", AnyType), idFuncDecl, idFuncDef) |
| 197 | if err != nil { |
| 198 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 199 | } |
| 200 | ast, iss := env.Compile("id(x)") |
| 201 | if iss.Err() != nil { |
| 202 | t.Fatalf("env.Compile(id(x)) failed: %v", iss.Err()) |
| 203 | } |
| 204 | prg, err := env.Program(ast) |
| 205 | if err != nil { |
| 206 | t.Fatalf("env.Program() failed: %v", err) |
| 207 | } |
| 208 | out, _, err := prg.Eval(map[string]any{"x": true}) |
| 209 | if err != nil { |
| 210 | t.Fatalf("prg.Eval(x: true) errored: %v", err) |
| 211 | } |
| 212 | if out != types.True { |
| 213 | t.Errorf("prg.Eval() yielded %v, wanted true", out) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | func TestFunctionMergeCollision(t *testing.T) { |
| 218 | maxFunc := Function("max", |
| 219 | Overload("max_int", []*Type{IntType}, IntType), |
| 220 | Overload("max_int2", []*Type{IntType}, IntType), |
| 221 | ) |
| 222 | _, err := NewCustomEnv(maxFunc, maxFunc) |
| 223 | if err == nil { |
| 224 | t.Fatal("NewCustomEnv() succeeded, wanted collision error") |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | func TestFunctionNoOverloads(t *testing.T) { |
| 229 | _, err := NewCustomEnv( |
| 230 | Function("right", SingletonBinaryBinding(func(arg1, arg2 ref.Val) ref.Val { |
| 231 | return arg2 |
| 232 | }))) |
| 233 | if err == nil || !strings.Contains(err.Error(), "must have at least one overload") { |
| 234 | t.Errorf("got %v, wanted 'must have at least one overload'", err) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | func TestSingletonUnaryBinding(t *testing.T) { |
| 239 | // Test the case where the singleton unary impl is merged with the earlier declaration. |
| 240 | e, err := NewCustomEnv( |
| 241 | Variable("x", AnyType), |
| 242 | Function("id", Overload("id_any", []*Type{AnyType}, AnyType)), |
| 243 | Function("id", Overload("id_any", []*Type{AnyType}, AnyType), SingletonUnaryBinding(func(arg ref.Val) ref.Val { return arg })), |
| 244 | ) |
| 245 | if err != nil { |
| 246 | t.Errorf("NewCustomEnv() failed: %v", err) |
| 247 | } |
| 248 | ast, iss := e.Parse("id(x)") |
| 249 | if iss.Err() != nil { |
| 250 | t.Fatalf("Parse('id(x)') failed: %v", iss.Err()) |
| 251 | } |
| 252 | prg, err := e.Program(ast) |
| 253 | if err != nil { |
| 254 | t.Fatalf("Program() failed: %v", err) |
| 255 | } |
| 256 | out, _, err := prg.Eval(map[string]any{"x": "hello"}) |
| 257 | if err != nil { |
| 258 | t.Errorf("prg.Eval(x=hello) failed: %v", err) |
| 259 | } |
| 260 | if out.Equal(types.String("hello")) != types.True { |
| 261 | t.Errorf("Eval got %v, wanted 'hello'", out) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | func TestSingletonUnaryBindingParameterized(t *testing.T) { |
| 266 | // Test the case where the singleton unary impl is merged with the earlier declaration. |
| 267 | e, err := NewCustomEnv( |
| 268 | Variable("x", AnyType), |
| 269 | Function("isSorted", MemberOverload("list_int_is_sorted", []*Type{ListType(IntType)}, BoolType)), |
| 270 | Function("isSorted", MemberOverload("list_uint_is_sorted", []*Type{ListType(UintType)}, BoolType), |
| 271 | SingletonUnaryBinding(func(arg ref.Val) ref.Val { return types.True })), |
| 272 | ) |
| 273 | if err != nil { |
| 274 | t.Errorf("NewCustomEnv() failed: %v", err) |
| 275 | } |
| 276 | ast, iss := e.Parse("x.isSorted()") |
| 277 | if iss.Err() != nil { |
| 278 | t.Fatalf("Parse('x.isSorted()') failed: %v", iss.Err()) |
| 279 | } |
| 280 | prg, err := e.Program(ast) |
| 281 | if err != nil { |
| 282 | t.Fatalf("Program() failed: %v", err) |
| 283 | } |
| 284 | out, _, err := prg.Eval(map[string]any{"x": []int{1, 2, 3}}) |
| 285 | if err != nil { |
| 286 | t.Errorf("prg.Eval(x=[1,2,3]) failed: %v", err) |
| 287 | } |
| 288 | if out != types.True { |
| 289 | t.Errorf("Eval got %v, wanted true", out) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | func TestSingletonBinaryBinding(t *testing.T) { |
| 294 | _, err := NewCustomEnv( |
| 295 | Function("right", |
| 296 | Overload("right_int_int", []*Type{IntType, IntType}, IntType), |
| 297 | Overload("right_double_double", []*Type{DoubleType, DoubleType}, DoubleType), |
| 298 | Overload("right_string_string", []*Type{StringType, StringType}, StringType), |
| 299 | SingletonBinaryBinding(func(arg1, arg2 ref.Val) ref.Val { |
| 300 | return arg2 |
| 301 | }, traits.ComparerType), |
| 302 | ), |
| 303 | ) |
| 304 | if err != nil { |
| 305 | t.Errorf("NewCustomEnv() failed: %v", err) |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | func TestSingletonFunctionBinding(t *testing.T) { |
| 310 | env, err := NewCustomEnv( |
| 311 | Variable("unk", DynType), |
| 312 | Variable("err", DynType), |
| 313 | Function("dyn", |
| 314 | Overload("dyn", []*Type{DynType}, DynType), |
| 315 | SingletonUnaryBinding(func(arg ref.Val) ref.Val { |
| 316 | return arg |
| 317 | })), |
| 318 | Function("max", |
| 319 | Overload("max_int", []*Type{IntType}, IntType), |
| 320 | Overload("max_int_int", []*Type{IntType, IntType}, IntType), |
| 321 | Overload("max_int_int_int", []*Type{IntType, IntType, IntType}, IntType), |
| 322 | SingletonFunctionBinding(func(args ...ref.Val) ref.Val { |
| 323 | max := types.Int(math.MinInt64) |
| 324 | for _, arg := range args { |
| 325 | i, ok := arg.(types.Int) |
| 326 | if !ok { |
| 327 | // With a singleton implementation, the error handling must be explicitly |
| 328 | // performed as a binding detail of the singleton function. |
| 329 | // With custom overload implementations, a function guard is automatically |
| 330 | // added to the function to validate that the runtime types are compatible |
| 331 | // to provide some basic invocation protections. |
| 332 | return decls.MaybeNoSuchOverload("max", args...) |
| 333 | } |
| 334 | if i > max { |
| 335 | max = i |
| 336 | } |
| 337 | } |
| 338 | return max |
| 339 | }), |
| 340 | ), |
| 341 | ) |
| 342 | if err != nil { |
| 343 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 344 | } |
| 345 | |
| 346 | for _, tc := range dispatchTests { |
| 347 | tc := tc |
| 348 | t.Run(fmt.Sprintf("Parse(%s)", tc.expr), func(t *testing.T) { |
| 349 | testParse(t, env, tc.expr, tc.out) |
| 350 | }) |
| 351 | } |
| 352 | for _, tc := range dispatchTests { |
| 353 | tc := tc |
| 354 | t.Run(fmt.Sprintf("Compile(%s)", tc.expr), func(t *testing.T) { |
| 355 | testCompile(t, env, tc.expr, tc.out) |
| 356 | }) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | func TestUnaryBinding(t *testing.T) { |
| 361 | _, err := NewCustomEnv( |
| 362 | Function("dyn", |
| 363 | Overload("dyn", []*Type{}, DynType, |
| 364 | // wrong arg count |
| 365 | UnaryBinding(func(arg ref.Val) ref.Val { return arg }), |
| 366 | ), |
| 367 | ), |
| 368 | ) |
| 369 | if err == nil || !strings.Contains(err.Error(), "function bound to non-unary overload") { |
| 370 | t.Errorf("bad binding did not produce expected error: %v", err) |
| 371 | } |
| 372 | |
| 373 | e, err := NewCustomEnv( |
| 374 | Function("size", |
| 375 | Overload("size_non_strict", []*Type{ListType(DynType)}, IntType, |
| 376 | OverloadIsNonStrict(), |
| 377 | OverloadOperandTrait(traits.SizerType), |
| 378 | UnaryBinding(func(arg ref.Val) ref.Val { |
| 379 | if types.IsUnknownOrError(arg) { |
| 380 | return arg |
| 381 | } |
| 382 | return arg.(traits.Sizer).Size() |
| 383 | }), |
| 384 | ), |
| 385 | ), |
| 386 | Variable("x", ListType(DynType)), |
| 387 | ) |
| 388 | if err != nil { |
| 389 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 390 | } |
| 391 | ast, iss := e.Compile("size(x)") |
| 392 | if iss.Err() != nil { |
| 393 | t.Fatalf("Compile(size(x)) failed: %v", iss.Err()) |
| 394 | } |
| 395 | prg, err := e.Program(ast) |
| 396 | if err != nil { |
| 397 | t.Fatalf("Program() failed: %v", err) |
| 398 | } |
| 399 | out, _, err := prg.Eval(map[string]any{"x": types.NewUnknown(1, nil)}) |
| 400 | if err != nil { |
| 401 | t.Fatalf("prg.Eval(x=unk) failed: %v", err) |
| 402 | } |
| 403 | if !types.NewUnknown(1, nil).Contains(out.(*types.Unknown)) { |
| 404 | t.Errorf("prg.Eval(x=unk) returned %v, wanted unknown{1}", out) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | func TestBinaryBinding(t *testing.T) { |
| 409 | e, err := NewCustomEnv( |
| 410 | Function("max", |
| 411 | Overload("max_int_int", []*Type{IntType, IntType}, IntType, |
| 412 | OverloadIsNonStrict(), |
| 413 | BinaryBinding(func(arg1, arg2 ref.Val) ref.Val { |
| 414 | if types.IsUnknownOrError(arg1) { |
| 415 | return arg2 |
| 416 | } |
| 417 | if types.IsUnknownOrError(arg2) { |
| 418 | return arg1 |
| 419 | } |
| 420 | i1 := arg1.(types.Int) |
| 421 | i2 := arg2.(types.Int) |
| 422 | if i1 > i2 { |
| 423 | return i1 |
| 424 | } |
| 425 | return i2 |
| 426 | }), |
| 427 | ), |
| 428 | ), |
| 429 | Variable("x", IntType), |
| 430 | Variable("y", IntType), |
| 431 | ) |
| 432 | if err != nil { |
| 433 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 434 | } |
| 435 | ast, iss := e.Parse("max(x, y)") |
| 436 | if iss.Err() != nil { |
| 437 | t.Fatalf("Parse(max(x, y))) failed: %v", iss.Err()) |
| 438 | } |
| 439 | prg, err := e.Program(ast) |
| 440 | if err != nil { |
| 441 | t.Fatalf("Program() failed: %v", err) |
| 442 | } |
| 443 | out, _, err := prg.Eval(map[string]any{"x": types.NewUnknown(1, nil), "y": 1}) |
| 444 | if err != nil { |
| 445 | t.Fatalf("prg.Eval(x=unk) failed: %v", err) |
| 446 | } |
| 447 | if !reflect.DeepEqual(out, types.IntOne) { |
| 448 | t.Errorf("prg.Eval(x=unk, y=1) returned %v, wanted 1", out) |
| 449 | } |
| 450 | out, _, err = prg.Eval(map[string]any{"x": 2, "y": types.NewUnknown(2, nil)}) |
| 451 | if err != nil { |
| 452 | t.Fatalf("prg.Eval(x=2, y=unk) failed: %v", err) |
| 453 | } |
| 454 | if !reflect.DeepEqual(out, types.Int(2)) { |
| 455 | t.Errorf("prg.Eval(x=2, y=unk) returned %v, wanted 2", out) |
| 456 | } |
| 457 | out, _, err = prg.Eval(map[string]any{"x": 2, "y": 1}) |
| 458 | if err != nil { |
| 459 | t.Fatalf("prg.Eval(x=2, y=1) failed: %v", err) |
| 460 | } |
| 461 | if !reflect.DeepEqual(out, types.Int(2)) { |
| 462 | t.Errorf("prg.Eval(x=2, y=1) returned %v, wanted 2", out) |
| 463 | } |
| 464 | |
| 465 | _, err = NewCustomEnv( |
| 466 | Function("right", |
| 467 | Overload("right_int_int", []*Type{IntType, IntType, IntType}, IntType, |
| 468 | // wrong arg count |
| 469 | BinaryBinding(func(arg1, arg2 ref.Val) ref.Val { return arg2 }), |
| 470 | ), |
| 471 | ), |
| 472 | ) |
| 473 | if err == nil || !strings.Contains(err.Error(), "function bound to non-binary overload") { |
| 474 | t.Errorf("bad binding did not produce expected error: %v", err) |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | func TestFunctionBinding(t *testing.T) { |
| 479 | e, err := NewCustomEnv( |
| 480 | Variable("unk", DynType), |
| 481 | Variable("err", DynType), |
| 482 | Function("dyn", |
| 483 | Overload("dyn", []*Type{DynType}, DynType), |
| 484 | SingletonUnaryBinding(func(arg ref.Val) ref.Val { |
| 485 | return arg |
| 486 | })), |
| 487 | Function("max", |
| 488 | Overload("max_int", []*Type{IntType}, IntType, |
| 489 | UnaryBinding(func(arg ref.Val) ref.Val { return arg })), |
| 490 | Overload("max_int_int", []*Type{IntType, IntType}, IntType, |
| 491 | BinaryBinding(func(lhs, rhs ref.Val) ref.Val { |
| 492 | if lhs.(types.Int).Compare(rhs) == types.IntNegOne { |
| 493 | return rhs |
| 494 | } |
| 495 | return lhs |
| 496 | })), |
| 497 | Overload("max_int_int_int", []*Type{IntType, IntType, IntType}, IntType, |
| 498 | FunctionBinding(func(args ...ref.Val) ref.Val { |
| 499 | max := types.Int(math.MinInt64) |
| 500 | for _, arg := range args { |
| 501 | i := arg.(types.Int) |
| 502 | if i > max { |
| 503 | max = i |
| 504 | } |
| 505 | } |
| 506 | return max |
| 507 | })), |
| 508 | ), |
| 509 | ) |
| 510 | if err != nil { |
| 511 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 512 | } |
| 513 | |
| 514 | for _, tc := range dispatchTests { |
| 515 | tc := tc |
| 516 | t.Run(fmt.Sprintf("Parse(%s)", tc.expr), func(t *testing.T) { |
| 517 | testParse(t, e, tc.expr, tc.out) |
| 518 | }) |
| 519 | } |
| 520 | for _, tc := range dispatchTests { |
| 521 | tc := tc |
| 522 | t.Run(fmt.Sprintf("Compile(%s)", tc.expr), func(t *testing.T) { |
| 523 | testCompile(t, e, tc.expr, tc.out) |
| 524 | }) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | func TestFunctionDisableDeclaration(t *testing.T) { |
| 529 | e, err := NewCustomEnv( |
| 530 | Function("disabled", |
| 531 | DisableDeclaration(true), |
| 532 | Overload("disabled_any", []*Type{BoolType}, BoolType), |
| 533 | SingletonFunctionImpl(func(args ...ref.Val) ref.Val { |
| 534 | return types.True |
| 535 | }), |
| 536 | ), |
| 537 | ) |
| 538 | if err != nil { |
| 539 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 540 | } |
| 541 | ast, iss := e.Parse("disabled(true)") |
| 542 | if iss.Err() != nil { |
| 543 | t.Errorf("Parse(disabled(true)) failed: %v", iss.Err()) |
| 544 | } |
| 545 | prg, err := e.Program(ast) |
| 546 | if err != nil { |
| 547 | t.Fatalf("Program(ast) failed: %v", err) |
| 548 | } |
| 549 | out, _, err := prg.Eval(NoVars()) |
| 550 | if err != nil { |
| 551 | t.Errorf("disabled runtime binding missing: %v", err) |
| 552 | } else if out != types.True { |
| 553 | t.Errorf("disabled runtime binding failed: %v", out) |
| 554 | } |
| 555 | _, iss = e.Compile("disabled(true)") |
| 556 | if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "undeclared reference to 'disabled'") { |
| 557 | t.Errorf("Compile(disabled(true)) got an unexpected error: %v", iss.Err()) |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | func TestFunctionDisableDeclarationMerge(t *testing.T) { |
| 562 | e, err := NewCustomEnv( |
| 563 | Function("disabled", |
| 564 | Overload("disabled_any", []*Type{BoolType}, BoolType), |
| 565 | ), |
| 566 | // Ensure the previously enabled declaration is disabled |
| 567 | Function("disabled", |
| 568 | DisableDeclaration(true), |
| 569 | Overload("disabled_any", []*Type{BoolType}, BoolType, |
| 570 | FunctionBinding(func(args ...ref.Val) ref.Val { |
| 571 | return types.True |
| 572 | })), |
| 573 | ), |
| 574 | ) |
| 575 | if err != nil { |
| 576 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 577 | } |
| 578 | ast, iss := e.Parse("disabled(true)") |
| 579 | if iss.Err() != nil { |
| 580 | t.Errorf("Parse(disabled(true)) failed: %v", iss.Err()) |
| 581 | } |
| 582 | prg, err := e.Program(ast) |
| 583 | if err != nil { |
| 584 | t.Fatalf("Program(ast) failed: %v", err) |
| 585 | } |
| 586 | out, _, err := prg.Eval(NoVars()) |
| 587 | if err != nil { |
| 588 | t.Errorf("disabled runtime binding missing: %v", err) |
| 589 | } else if out != types.True { |
| 590 | t.Errorf("disabled runtime binding failed: %v", out) |
| 591 | } |
| 592 | _, iss = e.Compile("disabled(true)") |
| 593 | if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "undeclared reference to 'disabled'") { |
| 594 | t.Errorf("Compile(disabled(true)) got an unexpected error: %v", iss.Err()) |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | func TestFunctionDisableDeclarationMergeReenable(t *testing.T) { |
| 599 | e, err := NewCustomEnv( |
| 600 | Function("enabled", |
| 601 | DisableDeclaration(true), |
| 602 | Overload("enabled_any", []*Type{BoolType}, BoolType), |
| 603 | ), |
| 604 | // Ensure the previously disabled declaration is enabled |
| 605 | Function("enabled", |
| 606 | DisableDeclaration(false), |
| 607 | Overload("enabled_any", []*Type{BoolType}, BoolType, |
| 608 | FunctionBinding(func(args ...ref.Val) ref.Val { |
| 609 | return types.True |
| 610 | })), |
| 611 | ), |
| 612 | ) |
| 613 | if err != nil { |
| 614 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 615 | } |
| 616 | ast, iss := e.Parse("enabled(true)") |
| 617 | if iss.Err() != nil { |
| 618 | t.Errorf("Parse(enabled(true)) failed: %v", iss.Err()) |
| 619 | } |
| 620 | prg, err := e.Program(ast) |
| 621 | if err != nil { |
| 622 | t.Fatalf("Program(ast) failed: %v", err) |
| 623 | } |
| 624 | out, _, err := prg.Eval(NoVars()) |
| 625 | if err != nil { |
| 626 | t.Errorf("enabled runtime binding missing: %v", err) |
| 627 | } else if out != types.True { |
| 628 | t.Errorf("enabled runtime binding failed: %v", out) |
| 629 | } |
| 630 | _, iss = e.Compile("enabled(true)") |
| 631 | if iss.Err() != nil { |
| 632 | t.Errorf("Compile(enabled(true)) got an unexpected error: %v", iss.Err()) |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | func TestExprDeclToDeclaration(t *testing.T) { |
| 637 | paramT := chkdecls.NewTypeParamType("T") |
| 638 | eq, err := ExprDeclToDeclaration( |
| 639 | chkdecls.NewFunction(operators.Equals, |
| 640 | chkdecls.NewParameterizedOverload(overloads.Equals, |
| 641 | []*exprpb.Type{paramT, paramT}, chkdecls.Bool, []string{"T"})), |
| 642 | ) |
| 643 | if err != nil { |
| 644 | t.Fatalf("ExprDeclToDeclaration(equals) failed: %v", err) |
| 645 | } |
| 646 | size, err := ExprDeclToDeclaration( |
| 647 | chkdecls.NewFunction(overloads.Size, |
| 648 | chkdecls.NewOverload(overloads.SizeString, |
| 649 | []*exprpb.Type{chkdecls.String}, chkdecls.Int), |
| 650 | chkdecls.NewInstanceOverload(overloads.SizeStringInst, |
| 651 | []*exprpb.Type{chkdecls.String}, chkdecls.Int)), |
| 652 | ) |
| 653 | if err != nil { |
| 654 | t.Fatalf("ExprDeclToDeclaration(size) failed: %v", err) |
| 655 | } |
| 656 | x, err := ExprDeclToDeclaration(chkdecls.NewVar("x", chkdecls.String)) |
| 657 | if err != nil { |
| 658 | t.Fatalf("ExprDeclToDeclaration(x) failed: %v", err) |
| 659 | } |
| 660 | constant, err := ExprDeclToDeclaration( |
| 661 | chkdecls.NewConst("constant", chkdecls.Bool, &exprpb.Constant{ |
| 662 | ConstantKind: &exprpb.Constant_BoolValue{BoolValue: true}, |
| 663 | })) |
| 664 | if err != nil { |
| 665 | t.Fatalf("ExprDeclToDeclaration(constant) failed: %v", err) |
| 666 | } |
| 667 | e, err := NewCustomEnv(size, eq, x, constant) |
| 668 | if err != nil { |
| 669 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 670 | } |
| 671 | ast, iss := e.Compile("(size(x) == x.size()) == constant") |
| 672 | if iss.Err() != nil { |
| 673 | t.Fatalf("Compile((size(x) == x.size()) == constant) failed: %v", iss.Err()) |
| 674 | } |
| 675 | prg, err := e.Program(ast, Functions(&functions.Overload{ |
| 676 | Operator: overloads.SizeString, |
| 677 | Unary: func(arg ref.Val) ref.Val { |
| 678 | str, ok := arg.(types.String) |
| 679 | if !ok { |
| 680 | return types.MaybeNoSuchOverloadErr(arg) |
| 681 | } |
| 682 | return types.Int(len([]rune(string(str)))) |
| 683 | }, |
| 684 | }, &functions.Overload{ |
| 685 | Operator: overloads.SizeStringInst, |
| 686 | Unary: func(arg ref.Val) ref.Val { |
| 687 | str, ok := arg.(types.String) |
| 688 | if !ok { |
| 689 | return types.MaybeNoSuchOverloadErr(arg) |
| 690 | } |
| 691 | return types.Int(len([]rune(string(str)))) |
| 692 | }, |
| 693 | })) |
| 694 | if err != nil { |
| 695 | t.Fatalf("Program(ast) failed: %v", err) |
| 696 | } |
| 697 | out, _, err := prg.Eval(map[string]any{"x": "hello"}) |
| 698 | if err != nil { |
| 699 | t.Fatalf("prg.Eval(x=hello) failed: %v", err) |
| 700 | } |
| 701 | if out != types.True { |
| 702 | t.Errorf("prg.Eval((size(x) == x.size()) == constant) got %v, wanted true", out) |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | func TestExprDeclToDeclarationInvalid(t *testing.T) { |
| 707 | tests := []struct { |
| 708 | in *exprpb.Decl |
| 709 | out string |
| 710 | }{ |
| 711 | { |
| 712 | in: &exprpb.Decl{}, |
| 713 | out: "unsupported decl", |
| 714 | }, |
| 715 | { |
| 716 | in: &exprpb.Decl{ |
| 717 | Name: "bad_var", |
| 718 | DeclKind: &exprpb.Decl_Ident{ |
| 719 | Ident: &exprpb.Decl_IdentDecl{ |
| 720 | Type: chkdecls.NewListType(&exprpb.Type{}), |
| 721 | }, |
| 722 | }, |
| 723 | }, |
| 724 | out: "unsupported type", |
| 725 | }, |
| 726 | { |
| 727 | in: &exprpb.Decl{ |
| 728 | Name: "bad_var", |
| 729 | DeclKind: &exprpb.Decl_Ident{ |
| 730 | Ident: &exprpb.Decl_IdentDecl{ |
| 731 | Type: chkdecls.Bool, |
| 732 | Value: &exprpb.Constant{}, |
| 733 | }, |
| 734 | }, |
| 735 | }, |
| 736 | out: "unsupported constant", |
| 737 | }, |
| 738 | { |
| 739 | in: &exprpb.Decl{ |
| 740 | Name: "bad_func_return", |
| 741 | DeclKind: &exprpb.Decl_Function{ |
| 742 | Function: &exprpb.Decl_FunctionDecl{ |
| 743 | Overloads: []*exprpb.Decl_FunctionDecl_Overload{ |
| 744 | { |
| 745 | OverloadId: "bad_overload", |
| 746 | ResultType: &exprpb.Type{}, |
| 747 | }, |
| 748 | }, |
| 749 | }, |
| 750 | }, |
| 751 | }, |
| 752 | out: "unsupported type", |
| 753 | }, |
| 754 | { |
| 755 | in: &exprpb.Decl{ |
| 756 | Name: "bad_func_arg", |
| 757 | DeclKind: &exprpb.Decl_Function{ |
| 758 | Function: &exprpb.Decl_FunctionDecl{ |
| 759 | Overloads: []*exprpb.Decl_FunctionDecl_Overload{ |
| 760 | { |
| 761 | OverloadId: "bad_overload", |
| 762 | Params: []*exprpb.Type{{}}, |
| 763 | ResultType: chkdecls.Dyn, |
| 764 | }, |
| 765 | }, |
| 766 | }, |
| 767 | }, |
| 768 | }, |
| 769 | out: "unsupported type", |
| 770 | }, |
| 771 | } |
| 772 | |
| 773 | for _, tc := range tests { |
| 774 | tc := tc |
| 775 | t.Run(tc.in.String(), func(t *testing.T) { |
| 776 | _, err := ExprDeclToDeclaration(tc.in) |
| 777 | if err == nil || !strings.Contains(err.Error(), tc.out) { |
| 778 | t.Fatalf("ExprDeclToDeclarations(%v) got %v, wanted error %v", tc.in, err, tc.out) |
| 779 | } |
| 780 | }) |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | func TestFunctionDeclExcludeOverloads(t *testing.T) { |
| 785 | funcs := []*decls.FunctionDecl{} |
| 786 | for _, fn := range stdlib.Functions() { |
| 787 | if fn.Name() == operators.Add { |
| 788 | fn = fn.Subset(ExcludeOverloads(overloads.AddList, overloads.AddBytes, overloads.AddString)) |
| 789 | } |
| 790 | funcs = append(funcs, fn) |
| 791 | } |
| 792 | env, err := NewCustomEnv(FunctionDecls(funcs...)) |
| 793 | if err != nil { |
| 794 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 795 | } |
| 796 | |
| 797 | successTests := []struct { |
| 798 | name string |
| 799 | expr string |
| 800 | want ref.Val |
| 801 | }{ |
| 802 | { |
| 803 | name: "ints", |
| 804 | expr: "1 + 1", |
| 805 | want: types.Int(2), |
| 806 | }, |
| 807 | { |
| 808 | name: "doubles", |
| 809 | expr: "1.5 + 1.5", |
| 810 | want: types.Double(3.0), |
| 811 | }, |
| 812 | { |
| 813 | name: "uints", |
| 814 | expr: "1u + 2u", |
| 815 | want: types.Uint(3), |
| 816 | }, |
| 817 | { |
| 818 | name: "timestamp plus duration", |
| 819 | expr: "timestamp('2001-01-01T00:00:00Z') + duration('1h') == timestamp('2001-01-01T01:00:00Z')", |
| 820 | want: types.True, |
| 821 | }, |
| 822 | { |
| 823 | name: "durations", |
| 824 | expr: "duration('1h') + duration('1m') == duration('1h1m')", |
| 825 | want: types.True, |
| 826 | }, |
| 827 | } |
| 828 | for _, tst := range successTests { |
| 829 | tc := tst |
| 830 | t.Run(tc.name, func(t *testing.T) { |
| 831 | ast, iss := env.Compile(tc.expr) |
| 832 | if iss.Err() != nil { |
| 833 | t.Fatalf("env.Compile() failed: %v", iss.Err()) |
| 834 | } |
| 835 | prg, err := env.Program(ast) |
| 836 | if err != nil { |
| 837 | t.Fatalf("env.Program() failed: %v", err) |
| 838 | } |
| 839 | out, _, err := prg.Eval(NoVars()) |
| 840 | if err != nil { |
| 841 | t.Fatalf("prg.Eval() errored: %v", err) |
| 842 | } |
| 843 | if out.Equal(tc.want) != types.True { |
| 844 | t.Errorf("Eval() got %v, wanted %v", out, tc.want) |
| 845 | } |
| 846 | }) |
| 847 | } |
| 848 | failureTests := []struct { |
| 849 | name string |
| 850 | expr string |
| 851 | }{ |
| 852 | { |
| 853 | name: "strings", |
| 854 | expr: "'a' + 'b'", |
| 855 | }, |
| 856 | { |
| 857 | name: "bytes", |
| 858 | expr: "b'123' + b'456'", |
| 859 | }, |
| 860 | { |
| 861 | name: "lists", |
| 862 | expr: "[1] + [2, 3]", |
| 863 | }, |
| 864 | } |
| 865 | for _, tst := range failureTests { |
| 866 | tc := tst |
| 867 | t.Run(tc.name, func(t *testing.T) { |
| 868 | _, iss := env.Compile(tc.expr) |
| 869 | if iss.Err() == nil { |
| 870 | t.Error("env.Compile() got ast, wanted error") |
| 871 | } |
| 872 | }) |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | func TestFunctionDeclIncludeOverloads(t *testing.T) { |
| 877 | funcs := []*decls.FunctionDecl{} |
| 878 | for _, fn := range stdlib.Functions() { |
| 879 | if fn.Name() == operators.Add { |
| 880 | fn = fn.Subset(IncludeOverloads(overloads.AddInt64, overloads.AddDouble)) |
| 881 | } |
| 882 | funcs = append(funcs, fn) |
| 883 | } |
| 884 | env, err := NewCustomEnv(FunctionDecls(funcs...)) |
| 885 | if err != nil { |
| 886 | t.Fatalf("NewCustomEnv() failed: %v", err) |
| 887 | } |
| 888 | |
| 889 | successTests := []struct { |
| 890 | name string |
| 891 | expr string |
| 892 | want ref.Val |
| 893 | }{ |
| 894 | { |
| 895 | name: "ints", |
| 896 | expr: "1 + 1", |
| 897 | want: types.Int(2), |
| 898 | }, |
| 899 | { |
| 900 | name: "doubles", |
| 901 | expr: "1.5 + 1.5", |
| 902 | want: types.Double(3.0), |
| 903 | }, |
| 904 | } |
| 905 | for _, tst := range successTests { |
| 906 | tc := tst |
| 907 | t.Run(tc.name, func(t *testing.T) { |
| 908 | ast, iss := env.Compile(tc.expr) |
| 909 | if iss.Err() != nil { |
| 910 | t.Fatalf("env.Compile() failed: %v", iss.Err()) |
| 911 | } |
| 912 | prg, err := env.Program(ast) |
| 913 | if err != nil { |
| 914 | t.Fatalf("env.Program() failed: %v", err) |
| 915 | } |
| 916 | out, _, err := prg.Eval(NoVars()) |
| 917 | if err != nil { |
| 918 | t.Fatalf("prg.Eval() errored: %v", err) |
| 919 | } |
| 920 | if out.Equal(tc.want) != types.True { |
| 921 | t.Errorf("Eval() got %v, wanted %v", out, tc.want) |
| 922 | } |
| 923 | }) |
| 924 | } |
| 925 | failureTests := []struct { |
| 926 | name string |
| 927 | expr string |
| 928 | }{ |
| 929 | { |
| 930 | name: "strings", |
| 931 | expr: "'a' + 'b'", |
| 932 | }, |
| 933 | { |
| 934 | name: "bytes", |
| 935 | expr: "b'123' + b'456'", |
| 936 | }, |
| 937 | { |
| 938 | name: "lists", |
| 939 | expr: "[1] + [2, 3]", |
| 940 | }, |
| 941 | { |
| 942 | name: "uints", |
| 943 | expr: "1u + 2u", |
| 944 | }, |
| 945 | { |
| 946 | name: "timestamp plus duration", |
| 947 | expr: "timestamp('2001-01-01T00:00:00Z') + duration('1h') == timestamp('2001-01-01T01:00:00Z')", |
| 948 | }, |
| 949 | { |
| 950 | name: "durations", |
| 951 | expr: "duration('1h') + duration('1m') == duration('1h1m')", |
| 952 | }, |
| 953 | } |
| 954 | for _, tst := range failureTests { |
| 955 | tc := tst |
| 956 | t.Run(tc.name, func(t *testing.T) { |
| 957 | _, iss := env.Compile(tc.expr) |
| 958 | if iss.Err() == nil { |
| 959 | t.Error("env.Compile() got ast, wanted error") |
| 960 | } |
| 961 | }) |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | func testParse(t testing.TB, env *Env, expr string, want any) { |
| 966 | t.Helper() |
| 967 | ast, iss := env.Parse(expr) |
| 968 | if iss.Err() != nil { |
| 969 | t.Fatalf("env.Parse(%s) failed: %v", expr, iss.Err()) |
| 970 | } |
| 971 | prg, err := env.Program(ast) |
| 972 | if err != nil { |
| 973 | t.Fatalf("env.Program() failed: %v", err) |
| 974 | } |
| 975 | out, _, err := prg.Eval(map[string]any{"err": types.NewErr("error argument"), "unk": types.NewUnknown(42, nil)}) |
| 976 | switch want := want.(type) { |
| 977 | case *types.Unknown: |
| 978 | if !want.Contains(out.(*types.Unknown)) { |
| 979 | t.Errorf("prg.Eval() got %v, wanted %v", out, want) |
| 980 | } |
| 981 | case ref.Val: |
| 982 | if want.Equal(out) != types.True { |
| 983 | t.Errorf("prg.Eval() got %v, wanted %v", out, want) |
| 984 | } |
| 985 | case error: |
| 986 | if err == nil || want.Error() != err.Error() { |
| 987 | t.Errorf("prg.Eval() got error '%v', wanted '%v'", err, want) |
| 988 | } |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | func testCompile(t testing.TB, env *Env, expr string, want any) { |
| 993 | t.Helper() |
| 994 | ast, iss := env.Compile(expr) |
| 995 | if iss.Err() != nil { |
| 996 | t.Fatalf("env.Compile(%s) failed: %v", expr, iss.Err()) |
| 997 | } |
| 998 | prg, err := env.Program(ast) |
| 999 | if err != nil { |
| 1000 | t.Fatalf("env.Program() failed: %v", err) |
| 1001 | } |
| 1002 | out, _, err := prg.Eval(map[string]any{"err": types.NewErr("error argument"), "unk": types.NewUnknown(42, nil)}) |
| 1003 | switch want := want.(type) { |
| 1004 | case *types.Unknown: |
| 1005 | if !want.Contains(out.(*types.Unknown)) { |
| 1006 | t.Errorf("prg.Eval() got %v, wanted %v", out, want) |
| 1007 | } |
| 1008 | case ref.Val: |
| 1009 | if want.Equal(out) != types.True { |
| 1010 | t.Errorf("prg.Eval() got %v, wanted %v", out, want) |
| 1011 | } |
| 1012 | case error: |
| 1013 | if err == nil || want.Error() != err.Error() { |
| 1014 | t.Errorf("prg.Eval() got error '%v', wanted '%v'", err, want) |
| 1015 | } |
| 1016 | } |
| 1017 | } |