/
if.go
118 lines (101 loc) · 2.11 KB
/
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package ast
import (
"bytes"
"fmt"
"strings"
)
func NewIf(p Node, e Expression, b *Block, elsa Node) (If, error) {
fi := If{
PreCondition: p,
Block: b,
Expression: e,
Clause: elsa,
}
return fi, nil
}
type If struct {
PreCondition Node
Expression Expression
Clause Node
Block *Block
Meta Meta
}
func (i If) String() string {
bb := &bytes.Buffer{}
bb.WriteString("if ")
if i.PreCondition != nil {
bb.WriteString(strings.TrimSpace(i.PreCondition.String()) + "; ")
}
bb.WriteString(strings.TrimSpace(i.Expression.String()))
bb.WriteString(" ")
if i.Block != nil {
bb.WriteString(i.Block.String())
}
if i.Clause != nil {
bb.WriteString(i.Clause.String())
}
return bb.String()
}
func (i If) GoString() string {
bb := &bytes.Buffer{}
bb.WriteString("if ")
if i.PreCondition != nil {
bb.WriteString(strings.TrimSpace(fmt.Sprintf("%#v;", i.PreCondition)))
}
bb.WriteString(strings.TrimSpace(fmt.Sprintf("%#v", i.Expression)))
bb.WriteString(" ")
if i.Block != nil {
bb.WriteString(fmt.Sprintf("%#v", i.Block))
}
if i.Clause != nil {
bb.WriteString(fmt.Sprintf("%#v", i.Clause))
}
return bb.String()
}
func (i If) Format(st fmt.State, verb rune) {
format(i, st, verb)
}
func (i If) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"PreCondition": i.PreCondition,
"Expression": i.Expression,
"Clause": i.Clause,
"Block": i.Block,
"Meta": i.Meta,
}
return toJSON(i, m)
}
func (i If) Bool(c *Context) (bool, error) {
if epc, ok := i.PreCondition.(Expression); ok {
b, err := epc.Bool(c)
if err != nil {
return false, err
}
if !b {
return false, nil
}
}
return i.Expression.Bool(c)
}
func (i If) Exec(c *Context) (interface{}, error) {
if i.Block == nil {
return nil, i.Meta.Errorf("if statement missing block")
}
if i.PreCondition != nil {
_, err := exec(c, i.PreCondition)
if err != nil {
return nil, err
}
}
b, err := i.Bool(c)
if err != nil {
return nil, err
}
if b {
return i.Block.Exec(c)
}
if ex, ok := i.Clause.(Execable); ok {
return ex.Exec(c)
}
return nil, nil
}