diff --git a/optimizer/optimizer_test.go b/optimizer/optimizer_test.go index 9c5cd68e..5fb6d1d5 100644 --- a/optimizer/optimizer_test.go +++ b/optimizer/optimizer_test.go @@ -2,8 +2,11 @@ package optimizer_test import ( "fmt" + "math" + "reflect" "strings" "testing" + "time" "github.com/expr-lang/expr/internal/testify/assert" "github.com/expr-lang/expr/internal/testify/require" @@ -497,3 +500,163 @@ func TestOptimize_predicate_combination_with_non_json_float(t *testing.T) { require.NoError(t, err, code) } } + +func TestOptimize_predicate_combination_same_string(t *testing.T) { + // predicateCombination must merge only calls on the same collection. + // These collections differ but print the same via String(). + env := map[string]any{"a": []int{1, 2, 3}, "n": 2, "NaN": 7} + for _, code := range []string{ + // filterMap sets BuiltinNode.Map, which String() does not print. + `all(map(filter(a, # > 0), # * 10), # > 5) && all(filter(a, # > 0), # < 5)`, + `not (any(map(filter(a, # > 0), # * 10), # == 1) || any(filter(a, # > 0), # == 30))`, + // Folded (-2) prints as -2, so (-2) ** n printed as -2 ** n. + `all([(-2) ** n], # > 0) && all([-2 ** n], # < 0)`, + `all([(-2.0) ** n], # > 0) && all([-2.0 ** n], # < 0)`, + // Folded constants print 2.0 as 2, and NaN like an identifier. + `all([2.0], type(#) == "float") && all([2], type(#) == "int")`, + `all([0/0], # != #) && all([NaN], # == 7)`, + // 0.0 and -0.0 are equal, but they are not the same constant. + `all([-0.0], 1 / # < 0) && all([0.0], 1 / # > 0)`, + } { + t.Run(code, func(t *testing.T) { + unoptimized, err := expr.Compile(code, expr.Env(env), expr.Optimize(false)) + require.NoError(t, err) + want, err := expr.Run(unoptimized, env) + require.NoError(t, err) + require.Equal(t, true, want) + + optimized, err := expr.Compile(code, expr.Env(env)) + require.NoError(t, err) + got, err := expr.Run(optimized, env) + require.NoError(t, err) + assert.Equal(t, want, got) + }) + } +} + +func TestOptimize_predicate_combination_same_constant(t *testing.T) { + // Collections holding folded constants still merge when they are the same. + env := map[string]any{"a": []int{1, 2, 3}} + for _, code := range []string{ + `all([1, 2, 3], # > 0) && all([1, 2, 3], # < 5)`, + `all(filter(a, # in [1, 2]), # > 0) && all(filter(a, # in [1, 2]), # < 5)`, + `all([0/0], # != #) && all([0/0], # != 0)`, + } { + t.Run(code, func(t *testing.T) { + tree, err := parser.Parse(code) + require.NoError(t, err) + config := conf.New(env) + _, err = checker.Check(tree, config) + require.NoError(t, err) + err = optimizer.Optimize(&tree.Node, config) + require.NoError(t, err) + + builtin, ok := tree.Node.(*ast.BuiltinNode) + require.True(t, ok, "not merged: %s", tree.Node) + assert.Equal(t, "all", builtin.Name) + }) + } +} + +func TestOptimize_predicate_combination_constant_values(t *testing.T) { + // Constants holding values that the comparison cannot check exactly must + // not be merged when they differ. The expression is true unless c2's + // predicate wrongly runs on c1's value. + code := `all([c1()], same(#, c1())) && all([c2()], same(#, c2()))` + x0, x5, y0, y5 := 0, 5, 0, 5 + for _, tt := range []struct { + name string + c1, c2 any + }{ + {"pointer keys", []any{map[*int]int{&x0: 1, &x5: 2}, &x0}, []any{map[*int]int{&y0: 1, &y5: 2}, &y5}}, + {"NaN keys", map[float64]int{math.NaN(): 1, math.NaN(): 1}, map[float64]int{math.NaN(): 1, math.NaN(): 2}}, + {"signed zero keys", map[float64]int{math.Copysign(0, -1): 1}, map[float64]int{0: 1}}, + } { + t.Run(tt.name, func(t *testing.T) { + env := map[string]any{ + "c1": func() any { return tt.c1 }, + "c2": func() any { return tt.c2 }, + // c1 and c2 return the same map or slice each time, so + // compare identity. + "same": func(a, b any) bool { + return reflect.ValueOf(a).Pointer() == reflect.ValueOf(b).Pointer() + }, + } + program, err := expr.Compile(code, expr.Env(env), expr.ConstExpr("c1"), expr.ConstExpr("c2")) + require.NoError(t, err) + out, err := expr.Run(program, env) + require.NoError(t, err) + assert.Equal(t, true, out) + }) + } +} + +func TestOptimize_predicate_combination_same_pointer(t *testing.T) { + // A constant holding pointers merges when both sides hold the same data. + type user struct{ Age int } + users := []*user{{Age: 20}, {Age: 30}} + env := map[string]any{"users": func() any { return users }} + tree, err := parser.Parse(`all(users(), .Age > 18) && all(users(), .Age < 40)`) + require.NoError(t, err) + config := conf.New(env) + config.ConstExpr("users") + _, err = checker.Check(tree, config) + require.NoError(t, err) + err = optimizer.Optimize(&tree.Node, config) + require.NoError(t, err) + + builtin, ok := tree.Node.(*ast.BuiltinNode) + require.True(t, ok, "not merged: %T", tree.Node) + assert.Equal(t, "all", builtin.Name) +} + +func TestOptimize_predicate_combination_large_constant(t *testing.T) { + // Constants that refer to themselves, or reuse one value in many places, + // must not hang the optimizer. Each case builds two equal values that do + // not share data, so the comparison has to walk them. + cycle := func() any { + m := map[string]any{} + m["a"] = m + m["b"] = m + return m + } + slices := func() any { + var v any = 1 + for i := 0; i < 40; i++ { + v = []any{v, v} + } + return v + } + arrays := func() any { + var v any = 1 + for i := 0; i < 40; i++ { + v = [2]any{v, v} + } + return v + } + for name, build := range map[string]func() any{"cycle": cycle, "shared slices": slices, "shared arrays": arrays} { + c1, c2 := build(), build() + t.Run(name, func(t *testing.T) { + env := map[string]any{ + "c1": func() any { return c1 }, + "c2": func() any { return c2 }, + } + tree, err := parser.Parse(`all([c1()], # != nil) && all([c2()], # != 1)`) + require.NoError(t, err) + config := conf.New(env) + config.ConstExpr("c1") + config.ConstExpr("c2") + _, err = checker.Check(tree, config) + require.NoError(t, err) + + done := make(chan error, 1) + go func() { done <- optimizer.Optimize(&tree.Node, config) }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("optimizer did not finish") + } + }) + } +} diff --git a/optimizer/predicate_combination.go b/optimizer/predicate_combination.go index 65f88e34..19778b36 100644 --- a/optimizer/predicate_combination.go +++ b/optimizer/predicate_combination.go @@ -1,6 +1,9 @@ package optimizer import ( + "math" + "reflect" + . "github.com/expr-lang/expr/ast" "github.com/expr-lang/expr/parser/operator" ) @@ -20,7 +23,7 @@ func (v *predicateCombination) Visit(node *Node) { if left, ok := op.Left.(*BuiltinNode); ok { if combinedOp, ok := combinedOperator(left.Name, op.Operator); ok { if right, ok := op.Right.(*BuiltinNode); ok && right.Name == left.Name { - if left.Arguments[0].Type() == right.Arguments[0].Type() && left.Arguments[0].String() == right.Arguments[0].String() { + if left.Arguments[0].Type() == right.Arguments[0].Type() && sameNode(left.Arguments[0], right.Arguments[0]) { predicate := &PredicateNode{ Node: &BinaryNode{ Operator: combinedOp, @@ -59,3 +62,144 @@ func combinedOperator(fn, op string) (string, bool) { } return "", false } + +// sameNode reports whether a and b are the same expression. It compares the +// trees field by field instead of comparing String() output, because different +// trees can print the same: a BuiltinNode's Map field is not printed, and a +// folded ConstantNode prints 2.0 as 2. +// +// A false result only skips an optimization, so the comparison is +// conservative: anything it cannot compare simply and quickly is different. +func sameNode(a, b Node) bool { + c := comparer{steps: maxCompareSteps} + return c.same(reflect.ValueOf(a), reflect.ValueOf(b), false) +} + +var constantNodeType = reflect.TypeOf(ConstantNode{}) + +// maxCompareSteps bounds the work of one comparison. Constant values can +// refer to themselves or reuse one value in many places, and walking them +// could otherwise take forever. +const maxCompareSteps = 100_000 + +type comparer struct { + steps int +} + +// same compares a and b by type and value. While walking nodes, it skips +// unexported fields: they hold the location and type, which differ between +// two copies of one expression. Inside a constant's value it compares every +// field, and allows only plain data: no pointers, funcs or channels, and only +// map keys that == compares exactly. The exception is the very same pointer, +// map or slice on both sides, which is always the same value. Floats compare by bits, so 0.0 and -0.0 +// differ. +func (c *comparer) same(a, b reflect.Value, constant bool) bool { + c.steps-- + if c.steps < 0 { + return false + } + if !a.IsValid() || !b.IsValid() { + return a.IsValid() == b.IsValid() + } + if a.Type() != b.Type() { + return false + } + if constant { + switch a.Kind() { + case reflect.Ptr, reflect.Map, reflect.Slice: + // The very same data is the same value, even where its parts + // could not be compared. + if a.Pointer() == b.Pointer() && (a.Kind() != reflect.Slice || a.Len() == b.Len()) { + return true + } + } + } + switch a.Kind() { + case reflect.Interface: + if a.IsNil() || b.IsNil() { + return a.IsNil() == b.IsNil() + } + return c.same(a.Elem(), b.Elem(), constant) + case reflect.Ptr: + if constant { + return false + } + if a.IsNil() || b.IsNil() { + return a.IsNil() == b.IsNil() + } + return c.same(a.Elem(), b.Elem(), constant) + case reflect.Struct: + if !constant && a.Type() == constantNodeType { + return c.same(a.FieldByName("Value"), b.FieldByName("Value"), true) + } + for i := 0; i < a.NumField(); i++ { + if !constant && !a.Type().Field(i).IsExported() { + continue + } + if !c.same(a.Field(i), b.Field(i), constant) { + return false + } + } + return true + case reflect.Slice, reflect.Array: + if a.Kind() == reflect.Slice && a.IsNil() != b.IsNil() { + return false + } + if a.Len() != b.Len() { + return false + } + for i := 0; i < a.Len(); i++ { + if !c.same(a.Index(i), b.Index(i), constant) { + return false + } + } + return true + case reflect.Map: + if a.IsNil() != b.IsNil() || a.Len() != b.Len() { + return false + } + iter := a.MapRange() + for iter.Next() { + if !exactKey(iter.Key()) { + return false + } + bv := b.MapIndex(iter.Key()) + if !bv.IsValid() || !c.same(iter.Value(), bv, constant) { + return false + } + } + return true + case reflect.Bool: + return a.Bool() == b.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() == b.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() == b.Uint() + case reflect.Float32, reflect.Float64: + return math.Float64bits(a.Float()) == math.Float64bits(b.Float()) + case reflect.Complex64, reflect.Complex128: + ac, bc := a.Complex(), b.Complex() + return math.Float64bits(real(ac)) == math.Float64bits(real(bc)) && + math.Float64bits(imag(ac)) == math.Float64bits(imag(bc)) + case reflect.String: + return a.String() == b.String() + default: + return false + } +} + +// exactKey reports whether == on a map key means the same value: true for +// bools, integers and strings, false for floats, pointers and anything else. +// With exact keys, the same key in two maps is found by a plain lookup. +func exactKey(key reflect.Value) bool { + switch key.Kind() { + case reflect.Bool, reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return true + case reflect.Interface: + return !key.IsNil() && exactKey(key.Elem()) + default: + return false + } +}