-
Notifications
You must be signed in to change notification settings - Fork 3
/
registry.go
938 lines (843 loc) · 28.2 KB
/
registry.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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
package annogo
import (
"fmt"
"reflect"
"sort"
"sync"
)
var (
registryMu sync.RWMutex
funcAnnotations = map[uintptr]annosMap{}
constAnnotations = map[reflect.Type]namedElementAnnos{}
varAnnotations = map[reflect.Type]namedElementAnnos{}
varAnnotationsByAddr = map[uintptr]annosMap{}
typeAnnotations = map[reflect.Type]*typeAnnos{}
adaptedFuncs = map[uintptr]interface{}{}
)
// AnnotationValue describes a single annotation, its type and its value.
type AnnotationValue struct {
Type reflect.Type
Value reflect.Value
}
// ValueDesc describes a value declaration, a var or a const.
type ValueDesc struct {
Type reflect.Type
PackagePath string
ValueName string
}
// TODO: also need to store map of uintptr to interface{} that
// maps pointer of adapter function to the actual wrapped function
// (for cases where adapter function must be created to adapt
// SelfType or AnyType in annotation field signature); need to
// provide exported API, GetUnderlyingFunction, for querying it.
type annosMap map[reflect.Type][]reflect.Value
type namedElementAnnos map[string]map[string]annosMap
type typeAnnos struct {
typeAnnotations annosMap
fieldAnnotations map[string]annosMap
ifaceMethodAnnotations map[string]annosMap
ifaceEmbedsAnnotations map[reflect.Type]annosMap
}
// RegisterFunctionAnnotation records the given annotations for the given
// function. This should only be used by init() functions generated by aptgo.
func RegisterFunctionAnnotation(function interface{}, annoType reflect.Type, annotation interface{}) {
fn := reflect.ValueOf(function)
if fn.Kind() != reflect.Func {
panic(fmt.Sprintf("given object must be a function but was %T", function))
}
anno := checkAnnotation(annoType, annotation, false)
ptr := fn.Pointer()
registryMu.Lock()
defer registryMu.Unlock()
annos := funcAnnotations[ptr]
if annos == nil {
annos = annosMap{}
funcAnnotations[ptr] = annos
}
annos[annoType] = append(annos[annoType], anno)
}
// GetAllAnnotationsForFunction returns all recorded annotations for the given
// function.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// func foo(bar int) bool {
// return bar == 24
// }
//
// // pass the function itself
// annos := annogo.GetAllAnnotationsForFunction(foo)
//
func GetAllAnnotationsForFunction(function interface{}) []AnnotationValue {
fn := reflect.ValueOf(function)
if fn.Kind() != reflect.Func {
panic(fmt.Sprintf("given object must be a function but was %T", function))
}
registryMu.RLock()
defer registryMu.RUnlock()
return annotationValues(funcAnnotations[fn.Pointer()])
}
// GetAnnotationsForFunction returns recorded annotations of the given type for
// the given function.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// func foo(bar int) bool {
// return bar == 24
// }
//
// // pass the function itself
// annos := annogo.GetAnnotationsForFunction(foo, reflect.TypeOf(MyAnnotation{}))
//
func GetAnnotationsForFunction(function interface{}, annoType reflect.Type) []reflect.Value {
fn := reflect.ValueOf(function)
if fn.Kind() != reflect.Func {
panic(fmt.Sprintf("given object must be a function but was %T", function))
}
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
return copyAll(funcAnnotations[fn.Pointer()][annoType])
}
// RegisterVarAnnotation records the given annotations for the given var. This
// should only be used by init() functions generated by aptgo.
func RegisterVarAnnotation(varAddr interface{}, pkgPath, varName string, annoType reflect.Type, annotation interface{}) {
vr := reflect.ValueOf(varAddr)
if vr.Kind() != reflect.Ptr {
panic(fmt.Sprintf("given object must be a pointer but was %T", varAddr))
}
anno := checkAnnotation(annoType, annotation, false)
varType := vr.Type().Elem()
registryMu.Lock()
defer registryMu.Unlock()
if varType.Size() > 0 {
// if non-zero size, can register by variable address
ptr := vr.Pointer()
annos := varAnnotationsByAddr[ptr]
if annos == nil {
annos = annosMap{}
varAnnotationsByAddr[ptr] = annos
}
annos[annoType] = append(annos[annoType], anno)
}
// register by name
byPackage := varAnnotations[varType]
if byPackage == nil {
byPackage = namedElementAnnos{}
varAnnotations[varType] = byPackage
}
byName := byPackage[pkgPath]
if byName == nil {
byName = map[string]annosMap{}
byPackage[pkgPath] = byName
}
annos := byName[varName]
if annos == nil {
annos = annosMap{}
byName[varName] = annos
}
annos[annoType] = append(annos[annoType], anno)
}
// GetAllAnnotationsForVar returns all recorded annotations for the given var.
// This will return no annotations, even if the var is annotated, if the given
// var has a storage size of zero. For zero-size vars, GetAllAnnotationsForValue
// must be used instead.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// var foo = bar{a: "b", c: 'd', e: 111}
//
// // pass the address of the var
// annos := annogo.GetAllAnnotationsForVar(&foo)
//
func GetAllAnnotationsForVar(varAddr interface{}) []AnnotationValue {
vr := reflect.ValueOf(varAddr)
if vr.Kind() != reflect.Ptr {
panic(fmt.Sprintf("given object must be a pointer but was %T", varAddr))
}
registryMu.RLock()
defer registryMu.RUnlock()
return annotationValues(varAnnotationsByAddr[vr.Pointer()])
}
// GetAnnotationsForVar returns all recorded annotations of the given type for
// the given var. This will return no annotations, even if the var is annotated,
// if the given var has a storage size of zero. For zero-size vars,
// GetAnnotationsForValue must be used instead.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// var foo = bar{a: "b", c: 'd', e: 111}
//
// // pass the address of the var
// annos := annogo.GetAllAnnotationsForVar(&foo, reflect.TypeOf(MyAnnotation{}))
//
func GetAnnotationsForVar(varAddr interface{}, annoType reflect.Type) []reflect.Value {
vr := reflect.ValueOf(varAddr)
if vr.Kind() != reflect.Ptr {
panic(fmt.Sprintf("given object must be a pointer but was %T", varAddr))
}
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
return copyAll(varAnnotationsByAddr[vr.Pointer()][annoType])
}
// GetAnnotatedVarsOfType returns descriptions for all vars of the given type
// that have annotations.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// var foo = bar{a: "b", c: 'd', e: 111}
//
// // "foo" returned in this list, along with any other annotated vars
// vars := annogo.GetAnnotatedVarsOfType(reflect.TypeOf(bar{}))
//
func GetAnnotatedVarsOfType(varType reflect.Type) []ValueDesc {
registryMu.RLock()
defer registryMu.RUnlock()
var vars []ValueDesc
for pkgName, varMap := range varAnnotations[varType] {
for varName := range varMap {
vars = append(vars, ValueDesc{Type: varType, PackagePath: pkgName, ValueName: varName})
}
}
return vars
}
// GetAnnotatedVarsOfTypeInPkg returns descriptions for all vars of the given
// type defined in the given package that have annotations.
//
// package fff; // import "github.com/foobar/fff"
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// var foo = bar{a: "b", c: 'd', e: 111}
//
// // "foo" returned in this list, along with any other annotated vars
// // must pass package import path, not package name
// vars := annogo.GetAnnotatedVarsOfTypeInPkg(
// reflect.TypeOf(bar{}), "github.com/foobar/fff")
//
func GetAnnotatedVarsOfTypeInPkg(varType reflect.Type, pkgName string) []ValueDesc {
registryMu.RLock()
defer registryMu.RUnlock()
var vars []ValueDesc
for varName := range varAnnotations[varType][pkgName] {
vars = append(vars, ValueDesc{Type: varType, PackagePath: pkgName, ValueName: varName})
}
return vars
}
// RegisterConstAnnotation records the given annotations for the given const.
// This should only be used by init() functions generated by aptgo.
func RegisterConstAnnotation(constType reflect.Type, pkgPath, constName string, annoType reflect.Type, annotation interface{}) {
anno := checkAnnotation(annoType, annotation, false)
registryMu.Lock()
defer registryMu.Unlock()
// register by name
byPackage := constAnnotations[constType]
if byPackage == nil {
byPackage = namedElementAnnos{}
constAnnotations[constType] = byPackage
}
byName := byPackage[pkgPath]
if byName == nil {
byName = map[string]annosMap{}
byPackage[pkgPath] = byName
}
annos := byName[constName]
if annos == nil {
annos = annosMap{}
byName[constName] = annos
}
annos[annoType] = append(annos[annoType], anno)
}
// GetAnnotatedConstsOfType returns descriptions for all consts of the given
// type that have annotations.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// const foo = bar(123123) // typed constants only
//
// // "foo" returned in this list, along with any other annotated consts
// consts := annogo.GetAnnotatedConstsOfType(reflect.TypeOf(bar(0)))
//
func GetAnnotatedConstsOfType(varType reflect.Type) []ValueDesc {
registryMu.RLock()
defer registryMu.RUnlock()
var consts []ValueDesc
for pkgName, varMap := range constAnnotations[varType] {
for varName := range varMap {
consts = append(consts, ValueDesc{Type: varType, PackagePath: pkgName, ValueName: varName})
}
}
return consts
}
// GetAnnotatedConstsOfTypeInPkg returns descriptions for all consts of the
// given type defined in the given package that have annotations.
//
// package fff; // import "github.com/foobar/fff"
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// const foo = bar(123123) // typed constants only
//
// // "foo" returned in this list, along with any other annotated consts
// // must pass package import path, not package name
// consts := annogo.GetAnnotatedConstsOfTypeInPkg(
// reflect.TypeOf(bar(0)), "github.com/foobar/fff")
//
func GetAnnotatedConstsOfTypeInPkg(varType reflect.Type, pkgName string) []ValueDesc {
registryMu.RLock()
defer registryMu.RUnlock()
var consts []ValueDesc
for varName := range constAnnotations[varType][pkgName] {
consts = append(consts, ValueDesc{Type: varType, PackagePath: pkgName, ValueName: varName})
}
return consts
}
// GetAllAnnotationsForValue returns all recorded annotations for the given
// value (which describes either a var or a const). The value will typically
// have come from a call to GetAnnotatedVarsOfType, GetAnnotatedVarsOfTypeInPkg,
// GetAnnotatedConstsOfType, or GetAnnotatedConstsOfTypeInPkg,
//
// package fff; // import "github.com/foobar/fff"
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// var foo = bar{a: "b", c: 'd', e: 111}
//
// valDesc := annogo.ValueDesc{
// Type: reflect.TypeOf(bar{}),
// PackagePath: "github.com/foobar/fff",
// ValueName: "foo",
// }
// annos := annogo.GetAllAnnotationsForValue(valDesc)
//
func GetAllAnnotationsForValue(val ValueDesc) []AnnotationValue {
registryMu.RLock()
defer registryMu.RUnlock()
annos := varAnnotations[val.Type][val.PackagePath][val.ValueName]
if annos == nil {
annos = constAnnotations[val.Type][val.PackagePath][val.ValueName]
}
return annotationValues(annos)
}
// GetAnnotationsForValue returns all recorded annotations of the given type for
// the given value (which describes either a var or a const).
//
// package fff; // import "github.com/foobar/fff"
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// var foo = bar{a: "b", c: 'd', e: 111}
//
// valDesc := annogo.ValueDesc{
// Type: reflect.TypeOf(bar{}),
// PackagePath: "github.com/foobar/fff",
// ValueName: "foo",
// }
// annos := annogo.GetAnnotationsForValue(valDesc, reflect.TypeOf(MyAnnotation{}))
//
func GetAnnotationsForValue(val ValueDesc, annoType reflect.Type) []reflect.Value {
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
annos := varAnnotations[val.Type][val.PackagePath][val.ValueName]
if annos == nil {
annos = constAnnotations[val.Type][val.PackagePath][val.ValueName]
}
return copyAll(annos[annoType])
}
// RegisterTypeAnnotation records the given annotations for the given type.
// This should only be used by init() functions generated by aptgo.
func RegisterTypeAnnotation(t, annoType reflect.Type, annotation interface{}) {
anno := checkAnnotation(annoType, annotation, true)
registryMu.Lock()
defer registryMu.Unlock()
annos := typeAnnotations[t]
if annos == nil {
annos = &typeAnnos{}
typeAnnotations[t] = annos
}
if annos.typeAnnotations == nil {
annos.typeAnnotations = annosMap{}
}
annos.typeAnnotations[annoType] = append(annos.typeAnnotations[annoType], anno)
}
// GetAllAnnotationsForType returns all recorded annotations for the given type.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// type foo struct {
// bar, baz string
// }
//
// annos := annogo.GetAllAnnotationsForType(reflect.TypeOf(foo{}))
//
func GetAllAnnotationsForType(t reflect.Type) []AnnotationValue {
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return annotationValues(typeAnnos.typeAnnotations)
}
// GetAnnotationsForType returns all recorded annotations of the given
// annotation type for the given annotated type.
//
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// type foo struct {
// bar, baz string
// }
//
// annos := annogo.GetAnnotationsForType(reflect.TypeOf(foo{}), reflect.TypeOf(MyAnnotation{}))
//
func GetAnnotationsForType(t reflect.Type, annoType reflect.Type) []reflect.Value {
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return copyAll(typeAnnos.typeAnnotations[annoType])
}
// RegisterFieldAnnotation records the given annotations for the given field.
// This should only be used by init() functions generated by aptgo.
func RegisterFieldAnnotation(t reflect.Type, fieldName string, annoType reflect.Type, annotation interface{}) {
if t.Kind() != reflect.Struct {
panic(fmt.Sprintf("given type must be a struct: %v", t))
}
_, ok := t.FieldByName(fieldName)
if !ok {
panic(fmt.Sprintf("struct type %v has no field named %q", t, fieldName))
}
anno := checkAnnotation(annoType, annotation, false)
registryMu.Lock()
defer registryMu.Unlock()
annos := typeAnnotations[t]
if annos == nil {
annos = &typeAnnos{}
typeAnnotations[t] = annos
}
if annos.fieldAnnotations == nil {
annos.fieldAnnotations = map[string]annosMap{}
}
fieldAnnos := annos.fieldAnnotations[fieldName]
if fieldAnnos == nil {
fieldAnnos = annosMap{}
annos.fieldAnnotations[fieldName] = fieldAnnos
}
fieldAnnos[annoType] = append(fieldAnnos[annoType], anno)
}
// GetAllAnnotationsForField returns all recorded annotations for the given
// field.
//
// type foo struct {
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// bar string
// baz string
// }
//
// // pass field name as string
// annos := annogo.GetAllAnnotationsForField(reflect.TypeOf(foo{}), "bar")
//
func GetAllAnnotationsForField(t reflect.Type, fieldName string) []AnnotationValue {
if t.Kind() != reflect.Struct {
panic(fmt.Sprintf("given type must be a struct: %v", t))
}
_, ok := t.FieldByName(fieldName)
if !ok {
panic(fmt.Sprintf("struct type %v has no field named %q", t, fieldName))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return annotationValues(typeAnnos.fieldAnnotations[fieldName])
}
// GetAnnotationsForField returns all recorded annotations of the given type for
// the given field.
//
// type foo struct {
// // @MyAnnotation{fiz:"buzz"}
// // @SomeAnnotation(42)
// // @SomeOtherAnnotation
// bar string
// baz string
// }
//
// // pass field name as string
// annos := annogo.GetAnnotationsForField(
// reflect.TypeOf(foo{}), "bar", reflect.TypeOf(MyAnnotation{}))
//
func GetAnnotationsForField(t reflect.Type, fieldName string, annoType reflect.Type) []reflect.Value {
if t.Kind() != reflect.Struct {
panic(fmt.Sprintf("given type must be a struct: %v", t))
}
_, ok := t.FieldByName(fieldName)
if !ok {
panic(fmt.Sprintf("struct type %v has no field named %q", t, fieldName))
}
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return copyAll(typeAnnos.fieldAnnotations[fieldName][annoType])
}
// RegisterInterfaceMethodAnnotation records the given annotations for the given
// interface method. This should only be used by init() functions generated by
// aptgo.
func RegisterInterfaceMethodAnnotation(t reflect.Type, methodName string, annoType reflect.Type, annotation interface{}) {
if t.Kind() != reflect.Interface {
panic(fmt.Sprintf("given type must be an interface: %v", t))
}
_, ok := t.MethodByName(methodName)
if !ok {
panic(fmt.Sprintf("interface type %v has no method named %q", t, methodName))
}
anno := checkAnnotation(annoType, annotation, false)
registryMu.Lock()
defer registryMu.Unlock()
annos := typeAnnotations[t]
if annos == nil {
annos = &typeAnnos{}
typeAnnotations[t] = annos
}
if annos.ifaceMethodAnnotations == nil {
annos.ifaceMethodAnnotations = map[string]annosMap{}
}
methodAnnos := annos.ifaceMethodAnnotations[methodName]
if methodAnnos == nil {
methodAnnos = annosMap{}
annos.ifaceMethodAnnotations[methodName] = methodAnnos
}
methodAnnos[annoType] = append(methodAnnos[annoType], anno)
}
// GetAllAnnotationsForInterfaceMethod returns all recorded annotations for the
// given interface method.
func GetAllAnnotationsForInterfaceMethod(t reflect.Type, methodName string) []AnnotationValue {
if t.Kind() != reflect.Interface {
panic(fmt.Sprintf("given type must be an interface: %v", t))
}
_, ok := t.MethodByName(methodName)
if !ok {
panic(fmt.Sprintf("interface type %v has no method named %q", t, methodName))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return annotationValues(typeAnnos.ifaceMethodAnnotations[methodName])
}
// GetAnnotationsForInterfaceMethod returns all recorded annotations of the
// given type for the given interface method.
func GetAnnotationsForInterfaceMethod(t reflect.Type, methodName string, annoType reflect.Type) []reflect.Value {
if t.Kind() != reflect.Interface {
panic(fmt.Sprintf("given type must be an interface: %v", t))
}
_, ok := t.MethodByName(methodName)
if !ok {
panic(fmt.Sprintf("interface type %v has no method named %q", t, methodName))
}
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return copyAll(typeAnnos.ifaceMethodAnnotations[methodName][annoType])
}
// RegisterInterfaceEmbedAnnotation records the given annotations for the given
// interface embed. This should only be used by init() functions generated by
// aptgo.
func RegisterInterfaceEmbedAnnotation(t, embedType, annoType reflect.Type, annotation interface{}) {
if t.Kind() != reflect.Interface {
panic(fmt.Sprintf("given type must be an interface: %v", t))
}
if !t.Implements(embedType) {
panic(fmt.Sprintf("interface type %v does not implement embedded type %v", t, embedType))
}
anno := checkAnnotation(annoType, annotation, false)
registryMu.Lock()
defer registryMu.Unlock()
annos := typeAnnotations[t]
if annos == nil {
annos = &typeAnnos{}
typeAnnotations[t] = annos
}
if annos.ifaceMethodAnnotations == nil {
annos.ifaceMethodAnnotations = map[string]annosMap{}
}
embedAnnos := annos.ifaceEmbedsAnnotations[embedType]
if embedAnnos == nil {
embedAnnos = annosMap{}
annos.ifaceEmbedsAnnotations[embedType] = embedAnnos
}
embedAnnos[annoType] = append(embedAnnos[annoType], anno)
}
// GetAllAnnotationsForInterfaceEmbed returns all recorded annotations for the
// given interface embed.
func GetAllAnnotationsForInterfaceEmbed(t, embedType reflect.Type) []AnnotationValue {
if t.Kind() != reflect.Interface {
panic(fmt.Sprintf("given type must be an interface: %v", t))
}
if !t.Implements(embedType) {
panic(fmt.Sprintf("interface type %v does not implement embedded type %v", t, embedType))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return annotationValues(typeAnnos.ifaceEmbedsAnnotations[embedType])
}
// GetAnnotationsForInterfaceEmbed returns all recorded annotations of the given
// type for the given interface embed.
func GetAnnotationsForInterfaceEmbed(t, embedType, annoType reflect.Type) []reflect.Value {
if t.Kind() != reflect.Interface {
panic(fmt.Sprintf("given type must be an interface: %v", t))
}
if !t.Implements(embedType) {
panic(fmt.Sprintf("interface type %v does not implement embedded type %v", t, embedType))
}
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given type is not an annotation type: %v", annoType))
}
registryMu.RLock()
defer registryMu.RUnlock()
typeAnnos := typeAnnotations[t]
if typeAnnos == nil {
return nil
}
return copyAll(typeAnnos.ifaceEmbedsAnnotations[embedType][annoType])
}
// RegisterAdaptedFunction is used to associated an underlying function with an
// adapter function. An adapter function is one that may have instances of
// annogo.AnyType or annogo.SelfType in its signature, whereas the underlying
// function may have some other type in those same locations. Adapters are
// created for annotation values that are functions where annogo.AnyType and/or
// annogo.SelfType is in the annotation signature, but may not be in the
// underlying function's signature.
func RegisterAdaptedFunction(adapter, underlying interface{}) {
// double-check they have compatible signatures
rvAdapter := reflect.ValueOf(adapter)
if !compatibleAdapter(rvAdapter.Type(), reflect.TypeOf(underlying)) {
panic(fmt.Sprintf("given functions are not compatible: %T is not a valid adapter type for %T", adapter, underlying))
}
adaptedFuncs[rvAdapter.Pointer()] = underlying
}
// GetUnderlyingFunction retrieves the actual underlying function that is
// wrapped by the given adapter function. If the given function is not known to
// be an adapter for any function value used in an annotation, it is returned
// as is (e.g. its underlying function is itself).
//
// Due to signature adaptation, the returned function may have a different
// signature than the given function: occurrences of annogo.AnyType or
// annogo.SelfType may be replaced with other types in the returned function's
// signature.
func GetUnderlyingFunction(fn interface{}) interface{} {
rv := reflect.ValueOf(fn)
if rv.Kind() != reflect.Func {
panic(fmt.Sprintf("can only query underlying function for adapter functions; given value is not a function: %T", fn))
}
underlying := adaptedFuncs[rv.Pointer()]
if underlying == nil {
return fn
}
return underlying
}
var typeOfAny = reflect.TypeOf((*AnyType)(nil))
var typeOfSelf = reflect.TypeOf((*SelfType)(nil))
func compatibleAdapter(adapter, underlying reflect.Type) bool {
if adapter == underlying {
return true
}
if adapter == typeOfAny || adapter == typeOfSelf {
return true
}
if adapter.Kind() != underlying.Kind() {
return false
}
switch adapter.Kind() {
case reflect.Func:
if adapter.NumIn() != underlying.NumIn() {
return false
}
if adapter.NumOut() != underlying.NumOut() {
return false
}
for i := 0; i < adapter.NumIn(); i++ {
if !compatibleAdapter(adapter.In(i), underlying.In(i)) {
return false
}
}
for i := 0; i < adapter.NumOut(); i++ {
if !compatibleAdapter(adapter.Out(i), underlying.Out(i)) {
return false
}
}
// signature is a match!
return true
case reflect.Map:
if !compatibleAdapter(adapter.Key(), underlying.Key()) {
return false
}
fallthrough
case reflect.Slice, reflect.Array:
if adapter.Kind() == reflect.Array && adapter.Len() != underlying.Len() {
return false
}
return compatibleAdapter(adapter.Elem(), underlying.Elem())
default:
// not a func, map, slice, or array? then types should be an
// exact match (which we've already checked, and they are not)
return false
}
}
func annotationValues(annos annosMap) []AnnotationValue {
if annos == nil {
return nil
}
var vals []AnnotationValue
for t, vs := range annos {
for _, v := range vs {
v, _ = copyIfNeeded(v)
vals = append(vals, AnnotationValue{Type: t, Value: v})
}
}
sort.SliceStable(vals, func(i, j int) bool {
if vals[i].Type.PkgPath() == vals[j].Type.PkgPath() {
return vals[i].Type.Name() < vals[j].Type.Name()
}
return vals[i].Type.PkgPath() <= vals[j].Type.PkgPath()
})
return vals
}
func copyAll(vals []reflect.Value) []reflect.Value {
cv, _ := copyIfNeeded(reflect.ValueOf(vals))
return cv.Interface().([]reflect.Value)
}
func copyIfNeeded(value reflect.Value) (reflect.Value, bool) {
switch value.Kind() {
case reflect.Map:
c := reflect.MakeMap(value.Type())
for _, k := range value.MapKeys() {
kv, _ := copyIfNeeded(k)
vv, _ := copyIfNeeded(value.MapIndex(k))
c.SetMapIndex(kv, vv)
}
return c, true
case reflect.Interface:
return copyIfNeeded(value.Elem())
case reflect.Slice:
c := reflect.MakeSlice(value.Type(), value.Len(), value.Len())
for i := 0; i < value.Len(); i++ {
v, _ := copyIfNeeded(value.Index(i))
c.Index(i).Set(v)
}
return c, true
case reflect.Array:
c := reflect.Zero(value.Type())
for i := 0; i < value.Len(); i++ {
v, _ := copyIfNeeded(value.Index(i))
c.Index(i).Set(v)
}
return c, true
case reflect.Struct:
if rv, ok := value.Interface().(reflect.Value); ok {
// don't use struct reflection to make copies of
// reflect.Value; instead unwrap and recurse
if v, copied := copyIfNeeded(rv); copied {
// re-wrap
return reflect.ValueOf(v), true
}
return value, false
}
var c reflect.Value
for i := 0; i < value.NumField(); i++ {
v, copied := copyIfNeeded(value.Field(i))
if copied && !c.IsValid() {
c = reflect.Zero(value.Type())
for j := 0; j < i; j++ {
c.Field(j).Set(value.Field(j))
}
}
if copied || c.IsValid() {
c.Field(i).Set(v)
}
}
if c.IsValid() {
return c, true
}
return value, false
case reflect.Ptr:
c := reflect.New(value.Type().Elem())
v, _ := copyIfNeeded(value.Elem())
c.Set(v)
return c, true
default:
return value, false
}
}
var typeOfAnnotation = reflect.TypeOf(Annotation{})
func checkAnnotation(annoType reflect.Type, annotation interface{}, allowBootstrap bool) reflect.Value {
if annotation == nil {
panic("registered annotation cannot be nil")
}
anno := reflect.ValueOf(annotation)
if !anno.Type().AssignableTo(annoType) {
panic(fmt.Sprintf("given annotation value (type %T) is not valid for annotation type %v", annotation, annoType))
}
// we skip the next check for Annotation because of the bootstrap case: it
// won't be considered an annotation type until *after* it is registered
if allowBootstrap && annoType == reflect.TypeOf(Annotation{}) {
return anno
}
if !IsAnnotationType(annoType) {
panic(fmt.Sprintf("given annotation value is not valid: %v is not an annotation type", annoType))
}
return anno
}
// IsAnnotationType determines if the given type can be used as an annotation.
// Annotation types are those that are themselves annotated with
// annogo.Annotation.
func IsAnnotationType(t reflect.Type) bool {
annos := typeAnnotations[t]
if annos == nil {
return false
}
v := annos.typeAnnotations[typeOfAnnotation]
return len(v) > 0
}