Apply in range optimization only for int type on lhs

This commit is contained in:
Anton Medvedev
2023-08-28 17:36:33 +02:00
parent 9acd95ada5
commit 16403049ac
2 changed files with 22 additions and 3 deletions
+12 -3
View File
@@ -1,6 +1,8 @@
package optimizer
import (
"reflect"
. "github.com/antonmedv/expr/ast"
)
@@ -10,9 +12,16 @@ func (*inRange) Visit(node *Node) {
switch n := (*node).(type) {
case *BinaryNode:
if n.Operator == "in" {
if rng, ok := n.Right.(*BinaryNode); ok && rng.Operator == ".." {
if from, ok := rng.Left.(*IntegerNode); ok {
if to, ok := rng.Right.(*IntegerNode); ok {
t := n.Left.Type()
if t == nil {
return
}
if t.Kind() != reflect.Int {
return
}
if rangeOp, ok := n.Right.(*BinaryNode); ok && rangeOp.Operator == ".." {
if from, ok := rangeOp.Left.(*IntegerNode); ok {
if to, ok := rangeOp.Right.(*IntegerNode); ok {
Patch(node, &BinaryNode{
Operator: "and",
Left: &BinaryNode{
+10
View File
@@ -4,6 +4,7 @@ import (
"strings"
"testing"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/ast"
"github.com/antonmedv/expr/checker"
"github.com/antonmedv/expr/conf"
@@ -77,6 +78,9 @@ func TestOptimize_in_range(t *testing.T) {
tree, err := parser.Parse(`age in 18..31`)
require.NoError(t, err)
config := conf.New(map[string]int{"age": 30})
_, err = checker.Check(tree, config)
err = optimizer.Optimize(&tree.Node, nil)
require.NoError(t, err)
@@ -104,6 +108,12 @@ func TestOptimize_in_range(t *testing.T) {
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}
func TestOptimize_in_range_with_floats(t *testing.T) {
out, err := expr.Eval(`f in 1..3`, map[string]any{"f": 1.5})
require.NoError(t, err)
assert.Equal(t, false, out)
}
func TestOptimize_const_range(t *testing.T) {
tree, err := parser.Parse(`-1..1`)
require.NoError(t, err)