Skip to content

Commit e49f6dd

Browse files
committed
Make optimized program unmarshalable
1 parent 20f453e commit e49f6dd

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

expr_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ func ExampleEval_marshal() {
236236
"bar": 2,
237237
}
238238

239-
program, err := expr.Compile("foo + bar", expr.Env(env))
239+
program, err := expr.Compile("(foo + bar) in [1, 2, 3]", expr.Env(env))
240240
if err != nil {
241241
fmt.Printf("%v", err)
242242
return
@@ -263,7 +263,7 @@ func ExampleEval_marshal() {
263263

264264
fmt.Printf("%v", output)
265265

266-
// Output: 3
266+
// Output: true
267267
}
268268

269269
func TestExpr(t *testing.T) {

optimizer/optimizer.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package optimizer
22

33
import (
4+
"encoding/json"
45
. "github.com/antonmedv/expr/ast"
56
"math"
67
)
@@ -27,6 +28,16 @@ func Optimize(node *Node) {
2728
Walk(node, &constRange{})
2829
}
2930

31+
type Map map[int]struct{}
32+
33+
func (m Map) MarshalJSON() ([]byte, error) {
34+
array := make([]int, 0, len(m))
35+
for key := range m {
36+
array = append(array, key)
37+
}
38+
return json.Marshal(array)
39+
}
40+
3041
func (*inArray) Enter(node *Node) {}
3142
func (*inArray) Exit(node *Node) {
3243
switch n := (*node).(type) {
@@ -41,9 +52,9 @@ func (*inArray) Exit(node *Node) {
4152
}
4253
}
4354
{
44-
value := make(map[int]bool)
55+
value := make(Map)
4556
for _, a := range array.Nodes {
46-
value[a.(*IntegerNode).Value] = true
57+
value[a.(*IntegerNode).Value] = struct{}{}
4758
}
4859
patch(node, &BinaryNode{
4960
Operator: n.Operator,
@@ -59,9 +70,9 @@ func (*inArray) Exit(node *Node) {
5970
}
6071
}
6172
{
62-
value := make(map[string]bool)
73+
value := make(map[string]struct{})
6374
for _, a := range array.Nodes {
64-
value[a.(*StringNode).Value] = true
75+
value[a.(*StringNode).Value] = struct{}{}
6576
}
6677
patch(node, &BinaryNode{
6778
Operator: n.Operator,

optimizer/optimizer_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ func TestOptimize_in_array(t *testing.T) {
3333
expected := &ast.BinaryNode{
3434
Operator: "in",
3535
Left: &ast.IdentifierNode{Value: "v"},
36-
Right: &ast.ConstantNode{Value: map[int]bool{1: true, 2: true, 3: true}},
36+
Right: &ast.ConstantNode{Value: optimizer.Map{1: {}, 2: {}, 3: {}}},
3737
}
3838

3939
assert.Equal(t, litter.Sdump(expected), litter.Sdump(tree.Node))

0 commit comments

Comments
 (0)