-
Notifications
You must be signed in to change notification settings - Fork 0
/
astx.go
276 lines (252 loc) · 6.54 KB
/
astx.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
package astx
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"path/filepath"
"reflect"
)
const (
// Parse imports within files
OptParseImports = 1
// Parse structs within files
OptParseStructs = 2
)
// Package represents a parsed Go package
type Package struct {
Name string
Files []File
}
// File represents a parsed Go source file
type File struct {
Package string
Path string
AbsPath string
Imports []Import
Structs []Struct
}
// Import represents an import spec parsed from a Go source file
type Import struct {
Name string
Path string
Doc []string
Comments []string
}
// Struct represents a struct type definition parsed from a Go source file
type Struct struct {
Name string
Comments []string
Fields []StructField
}
// StructField represents a field definition, within a struct type definition,
// parsed from a Go source file
type StructField struct {
Name string
Type string
Doc []string
Comments []string
Tag reflect.StructTag
RawTag string
// A field definition may contain an embedded struct type definition
StructType *Struct
}
// ParseDir parses all packages at path. All options will be set to their
// default values.
func ParseDir(path string) (map[string]Package, error) {
return ParseDirOptions(path, OptParseImports|OptParseStructs)
}
// ParseDirOptions parses all packages within path with options.
func ParseDirOptions(path string, options int) (map[string]Package, error) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, err
}
result := make(map[string]Package, len(pkgs))
for pkgName, astPkg := range pkgs {
p := Package{Name: pkgName}
for filename, astFile := range astPkg.Files {
f, err := parseFileOptions(filename, fset, astFile, options)
if err != nil {
return nil, err
}
p.Files = append(p.Files, *f)
}
result[pkgName] = p
}
return result, nil
}
// ParseFile parses the file at path. All options will be set to their
// default values.
func ParseFile(path string) (*File, error) {
return ParseFileOptions(path, OptParseImports|OptParseStructs)
}
// ParseFileOptions parses the file at path with options.
func ParseFileOptions(path string, options int) (*File, error) {
fset := token.NewFileSet()
af, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, err
}
return parseFileOptions(path, fset, af, options)
}
func parseFileOptions(path string, fset *token.FileSet, af *ast.File, options int) (*File, error) {
abs, err := filepath.Abs(path)
if err != nil {
return nil, err
}
f := &File{
Package: af.Name.Name,
Path: path,
AbsPath: abs,
}
if options&OptParseImports != 0 {
f.Imports = parseFileImports(af)
}
if options&OptParseStructs != 0 {
f.Structs = parseFileStructs(fset, af)
}
return f, nil
}
// ParseSource parses src. src may be of type a string, []byte, or io.Reader.
// All options will be set to their default values.
func ParseSource(src interface{}) (*File, error) {
return ParseSourceOptions(src, OptParseImports|OptParseStructs)
}
// ParseSourceOptions parses src with options. src may be of type a string,
// []byte, or io.Reader.
func ParseSourceOptions(src interface{}, options int) (*File, error) {
fset := token.NewFileSet()
af, err := parser.ParseFile(fset, "source", src, parser.ParseComments)
if err != nil {
return nil, err
}
f := &File{
Package: af.Name.Name,
Path: "source",
}
if options&OptParseImports != 0 {
f.Imports = parseFileImports(af)
}
if options&OptParseStructs != 0 {
f.Structs = parseFileStructs(fset, af)
}
return f, nil
}
func parseFileImports(f *ast.File) []Import {
if f.Imports == nil {
return nil
}
imports := make([]Import, 0, len(f.Imports))
for _, spec := range f.Imports {
var name, path string
if spec.Name != nil {
name = spec.Name.Name
}
if spec.Path != nil {
path = spec.Path.Value
}
imp := Import{
Name: name,
Path: path,
}
imp.Doc = parseComments(spec.Doc)
imp.Comments = parseComments(spec.Comment)
imports = append(imports, imp)
}
return imports
}
func parseFileStructs(fset *token.FileSet, f *ast.File) []Struct {
parsedStructs := []Struct{}
commentMap := ast.NewCommentMap(fset, f, f.Comments)
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
structName := typeSpec.Name.Name
var comments []string
commentGroups := commentMap[genDecl]
if commentGroups != nil {
for _, group := range commentGroups {
comments = append(comments, parseComments(group)...)
}
}
parsedStruct := parseStruct(fset, structType)
parsedStruct.Name = structName
parsedStruct.Comments = comments
parsedStructs = append(parsedStructs, *parsedStruct)
}
}
if len(parsedStructs) == 0 {
return nil
}
return parsedStructs
}
func parseStruct(fset *token.FileSet, s *ast.StructType) *Struct {
parsedStruct := &Struct{}
if s.Fields.List != nil {
parsedStruct.Fields = make([]StructField, 0, len(s.Fields.List))
}
for _, field := range s.Fields.List {
parsedField := StructField{}
for i, name := range field.Names {
parsedField.Name += name.Name
if i != len(field.Names)-1 {
parsedField.Name += ", "
}
}
parsedField.Doc = parseComments(field.Doc)
parsedField.Comments = parseComments(field.Comment)
if field.Tag != nil {
raw := field.Tag.Value
parsedField.RawTag = raw
if len(raw) >= 2 {
// Strip leading/trailing back-ticks:
parsedField.Tag = reflect.StructTag(raw[1 : len(raw)-1])
}
}
parsedField.Type = formatTypeExpr(fset, field.Type)
parsedField.StructType = parseEmbeddedStructType(fset, field.Type)
parsedStruct.Fields = append(parsedStruct.Fields, parsedField)
}
return parsedStruct
}
func formatTypeExpr(fset *token.FileSet, expr ast.Expr) string {
var b bytes.Buffer
if err := printer.Fprint(&b, fset, expr); err != nil {
return "?"
}
return b.String()
}
func parseEmbeddedStructType(fset *token.FileSet, expr ast.Expr) *Struct {
switch V := expr.(type) {
default:
return nil
case *ast.StructType:
return parseStruct(fset, V)
case *ast.StarExpr:
return parseEmbeddedStructType(fset, V.X)
}
}
func parseComments(g *ast.CommentGroup) []string {
if g == nil || g.List == nil {
return nil
}
comments := make([]string, len(g.List))
for i, comment := range g.List {
comments[i] = comment.Text
}
return comments
}