-
Notifications
You must be signed in to change notification settings - Fork 6
/
divide.go
76 lines (63 loc) · 1.52 KB
/
divide.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
package ast
import (
"fmt"
"github.com/NicoNex/tau/internal/code"
"github.com/NicoNex/tau/internal/compiler"
"github.com/NicoNex/tau/internal/obj"
)
type Divide struct {
l Node
r Node
pos int
}
func NewDivide(l, r Node, pos int) Node {
return Divide{
l: l,
r: r,
pos: pos,
}
}
func (d Divide) Eval() (obj.Object, error) {
left, err := d.l.Eval()
if err != nil {
return obj.NullObj, err
}
right, err := d.r.Eval()
if err != nil {
return obj.NullObj, err
}
if !obj.AssertTypes(left, obj.IntType, obj.FloatType) {
return obj.NullObj, fmt.Errorf("unsupported operator '/' for type %v", left.Type())
}
if !obj.AssertTypes(right, obj.IntType, obj.FloatType) {
return obj.NullObj, fmt.Errorf("unsupported operator '/' for type %v", right.Type())
}
l, r := obj.ToFloat(left, right)
return obj.NewFloat(float64(l.(obj.Float)) / float64(r.(obj.Float))), nil
}
func (d Divide) String() string {
return fmt.Sprintf("(%v / %v)", d.l, d.r)
}
func (d Divide) Compile(c *compiler.Compiler) (position int, err error) {
if d.IsConstExpression() {
o, err := d.Eval()
if err != nil {
return 0, c.NewError(d.pos, err.Error())
}
position = c.Emit(code.OpConstant, c.AddConstant(o))
c.Bookmark(d.pos)
return position, err
}
if position, err = d.l.Compile(c); err != nil {
return
}
if position, err = d.r.Compile(c); err != nil {
return
}
position = c.Emit(code.OpDiv)
c.Bookmark(d.pos)
return
}
func (d Divide) IsConstExpression() bool {
return d.l.IsConstExpression() && d.r.IsConstExpression()
}