Update to current version of Go library.
[gcc.git] / libgo / go / reflect / type.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package reflect implements run-time reflection, allowing a program to
6 // manipulate objects with arbitrary types. The typical use is to take a value
7 // with static type interface{} and extract its dynamic type information by
8 // calling TypeOf, which returns a Type.
9 //
10 // A call to ValueOf returns a Value representing the run-time data.
11 // Zero takes a Type and returns a Value representing a zero value
12 // for that type.
13 package reflect
14
15 import (
16 "runtime"
17 "strconv"
18 "sync"
19 "unsafe"
20 )
21
22 // Type is the representation of a Go type.
23 //
24 // Not all methods apply to all kinds of types. Restrictions,
25 // if any, are noted in the documentation for each method.
26 // Use the Kind method to find out the kind of type before
27 // calling kind-specific methods. Calling a method
28 // inappropriate to the kind of type causes a run-time panic.
29 type Type interface {
30 // Methods applicable to all types.
31
32 // Align returns the alignment in bytes of a value of
33 // this type when allocated in memory.
34 Align() int
35
36 // FieldAlign returns the alignment in bytes of a value of
37 // this type when used as a field in a struct.
38 FieldAlign() int
39
40 // Method returns the i'th method in the type's method set.
41 // It panics if i is not in the range [0, NumMethod()).
42 //
43 // For a non-interface type T or *T, the returned Method's Type and Func
44 // fields describe a function whose first argument is the receiver.
45 //
46 // For an interface type, the returned Method's Type field gives the
47 // method signature, without a receiver, and the Func field is nil.
48 Method(int) Method
49
50 // NumMethod returns the number of methods in the type's method set.
51 NumMethod() int
52
53 // Name returns the type's name within its package.
54 // It returns an empty string for unnamed types.
55 Name() string
56
57 // PkgPath returns the type's package path.
58 // The package path is a full package import path like "container/vector".
59 // PkgPath returns an empty string for unnamed types.
60 PkgPath() string
61
62 // Size returns the number of bytes needed to store
63 // a value of the given type; it is analogous to unsafe.Sizeof.
64 Size() uintptr
65
66 // String returns a string representation of the type.
67 // The string representation may use shortened package names
68 // (e.g., vector instead of "container/vector") and is not
69 // guaranteed to be unique among types. To test for equality,
70 // compare the Types directly.
71 String() string
72
73 // Kind returns the specific kind of this type.
74 Kind() Kind
75
76 // Implements returns true if the type implements the interface type u.
77 Implements(u Type) bool
78
79 // AssignableTo returns true if a value of the type is assignable to type u.
80 AssignableTo(u Type) bool
81
82 // Methods applicable only to some types, depending on Kind.
83 // The methods allowed for each kind are:
84 //
85 // Int*, Uint*, Float*, Complex*: Bits
86 // Array: Elem, Len
87 // Chan: ChanDir, Elem
88 // Func: In, NumIn, Out, NumOut, IsVariadic.
89 // Map: Key, Elem
90 // Ptr: Elem
91 // Slice: Elem
92 // Struct: Field, FieldByIndex, FieldByName, FieldByNameFunc, NumField
93
94 // Bits returns the size of the type in bits.
95 // It panics if the type's Kind is not one of the
96 // sized or unsized Int, Uint, Float, or Complex kinds.
97 Bits() int
98
99 // ChanDir returns a channel type's direction.
100 // It panics if the type's Kind is not Chan.
101 ChanDir() ChanDir
102
103 // IsVariadic returns true if a function type's final input parameter
104 // is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's
105 // implicit actual type []T.
106 //
107 // For concreteness, if t represents func(x int, y ... float), then
108 //
109 // t.NumIn() == 2
110 // t.In(0) is the reflect.Type for "int"
111 // t.In(1) is the reflect.Type for "[]float"
112 // t.IsVariadic() == true
113 //
114 // IsVariadic panics if the type's Kind is not Func.
115 IsVariadic() bool
116
117 // Elem returns a type's element type.
118 // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
119 Elem() Type
120
121 // Field returns a struct type's i'th field.
122 // It panics if the type's Kind is not Struct.
123 // It panics if i is not in the range [0, NumField()).
124 Field(i int) StructField
125
126 // FieldByIndex returns the nested field corresponding
127 // to the index sequence. It is equivalent to calling Field
128 // successively for each index i.
129 // It panics if the type's Kind is not Struct.
130 FieldByIndex(index []int) StructField
131
132 // FieldByName returns the struct field with the given name
133 // and a boolean indicating if the field was found.
134 FieldByName(name string) (StructField, bool)
135
136 // FieldByNameFunc returns the first struct field with a name
137 // that satisfies the match function and a boolean indicating if
138 // the field was found.
139 FieldByNameFunc(match func(string) bool) (StructField, bool)
140
141 // In returns the type of a function type's i'th input parameter.
142 // It panics if the type's Kind is not Func.
143 // It panics if i is not in the range [0, NumIn()).
144 In(i int) Type
145
146 // Key returns a map type's key type.
147 // It panics if the type's Kind is not Map.
148 Key() Type
149
150 // Len returns an array type's length.
151 // It panics if the type's Kind is not Array.
152 Len() int
153
154 // NumField returns a struct type's field count.
155 // It panics if the type's Kind is not Struct.
156 NumField() int
157
158 // NumIn returns a function type's input parameter count.
159 // It panics if the type's Kind is not Func.
160 NumIn() int
161
162 // NumOut returns a function type's output parameter count.
163 // It panics if the type's Kind is not Func.
164 NumOut() int
165
166 // Out returns the type of a function type's i'th output parameter.
167 // It panics if the type's Kind is not Func.
168 // It panics if i is not in the range [0, NumOut()).
169 Out(i int) Type
170
171 runtimeType() *runtime.Type
172 common() *commonType
173 uncommon() *uncommonType
174 }
175
176 // A Kind represents the specific kind of type that a Type represents.
177 // The zero Kind is not a valid kind.
178 type Kind uint8
179
180 const (
181 Invalid Kind = iota
182 Bool
183 Int
184 Int8
185 Int16
186 Int32
187 Int64
188 Uint
189 Uint8
190 Uint16
191 Uint32
192 Uint64
193 Uintptr
194 Float32
195 Float64
196 Complex64
197 Complex128
198 Array
199 Chan
200 Func
201 Interface
202 Map
203 Ptr
204 Slice
205 String
206 Struct
207 UnsafePointer
208 )
209
210 /*
211 * Copy of data structures from ../runtime/type.go.
212 * For comments, see the ones in that file.
213 *
214 * These data structures are known to the compiler and the runtime.
215 *
216 * Putting these types in runtime instead of reflect means that
217 * reflect doesn't need to be autolinked into every binary, which
218 * simplifies bootstrapping and package dependencies.
219 * Unfortunately, it also means that reflect needs its own
220 * copy in order to access the private fields.
221 */
222
223 // commonType is the common implementation of most values.
224 // It is embedded in other, public struct types, but always
225 // with a unique tag like "uint" or "float" so that the client cannot
226 // convert from, say, *UintType to *FloatType.
227
228 type commonType struct {
229 kind uint8
230 align int8
231 fieldAlign uint8
232 size uintptr
233 hash uint32
234 hashfn func(unsafe.Pointer, uintptr)
235 equalfn func(unsafe.Pointer, unsafe.Pointer, uintptr)
236 string *string
237 *uncommonType
238 ptrToThis *runtime.Type
239 }
240
241 type method struct {
242 name *string
243 pkgPath *string
244 mtyp *runtime.Type
245 typ *runtime.Type
246 tfn unsafe.Pointer
247 }
248
249 type uncommonType struct {
250 name *string
251 pkgPath *string
252 methods []method
253 }
254
255 // ChanDir represents a channel type's direction.
256 type ChanDir int
257
258 const (
259 RecvDir ChanDir = 1 << iota
260 SendDir
261 BothDir = RecvDir | SendDir
262 )
263
264
265 // arrayType represents a fixed array type.
266 type arrayType struct {
267 commonType "array"
268 elem *runtime.Type
269 slice *runtime.Type
270 len uintptr
271 }
272
273 // chanType represents a channel type.
274 type chanType struct {
275 commonType "chan"
276 elem *runtime.Type
277 dir uintptr
278 }
279
280 // funcType represents a function type.
281 type funcType struct {
282 commonType "func"
283 dotdotdot bool
284 in []*runtime.Type
285 out []*runtime.Type
286 }
287
288 // imethod represents a method on an interface type
289 type imethod struct {
290 name *string
291 pkgPath *string
292 typ *runtime.Type
293 }
294
295 // interfaceType represents an interface type.
296 type interfaceType struct {
297 commonType "interface"
298 methods []imethod
299 }
300
301 // mapType represents a map type.
302 type mapType struct {
303 commonType "map"
304 key *runtime.Type
305 elem *runtime.Type
306 }
307
308 // ptrType represents a pointer type.
309 type ptrType struct {
310 commonType "ptr"
311 elem *runtime.Type
312 }
313
314 // sliceType represents a slice type.
315 type sliceType struct {
316 commonType "slice"
317 elem *runtime.Type
318 }
319
320 // Struct field
321 type structField struct {
322 name *string
323 pkgPath *string
324 typ *runtime.Type
325 tag *string
326 offset uintptr
327 }
328
329 // structType represents a struct type.
330 type structType struct {
331 commonType "struct"
332 fields []structField
333 }
334
335
336 /*
337 * The compiler knows the exact layout of all the data structures above.
338 * The compiler does not know about the data structures and methods below.
339 */
340
341 // Method represents a single method.
342 type Method struct {
343 PkgPath string // empty for uppercase Name
344 Name string
345 Type Type
346 Func Value
347 }
348
349 // High bit says whether type has
350 // embedded pointers,to help garbage collector.
351 const kindMask = 0x7f
352
353 func (k Kind) String() string {
354 if int(k) < len(kindNames) {
355 return kindNames[k]
356 }
357 return "kind" + strconv.Itoa(int(k))
358 }
359
360 var kindNames = []string{
361 Invalid: "invalid",
362 Bool: "bool",
363 Int: "int",
364 Int8: "int8",
365 Int16: "int16",
366 Int32: "int32",
367 Int64: "int64",
368 Uint: "uint",
369 Uint8: "uint8",
370 Uint16: "uint16",
371 Uint32: "uint32",
372 Uint64: "uint64",
373 Uintptr: "uintptr",
374 Float32: "float32",
375 Float64: "float64",
376 Complex64: "complex64",
377 Complex128: "complex128",
378 Array: "array",
379 Chan: "chan",
380 Func: "func",
381 Interface: "interface",
382 Map: "map",
383 Ptr: "ptr",
384 Slice: "slice",
385 String: "string",
386 Struct: "struct",
387 UnsafePointer: "unsafe.Pointer",
388 }
389
390 func (t *uncommonType) uncommon() *uncommonType {
391 return t
392 }
393
394 func (t *uncommonType) PkgPath() string {
395 if t == nil || t.pkgPath == nil {
396 return ""
397 }
398 return *t.pkgPath
399 }
400
401 func (t *uncommonType) Name() string {
402 if t == nil || t.name == nil {
403 return ""
404 }
405 return *t.name
406 }
407
408 func (t *commonType) toType() Type {
409 if t == nil {
410 return nil
411 }
412 return canonicalize(t)
413 }
414
415 func (t *commonType) String() string { return *t.string }
416
417 func (t *commonType) Size() uintptr { return t.size }
418
419 func (t *commonType) Bits() int {
420 if t == nil {
421 panic("reflect: Bits of nil Type")
422 }
423 k := t.Kind()
424 if k < Int || k > Complex128 {
425 panic("reflect: Bits of non-arithmetic Type " + t.String())
426 }
427 return int(t.size) * 8
428 }
429
430 func (t *commonType) Align() int { return int(t.align) }
431
432 func (t *commonType) FieldAlign() int { return int(t.fieldAlign) }
433
434 func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) }
435
436 func (t *commonType) common() *commonType { return t }
437
438 func (t *uncommonType) Method(i int) (m Method) {
439 if t == nil || i < 0 || i >= len(t.methods) {
440 return
441 }
442 p := &t.methods[i]
443 if p.name != nil {
444 m.Name = *p.name
445 }
446 flag := uint32(0)
447 if p.pkgPath != nil {
448 m.PkgPath = *p.pkgPath
449 flag |= flagRO
450 }
451 m.Type = toType(p.typ)
452 x := new(unsafe.Pointer)
453 *x = p.tfn
454 m.Func = valueFromIword(flag, m.Type, iword(uintptr(unsafe.Pointer(x))))
455 return
456 }
457
458 func (t *uncommonType) NumMethod() int {
459 if t == nil {
460 return 0
461 }
462 return len(t.methods)
463 }
464
465 // TODO(rsc): 6g supplies these, but they are not
466 // as efficient as they could be: they have commonType
467 // as the receiver instead of *commonType.
468 func (t *commonType) NumMethod() int {
469 if t.Kind() == Interface {
470 tt := (*interfaceType)(unsafe.Pointer(t))
471 return tt.NumMethod()
472 }
473 return t.uncommonType.NumMethod()
474 }
475
476 func (t *commonType) Method(i int) (m Method) {
477 if t.Kind() == Interface {
478 tt := (*interfaceType)(unsafe.Pointer(t))
479 return tt.Method(i)
480 }
481 return t.uncommonType.Method(i)
482 }
483
484 func (t *commonType) PkgPath() string {
485 return t.uncommonType.PkgPath()
486 }
487
488 func (t *commonType) Name() string {
489 return t.uncommonType.Name()
490 }
491
492 func (t *commonType) ChanDir() ChanDir {
493 if t.Kind() != Chan {
494 panic("reflect: ChanDir of non-chan type")
495 }
496 tt := (*chanType)(unsafe.Pointer(t))
497 return ChanDir(tt.dir)
498 }
499
500 func (t *commonType) IsVariadic() bool {
501 if t.Kind() != Func {
502 panic("reflect: IsVariadic of non-func type")
503 }
504 tt := (*funcType)(unsafe.Pointer(t))
505 return tt.dotdotdot
506 }
507
508 func (t *commonType) Elem() Type {
509 switch t.Kind() {
510 case Array:
511 tt := (*arrayType)(unsafe.Pointer(t))
512 return toType(tt.elem)
513 case Chan:
514 tt := (*chanType)(unsafe.Pointer(t))
515 return toType(tt.elem)
516 case Map:
517 tt := (*mapType)(unsafe.Pointer(t))
518 return toType(tt.elem)
519 case Ptr:
520 tt := (*ptrType)(unsafe.Pointer(t))
521 return toType(tt.elem)
522 case Slice:
523 tt := (*sliceType)(unsafe.Pointer(t))
524 return toType(tt.elem)
525 }
526 panic("reflect; Elem of invalid type")
527 }
528
529 func (t *commonType) Field(i int) StructField {
530 if t.Kind() != Struct {
531 panic("reflect: Field of non-struct type")
532 }
533 tt := (*structType)(unsafe.Pointer(t))
534 return tt.Field(i)
535 }
536
537 func (t *commonType) FieldByIndex(index []int) StructField {
538 if t.Kind() != Struct {
539 panic("reflect: FieldByIndex of non-struct type")
540 }
541 tt := (*structType)(unsafe.Pointer(t))
542 return tt.FieldByIndex(index)
543 }
544
545 func (t *commonType) FieldByName(name string) (StructField, bool) {
546 if t.Kind() != Struct {
547 panic("reflect: FieldByName of non-struct type")
548 }
549 tt := (*structType)(unsafe.Pointer(t))
550 return tt.FieldByName(name)
551 }
552
553 func (t *commonType) FieldByNameFunc(match func(string) bool) (StructField, bool) {
554 if t.Kind() != Struct {
555 panic("reflect: FieldByNameFunc of non-struct type")
556 }
557 tt := (*structType)(unsafe.Pointer(t))
558 return tt.FieldByNameFunc(match)
559 }
560
561 func (t *commonType) In(i int) Type {
562 if t.Kind() != Func {
563 panic("reflect: In of non-func type")
564 }
565 tt := (*funcType)(unsafe.Pointer(t))
566 return toType(tt.in[i])
567 }
568
569 func (t *commonType) Key() Type {
570 if t.Kind() != Map {
571 panic("reflect: Key of non-map type")
572 }
573 tt := (*mapType)(unsafe.Pointer(t))
574 return toType(tt.key)
575 }
576
577 func (t *commonType) Len() int {
578 if t.Kind() != Array {
579 panic("reflect: Len of non-array type")
580 }
581 tt := (*arrayType)(unsafe.Pointer(t))
582 return int(tt.len)
583 }
584
585 func (t *commonType) NumField() int {
586 if t.Kind() != Struct {
587 panic("reflect: NumField of non-struct type")
588 }
589 tt := (*structType)(unsafe.Pointer(t))
590 return len(tt.fields)
591 }
592
593 func (t *commonType) NumIn() int {
594 if t.Kind() != Func {
595 panic("reflect; NumIn of non-func type")
596 }
597 tt := (*funcType)(unsafe.Pointer(t))
598 return len(tt.in)
599 }
600
601 func (t *commonType) NumOut() int {
602 if t.Kind() != Func {
603 panic("reflect; NumOut of non-func type")
604 }
605 tt := (*funcType)(unsafe.Pointer(t))
606 return len(tt.out)
607 }
608
609 func (t *commonType) Out(i int) Type {
610 if t.Kind() != Func {
611 panic("reflect: Out of non-func type")
612 }
613 tt := (*funcType)(unsafe.Pointer(t))
614 return toType(tt.out[i])
615 }
616
617 func (d ChanDir) String() string {
618 switch d {
619 case SendDir:
620 return "chan<-"
621 case RecvDir:
622 return "<-chan"
623 case BothDir:
624 return "chan"
625 }
626 return "ChanDir" + strconv.Itoa(int(d))
627 }
628
629 // Method returns the i'th method in the type's method set.
630 func (t *interfaceType) Method(i int) (m Method) {
631 if i < 0 || i >= len(t.methods) {
632 return
633 }
634 p := &t.methods[i]
635 m.Name = *p.name
636 if p.pkgPath != nil {
637 m.PkgPath = *p.pkgPath
638 }
639 m.Type = toType(p.typ)
640 return
641 }
642
643 // NumMethod returns the number of interface methods in the type's method set.
644 func (t *interfaceType) NumMethod() int { return len(t.methods) }
645
646 type StructField struct {
647 PkgPath string // empty for uppercase Name
648 Name string
649 Type Type
650 Tag string
651 Offset uintptr
652 Index []int
653 Anonymous bool
654 }
655
656 // Field returns the i'th struct field.
657 func (t *structType) Field(i int) (f StructField) {
658 if i < 0 || i >= len(t.fields) {
659 return
660 }
661 p := t.fields[i]
662 f.Type = toType(p.typ)
663 if p.name != nil {
664 f.Name = *p.name
665 } else {
666 t := f.Type
667 if t.Kind() == Ptr {
668 t = t.Elem()
669 }
670 f.Name = t.Name()
671 f.Anonymous = true
672 }
673 if p.pkgPath != nil {
674 f.PkgPath = *p.pkgPath
675 }
676 if p.tag != nil {
677 f.Tag = *p.tag
678 }
679 f.Offset = p.offset
680 f.Index = []int{i}
681 return
682 }
683
684 // TODO(gri): Should there be an error/bool indicator if the index
685 // is wrong for FieldByIndex?
686
687 // FieldByIndex returns the nested field corresponding to index.
688 func (t *structType) FieldByIndex(index []int) (f StructField) {
689 f.Type = Type(t.toType())
690 for i, x := range index {
691 if i > 0 {
692 ft := f.Type
693 if ft.Kind() == Ptr && ft.Elem().Kind() == Struct {
694 ft = ft.Elem()
695 }
696 f.Type = ft
697 }
698 f = f.Type.Field(x)
699 }
700 return
701 }
702
703 const inf = 1 << 30 // infinity - no struct has that many nesting levels
704
705 func (t *structType) fieldByNameFunc(match func(string) bool, mark map[*structType]bool, depth int) (ff StructField, fd int) {
706 fd = inf // field depth
707
708 if mark[t] {
709 // Struct already seen.
710 return
711 }
712 mark[t] = true
713
714 var fi int // field index
715 n := 0 // number of matching fields at depth fd
716 L:
717 for i := range t.fields {
718 f := t.Field(i)
719 d := inf
720 switch {
721 case match(f.Name):
722 // Matching top-level field.
723 d = depth
724 case f.Anonymous:
725 ft := f.Type
726 if ft.Kind() == Ptr {
727 ft = ft.Elem()
728 }
729 switch {
730 case match(ft.Name()):
731 // Matching anonymous top-level field.
732 d = depth
733 case fd > depth:
734 // No top-level field yet; look inside nested structs.
735 if ft.Kind() == Struct {
736 st := (*structType)(unsafe.Pointer(ft.(*commonType)))
737 f, d = st.fieldByNameFunc(match, mark, depth+1)
738 }
739 }
740 }
741
742 switch {
743 case d < fd:
744 // Found field at shallower depth.
745 ff, fi, fd = f, i, d
746 n = 1
747 case d == fd:
748 // More than one matching field at the same depth (or d, fd == inf).
749 // Same as no field found at this depth.
750 n++
751 if d == depth {
752 // Impossible to find a field at lower depth.
753 break L
754 }
755 }
756 }
757
758 if n == 1 {
759 // Found matching field.
760 if len(ff.Index) <= depth {
761 ff.Index = make([]int, depth+1)
762 }
763 ff.Index[depth] = fi
764 } else {
765 // None or more than one matching field found.
766 fd = inf
767 }
768
769 mark[t] = false, false
770 return
771 }
772
773 // FieldByName returns the struct field with the given name
774 // and a boolean to indicate if the field was found.
775 func (t *structType) FieldByName(name string) (f StructField, present bool) {
776 return t.FieldByNameFunc(func(s string) bool { return s == name })
777 }
778
779 // FieldByNameFunc returns the struct field with a name that satisfies the
780 // match function and a boolean to indicate if the field was found.
781 func (t *structType) FieldByNameFunc(match func(string) bool) (f StructField, present bool) {
782 if ff, fd := t.fieldByNameFunc(match, make(map[*structType]bool), 0); fd < inf {
783 ff.Index = ff.Index[0 : fd+1]
784 f, present = ff, true
785 }
786 return
787 }
788
789 // Convert runtime type to reflect type.
790 func toCommonType(p *runtime.Type) *commonType {
791 if p == nil {
792 return nil
793 }
794 x := unsafe.Pointer(p)
795 if uintptr(x)&reflectFlags != 0 {
796 panic("invalid interface value")
797 }
798 return (*commonType)(x)
799 }
800
801 // Canonicalize a Type.
802 var canonicalType = make(map[string]Type)
803
804 var canonicalTypeLock sync.RWMutex
805
806 func canonicalize(t Type) Type {
807 if t == nil {
808 return nil
809 }
810 u := t.uncommon()
811 var s string
812 if u == nil || u.PkgPath() == "" {
813 s = t.String()
814 } else {
815 s = u.PkgPath() + "." + u.Name()
816 }
817 canonicalTypeLock.RLock()
818 if r, ok := canonicalType[s]; ok {
819 canonicalTypeLock.RUnlock()
820 return r
821 }
822 canonicalTypeLock.RUnlock()
823 canonicalTypeLock.Lock()
824 if r, ok := canonicalType[s]; ok {
825 canonicalTypeLock.Unlock()
826 return r
827 }
828 canonicalType[s] = t
829 canonicalTypeLock.Unlock()
830 return t
831 }
832
833 func toType(p *runtime.Type) Type {
834 if p == nil {
835 return nil
836 }
837 return toCommonType(p).toType()
838 }
839
840 // TypeOf returns the reflection Type of the value in the interface{}.
841 func TypeOf(i interface{}) Type {
842 eface := *(*emptyInterface)(unsafe.Pointer(&i))
843 return toType(eface.typ)
844 }
845
846 // ptrMap is the cache for PtrTo.
847 var ptrMap struct {
848 sync.RWMutex
849 m map[*commonType]*ptrType
850 }
851
852 func (t *commonType) runtimeType() *runtime.Type {
853 return (*runtime.Type)(unsafe.Pointer(t))
854 }
855
856 // PtrTo returns the pointer type with element t.
857 // For example, if t represents type Foo, PtrTo(t) represents *Foo.
858 func PtrTo(t Type) Type {
859 // If t records its pointer-to type, use it.
860 ct := t.(*commonType)
861 if p := ct.ptrToThis; p != nil {
862 return toType(p)
863 }
864
865 // Otherwise, synthesize one.
866 // This only happens for pointers with no methods.
867 // We keep the mapping in a map on the side, because
868 // this operation is rare and a separate map lets us keep
869 // the type structures in read-only memory.
870 ptrMap.RLock()
871 if m := ptrMap.m; m != nil {
872 if p := m[ct]; p != nil {
873 ptrMap.RUnlock()
874 return p.commonType.toType()
875 }
876 }
877 ptrMap.RUnlock()
878 ptrMap.Lock()
879 if ptrMap.m == nil {
880 ptrMap.m = make(map[*commonType]*ptrType)
881 }
882 p := ptrMap.m[ct]
883 if p != nil {
884 // some other goroutine won the race and created it
885 ptrMap.Unlock()
886 return p
887 }
888
889 rt := (*runtime.Type)(unsafe.Pointer(ct))
890
891 rp := new(runtime.PtrType)
892
893 // initialize p using *byte's PtrType as a prototype.
894 // have to do assignment as PtrType, not runtime.PtrType,
895 // in order to write to unexported fields.
896 p = (*ptrType)(unsafe.Pointer(rp))
897 bp := (*ptrType)(unsafe.Pointer(unsafe.Typeof((*byte)(nil)).(*runtime.PtrType)))
898 *p = *bp
899
900 s := "*" + *ct.string
901 p.string = &s
902
903 // For the type structures linked into the binary, the
904 // compiler provides a good hash of the string.
905 // Create a good hash for the new string by using
906 // the FNV-1 hash's mixing function to combine the
907 // old hash and the new "*".
908 p.hash = ct.hash*16777619 ^ '*'
909
910 p.uncommonType = nil
911 p.ptrToThis = nil
912 p.elem = (*runtime.Type)(unsafe.Pointer(ct))
913
914 ptrMap.m[ct] = p
915 ptrMap.Unlock()
916 return p.commonType.toType()
917 }
918
919 func (t *commonType) Implements(u Type) bool {
920 if u == nil {
921 panic("reflect: nil type passed to Type.Implements")
922 }
923 if u.Kind() != Interface {
924 panic("reflect: non-interface type passed to Type.Implements")
925 }
926 return implements(u.(*commonType), t)
927 }
928
929 func (t *commonType) AssignableTo(u Type) bool {
930 if u == nil {
931 panic("reflect: nil type passed to Type.AssignableTo")
932 }
933 uu := u.(*commonType)
934 return directlyAssignable(uu, t) || implements(uu, t)
935 }
936
937 // implements returns true if the type V implements the interface type T.
938 func implements(T, V *commonType) bool {
939 if T.Kind() != Interface {
940 return false
941 }
942 t := (*interfaceType)(unsafe.Pointer(T))
943 if len(t.methods) == 0 {
944 return true
945 }
946
947 // The same algorithm applies in both cases, but the
948 // method tables for an interface type and a concrete type
949 // are different, so the code is duplicated.
950 // In both cases the algorithm is a linear scan over the two
951 // lists - T's methods and V's methods - simultaneously.
952 // Since method tables are stored in a unique sorted order
953 // (alphabetical, with no duplicate method names), the scan
954 // through V's methods must hit a match for each of T's
955 // methods along the way, or else V does not implement T.
956 // This lets us run the scan in overall linear time instead of
957 // the quadratic time a naive search would require.
958 // See also ../runtime/iface.c.
959 if V.Kind() == Interface {
960 v := (*interfaceType)(unsafe.Pointer(V))
961 i := 0
962 for j := 0; j < len(v.methods); j++ {
963 tm := &t.methods[i]
964 vm := &v.methods[j]
965 if *vm.name == *tm.name && (vm.pkgPath == tm.pkgPath || (vm.pkgPath != nil && tm.pkgPath != nil && *vm.pkgPath == *tm.pkgPath)) && toType(vm.typ).common() == toType(tm.typ).common() {
966 if i++; i >= len(t.methods) {
967 return true
968 }
969 }
970 }
971 return false
972 }
973
974 v := V.uncommon()
975 if v == nil {
976 return false
977 }
978 i := 0
979 for j := 0; j < len(v.methods); j++ {
980 tm := &t.methods[i]
981 vm := &v.methods[j]
982 if *vm.name == *tm.name && (vm.pkgPath == tm.pkgPath || (vm.pkgPath != nil && tm.pkgPath != nil && *vm.pkgPath == *tm.pkgPath)) && toType(vm.mtyp).common() == toType(tm.typ).common() {
983 if i++; i >= len(t.methods) {
984 return true
985 }
986 }
987 }
988 return false
989 }
990
991 // directlyAssignable returns true if a value x of type V can be directly
992 // assigned (using memmove) to a value of type T.
993 // http://golang.org/doc/go_spec.html#Assignability
994 // Ignoring the interface rules (implemented elsewhere)
995 // and the ideal constant rules (no ideal constants at run time).
996 func directlyAssignable(T, V *commonType) bool {
997 // x's type V is identical to T?
998 if T == V {
999 return true
1000 }
1001
1002 // Otherwise at least one of T and V must be unnamed
1003 // and they must have the same kind.
1004 if T.Name() != "" && V.Name() != "" || T.Kind() != V.Kind() {
1005 return false
1006 }
1007
1008 // x's type T and V have identical underlying types.
1009 // Since at least one is unnamed, only the composite types
1010 // need to be considered.
1011 switch T.Kind() {
1012 case Array:
1013 return T.Elem() == V.Elem() && T.Len() == V.Len()
1014
1015 case Chan:
1016 // Special case:
1017 // x is a bidirectional channel value, T is a channel type,
1018 // and x's type V and T have identical element types.
1019 if V.ChanDir() == BothDir && T.Elem() == V.Elem() {
1020 return true
1021 }
1022
1023 // Otherwise continue test for identical underlying type.
1024 return V.ChanDir() == T.ChanDir() && T.Elem() == V.Elem()
1025
1026 case Func:
1027 t := (*funcType)(unsafe.Pointer(T))
1028 v := (*funcType)(unsafe.Pointer(V))
1029 if t.dotdotdot != v.dotdotdot || len(t.in) != len(v.in) || len(t.out) != len(v.out) {
1030 return false
1031 }
1032 for i, typ := range t.in {
1033 if typ != v.in[i] {
1034 return false
1035 }
1036 }
1037 for i, typ := range t.out {
1038 if typ != v.out[i] {
1039 return false
1040 }
1041 }
1042 return true
1043
1044 case Interface:
1045 t := (*interfaceType)(unsafe.Pointer(T))
1046 v := (*interfaceType)(unsafe.Pointer(V))
1047 if len(t.methods) == 0 && len(v.methods) == 0 {
1048 return true
1049 }
1050 // Might have the same methods but still
1051 // need a run time conversion.
1052 return false
1053
1054 case Map:
1055 return T.Key() == V.Key() && T.Elem() == V.Elem()
1056
1057 case Ptr, Slice:
1058 return T.Elem() == V.Elem()
1059
1060 case Struct:
1061 t := (*structType)(unsafe.Pointer(T))
1062 v := (*structType)(unsafe.Pointer(V))
1063 if len(t.fields) != len(v.fields) {
1064 return false
1065 }
1066 for i := range t.fields {
1067 tf := &t.fields[i]
1068 vf := &v.fields[i]
1069 if tf.name != vf.name || tf.pkgPath != vf.pkgPath ||
1070 tf.typ != vf.typ || tf.tag != vf.tag || tf.offset != vf.offset {
1071 return false
1072 }
1073 }
1074 return true
1075 }
1076
1077 return false
1078 }