/
switch.go
77 lines (66 loc) · 2 KB
/
switch.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
package generator
import "fmt"
// Switch represents a code generator for `switch` statement.
// See also: https://tour.golang.org/flowcontrol/9
type Switch struct {
condition string
caseStatements []*Case
defaultStatement *DefaultCase
}
// NewSwitch returns a new `Switch`.
func NewSwitch(condition string) *Switch {
return &Switch{
condition: condition,
}
}
// AddCase adds `case` statements to `Switch`. This does *not* set, just add.
// This method returns a *new* `Switch`; it means this method acts as immutable.
func (s *Switch) AddCase(statements ...*Case) *Switch {
return &Switch{
condition: s.condition,
caseStatements: append(s.caseStatements, statements...),
defaultStatement: s.defaultStatement,
}
}
// Case sets `case` statements to `Switch`. This does *not* add, just set.
// This method returns a *new* `Switch`; it means this method acts as immutable.
func (s *Switch) Case(statements ...*Case) *Switch {
return &Switch{
condition: s.condition,
caseStatements: statements,
defaultStatement: s.defaultStatement,
}
}
// Default sets a `default` statement to `Switch`.
// This method returns a *new* `Switch`; it means this method acts as immutable.
func (s *Switch) Default(statement *DefaultCase) *Switch {
return &Switch{
condition: s.condition,
caseStatements: s.caseStatements,
defaultStatement: statement,
}
}
// Generate generates `switch` statement as golang code.
func (s *Switch) Generate(indentLevel int) (string, error) {
indent := buildIndent(indentLevel)
stmt := fmt.Sprintf("%sswitch %s {\n", indent, s.condition)
for _, statement := range s.caseStatements {
if statement == nil {
continue
}
gen, err := statement.Generate(indentLevel)
if err != nil {
return "", err
}
stmt += gen
}
if defaultStatement := s.defaultStatement; defaultStatement != nil {
gen, err := defaultStatement.Generate(indentLevel)
if err != nil {
return "", err
}
stmt += gen
}
stmt += fmt.Sprintf("%s}\n", indent)
return stmt, nil
}