/
walker_definitions.go
382 lines (302 loc) · 8.01 KB
/
walker_definitions.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
package main
import (
"fmt"
"github.com/jackmanlabs/bucket/jlog"
"github.com/jackmanlabs/errors"
"go/ast"
"go/build"
"go/parser"
"go/token"
"log"
"regexp"
"strings"
"unicode"
)
func findDefinition(referringPackage, typeName string) (*DefinitionIntermediate, error) {
pkgInfo := pkgInfos[referringPackage]
typeName = strings.TrimPrefix(typeName, "*")
importPaths := possibleImportPaths(pkgInfo, typeName)
if len(importPaths) == 0 {
log.Print("ERROR: Import paths not available for this type: ", typeName)
jlog.Log(pkgInfo)
}
if len(importPaths) > 1 {
log.Printf("WARNING: Multiple package candidates found for type (%s):", typeName)
jlog.Log(importPaths)
}
if strings.Contains(typeName, ".") {
index := strings.Index(typeName, ".") + 1
typeName = typeName[index:]
}
for _, importPath := range importPaths {
if importPath == "" {
log.Print("Import path is blank!")
}
bpkg, err := build.Import(importPath, srcPath, 0)
if err != nil {
return nil, errors.Stack(err)
}
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, bpkg.Dir, nil, parser.AllErrors|parser.ParseComments)
if err != nil {
return nil, errors.Stack(err)
}
for _, pkg := range pkgs {
definitionVisitor := &DefinitionVisitor{
Fset: fset,
TypeName: typeName,
}
ast.Walk(definitionVisitor, pkg)
if definitionVisitor.Definition != nil {
definition := definitionVisitor.Definition
definition.PackageName = pkg.Name
definition.PackagePath = importPath
// If this definition is an enum (underlying type is primitive), then we assume it's an enum type that needs enum values.
if isPrimitive, _, _ := IsPrimitive(definition.UnderlyingType); isPrimitive {
values, err := findEnumValues(definition.PackagePath, definition.Name)
if err != nil {
return nil, errors.Stack(err)
}
definition.Enums = make([]interface{}, 0)
for _, v := range values {
definition.Enums = append(definition.Enums, v)
}
}
return definition, nil
}
}
}
return nil, nil
}
type DefinitionVisitor struct {
Fset *token.FileSet
TypeName string
Definition *DefinitionIntermediate
}
func (this *DefinitionVisitor) Visit(node ast.Node) (w ast.Visitor) {
/*
Name string
PackageName string
PackagePath string
Members []MemberIntermediate
IsStruct bool
EmbeddedTypes []string
*/
if this.Fset == nil {
log.Println("fset is nil.")
return nil
}
switch t := node.(type) {
case *ast.TypeSpec:
if t.Name.String() == this.TypeName {
this.Definition = &DefinitionIntermediate{
Name: t.Name.String(),
Comment: t.Comment.Text(),
Documentation: t.Doc.Text(),
UnderlyingType: resolveTypeExpression(t.Type),
Members: make(map[string]SchemerDefiner),
EmbeddedTypes: make([]string, 0),
}
} else {
return nil
}
case *ast.Field:
controlsDoc := parseOpenApiControls(t.Doc.Text())
controlsComment := parseOpenApiControls(t.Comment.Text())
controls := OpenApiControls{
Ignore: controlsDoc.Ignore || controlsComment.Ignore,
Deprecated: controlsDoc.Deprecated || controlsComment.Deprecated,
}
if controls.Ignore {
return nil
}
if this.Definition == nil {
// Ignore fields that don't belong to our definition.
return nil
}
if len(t.Names) > 1 {
// On our test code base, this was never printed.
log.Print("WARNING: Multiple names discovered.")
}
// Handle embedded structs.
if len(t.Names) == 0 {
//ast.Fprint(os.Stderr, this.Fset, t, nil)
embedded := resolveTypeExpression(t.Type)
this.Definition.EmbeddedTypes = append(this.Definition.EmbeddedTypes, embedded)
return nil
}
name := t.Names[0].String()
// Ignore fields that are not exported.
name_ := []rune(name)
if unicode.IsLower(name_[0]) {
return nil
}
var (
jsonName string
jsonOmitEmpty bool
validations ValidationMap
)
if t.Tag != nil {
jsonName, jsonOmitEmpty = parseJsonInfo(t.Tag.Value)
if jsonName == "-" {
return nil
}
validations = parseValidateTag(t.Tag.Value)
} else {
validations = make(ValidationMap)
}
var desc string = parseMemberDescription(t.Doc.Text())
if desc == "" {
desc = parseMemberDescription(t.Comment.Text())
}
goType := resolveTypeExpression(t.Type)
var member SchemerDefiner
if isMap, k, v := IsMap(goType); isMap {
keyType := &MemberIntermediate{
Type: k,
Name: name,
Validations: validations,
}
valueType := &MemberIntermediate{
Type: v,
Name: name,
Validations: validations,
}
member = &MapIntermediate{
Name: name,
Type: goType,
JsonName: jsonName,
JsonOmitEmpty: jsonOmitEmpty,
ValueType: valueType,
KeyType: keyType,
Description: desc,
Validations: validations,
Deprecated: controls.Deprecated,
}
} else if isSlice, v := IsSlice(goType); isSlice {
valueType := &MemberIntermediate{
Type: v,
Name: name,
Validations: validations,
}
member = &SliceIntermediate{
Name: name,
Type: goType,
JsonName: jsonName,
JsonOmitEmpty: jsonOmitEmpty,
ValueType: valueType,
Description: desc,
Validations: validations,
Deprecated: controls.Deprecated,
}
} else {
member = &MemberIntermediate{
Type: goType,
Name: name,
JsonName: jsonName,
JsonOmitEmpty: jsonOmitEmpty,
Description: desc,
Validations: validations,
Deprecated: controls.Deprecated,
}
}
this.Definition.Members[name] = member
return nil
case *ast.FuncDecl:
// Ignore function declarations.
return nil
case *ast.ImportSpec:
// Ignore import declarations.
return nil
case *ast.FuncType:
return nil
case nil:
default:
//log.Printf("unexpected type %T\n", t) // %T prints whatever type t has
}
return this
}
func resolveTypeExpression(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.StarExpr:
return "*" + resolveTypeExpression(t.X)
case *ast.ArrayType:
return "[]" + resolveTypeExpression(t.Elt)
case *ast.Ident:
return t.Name
case *ast.SelectorExpr:
return resolveTypeExpression(t.X) + "." + t.Sel.Name
case *ast.MapType:
return fmt.Sprintf("map[%s]%s", resolveTypeExpression(t.Key), resolveTypeExpression(t.Value))
case *ast.InterfaceType:
return "interface{}"
case *ast.StructType:
return "struct"
default:
return fmt.Sprintf("Unknown<%T>", t)
}
}
func parseJsonInfo(s string) (string, bool) {
rxJson := regexp.MustCompile(`json:"([^"]+)"`)
if !rxJson.MatchString(s) {
return "", false
}
matches := rxJson.FindStringSubmatch(s)
words := strings.Split(matches[1], ",")
name := words[0]
if len(words) == 1 {
return name, false
}
for _, word := range words[1:] {
if word == "omitempty" {
return name, true
}
}
return name, false
}
func parseMemberDescription(s string) string {
if s == "" {
return ""
}
rxDesc := regexp.MustCompile(`@(?i:desc)\s+"?([^"]+)"?`)
if !rxDesc.MatchString(s) {
return ""
}
matches := rxDesc.FindStringSubmatch(s)
return matches[1]
}
func parseValidateTag(s string) map[string]string {
rxValidate := regexp.MustCompile(`validate:"([^"]+)"`)
validations := make(map[string]string)
if !rxValidate.MatchString(s) {
return validations
}
matches := rxValidate.FindStringSubmatch(s)
expressions := strings.Split(matches[1], ",")
for _, expression := range expressions {
parts := strings.Split(expression, "=")
k := parts[0]
v := ""
if len(parts) > 1 {
v = parts[1]
}
validations[k] = v
}
return validations
}
type OpenApiControls struct {
Ignore bool
Deprecated bool
}
func parseOpenApiControls(s string) OpenApiControls {
var controls OpenApiControls
rxIgnore := regexp.MustCompile(`@(?i:ignore)`)
rxDeprecated := regexp.MustCompile(`@(?i:deprecated)`)
if rxIgnore.MatchString(s) {
controls.Ignore = true
}
if rxDeprecated.MatchString(s) {
controls.Deprecated = true
}
return controls
}