-
Notifications
You must be signed in to change notification settings - Fork 6
/
ifelse.go
73 lines (60 loc) · 1.39 KB
/
ifelse.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 (
"errors"
"fmt"
"github.com/NicoNex/tau/internal/code"
"github.com/NicoNex/tau/internal/compiler"
"github.com/NicoNex/tau/internal/obj"
)
type IfExpr struct {
cond Node
body Node
altern Node
pos int
}
func NewIfExpr(cond, body, alt Node, pos int) Node {
return IfExpr{
cond: cond,
body: body,
altern: alt,
pos: pos,
}
}
func (i IfExpr) Eval() (obj.Object, error) {
return obj.NullObj, errors.New("ast.IfExpr: not a constant expression")
}
func (i IfExpr) String() string {
if i.altern != nil {
return fmt.Sprintf("if %v { %v } else { %v }", i.cond, i.body, i.altern)
}
return fmt.Sprintf("if %v { %v }", i.cond, i.body)
}
func (i IfExpr) Compile(c *compiler.Compiler) (position int, err error) {
if position, err = i.cond.Compile(c); err != nil {
return
}
jumpNotTruthyPos := c.Emit(code.OpJumpNotTruthy, compiler.GenericPlaceholder)
if position, err = i.body.Compile(c); err != nil {
return
}
if c.LastIs(code.OpPop) {
c.RemoveLast()
}
jumpPos := c.Emit(code.OpJump, compiler.GenericPlaceholder)
c.ReplaceOperand(jumpNotTruthyPos, c.Pos())
if i.altern == nil {
c.Emit(code.OpNull)
} else {
if position, err = i.altern.Compile(c); err != nil {
return
}
if c.LastIs(code.OpPop) {
c.RemoveLast()
}
}
c.ReplaceOperand(jumpPos, c.Pos())
return c.Pos(), nil
}
func (i IfExpr) IsConstExpression() bool {
return false
}