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