-
Notifications
You must be signed in to change notification settings - Fork 1
/
enameg.go
237 lines (195 loc) · 4.95 KB
/
enameg.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package enameg
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"sort"
"strings"
"github.com/moznion/gowrtr/generator"
)
const annotation = "enameg"
var specialCharMap = map[string]string{
"\\": "\\\\",
`"`: `\"`,
}
type constantVal struct {
Name string
CommentVal string
}
type constant struct {
TypeName string
Vals []constantVal
}
// Generate returns packageName and generated functions by paths.
func Generate(paths []string, useFormatter bool) (string, string) {
constMap, err := collectConstants(paths)
if err != nil {
log.Fatal(err)
}
var packageName string
var constants []constant
sort.Strings(paths)
for _, path := range paths {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
if packageName == "" {
packageName = f.Name.Name
}
if packageName != f.Name.Name {
log.Fatal("error: multiple packages")
}
cmap := ast.NewCommentMap(fset, f, f.Comments)
// sort by node pos
nodes := make([]ast.Node, 0, len(cmap))
for n, _ := range cmap {
nodes = append(nodes, n)
}
sort.Slice(nodes, func(i, j int) bool {
lhs := nodes[i]
rhs := nodes[j]
return lhs.Pos() < rhs.Pos()
})
for _, node := range nodes {
commentGroups := cmap[node]
for _, cg := range commentGroups {
if hasAnnotation(cg) {
gen, ok := node.(*ast.GenDecl)
if !ok || len(gen.Specs) <= 0 {
continue
}
spec, ok := gen.Specs[0].(*ast.TypeSpec)
if !ok {
continue
}
c := newConst(spec.Name.Name, constMap)
constants = append(constants, c)
}
}
}
}
if len(constants) == 0 {
return packageName, ""
}
generated, err := generateNameFunc(packageName, constants, useFormatter)
if err != nil {
log.Fatal(err)
}
return packageName, generated
}
func hasAnnotation(cg *ast.CommentGroup) bool {
commentAnnotation := "+" + annotation
for _, c := range cg.List {
comment := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
if strings.HasPrefix(comment, commentAnnotation) {
return true
}
}
return false
}
func collectConstants(paths []string) (map[string][]*ast.ValueSpec, error) {
constMap := make(map[string][]*ast.ValueSpec)
for _, path := range paths {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, err
}
constMap = collectConstantsInFile(constMap, f)
}
return constMap, nil
}
func collectConstantsInFile(constMap map[string][]*ast.ValueSpec, f *ast.File) map[string][]*ast.ValueSpec {
for _, dec := range f.Decls {
gen, ok := dec.(*ast.GenDecl)
if !ok {
continue
}
if gen.Tok != token.CONST {
continue
}
for _, spec := range gen.Specs {
val, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
valType, ok := val.Type.(*ast.Ident)
if !ok {
continue
}
typeName := valType.Name
if constMap[typeName] == nil {
constMap[typeName] = []*ast.ValueSpec{}
}
constMap[typeName] = append(constMap[typeName], val)
}
}
return constMap
}
func newCommentVal(comment string) string {
comment = strings.TrimSpace(strings.TrimLeft(comment, "//"))
comment = strings.Fields(comment)[0]
specialDelimiters := []string{".", "。"}
for _, del := range specialDelimiters {
comment = strings.Split(comment, del)[0]
}
for c, rep := range specialCharMap {
comment = strings.Replace(comment, c, rep, -1)
}
return comment
}
func newConst(typeName string, constMap map[string][]*ast.ValueSpec) constant {
nodes := constMap[typeName]
vals := make([]constantVal, 0, len(nodes))
for _, n := range nodes {
if n.Comment == nil || len(n.Comment.List) == 0 {
continue
}
vals = append(vals, constantVal{
Name: n.Names[0].Name,
CommentVal: newCommentVal(n.Comment.List[0].Text),
})
}
return constant{
TypeName: typeName,
Vals: vals,
}
}
func generateNameFunc(packageName string, consts []constant, useFormatter bool) (string, error) {
g := generator.NewRoot(
generator.NewPackage(packageName),
generator.NewNewline(),
generator.NewImport("fmt"),
generator.NewNewline(),
)
for _, c := range consts {
caseStatements := make([]*generator.Case, 0, len(c.Vals))
for _, v := range c.Vals {
caseStatements = append(caseStatements, generator.NewCase(v.Name, generator.NewReturnStatement(fmt.Sprintf(`"%s"`, v.CommentVal))))
}
g = g.AddStatements(
generator.NewComment(fmt.Sprintf(" Name returns the %s Name.", c.TypeName)),
generator.NewFunc(
generator.NewFuncReceiver("src", c.TypeName),
generator.NewFuncSignature("Name").AddReturnTypes("string"),
).AddStatements(
generator.NewSwitch("src").
AddCase(caseStatements...).
Default(generator.NewDefaultCase(generator.NewReturnStatement(`fmt.Sprintf("%v", src)`))),
),
generator.NewNewline(),
)
}
if useFormatter {
g = g.Gofmt("-s").Goimports()
}
generated, err := g.Generate(0)
if err != nil {
return "", err
}
return generated, nil
}