/
types.go
352 lines (328 loc) · 8.77 KB
/
types.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
/*
Copyright 2018 Caicloud Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"fmt"
"go/types"
"reflect"
"runtime"
"strings"
"sync"
"unsafe"
)
// TypeName is unique name for go types.
type TypeName string
// TypeNameInvalid indicates an invalid type name.
const TypeNameInvalid = ""
// StructField describes a field of a struct.
type StructField struct {
// Name is the field name.
Name string
// Comments of the type.
Comments string
// PkgPath is the package path that qualifies a lower case (unexported)
// field name. It is empty for upper case (exported) field names.
PkgPath string
// Type is field type name.
Type TypeName
// Tag is field tag.
Tag reflect.StructTag
// Offset within struct, in bytes.
Offset uintptr
// Index sequence for Type.FieldByIndex.
Index []int
// Anonymous shows whether the field is an embedded field.
Anonymous bool
}
// FuncField describes a field of function.
type FuncField struct {
// Name is the field name.
Name string
// Type is field type name.
Type TypeName
}
// Type describes an go type.
type Type struct {
// Name is short type name.
Name string
// Comments of the type.
Comments string
// PkgPath is the package for this type.
PkgPath string
// Kind is type kind.
Kind reflect.Kind
// Key is map key type. Only used in map.
Key TypeName
// Elem is the element type of map, slice, array, pointer.
Elem TypeName
// Fields contains all struct fields of a struct.
Fields []StructField
// In presents fields of function input parameters.
In []FuncField
// Out presents fields of function output results.
Out []FuncField
// Conflict identifies the index of current type in a list of
// types which have same type names. In most cases, this field is 0.
Conflict int
}
// RawTypeName returns raw type name without confliction.
func (t *Type) RawTypeName() TypeName {
if t.Name == "" {
return TypeNameInvalid
}
if t.PkgPath == "" {
return TypeName(t.Name)
}
return TypeName(t.PkgPath + "." + t.Name)
}
// TypeName returns type unique name.
func (t *Type) TypeName() TypeName {
tn := t.RawTypeName()
if tn != TypeNameInvalid && t.Conflict > 0 {
tn = TypeName(fmt.Sprintf("%s [%d]", tn, t.Conflict))
}
return tn
}
// TypeContainer contains types.
type TypeContainer struct {
lock sync.RWMutex
types map[TypeName]*Type
real map[TypeName][]reflect.Type
}
// NewTypeContainer creates a type container.
func NewTypeContainer() *TypeContainer {
return &TypeContainer{
types: make(map[TypeName]*Type),
real: make(map[TypeName][]reflect.Type),
}
}
// Type gets type via type name.
func (tc *TypeContainer) Type(name TypeName) *Type {
if name == TypeNameInvalid {
return nil
}
tc.lock.RLock()
defer tc.lock.RUnlock()
return tc.types[name]
}
// Types returns all types
func (tc *TypeContainer) Types() map[TypeName]*Type {
return tc.types
}
// setType sets type with unique name.
func (tc *TypeContainer) setType(t *Type, typ reflect.Type) {
tn := t.RawTypeName()
if tn == TypeNameInvalid {
return
}
tc.lock.Lock()
defer tc.lock.Unlock()
typs := tc.real[tn]
index := len(typs)
for i, originalType := range typs {
if originalType == typ {
index = i
}
}
t.Conflict = index
tn = t.TypeName()
tc.types[tn] = t
tc.real[tn] = append(typs, typ)
}
func (tc *TypeContainer) getStructFieldType(typ, field reflect.Type) TypeName {
// handle the nested element that may cause infinite recursion when nirvana trying to fetch the struct info which is
// used to generate API docs. eg:
// type Message struct {
// Msg []Message
// }
// typ.String(): message.Message
// field.String(): []message.Message
if !strings.HasSuffix(field.String(), typ.String()) {
return tc.NameOf(field)
}
if field.String() == typ.String() {
return TypeName(typ.PkgPath() + "." + typ.Name())
}
t := &Type{
PkgPath: field.PkgPath(),
Kind: field.Kind(),
}
switch t.Kind {
case reflect.Array, reflect.Slice:
t.Elem = tc.getStructFieldType(typ, field.Elem())
t.Name = fmt.Sprint("[]", t.Elem)
case reflect.Ptr:
t.Elem = tc.getStructFieldType(typ, field.Elem())
t.Name = fmt.Sprint("*", t.Elem)
case reflect.Map:
t.Key = tc.getStructFieldType(typ, field.Key())
t.Elem = tc.getStructFieldType(typ, field.Elem())
t.Name = fmt.Sprintf("map[%s]%s", t.Key, t.Elem)
case reflect.Chan:
t.Elem = tc.getStructFieldType(typ, field.Elem())
t.Name = fmt.Sprint("chan ", t.Elem)
}
tc.setType(t, field)
return t.TypeName()
}
// NameOf gets an unique name of a type.
func (tc *TypeContainer) NameOf(typ reflect.Type) TypeName {
t := &Type{
Name: typ.Name(),
PkgPath: typ.PkgPath(),
Kind: typ.Kind(),
}
if t.Name == "" && t.Kind == reflect.Interface {
// Type interface{} has no name. Set it.
t.Name = "interface{}"
}
tn := t.TypeName()
if tn != TypeNameInvalid && tc.Type(tn) != nil {
return tn
}
switch t.Kind {
case reflect.Array, reflect.Slice:
t.Elem = tc.NameOf(typ.Elem())
if t.Name == "" {
t.Name = fmt.Sprint("[]", t.Elem)
}
case reflect.Ptr:
t.Elem = tc.NameOf(typ.Elem())
if t.Name == "" {
t.Name = fmt.Sprint("*", t.Elem)
}
case reflect.Map:
t.Key = tc.NameOf(typ.Key())
t.Elem = tc.NameOf(typ.Elem())
if t.Name == "" {
t.Name = fmt.Sprintf("map[%s]%s", t.Key, t.Elem)
}
case reflect.Chan:
t.Elem = tc.NameOf(typ.Elem())
if t.Name == "" {
t.Name = fmt.Sprint("chan ", t.Elem)
}
case reflect.Struct:
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
field := StructField{
Name: f.Name,
PkgPath: f.PkgPath,
Tag: f.Tag,
Offset: f.Offset,
Index: f.Index,
Anonymous: f.Anonymous,
Type: tc.getStructFieldType(typ, f.Type),
}
t.Fields = append(t.Fields, field)
}
case reflect.Func:
tc.fillFunctionSignature(t, typ)
if t.Name == "" {
t.Name = fmt.Sprintf("func(%s)", strings.Join(*(*[]string)(unsafe.Pointer(&t.In)), ", "))
if len(t.Out) == 1 {
t.Name += fmt.Sprintf(" %s", t.Out[0])
} else if len(t.Out) > 1 {
t.Name += fmt.Sprintf(" (%s)", strings.Join(*(*[]string)(unsafe.Pointer(&t.Out)), ", "))
}
}
}
tc.setType(t, typ)
return t.TypeName()
}
func (tc *TypeContainer) fillFunctionSignature(t *Type, typ reflect.Type) {
for i := 0; i < typ.NumIn(); i++ {
t.In = append(t.In, FuncField{Type: tc.NameOf(typ.In(i))})
}
for i := 0; i < typ.NumOut(); i++ {
t.Out = append(t.Out, FuncField{Type: tc.NameOf(typ.Out(i))})
}
}
// NameOfInstance gets type name of an instance.
func (tc *TypeContainer) NameOfInstance(ins interface{}) TypeName {
typ := reflect.TypeOf(ins)
if typ.Kind() != reflect.Func {
return tc.NameOf(typ)
}
funcInfo := runtime.FuncForPC(reflect.ValueOf(ins).Pointer())
t := &Type{
Kind: typ.Kind(),
Name: funcInfo.Name(),
}
if index := strings.LastIndexByte(t.Name, '.'); index >= 0 {
t.PkgPath = t.Name[:index]
t.Name = t.Name[index+1:]
}
tc.fillFunctionSignature(t, typ)
tc.setType(t, typ)
return t.TypeName()
}
// Complete fills comments for all types.
func (tc *TypeContainer) Complete(analyzer *Analyzer) error {
tc.lock.Lock()
defer tc.lock.Unlock()
errors := make([]error, 0)
for _, typ := range tc.types {
if typ.PkgPath == "" || strings.HasSuffix(typ.PkgPath, ".glob.") {
// xxx.glob. is the PkgPath of an anonymous function
continue
}
obj, err := analyzer.ObjectOf(typ.PkgPath, typ.Name)
if err != nil {
errors = append(errors, err)
continue
}
if comments := analyzer.Comments(typ.PkgPath, obj.Pos()); comments != nil {
typ.Comments = comments.Text()
}
switch typ.Kind {
case reflect.Struct:
o, ok := obj.Type().(*types.Named)
if !ok {
continue
}
st, ok := o.Underlying().(*types.Struct)
if !ok {
continue
}
for i := 0; i < st.NumFields(); i++ {
field := st.Field(i)
for j := 0; j < len(typ.Fields); j++ {
if typ.Fields[j].Name == field.Name() {
if comments := analyzer.Comments(typ.PkgPath, field.Pos()); comments != nil {
typ.Fields[j].Comments = comments.Text()
}
break
}
}
}
case reflect.Func:
o, ok := obj.Type().(*types.Signature)
if !ok {
continue
}
for i := 0; i < o.Params().Len(); i++ {
param := o.Params().At(i)
typ.In[i].Name = param.Name()
}
for i := 0; i < o.Results().Len(); i++ {
result := o.Results().At(i)
typ.Out[i].Name = result.Name()
}
}
}
if len(errors) == 0 {
return nil
}
return fmt.Errorf("%v", errors)
}