@@ -2,6 +2,7 @@ package optimizer
2
2
3
3
import (
4
4
"math"
5
+ "reflect"
5
6
6
7
. "github.com/antonmedv/expr/ast"
7
8
)
@@ -16,17 +17,24 @@ func (fold *fold) Exit(node *Node) {
16
17
fold .applied = true
17
18
Patch (node , newNode )
18
19
}
20
+ // for IntegerNode the type may have been changed from int->float
21
+ // preserve this information by setting the type after the Patch
22
+ patchWithType := func (newNode Node , leafType reflect.Type ) {
23
+ fold .applied = true
24
+ Patch (node , newNode )
25
+ newNode .SetType (leafType )
26
+ }
19
27
20
28
switch n := (* node ).(type ) {
21
29
case * UnaryNode :
22
30
switch n .Operator {
23
31
case "-" :
24
32
if i , ok := n .Node .(* IntegerNode ); ok {
25
- patch (& IntegerNode {Value : - i .Value })
33
+ patchWithType (& IntegerNode {Value : - i .Value }, n . Node . Type () )
26
34
}
27
35
case "+" :
28
36
if i , ok := n .Node .(* IntegerNode ); ok {
29
- patch (& IntegerNode {Value : i .Value })
37
+ patchWithType (& IntegerNode {Value : i .Value }, n . Node . Type () )
30
38
}
31
39
}
32
40
@@ -35,7 +43,7 @@ func (fold *fold) Exit(node *Node) {
35
43
case "+" :
36
44
if a , ok := n .Left .(* IntegerNode ); ok {
37
45
if b , ok := n .Right .(* IntegerNode ); ok {
38
- patch (& IntegerNode {Value : a .Value + b .Value })
46
+ patchWithType (& IntegerNode {Value : a .Value + b .Value }, a . Type () )
39
47
}
40
48
}
41
49
if a , ok := n .Left .(* StringNode ); ok {
@@ -46,19 +54,19 @@ func (fold *fold) Exit(node *Node) {
46
54
case "-" :
47
55
if a , ok := n .Left .(* IntegerNode ); ok {
48
56
if b , ok := n .Right .(* IntegerNode ); ok {
49
- patch (& IntegerNode {Value : a .Value - b .Value })
57
+ patchWithType (& IntegerNode {Value : a .Value - b .Value }, a . Type () )
50
58
}
51
59
}
52
60
case "*" :
53
61
if a , ok := n .Left .(* IntegerNode ); ok {
54
62
if b , ok := n .Right .(* IntegerNode ); ok {
55
- patch (& IntegerNode {Value : a .Value * b .Value })
63
+ patchWithType (& IntegerNode {Value : a .Value * b .Value }, a . Type () )
56
64
}
57
65
}
58
66
case "/" :
59
67
if a , ok := n .Left .(* IntegerNode ); ok {
60
68
if b , ok := n .Right .(* IntegerNode ); ok {
61
- patch (& IntegerNode {Value : a .Value / b .Value })
69
+ patchWithType (& IntegerNode {Value : a .Value / b .Value }, a . Type () )
62
70
}
63
71
}
64
72
case "%" :
0 commit comments