-
Notifications
You must be signed in to change notification settings - Fork 6
/
assign.go
76 lines (63 loc) · 1.4 KB
/
assign.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 (
"errors"
"fmt"
"github.com/NicoNex/tau/internal/code"
"github.com/NicoNex/tau/internal/compiler"
"github.com/NicoNex/tau/internal/obj"
)
type Assign struct {
l Node
r Node
pos int
}
type Definable interface {
CompileDefine(c *compiler.Compiler) (position int, err error)
}
func NewAssign(l, r Node, pos int) Node {
return Assign{
l: l,
r: r,
pos: pos,
}
}
func (a Assign) Eval() (obj.Object, error) {
return obj.NullObj, errors.New("ast.Assign: not a constant expression")
}
func (a Assign) String() string {
return fmt.Sprintf("(%v = %v)", a.l, a.r)
}
func (a Assign) Compile(c *compiler.Compiler) (position int, err error) {
defer c.Bookmark(position)
switch left := a.l.(type) {
case Identifier:
symbol := c.Define(left.String())
if position, err = a.r.Compile(c); err != nil {
return
}
if symbol.Scope == compiler.GlobalScope {
position = c.Emit(code.OpSetGlobal, symbol.Index)
c.Bookmark(a.pos)
return
} else {
position = c.Emit(code.OpSetLocal, symbol.Index)
c.Bookmark(a.pos)
return
}
case Definable:
if position, err = left.CompileDefine(c); err != nil {
return
}
if position, err = a.r.Compile(c); err != nil {
return
}
position = c.Emit(code.OpDefine)
c.Bookmark(a.pos)
return
default:
return 0, fmt.Errorf("cannot assign to literal")
}
}
func (a Assign) IsConstExpression() bool {
return false
}