This repository has been archived by the owner on Jul 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
constant.go
121 lines (112 loc) · 2.24 KB
/
constant.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
package humanize
import (
"go/ast"
"go/token"
)
var (
lastConst Type
)
// Constant is a string represent of a function parameter
type Constant struct {
Name string
Type Type
Docs Docs
Value string
caller *ast.CallExpr
indx int
}
func constantFromValue(name string, indx int, e []ast.Expr, src string, f *File, p *Package) *Constant {
var t Type
var caller *ast.CallExpr
var ok bool
if len(e) == 0 {
return &Constant{
Name: name,
}
}
first := e[0]
if caller, ok = first.(*ast.CallExpr); !ok {
switch data := e[indx].(type) {
case *ast.BasicLit:
switch data.Kind {
case token.INT:
t = &IdentType{
srcBase{p, getSource(data, src)},
"int",
}
case token.FLOAT:
t = &IdentType{
srcBase{p, getSource(data, src)},
"float64",
}
case token.IMAG:
t = &IdentType{
srcBase{p, getSource(data, src)},
"complex64",
}
case token.CHAR:
t = &IdentType{
srcBase{p, getSource(data, src)},
"char",
}
case token.STRING:
t = &IdentType{
srcBase{p, getSource(data, src)},
"string",
}
}
case *ast.Ident:
t = &IdentType{
srcBase{p, getSource(data, src)},
nameFromIdent(data),
}
// default:
}
}
return &Constant{
Name: name,
Type: t,
caller: caller,
indx: indx,
}
}
func constantFromExpr(name string, e ast.Expr, src string, f *File, p *Package) *Constant {
return &Constant{
Name: name,
Type: getType(e, src, f, p),
}
}
func getConstantValue(a []ast.Expr) string {
if len(a) == 0 {
return ""
}
switch first := a[0].(type) {
case *ast.BasicLit:
return first.Value
default:
return "NotSupportedYet"
}
}
// NewConstant return an array of constant in the scope
func NewConstant(v *ast.ValueSpec, c *ast.CommentGroup, src string, f *File, p *Package) []*Constant {
var res []*Constant
for i := range v.Names {
name := nameFromIdent(v.Names[i])
var n *Constant
if v.Type != nil {
n = constantFromExpr(name, v.Type, src, f, p)
} else {
n = constantFromValue(name, i, v.Values, src, f, p)
}
n.Value = getConstantValue(v.Values)
if n.Type == nil {
n.Type = lastConst
} else {
lastConst = n.Type
}
n.Name = name
n.Docs = docsFromNodeDoc(c, v.Doc)
res = append(res, n)
}
return res
}