-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstmt_if.go
79 lines (63 loc) · 1.6 KB
/
stmt_if.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
package codegen
import "strings"
type ifStmt struct {
declaration *declarationStmt
value Value
stmts []Stmt
prev *ifStmt
isFinal bool
}
// Creates a new if statement
func If(val Value) *ifStmt {
return newIf(nil, nil, val)
}
// Creates a new if statement with variable declaration
func IfDecl(declare *declarationStmt, val Value) *ifStmt {
return newIf(nil, declare, val)
}
// Appends a new else-if statement to the existing if statement
func (i *ifStmt) ElseIf(val Value) *ifStmt {
return newIf(i, nil, val)
}
// Appends a new else-if statement with variable declaration to the existing if statement
func (i *ifStmt) ElseIfDecl(declare *declarationStmt, val Value) *ifStmt {
return newIf(i, declare, val)
}
// Appends the final else statement to the existing if statement
func (i *ifStmt) Else(stmts ...Stmt) Stmt {
stmt := newIf(i, nil, nil)
stmt.stmts = stmts
return stmt
}
// Appends a block statement to the existing if statement
func (i *ifStmt) Block(stmts ...Stmt) *ifStmt {
i.stmts = stmts
return i
}
func newIf(prev *ifStmt, declare *declarationStmt, val Value) *ifStmt {
if prev != nil {
prev.isFinal = false
}
return &ifStmt{
declaration: declare,
value: val,
prev: prev,
isFinal: true,
}
}
func (i *ifStmt) writeStmt(sb *strings.Builder) bool {
if i.prev != nil {
i.prev.writeStmt(sb)
sb.WriteString(" else ")
}
if i.value != nil {
sb.WriteString("if ")
if i.declaration != nil {
i.declaration.writeStmt(sb)
sb.WriteByte(';')
}
i.value.writeValue(sb)
}
writeStmtsBlock(sb, i.stmts, i.isFinal)
return !i.isFinal
}