-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_ast.go
100 lines (90 loc) · 2.17 KB
/
utils_ast.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func loadAstFromFile(path string) (*ast.File, error) {
fset := token.NewFileSet()
return parser.ParseFile(fset, path, nil, 0)
}
func getPackage(node *ast.File) string {
return node.Name.String()
}
func getImports(node *ast.File) []string {
var res []string
for _, i := range node.Imports {
res = append(res, i.Path.Value[1:len(i.Path.Value)-1])
}
return res
}
func getFields(node *ast.File, typeName string) ([]Field, error) {
var fields []Field
var found bool
var err error
ast.Inspect(node, func(n ast.Node) bool {
if typeSpec, ok := n.(*ast.TypeSpec); ok {
if typeSpec.Name != nil && typeSpec.Name.String() == typeName {
found = true
switch t := typeSpec.Type.(type) {
case *ast.StructType:
for _, f := range t.Fields.List {
for _, n := range f.Names {
fields = append(fields, Field{
Name: n.Name,
Type: extractTypeFromExpression(f.Type),
})
}
}
case *ast.MapType:
fields = append(fields, Field{
Name: "key",
Type: extractTypeFromExpression(t.Key),
})
fields = append(fields, Field{
Name: "value",
Type: extractTypeFromExpression(t.Value),
})
}
return false
}
}
return true
})
if !found {
err = fmt.Errorf("type(%s): %w", typeName, errTypeNotFound)
}
return fields, err
}
func extractTypeFromExpression(expr ast.Expr) string {
switch expr := expr.(type) {
case *ast.Ident:
return expr.Name
case *ast.StarExpr:
return "*" + extractTypeFromExpression(expr.X)
case *ast.ArrayType:
return "[]" + extractTypeFromExpression(expr.Elt)
case *ast.MapType:
return "map[" + extractTypeFromExpression(expr.Key) + "]" + extractTypeFromExpression(expr.Value)
case *ast.StructType:
return "struct{}"
case *ast.InterfaceType:
return "interface{}"
case *ast.ChanType:
var dir string
switch expr.Dir {
case ast.SEND:
dir = "chan<- "
case ast.RECV:
dir = "<-chan "
default:
dir = "chan "
}
return dir + extractTypeFromExpression(expr.Value)
case *ast.SelectorExpr:
return extractTypeFromExpression(expr.X) + "." + expr.Sel.Name
default:
return "unknown"
}
}