-
Notifications
You must be signed in to change notification settings - Fork 5
/
method.go
503 lines (473 loc) · 12.1 KB
/
method.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package reflectx
import (
"fmt"
"go/token"
"log"
"reflect"
"sort"
"strings"
"unsafe"
)
// MakeMethod make reflect.Method for MethodOf
// - name: method name
// - pointer: flag receiver struct or pointer
// - typ: method func type without receiver
// - fn: func with receiver as first argument
func MakeMethod(name string, pkgpath string, pointer bool, typ reflect.Type, fn func(args []reflect.Value) (result []reflect.Value)) Method {
return Method{
Name: name,
PkgPath: pkgpath,
Pointer: pointer,
Type: typ,
Func: fn,
}
}
// Method struct for MethodOf
// - name: method name
// - pointer: flag receiver struct or pointer
// - typ: method func type without receiver
// - fn: func with receiver as first argument
type Method struct {
Name string
PkgPath string
Pointer bool
Type reflect.Type
Func func([]reflect.Value) []reflect.Value
}
func extraFieldMethod(ifield int, typ reflect.Type, skip map[string]bool) (methods []Method) {
isPtr := typ.Kind() == reflect.Ptr
for i := 0; i < typ.NumMethod(); i++ {
m := MethodByIndex(typ, i)
if skip[m.Name] {
continue
}
in, out := parserFuncIO(m.Type)
mtyp := reflect.FuncOf(in[1:], out, m.Type.IsVariadic())
var fn func(args []reflect.Value) []reflect.Value
if isPtr {
fn = func(args []reflect.Value) []reflect.Value {
args[0] = args[0].Elem().Field(ifield).Addr()
return m.Func.Call(args)
}
} else {
fn = func(args []reflect.Value) []reflect.Value {
args[0] = args[0].Field(ifield)
if mtyp.IsVariadic() {
return m.Func.CallSlice(args)
}
return m.Func.Call(args)
}
}
methods = append(methods, Method{
Name: m.Name,
Pointer: in[0].Kind() == reflect.Ptr,
Type: mtyp,
Func: fn,
})
}
return
}
func parserFuncIO(typ reflect.Type) (in, out []reflect.Type) {
numIn := typ.NumIn()
numOut := typ.NumOut()
for i := 0; i < numIn; i++ {
in = append(in, typ.In(i))
}
for i := 0; i < numOut; i++ {
out = append(out, typ.Out(i))
}
return
}
func extraPtrFieldMethod(ifield int, typ reflect.Type) (methods []Method) {
for i := 0; i < typ.NumMethod(); i++ {
m := typ.Method(i)
in, out := parserFuncIO(m.Type)
mtyp := reflect.FuncOf(in[1:], out, m.Type.IsVariadic())
imethod := i
methods = append(methods, Method{
Name: m.Name,
Type: mtyp,
Func: func(args []reflect.Value) []reflect.Value {
var recv = args[0]
if mtyp.IsVariadic() {
return recv.Field(ifield).Method(imethod).CallSlice(args[1:])
}
return recv.Field(ifield).Method(imethod).Call(args[1:])
},
})
}
return
}
func extraInterfaceFieldMethod(ifield int, typ reflect.Type) (methods []Method) {
for i := 0; i < typ.NumMethod(); i++ {
m := typ.Method(i)
in, out := parserFuncIO(m.Type)
mtyp := reflect.FuncOf(in, out, m.Type.IsVariadic())
imethod := i
methods = append(methods, Method{
Name: m.Name,
Type: mtyp,
Func: func(args []reflect.Value) []reflect.Value {
var recv = args[0]
return recv.Field(ifield).Method(imethod).Call(args[1:])
},
})
}
return
}
func extractEmbedMethod(styp reflect.Type) []Method {
var methods []Method
for i := 0; i < styp.NumField(); i++ {
sf := styp.Field(i)
if !sf.Anonymous {
continue
}
switch sf.Type.Kind() {
case reflect.Interface:
ms := extraInterfaceFieldMethod(i, sf.Type)
methods = append(methods, ms...)
case reflect.Ptr:
ms := extraPtrFieldMethod(i, sf.Type)
methods = append(methods, ms...)
default:
skip := make(map[string]bool)
ms := extraFieldMethod(i, sf.Type, skip)
for _, m := range ms {
skip[m.Name] = true
}
pms := extraFieldMethod(i, reflect.PtrTo(sf.Type), skip)
methods = append(methods, ms...)
methods = append(methods, pms...)
}
}
// ambiguous selector check
chk := make(map[string]int)
for _, m := range methods {
chk[m.Name]++
}
var ms []Method
for _, m := range methods {
if chk[m.Name] == 1 {
ms = append(ms, m)
}
}
return ms
}
func UpdateField(typ reflect.Type, rmap map[reflect.Type]reflect.Type) bool {
if rmap == nil || typ.Kind() != reflect.Struct {
return false
}
rt := totype(typ)
st := toStructType(rt)
for i := 0; i < len(st.fields); i++ {
t := replaceType(toType(st.fields[i].typ), rmap)
st.fields[i].typ = totype(t)
}
return true
}
func Reset() {
Default.Reset()
}
func ResetAll() {
resetAll()
}
func StructToMethodSet(styp reflect.Type) reflect.Type {
return Default.StructToMethodSet(styp)
}
// StructToMethodSet extract method form struct embed fields
func (ctx *Context) StructToMethodSet(styp reflect.Type) reflect.Type {
if styp.Kind() != reflect.Struct {
return styp
}
ms := extractEmbedMethod(styp)
if len(ms) == 0 {
return styp
}
if typ, ok := ctx.embedLookupCache[styp]; ok {
return typ
}
var methods []Method
var mcout, pcount int
for _, m := range ms {
if !m.Pointer {
mcout++
}
pcount++
methods = append(methods, m)
}
typ := newMethodSet(styp, mcout, pcount)
err := ctx.setMethodSet(typ, methods)
if err != nil {
log.Panicln("error loadMethods", err)
}
ctx.embedLookupCache[styp] = typ
return typ
}
// NewMethodSet is pre define method set of styp
// maxmfunc - set methodset of T max member func
// maxpfunc - set methodset of *T + T max member func
func NewMethodSet(styp reflect.Type, maxmfunc, maxpfunc int) reflect.Type {
return Default.NewMethodSet(styp, maxmfunc, maxpfunc)
}
func (ctx *Context) NewMethodSet(styp reflect.Type, maxmfunc, maxpfunc int) reflect.Type {
if maxpfunc == 0 {
return ctx.StructToMethodSet(styp)
}
chk := make(map[string]int)
if styp.Kind() == reflect.Struct {
ms := extractEmbedMethod(styp)
for _, m := range ms {
if chk[m.Name] == 1 {
continue
}
maxpfunc++
if !m.Pointer {
maxmfunc++
}
}
}
typ := newMethodSet(styp, maxmfunc, maxpfunc)
return typ
}
func SetMethodSet(styp reflect.Type, methods []Method, extractStructEmbed bool) error {
return Default.SetMethodSet(styp, methods, extractStructEmbed)
}
func (ctx *Context) SetMethodSet(styp reflect.Type, methods []Method, extractStructEmbed bool) error {
chk := make(map[string]Method)
for _, m := range methods {
if v, ok := chk[m.Name]; ok && v.PkgPath == m.PkgPath {
return fmt.Errorf("method redeclared: %v", m.Name)
}
chk[m.Name] = m
}
if extractStructEmbed && styp.Kind() == reflect.Struct {
ms := extractEmbedMethod(styp)
for _, m := range ms {
if _, ok := chk[m.Name]; ok {
continue
}
methods = append(methods, m)
}
}
return ctx.setMethodSet(styp, methods)
}
func MakeEmptyInterface(pkgpath string, name string) reflect.Type {
return NamedTypeOf(pkgpath, name, tyEmptyInterface)
}
func NamedInterfaceOf(pkgpath string, name string, embedded []reflect.Type, methods []reflect.Method) reflect.Type {
typ := NewInterfaceType(pkgpath, name)
SetInterfaceType(typ, embedded, methods)
return typ
}
func NewInterfaceType(pkgpath string, name string) reflect.Type {
rt, _ := newType("", "", tyEmptyInterface, 0, 0)
setTypeName(rt, pkgpath, name)
return toType(rt)
}
func SetInterfaceType(typ reflect.Type, embedded []reflect.Type, methods []reflect.Method) error {
for _, e := range embedded {
if e.Kind() != reflect.Interface {
return fmt.Errorf("interface contains embedded non-interface %v", e)
}
for i := 0; i < e.NumMethod(); i++ {
m := e.Method(i)
methods = append(methods, reflect.Method{
Name: m.Name,
Type: m.Type,
})
}
}
sort.Slice(methods, func(i, j int) bool {
n := strings.Compare(methods[i].Name, methods[j].Name)
if n == 0 && methods[i].Type != methods[j].Type {
panic(fmt.Errorf("duplicate method %v", methods[j].Name))
}
return n < 0
})
rt := totype(typ)
st := (*interfaceType)(toKindType(rt))
st.methods = nil
var info []string
var lastname string
var unnamed bool
if typ.Name() == "" {
unnamed = true
}
for _, m := range methods {
if m.Name == lastname {
continue
}
lastname = m.Name
isexport := methodIsExported(m.Name)
var mname nameOff
if unnamed {
nm := newNameEx(m.Name, "", isexport, !isexport)
mname = resolveReflectName(nm)
if !isexport {
nm.setPkgPath(m.PkgPath)
}
} else {
mname = resolveReflectName(newName(m.Name, "", isexport))
}
st.methods = append(st.methods, imethod{
name: mname,
typ: resolveReflectType(totype(m.Type)),
})
info = append(info, methodStr(m.Name, m.Type))
}
return nil
}
//go:linkname interequal runtime.interequal
func interequal(p, q unsafe.Pointer) bool
func InterfaceOf(embedded []reflect.Type, methods []reflect.Method) reflect.Type {
return Default.InterfaceOf(embedded, methods)
}
func (ctx *Context) InterfaceOf(embedded []reflect.Type, methods []reflect.Method) reflect.Type {
for _, e := range embedded {
if e.Kind() != reflect.Interface {
panic(fmt.Errorf("interface contains embedded non-interface %v", e))
}
for i := 0; i < e.NumMethod(); i++ {
m := e.Method(i)
methods = append(methods, reflect.Method{
Name: m.Name,
Type: m.Type,
})
}
}
sort.Slice(methods, func(i, j int) bool {
n := strings.Compare(methods[i].Name, methods[j].Name)
if n == 0 && methods[i].Type != methods[j].Type {
panic(fmt.Sprintf("duplicate method %v", methods[j].Name))
}
return n < 0
})
rt, _ := newType("", "", tyEmptyInterface, 0, 0)
st := (*interfaceType)(toKindType(rt))
st.methods = nil
var info []string
var lastname string
for _, m := range methods {
if m.Name == lastname {
continue
}
lastname = m.Name
isexport := methodIsExported(m.Name)
var mname nameOff
nm := newNameEx(m.Name, "", isexport, !isexport)
mname = resolveReflectName(nm)
if !isexport {
nm.setPkgPath(m.PkgPath)
}
st.methods = append(st.methods, imethod{
name: mname,
typ: resolveReflectType(totype(m.Type)),
})
info = append(info, methodStr(m.Name, m.Type))
}
if len(st.methods) > 0 {
rt.equal = interequal
}
var str string
if len(info) > 0 {
str = fmt.Sprintf("*interface { %v }", strings.Join(info, "; "))
} else {
str = "*interface {}"
}
if t, ok := ctx.interfceLookupCache[str]; ok {
return t
}
rt.str = resolveReflectName(newName(str, "", false))
typ := toType(rt)
ctx.interfceLookupCache[str] = typ
return typ
}
func methodIsExported(name string) bool {
return token.IsExported(name)
}
func methodStr(name string, typ reflect.Type) string {
return strings.Replace(typ.String(), "func", name, 1)
}
func toElem(typ reflect.Type) reflect.Type {
if typ.Kind() == reflect.Ptr {
return typ.Elem()
}
return typ
}
func toElemValue(v reflect.Value) reflect.Value {
if v.Kind() == reflect.Ptr {
return v.Elem()
}
return v
}
func replaceType(typ reflect.Type, rmap map[reflect.Type]reflect.Type) reflect.Type {
var fnx func(t reflect.Type) (reflect.Type, bool)
fnx = func(t reflect.Type) (reflect.Type, bool) {
for k, v := range rmap {
if k.String() == t.String() {
return v, true
}
}
switch t.Kind() {
case reflect.Ptr:
if e, ok := fnx(t.Elem()); ok {
return reflect.PtrTo(e), true
}
case reflect.Slice:
if e, ok := fnx(t.Elem()); ok {
return reflect.SliceOf(e), true
}
case reflect.Array:
if e, ok := fnx(t.Elem()); ok {
return reflect.ArrayOf(t.Len(), e), true
}
case reflect.Map:
k, ok1 := fnx(t.Key())
v, ok2 := fnx(t.Elem())
if ok1 || ok2 {
return reflect.MapOf(k, v), true
}
}
return t, false
}
if r, ok := fnx(typ); ok {
return r
}
return typ
}
func parserMethodType(mtyp reflect.Type, rmap map[reflect.Type]reflect.Type) (in, out []reflect.Type, ntyp, inTyp, outTyp reflect.Type) {
var inFields []reflect.StructField
var outFields []reflect.StructField
numIn := mtyp.NumIn()
numOut := mtyp.NumOut()
for i := 0; i < numIn; i++ {
t := mtyp.In(i)
if rmap != nil {
t = replaceType(t, rmap)
}
in = append(in, t)
inFields = append(inFields, reflect.StructField{
Name: fmt.Sprintf("Arg%v", i),
Type: t,
})
}
for i := 0; i < numOut; i++ {
t := mtyp.Out(i)
if rmap != nil {
t = replaceType(t, rmap)
}
out = append(out, t)
outFields = append(outFields, reflect.StructField{
Name: fmt.Sprintf("Out%v", i),
Type: t,
})
}
if rmap == nil {
ntyp = mtyp
} else {
ntyp = reflect.FuncOf(in, out, mtyp.IsVariadic())
}
inTyp = reflect.StructOf(inFields)
outTyp = reflect.StructOf(outFields)
return
}