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.
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.
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
22 // Type is the representation of a Go type.
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.
30 // Methods applicable to all types.
32 // Align returns the alignment in bytes of a value of
33 // this type when allocated in memory.
36 // FieldAlign returns the alignment in bytes of a value of
37 // this type when used as a field in a struct.
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()).
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.
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.
50 // NumMethod returns the number of methods in the type's method set.
53 // Name returns the type's name within its package.
54 // It returns an empty string for unnamed types.
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.
62 // Size returns the number of bytes needed to store
63 // a value of the given type; it is analogous to unsafe.Sizeof.
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.
73 // Kind returns the specific kind of this type.
76 // Implements returns true if the type implements the interface type u.
77 Implements(u Type) bool
79 // AssignableTo returns true if a value of the type is assignable to type u.
80 AssignableTo(u Type) bool
82 // Methods applicable only to some types, depending on Kind.
83 // The methods allowed for each kind are:
85 // Int*, Uint*, Float*, Complex*: Bits
87 // Chan: ChanDir, Elem
88 // Func: In, NumIn, Out, NumOut, IsVariadic.
92 // Struct: Field, FieldByIndex, FieldByName, FieldByNameFunc, NumField
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.
99 // ChanDir returns a channel type's direction.
100 // It panics if the type's Kind is not Chan.
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.
107 // For concreteness, if t represents func(x int, y ... float), then
110 // t.In(0) is the reflect.Type for "int"
111 // t.In(1) is the reflect.Type for "[]float"
112 // t.IsVariadic() == true
114 // IsVariadic panics if the type's Kind is not Func.
117 // Elem returns a type's element type.
118 // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
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
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
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)
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)
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()).
146 // Key returns a map type's key type.
147 // It panics if the type's Kind is not Map.
150 // Len returns an array type's length.
151 // It panics if the type's Kind is not Array.
154 // NumField returns a struct type's field count.
155 // It panics if the type's Kind is not Struct.
158 // NumIn returns a function type's input parameter count.
159 // It panics if the type's Kind is not Func.
162 // NumOut returns a function type's output parameter count.
163 // It panics if the type's Kind is not Func.
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()).
171 runtimeType() *runtime.Type
173 uncommon() *uncommonType
176 // A Kind represents the specific kind of type that a Type represents.
177 // The zero Kind is not a valid kind.
211 * Copy of data structures from ../runtime/type.go.
212 * For comments, see the ones in that file.
214 * These data structures are known to the compiler and the runtime.
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.
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.
228 type commonType struct {
234 hashfn func(unsafe.Pointer, uintptr)
235 equalfn func(unsafe.Pointer, unsafe.Pointer, uintptr)
238 ptrToThis *runtime.Type
249 type uncommonType struct {
255 // ChanDir represents a channel type's direction.
259 RecvDir ChanDir = 1 << iota
261 BothDir = RecvDir | SendDir
265 // arrayType represents a fixed array type.
266 type arrayType struct {
273 // chanType represents a channel type.
274 type chanType struct {
280 // funcType represents a function type.
281 type funcType struct {
288 // imethod represents a method on an interface type
289 type imethod struct {
295 // interfaceType represents an interface type.
296 type interfaceType struct {
297 commonType "interface"
301 // mapType represents a map type.
302 type mapType struct {
308 // ptrType represents a pointer type.
309 type ptrType struct {
314 // sliceType represents a slice type.
315 type sliceType struct {
321 type structField struct {
329 // structType represents a struct type.
330 type structType struct {
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.
341 // Method represents a single method.
343 PkgPath string // empty for uppercase Name
349 // High bit says whether type has
350 // embedded pointers,to help garbage collector.
351 const kindMask = 0x7f
353 func (k Kind) String() string {
354 if int(k) < len(kindNames) {
357 return "kind" + strconv.Itoa(int(k))
360 var kindNames = []string{
376 Complex64: "complex64",
377 Complex128: "complex128",
381 Interface: "interface",
387 UnsafePointer: "unsafe.Pointer",
390 func (t *uncommonType) uncommon() *uncommonType {
394 func (t *uncommonType) PkgPath() string {
395 if t == nil || t.pkgPath == nil {
401 func (t *uncommonType) Name() string {
402 if t == nil || t.name == nil {
408 func (t *commonType) toType() Type {
412 return canonicalize(t)
415 func (t *commonType) String() string { return *t.string }
417 func (t *commonType) Size() uintptr { return t.size }
419 func (t *commonType) Bits() int {
421 panic("reflect: Bits of nil Type")
424 if k < Int || k > Complex128 {
425 panic("reflect: Bits of non-arithmetic Type " + t.String())
427 return int(t.size) * 8
430 func (t *commonType) Align() int { return int(t.align) }
432 func (t *commonType) FieldAlign() int { return int(t.fieldAlign) }
434 func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) }
436 func (t *commonType) common() *commonType { return t }
438 func (t *uncommonType) Method(i int) (m Method) {
439 if t == nil || i < 0 || i >= len(t.methods) {
447 if p.pkgPath != nil {
448 m.PkgPath = *p.pkgPath
451 m.Type = toType(p.typ)
452 x := new(unsafe.Pointer)
454 m.Func = valueFromIword(flag, m.Type, iword(uintptr(unsafe.Pointer(x))))
458 func (t *uncommonType) NumMethod() int {
462 return len(t.methods)
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()
473 return t.uncommonType.NumMethod()
476 func (t *commonType) Method(i int) (m Method) {
477 if t.Kind() == Interface {
478 tt := (*interfaceType)(unsafe.Pointer(t))
481 return t.uncommonType.Method(i)
484 func (t *commonType) PkgPath() string {
485 return t.uncommonType.PkgPath()
488 func (t *commonType) Name() string {
489 return t.uncommonType.Name()
492 func (t *commonType) ChanDir() ChanDir {
493 if t.Kind() != Chan {
494 panic("reflect: ChanDir of non-chan type")
496 tt := (*chanType)(unsafe.Pointer(t))
497 return ChanDir(tt.dir)
500 func (t *commonType) IsVariadic() bool {
501 if t.Kind() != Func {
502 panic("reflect: IsVariadic of non-func type")
504 tt := (*funcType)(unsafe.Pointer(t))
508 func (t *commonType) Elem() Type {
511 tt := (*arrayType)(unsafe.Pointer(t))
512 return toType(tt.elem)
514 tt := (*chanType)(unsafe.Pointer(t))
515 return toType(tt.elem)
517 tt := (*mapType)(unsafe.Pointer(t))
518 return toType(tt.elem)
520 tt := (*ptrType)(unsafe.Pointer(t))
521 return toType(tt.elem)
523 tt := (*sliceType)(unsafe.Pointer(t))
524 return toType(tt.elem)
526 panic("reflect; Elem of invalid type")
529 func (t *commonType) Field(i int) StructField {
530 if t.Kind() != Struct {
531 panic("reflect: Field of non-struct type")
533 tt := (*structType)(unsafe.Pointer(t))
537 func (t *commonType) FieldByIndex(index []int) StructField {
538 if t.Kind() != Struct {
539 panic("reflect: FieldByIndex of non-struct type")
541 tt := (*structType)(unsafe.Pointer(t))
542 return tt.FieldByIndex(index)
545 func (t *commonType) FieldByName(name string) (StructField, bool) {
546 if t.Kind() != Struct {
547 panic("reflect: FieldByName of non-struct type")
549 tt := (*structType)(unsafe.Pointer(t))
550 return tt.FieldByName(name)
553 func (t *commonType) FieldByNameFunc(match func(string) bool) (StructField, bool) {
554 if t.Kind() != Struct {
555 panic("reflect: FieldByNameFunc of non-struct type")
557 tt := (*structType)(unsafe.Pointer(t))
558 return tt.FieldByNameFunc(match)
561 func (t *commonType) In(i int) Type {
562 if t.Kind() != Func {
563 panic("reflect: In of non-func type")
565 tt := (*funcType)(unsafe.Pointer(t))
566 return toType(tt.in[i])
569 func (t *commonType) Key() Type {
571 panic("reflect: Key of non-map type")
573 tt := (*mapType)(unsafe.Pointer(t))
574 return toType(tt.key)
577 func (t *commonType) Len() int {
578 if t.Kind() != Array {
579 panic("reflect: Len of non-array type")
581 tt := (*arrayType)(unsafe.Pointer(t))
585 func (t *commonType) NumField() int {
586 if t.Kind() != Struct {
587 panic("reflect: NumField of non-struct type")
589 tt := (*structType)(unsafe.Pointer(t))
590 return len(tt.fields)
593 func (t *commonType) NumIn() int {
594 if t.Kind() != Func {
595 panic("reflect; NumIn of non-func type")
597 tt := (*funcType)(unsafe.Pointer(t))
601 func (t *commonType) NumOut() int {
602 if t.Kind() != Func {
603 panic("reflect; NumOut of non-func type")
605 tt := (*funcType)(unsafe.Pointer(t))
609 func (t *commonType) Out(i int) Type {
610 if t.Kind() != Func {
611 panic("reflect: Out of non-func type")
613 tt := (*funcType)(unsafe.Pointer(t))
614 return toType(tt.out[i])
617 func (d ChanDir) String() string {
626 return "ChanDir" + strconv.Itoa(int(d))
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) {
636 if p.pkgPath != nil {
637 m.PkgPath = *p.pkgPath
639 m.Type = toType(p.typ)
643 // NumMethod returns the number of interface methods in the type's method set.
644 func (t *interfaceType) NumMethod() int { return len(t.methods) }
646 type StructField struct {
647 PkgPath string // empty for uppercase Name
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) {
662 f.Type = toType(p.typ)
673 if p.pkgPath != nil {
674 f.PkgPath = *p.pkgPath
684 // TODO(gri): Should there be an error/bool indicator if the index
685 // is wrong for FieldByIndex?
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 {
693 if ft.Kind() == Ptr && ft.Elem().Kind() == Struct {
703 const inf = 1 << 30 // infinity - no struct has that many nesting levels
705 func (t *structType) fieldByNameFunc(match func(string) bool, mark map[*structType]bool, depth int) (ff StructField, fd int) {
706 fd = inf // field depth
709 // Struct already seen.
714 var fi int // field index
715 n := 0 // number of matching fields at depth fd
717 for i := range t.fields {
722 // Matching top-level field.
726 if ft.Kind() == Ptr {
730 case match(ft.Name()):
731 // Matching anonymous top-level field.
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)
744 // Found field at shallower depth.
748 // More than one matching field at the same depth (or d, fd == inf).
749 // Same as no field found at this depth.
752 // Impossible to find a field at lower depth.
759 // Found matching field.
760 if len(ff.Index) <= depth {
761 ff.Index = make([]int, depth+1)
765 // None or more than one matching field found.
769 mark[t] = false, false
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 })
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
789 // Convert runtime type to reflect type.
790 func toCommonType(p *runtime.Type) *commonType {
794 x := unsafe.Pointer(p)
795 if uintptr(x)&reflectFlags != 0 {
796 panic("invalid interface value")
798 return (*commonType)(x)
801 // Canonicalize a Type.
802 var canonicalType = make(map[string]Type)
804 var canonicalTypeLock sync.RWMutex
806 func canonicalize(t Type) Type {
812 if u == nil || u.PkgPath() == "" {
815 s = u.PkgPath() + "." + u.Name()
817 canonicalTypeLock.RLock()
818 if r, ok := canonicalType[s]; ok {
819 canonicalTypeLock.RUnlock()
822 canonicalTypeLock.RUnlock()
823 canonicalTypeLock.Lock()
824 if r, ok := canonicalType[s]; ok {
825 canonicalTypeLock.Unlock()
829 canonicalTypeLock.Unlock()
833 func toType(p *runtime.Type) Type {
837 return toCommonType(p).toType()
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)
846 // ptrMap is the cache for PtrTo.
849 m map[*commonType]*ptrType
852 func (t *commonType) runtimeType() *runtime.Type {
853 return (*runtime.Type)(unsafe.Pointer(t))
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 {
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.
871 if m := ptrMap.m; m != nil {
872 if p := m[ct]; p != nil {
874 return p.commonType.toType()
880 ptrMap.m = make(map[*commonType]*ptrType)
884 // some other goroutine won the race and created it
889 rt := (*runtime.Type)(unsafe.Pointer(ct))
891 rp := new(runtime.PtrType)
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)))
900 s := "*" + *ct.string
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 ^ '*'
912 p.elem = (*runtime.Type)(unsafe.Pointer(ct))
916 return p.commonType.toType()
919 func (t *commonType) Implements(u Type) bool {
921 panic("reflect: nil type passed to Type.Implements")
923 if u.Kind() != Interface {
924 panic("reflect: non-interface type passed to Type.Implements")
926 return implements(u.(*commonType), t)
929 func (t *commonType) AssignableTo(u Type) bool {
931 panic("reflect: nil type passed to Type.AssignableTo")
933 uu := u.(*commonType)
934 return directlyAssignable(uu, t) || implements(uu, t)
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 {
942 t := (*interfaceType)(unsafe.Pointer(T))
943 if len(t.methods) == 0 {
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))
962 for j := 0; j < len(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) {
979 for j := 0; j < len(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) {
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?
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() {
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.
1013 return T.Elem() == V.Elem() && T.Len() == V.Len()
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() {
1023 // Otherwise continue test for identical underlying type.
1024 return V.ChanDir() == T.ChanDir() && T.Elem() == V.Elem()
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) {
1032 for i, typ := range t.in {
1037 for i, typ := range t.out {
1038 if typ != v.out[i] {
1045 t := (*interfaceType)(unsafe.Pointer(T))
1046 v := (*interfaceType)(unsafe.Pointer(V))
1047 if len(t.methods) == 0 && len(v.methods) == 0 {
1050 // Might have the same methods but still
1051 // need a run time conversion.
1055 return T.Key() == V.Key() && T.Elem() == V.Elem()
1058 return T.Elem() == V.Elem()
1061 t := (*structType)(unsafe.Pointer(T))
1062 v := (*structType)(unsafe.Pointer(V))
1063 if len(t.fields) != len(v.fields) {
1066 for i := range t.fields {
1069 if tf.name != vf.name || tf.pkgPath != vf.pkgPath ||
1070 tf.typ != vf.typ || tf.tag != vf.tag || tf.offset != vf.offset {