mirror of
https://github.com/hanzoai/expr.git
synced 2026-09-24 16:58:58 +00:00
Apply in range optimization only for int type on lhs
This commit is contained in:
+12
-3
@@ -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{
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user