-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstmt_declareVars.go
99 lines (78 loc) · 1.98 KB
/
stmt_declareVars.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
package codegen
import "strings"
type varsDeclarationStmt struct {
vars []*VarValue
}
type VarValue struct {
name string
typeName *nameHelper
}
// DeclareVars creates a new variable declaration block
func (f *File) DeclareVars(vars ...*VarValue) Block {
decl := newVars(vars)
f.append(decl)
return decl
}
// DeclareVars creates a new variable declaration statement
func DeclareVars(vars ...*VarValue) Stmt {
return newVars(vars)
}
// Var creates a new variable with a type name
func Var(varName, typeName string) *VarValue {
return &VarValue{
name: varName,
typeName: newNameHelper("", typeName),
}
}
// QualVar creates a new variable with a type name and its alias
func QualVar(varName, typeAlias, typeName string) *VarValue {
return &VarValue{
name: varName,
typeName: newNameHelper(typeAlias, typeName),
}
}
// Pointer turns the variable type into a pointer
func (v *VarValue) Pointer() *VarValue {
v.SetIsPointer(true)
return v
}
// SetIsPointer sets whether or not a variable is a pointer
func (v *VarValue) SetIsPointer(isPointer bool) *VarValue {
v.typeName.setIsPointer(isPointer)
return v
}
func newVars(vars []*VarValue) *varsDeclarationStmt {
return &varsDeclarationStmt{
vars: vars,
}
}
func (v *varsDeclarationStmt) write(sb *strings.Builder) {
v.writeStmt(sb)
}
func (v *varsDeclarationStmt) writeStmt(sb *strings.Builder) bool {
if len(v.vars) != 0 {
typeMap := make(map[string][]string)
keys := make([]string, 0)
for _, val := range v.vars {
typeName := val.typeName.getTypeName()
if grouping, ok := typeMap[typeName]; ok {
typeMap[typeName] = append(grouping, val.name)
} else {
keys = append(keys, typeName)
typeMap[typeName] = []string{val.name}
}
}
for _, typeName := range keys {
vars := typeMap[typeName]
sb.WriteString("var ")
for i, varName := range vars {
if i != 0 {
sb.WriteByte(',')
}
sb.WriteString(varName)
}
writeNewLineF(sb, " %s", typeName)
}
}
return false
}