Skip to content

Commit e81f517

Browse files
committed
Apply in range optimization only for int type on lhs
1 parent 2dc1c7d commit e81f517

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

optimizer/in_range.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package optimizer
22

33
import (
4+
"reflect"
5+
46
. "github.com/antonmedv/expr/ast"
57
)
68

@@ -10,9 +12,16 @@ func (*inRange) Visit(node *Node) {
1012
switch n := (*node).(type) {
1113
case *BinaryNode:
1214
if n.Operator == "in" {
13-
if rng, ok := n.Right.(*BinaryNode); ok && rng.Operator == ".." {
14-
if from, ok := rng.Left.(*IntegerNode); ok {
15-
if to, ok := rng.Right.(*IntegerNode); ok {
15+
t := n.Left.Type()
16+
if t == nil {
17+
return
18+
}
19+
if t.Kind() != reflect.Int {
20+
return
21+
}
22+
if rangeOp, ok := n.Right.(*BinaryNode); ok && rangeOp.Operator == ".." {
23+
if from, ok := rangeOp.Left.(*IntegerNode); ok {
24+
if to, ok := rangeOp.Right.(*IntegerNode); ok {
1625
Patch(node, &BinaryNode{
1726
Operator: "and",
1827
Left: &BinaryNode{

optimizer/optimizer_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"strings"
55
"testing"
66

7+
"github.com/antonmedv/expr"
78
"github.com/antonmedv/expr/ast"
89
"github.com/antonmedv/expr/checker"
910
"github.com/antonmedv/expr/conf"
@@ -77,6 +78,9 @@ func TestOptimize_in_range(t *testing.T) {
7778
tree, err := parser.Parse(`age in 18..31`)
7879
require.NoError(t, err)
7980

81+
config := conf.New(map[string]int{"age": 30})
82+
_, err = checker.Check(tree, config)
83+
8084
err = optimizer.Optimize(&tree.Node, nil)
8185
require.NoError(t, err)
8286

@@ -104,6 +108,12 @@ func TestOptimize_in_range(t *testing.T) {
104108
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
105109
}
106110

111+
func TestOptimize_in_range_with_floats(t *testing.T) {
112+
out, err := expr.Eval(`f in 1..3`, map[string]any{"f": 1.5})
113+
require.NoError(t, err)
114+
assert.Equal(t, false, out)
115+
}
116+
107117
func TestOptimize_const_range(t *testing.T) {
108118
tree, err := parser.Parse(`-1..1`)
109119
require.NoError(t, err)

0 commit comments

Comments
 (0)