-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
456 lines (359 loc) · 9.05 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package pkgdmp
import (
"fmt"
"go/ast"
"go/doc"
"go/token"
"strings"
)
var typeNames = map[token.Token]string{
token.INT: "int",
token.FLOAT: "float64",
token.IMAG: "complex128",
token.CHAR: "rune",
token.STRING: "string",
}
// ParserOption configures a [Parser].
type ParserOption interface {
// String should return a string representation of the option.
//
// This method is mainly intended for testing purposes.
String() string
apply(*Parser) error
}
// Parser parses go packages to simple structs.
type Parser struct {
filters []SymbolFilter
fullDocs bool
noDocs bool
noTags bool
}
// NewParser returns a parser configured with options.
func NewParser(opts ...ParserOption) (*Parser, error) {
p := &Parser{}
for _, opt := range opts {
if err := opt.apply(p); err != nil {
return nil, fmt.Errorf("applying parser option: %w", err)
}
}
return p, nil
}
// Package parses dPkg to a simplified [Package].
func (p *Parser) Package(dPkg *doc.Package) (*Package, error) {
pkg := &Package{
Name: dPkg.Name,
Doc: p.mkDoc(dPkg.Doc),
}
if err := p.parseConsts(pkg, dPkg.Consts); err != nil {
return nil, fmt.Errorf("parsing constants: %w", err)
}
if err := p.parseTypes(pkg, dPkg.Types); err != nil {
return nil, fmt.Errorf("parsing types: %w", err)
}
if err := p.parseFuncs(pkg, dPkg.Funcs); err != nil {
return nil, fmt.Errorf("parsing functions: %w", err)
}
return pkg, nil
}
func (p *Parser) parseConsts(pkg *Package, cnsts []*doc.Value) error {
for _, dVal := range cnsts {
cg := p.parseConst(dVal)
if len(cg.Consts) == 0 {
continue
}
pkg.Consts = append(pkg.Consts, cg)
}
return nil
}
func (p *Parser) parseConst(dVal *doc.Value) ConstGroup {
cg := ConstGroup{Doc: p.mkDoc(dVal.Doc)}
for _, s := range dVal.Decl.Specs {
vs, ok := s.(*ast.ValueSpec)
if !ok {
panic(fmt.Errorf("unsupported const spec type %T", s))
}
c := Const{
Names: identNames(vs.Names),
Values: make([]Value, 0, len(vs.Values)),
valSpec: vs,
}
if !p.includeSymbol(c) {
continue
}
for _, v := range vs.Values {
var val Value
switch vt := v.(type) {
case *ast.BasicLit:
val.Value = vt.Value
val.Type = typeNames[vt.Kind]
case *ast.CallExpr:
if lit, ok := vt.Args[0].(*ast.BasicLit); ok {
val.Value = lit.Value
}
val.Type = printNodes(vt.Fun)
val.Specific = true
case *ast.Ident:
val.Type = vt.Name
default:
panic(fmt.Errorf("unsupported const value type %T", vt))
}
if vs.Type != nil {
val.Type = printNodes(vs.Type)
val.Specific = true
}
c.Values = append(c.Values, val)
}
cg.Consts = append(cg.Consts, c)
}
return cg
}
func (p *Parser) parseFuncs(pkg *Package, fns []*doc.Func) error {
for _, fn := range fns {
pfn := p.parseFunc(fn, SymbolFunc)
if !p.includeSymbol(pfn) {
continue
}
pkg.Funcs = append(pkg.Funcs, pfn)
}
return nil
}
func (p *Parser) parseTypes(pkg *Package, types []*doc.Type) error {
for _, t := range types {
if t.Decl.Tok != token.TYPE {
continue
}
for _, spec := range t.Decl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
if err := p.parseConsts(pkg, t.Consts); err != nil {
return fmt.Errorf("parsing consts for %s type: %w", t.Name, err)
}
if err := p.parseFuncs(pkg, t.Funcs); err != nil {
return fmt.Errorf("parsing functions for %s type: %w", t.Name, err)
}
td := TypeDef{
Name: t.Name,
Doc: p.mkDoc(t.Doc),
}
switch ts := typeSpec.Type.(type) {
case *ast.Ident:
td.Type = ts.Name
case *ast.StructType:
td.Type = "struct"
td.Fields = p.parseFieldList(ts.Fields, SymbolStructField)
case *ast.InterfaceType:
td.Type = "interface"
if ts.Methods != nil {
for _, m := range ts.Methods.List {
ft, ok := m.Type.(*ast.FuncType)
if !ok {
continue
}
f := Func{
Name: m.Names[0].Name,
Params: p.parseFieldList(ft.Params, SymbolParamField),
Results: p.parseFieldList(ft.Results, SymbolResultField),
funcKw: false,
symbolType: SymbolMethod,
}
if m.Doc != nil {
f.Doc = p.mkDoc(m.Doc.Text())
}
if m.Comment != nil {
f.Comment = p.mkDoc(m.Comment.Text())
}
td.Methods = append(td.Methods, f)
}
}
case *ast.FuncType:
td.Type = "func"
td.Params = p.parseFieldList(ts.Params, SymbolParamField)
td.Results = p.parseFieldList(ts.Results, SymbolResultField)
case *ast.MapType:
td.Type = "map"
td.Key = printNodes(ts.Key)
td.Value = printNodes(ts.Value)
case *ast.ChanType:
td.Type = "chan"
td.Value = printNodes(ts.Value)
switch ts.Dir {
case ast.RECV:
td.Dir = "recv"
case ast.SEND:
td.Dir = "send"
}
case *ast.ArrayType:
td.Type = "array"
td.Elt = printNodes(ts.Elt)
if ts.Len != nil {
td.Len = printNodes(ts.Len)
}
default:
continue
}
methods := make([]Func, 0, len(t.Methods))
for _, m := range t.Methods {
pm := p.parseFunc(m, SymbolMethod)
if !p.includeSymbol(pm) {
continue
}
methods = append(methods, pm)
}
if !p.includeSymbol(td) {
pkg.Funcs = append(pkg.Funcs, methods...)
continue
}
td.Methods = append(td.Methods, methods...)
pkg.Types = append(pkg.Types, td)
}
}
return nil
}
func (p *Parser) parseFunc(df *doc.Func, st SymbolType) Func {
if st != SymbolFunc && st != SymbolMethod {
panic(fmt.Errorf("symbol type must be %v or %v for Func", SymbolFunc, SymbolMethod))
}
decl := df.Decl
fn := Func{
Name: df.Name,
Doc: p.mkDoc(df.Doc),
funcKw: decl.Type.Func != token.NoPos,
symbolType: st,
}
if decl.Recv != nil && decl.Recv.NumFields() != 0 {
fr := p.parseField(decl.Recv.List[0], SymbolReceiverField)
fn.Receiver = &fr
}
if decl.Type.Params != nil && decl.Type.Params.NumFields() != 0 {
fn.Params = p.parseFieldList(decl.Type.Params, SymbolParamField)
}
if decl.Type.Results != nil && decl.Type.Results.NumFields() != 0 {
fn.Results = p.parseFieldList(decl.Type.Results, SymbolResultField)
}
return fn
}
func (p *Parser) parseFieldList(fl *ast.FieldList, st SymbolType) []Field {
if !isFieldSymbolType(st) {
panic(fmt.Errorf("symbol type must be %v, %v, %v, or %v for Field",
SymbolStructField, SymbolPackage, SymbolResultField, SymbolReceiverField),
)
}
if fl == nil {
return nil
}
res := make([]Field, 0, len(fl.List))
for _, f := range fl.List {
pf := p.parseField(f, st)
if !p.includeSymbol(pf) {
continue
}
res = append(res, pf)
}
return res
}
func (p *Parser) parseField(af *ast.Field, st SymbolType) Field {
f := Field{
Names: identNames(af.Names),
Type: printNodes(af.Type),
symbolType: st,
}
if af.Doc != nil {
f.Doc = p.mkDoc(af.Doc.Text())
}
if af.Comment != nil {
f.Comment = p.mkDoc(af.Comment.Text())
}
if !p.noTags && af.Tag != nil {
f.Tags = p.parseFieldTags(af.Tag)
}
return f
}
func (*Parser) parseFieldTags(aft *ast.BasicLit) []FieldTag {
parsed := parseFieldTags(aft.Value)
if len(parsed) == 0 {
return nil
}
tags := make([]FieldTag, 0, len(parsed))
for _, p := range parsed {
tags = append(tags, FieldTag{Name: p[0], Values: p[1:]})
}
return tags
}
func (p *Parser) includeSymbol(s Symbol) bool {
for _, f := range p.filters {
if !f.Include(s) {
return false
}
}
return true
}
func (p *Parser) mkDoc(fullDoc string) string {
fullDoc = strings.TrimSpace(fullDoc)
if p.noDocs {
return ""
}
fullDoc = strings.TrimPrefix(strings.TrimSpace(fullDoc), "// ")
if p.fullDocs {
return fullDoc
}
pkg := doc.Package{}
return pkg.Synopsis(fullDoc)
}
// WithFullDocs configures a [Parser] to include full doc comments instead of
// short synopsis comments.
func WithFullDocs() ParserOption {
return &fullDocs{}
}
type fullDocs struct{}
func (*fullDocs) String() string {
return "fullDocs"
}
func (*fullDocs) apply(p *Parser) error {
p.fullDocs = true
return nil
}
// WithNoDocs configures a [Parser] to not include any doc comments for symbols.
func WithNoDocs() ParserOption {
return &noDocs{}
}
type noDocs struct{}
func (*noDocs) String() string {
return "noDocs"
}
func (*noDocs) apply(p *Parser) error {
p.noDocs = true
return nil
}
// WithNoDocs configures a [Parser] to not include any struct field tags.
func WithNoTags() ParserOption {
return &noTags{}
}
type noTags struct{}
func (*noTags) String() string {
return "noTags"
}
func (*noTags) apply(p *Parser) error {
p.noTags = true
return nil
}
// WithSymbolFilters configures a [Parser] to filter package symbols with
// provided filter functions.
func WithSymbolFilters(filters ...SymbolFilter) ParserOption {
return &symbolFilters{filters: filters}
}
type symbolFilters struct {
filters []SymbolFilter
}
func (sf *symbolFilters) String() string {
filters := make([]string, 0, len(sf.filters))
for _, f := range sf.filters {
filters = append(filters, f.String())
}
return fmt.Sprintf("symbolFilters(filters=%s)", strings.Join(filters, ","))
}
func (sf *symbolFilters) apply(p *Parser) error {
p.filters = sf.filters
return nil
}