-
Notifications
You must be signed in to change notification settings - Fork 6
/
equals.go
96 lines (80 loc) · 2.28 KB
/
equals.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package ast
import (
"fmt"
"github.com/NicoNex/tau/internal/code"
"github.com/NicoNex/tau/internal/compiler"
"github.com/NicoNex/tau/internal/obj"
)
type Equals struct {
l Node
r Node
pos int
}
func NewEquals(l, r Node, pos int) Node {
return Equals{
l: l,
r: r,
pos: pos,
}
}
func (e Equals) Eval() (obj.Object, error) {
left, err := e.l.Eval()
if err != nil {
return obj.NullObj, err
}
right, err := e.r.Eval()
if err != nil {
return obj.NullObj, err
}
if !obj.AssertTypes(left, obj.IntType, obj.FloatType, obj.StringType, obj.BoolType, obj.NullType) {
return obj.NullObj, fmt.Errorf("unsupported operator '==' for type %v", left.Type())
}
if !obj.AssertTypes(right, obj.IntType, obj.FloatType, obj.StringType, obj.BoolType, obj.NullType) {
return obj.NullObj, fmt.Errorf("unsupported operator '==' for type %v", right.Type())
}
switch {
case obj.AssertTypes(left, obj.BoolType, obj.NullType) || obj.AssertTypes(right, obj.BoolType, obj.NullType):
return obj.ParseBool(left == right), nil
case obj.AssertTypes(left, obj.StringType) && obj.AssertTypes(right, obj.StringType):
l := left.(obj.String)
r := right.(obj.String)
return obj.ParseBool(l == r), nil
case obj.AssertTypes(left, obj.IntType) && obj.AssertTypes(right, obj.IntType):
l := left.(obj.Integer)
r := right.(obj.Integer)
return obj.ParseBool(l == r), nil
case obj.AssertTypes(left, obj.FloatType, obj.IntType) && obj.AssertTypes(right, obj.FloatType, obj.IntType):
left, right = obj.ToFloat(left, right)
l := left.(obj.Float)
r := right.(obj.Float)
return obj.ParseBool(l == r), nil
default:
return obj.False, nil
}
}
func (e Equals) String() string {
return fmt.Sprintf("(%v == %v)", e.l, e.r)
}
func (e Equals) Compile(c *compiler.Compiler) (position int, err error) {
if e.IsConstExpression() {
o, err := e.Eval()
if err != nil {
return 0, c.NewError(e.pos, err.Error())
}
position = c.Emit(code.OpConstant, c.AddConstant(o))
c.Bookmark(e.pos)
return position, err
}
if position, err = e.l.Compile(c); err != nil {
return
}
if position, err = e.r.Compile(c); err != nil {
return
}
position = c.Emit(code.OpEqual)
c.Bookmark(e.pos)
return
}
func (e Equals) IsConstExpression() bool {
return e.l.IsConstExpression() && e.r.IsConstExpression()
}