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