forked from XSAM/optionGen
-
Notifications
You must be signed in to change notification settings - Fork 4
/
parse.go
364 lines (338 loc) · 9.77 KB
/
parse.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package optiongen
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"runtime"
"myitcv.io/gogenerate"
)
func paniwWith(format string, v ...interface{}) {
info := fmt.Sprintf(format, v...)
panic(info)
}
var fset = token.NewFileSet()
func inspectDir(wd string) (envFile string, lineNo int) {
envFile, ok := os.LookupEnv(gogenerate.GOFILE)
if !ok {
paniwWith("env not correct; missing %v", gogenerate.GOFILE)
}
lineStr, ok := os.LookupEnv(gogenerate.GOLINE)
if !ok {
paniwWith("env not correct; missing %v", gogenerate.GOLINE)
}
lineNo, err := strconv.Atoi(lineStr)
if err != nil {
paniwWith("env not correct; env %v convert to int failed. %s", gogenerate.GOLINE, err)
}
tags := make(map[string]bool)
goos := os.Getenv("GOOS")
if goos == "" {
goos = runtime.GOOS
}
tags[goos] = true
goarch := os.Getenv("GOARCH")
if goarch == "" {
goarch = runtime.GOARCH
}
tags[goarch] = true
dirFiles, err := gogenerate.FilesContainingCmd(wd, OptionGen, tags)
if err != nil {
paniwWith("could not determine if we are the first file: %v", err)
}
if dirFiles == nil {
paniwWith("cannot find any files containing the %v directive", OptionGen)
}
return
}
var gofmtBuf bytes.Buffer
// gofmt returns the gofmt-formatted string for an AST node.
func gofmt(n interface{}) string {
gofmtBuf.Reset()
err := printer.Fprint(&gofmtBuf, fset, n)
if err != nil {
return "<" + err.Error() + ">"
}
return gofmtBuf.String()
}
func printLog(format string, a ...interface{}) {
if AtomicConfig().GetDebug() {
fmt.Println(fmt.Sprintf(format, a...))
}
}
var commentReg = regexp.MustCompile(`@MethodComment\(([^)]+)\)`)
func parseComment(comment string) (string, []string) {
if len(comment) == 0 {
return "", nil
}
out := commentReg.FindAllStringSubmatch(comment, -1)
if len(out) == 0 {
return comment, nil
}
var mc []string
for _, v := range out {
comment = strings.ReplaceAll(comment, v[0], "")
if len(v[1]) > 0 {
mc = append(mc, fmt.Sprintf("// %s", v[1]))
}
}
if strings.TrimSpace(comment) == "//" {
return "", mc
}
return comment, mc
}
func ParseDir(dir string) {
fileName, lineNo := inspectDir(dir)
DstName := ""
declareName := ""
file, err := parser.ParseFile(fset, fileName, nil, parser.ParseComments)
if err != nil {
paniwWith("unable to parse %v: %v", fileName, err)
}
var importPath []string
for _, imp := range file.Imports {
importPath = append(importPath, imp.Path.Value)
}
comments := file.Comments
var classComments []string
var classOptionFields []optionField
var lastMaxBodyPos token.Pos
for _, d := range file.Decls {
switch d := d.(type) {
default:
if lastMaxBodyPos < d.End() {
lastMaxBodyPos = d.End()
}
case *ast.FuncDecl:
if d.Recv != nil {
continue
}
// name check valid
if !strings.HasSuffix(d.Name.Name, optionDeclarationSuffix) {
if lastMaxBodyPos < d.End() {
lastMaxBodyPos = d.End()
}
continue
}
// command line check valid
p := fset.Position(d.Pos())
if p.Line != lineNo+1 {
if lastMaxBodyPos < d.End() {
lastMaxBodyPos = d.End()
}
continue
}
// Only allow return expr in class option declaration function
if len(d.Body.List) != 1 {
continue
}
// Only allow return one value
stmt, ok := d.Body.List[0].(*ast.ReturnStmt)
if !ok {
continue
}
if len(stmt.Results) != 1 {
continue
}
var pos token.Pos
if d.Doc != nil {
pos = d.Doc.Pos()
}
declareName = d.Name.Name
declarationClassName := strings.TrimPrefix(strings.TrimSuffix(d.Name.Name, optionDeclarationSuffix), "_")
for k, v := range comments {
if v.Pos() == pos {
for _, v1 := range comments[:k] {
if v1.Pos() < lastMaxBodyPos {
continue
}
for _, v2 := range v1.List {
classComments = append(classComments, v2.Text)
}
}
comments = comments[k+1:]
break
}
}
result := stmt.Results[0].(*ast.CompositeLit)
optionFields := make([]optionField, len(result.Elts))
for i, elt := range result.Elts {
switch elt := elt.(type) {
case *ast.KeyValueExpr:
// Option Field Name
key := elt.Key.(*ast.BasicLit)
optionFields[i].Name = key.Value
for _, v := range comments {
if v.Pos() <= elt.Pos() {
comments = comments[1:]
for _, vv := range v.List {
fc, mc := parseComment(vv.Text)
if len(fc) > 0 {
optionFields[i].LastRowComments = append(optionFields[i].LastRowComments, fc)
}
if len(mc) > 0 {
optionFields[i].MethodComments = append(optionFields[i].MethodComments, mc...)
}
}
continue
}
eltP := fset.Position(elt.Pos())
vP := fset.Position(v.Pos())
if eltP.Line == vP.Line {
comments = comments[1:]
for _, vv := range v.List {
fc, mc := parseComment(vv.Text)
if len(fc) > 0 {
optionFields[i].SameRowComment = fc
}
if len(mc) > 0 {
optionFields[i].MethodComments = append(optionFields[i].MethodComments, mc...)
}
break
}
continue
}
break
}
switch value := elt.Value.(type) {
case *ast.FuncLit:
printLog("%s type: %s", optionFields[i].Name, "ast.FuncLit")
optionFields[i].FieldType = FieldTypeFunc
buf := bytes.NewBufferString("")
// Option func Type
_ = printer.Fprint(buf, fset, value.Type)
optionFields[i].Type = buf.String()
// Option func Body
buf.Reset()
_ = printer.Fprint(buf, fset, value.Body)
optionFields[i].Body = buf.String()
case *ast.CallExpr:
printLog("%s type: %s", optionFields[i].Name, "ast.CallExpr")
optionFields[i].FieldType = FieldTypeVar
buf := bytes.NewBufferString("")
// Option Variable Type
_ = printer.Fprint(buf, fset, value.Fun)
optionFields[i].Type = buf.String()
// Option Variable Value
buf.Reset()
_ = printer.Fprint(buf, fset, value.Args[0])
optionFields[i].Body = buf.String()
case *ast.BasicLit: // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
printLog("%s type: %s", optionFields[i].Name, "ast.BasicLit")
optionFields[i].FieldType = FieldTypeVar
switch value.Kind {
case token.INT:
optionFields[i].Type = "int"
optionFields[i].Body = value.Value
case token.FLOAT:
optionFields[i].Type = "float"
optionFields[i].Body = value.Value
case token.CHAR:
optionFields[i].Type = "byte"
optionFields[i].Body = value.Value
case token.STRING:
optionFields[i].Type = "string"
optionFields[i].Body = value.Value
}
case *ast.CompositeLit:
printLog("%s type: %s", optionFields[i].Name, "ast.CompositeLit")
optionFields[i].FieldType = FieldTypeVar
optionFields[i].Type = gofmt(value.Type)
buf := bytes.NewBufferString("")
buf.Reset()
var data []string
for _, p := range value.Elts {
switch t := p.(type) {
case *ast.BasicLit:
data = append(data, t.Value)
case *ast.Ident:
if t.Name == "false" || t.Name == "true" {
data = append(data, t.Name)
}
case *ast.KeyValueExpr:
blKey, okKey := t.Key.(*ast.BasicLit)
blVal, okVal := t.Value.(*ast.BasicLit)
if !okKey || !okVal {
paniwWith("optionGen %s got type %s support basic types only", optionFields[i].Name, optionFields[i].Type)
}
data = append(data, fmt.Sprintf("%s:%s", blKey.Value, blVal.Value))
default:
paniwWith("optionGen %s got type %s support basic types only", optionFields[i].Name, optionFields[i].Type)
}
}
val := "make(" + optionFields[i].Type + ",0)"
if AtomicConfig().GetEmptyCompositeNil() {
val = "nil"
}
if len(data) > 0 {
val = fmt.Sprintf("%s{%s}", optionFields[i].Type, strings.Join(data, ","))
}
optionFields[i].Body = val
case *ast.Ident:
if value.Obj == nil {
printLog("%s type: %s", optionFields[i].Name, "ast.Ident")
} else {
printLog("%s type: %s Object:%v Type:%v", optionFields[i].Name, "ast.Ident", value.Obj, value.Obj.Type)
}
optionFields[i].FieldType = FieldTypeVar
if value.Name == "false" || value.Name == "true" {
optionFields[i].Type = "bool"
optionFields[i].Body = value.Name
break
}
if value.Name == "nil" {
optionFields[i].Type = "interface{}"
optionFields[i].Body = value.Name
break
}
paniwWith("optionGen %s got type ast.Ident, please give some type hint like: string(DefaultValue) ", optionFields[i].Name)
default:
paniwWith("optionGen %s got type %s support basic types only", optionFields[i].Name, optionFields[i].Type)
}
}
}
classOptionFields = optionFields
DstName = declarationClassName
}
// find dst file line specify name
if DstName != "" {
break
}
}
if DstName == "" {
paniwWith("specify file %s line %d cannot find generate declare", fileName, lineNo+1)
}
info := fmt.Sprintf("%s:%d [%s]", filepath.Join(dir, fileName), lineNo, declareName)
fmt.Printf("🚀 %s running => %s ...\n", OptionGen, info)
defer func() {
if reason := recover(); reason != nil {
err = fmt.Errorf("%v", reason)
}
if err != nil {
fmt.Printf("💀 got error when process:%s , err:%s\n", info, err.Error())
}
}()
pkgName := file.Name.Name
g := fileOptionGen{
FilePath: filepath.Join(dir, fileName),
NameDeclare: declareName,
FileName: strings.ToLower(DstName),
PkgName: pkgName,
ImportPath: importPath,
ClassName: DstName,
ClassOptionFields: classOptionFields,
Comments: classComments,
}
err = g.ParseAnnotations()
if err != nil {
panic(err)
}
g.gen()
}