-
Notifications
You must be signed in to change notification settings - Fork 0
/
param.go
98 lines (75 loc) · 1.79 KB
/
param.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
package autonats
import (
"go/ast"
"strings"
)
type Param struct {
Name, Type, TypePackage string
Pointer, Array bool
RequiredImports map[string]bool
}
func ParseParam(f *ast.Field) *Param {
param := &Param{
RequiredImports: make(map[string]bool),
}
switch p := f.Type.(type) {
case *ast.SelectorExpr:
param.typeFromSelectorExpr(p)
case *ast.Ident:
param.typeFromIdent(p)
case *ast.StarExpr:
param.typeFromStarExpr(p)
case *ast.ArrayType:
param.typeFromArray(p)
default:
panic("unhandled type")
}
if len(f.Names) > 0 {
param.Name = f.Names[0].Name
}
return param
}
func (param *Param) typeFromSelectorExpr(sExp *ast.SelectorExpr) {
if sExp.X != nil {
ident := sExp.X.(*ast.Ident)
param.TypePackage = ident.Name
param.RequiredImports[ident.Name] = true
}
param.Type = sExp.Sel.Name
if param.Name == "" {
param.Name = strings.ToLower(sExp.Sel.Name)
}
}
func (param *Param) typeFromStarExpr(sExp *ast.StarExpr) {
param.Pointer = true
switch sExp.X.(type) {
case *ast.Ident:
param.Type = sExp.X.(*ast.Ident).Name
param.Name = strings.ToLower(param.Type)
case *ast.SelectorExpr:
sExpX := sExp.X.(*ast.SelectorExpr)
param.typeFromSelectorExpr(sExpX)
param.Name = strings.ToLower(sExpX.Sel.Name)
default:
panic("unhandled type")
}
}
func (param *Param) typeFromIdent(ident *ast.Ident) {
param.Type = ident.Name
if param.Name == "" {
param.Name = strings.ToLower(param.Name)
}
}
func (param *Param) typeFromArray(arr *ast.ArrayType) {
param.Array = true
switch arr.Elt.(type) {
case *ast.SelectorExpr:
param.typeFromSelectorExpr(arr.Elt.(*ast.SelectorExpr))
case *ast.Ident:
param.typeFromIdent(arr.Elt.(*ast.Ident))
case *ast.StarExpr:
param.typeFromStarExpr(arr.Elt.(*ast.StarExpr))
default:
panic("unhandled type")
}
}