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 // The reflect package implements run-time reflection, allowing a program to
6 // manipulate objects with arbitrary types. The typical use is to take a
7 // value with static type interface{} and extract its dynamic type
8 // information by calling Typeof, which returns an object with interface
9 // type Type. That contains a pointer to a struct of type *StructType,
10 // *IntType, etc. representing the details of the underlying type. A type
11 // switch or type assertion can reveal which.
13 // A call to NewValue creates a Value representing the run-time data; it
14 // contains a *StructValue, *IntValue, etc. MakeZero takes a Type and
15 // returns a Value representing a zero value for that type.
26 * Copy of data structures from ../runtime/type.go.
27 * For comments, see the ones in that file.
29 * These data structures are known to the compiler and the runtime.
31 * Putting these types in runtime instead of reflect means that
32 * reflect doesn't need to be autolinked into every binary, which
33 * simplifies bootstrapping and package dependencies.
34 * Unfortunately, it also means that reflect needs its own
35 * copy in order to access the private fields.
38 // commonType is the common implementation of most values.
39 // It is embedded in other, public struct types, but always
40 // with a unique tag like "uint" or "float" so that the client cannot
41 // convert from, say, *UintType to *FloatType.
43 type commonType struct {
49 hashfn func(unsafe.Pointer, uintptr)
50 equalfn func(unsafe.Pointer, unsafe.Pointer, uintptr)
63 type uncommonType struct {
69 // BoolType represents a boolean type.
70 type BoolType struct {
74 // FloatType represents a float type.
75 type FloatType struct {
79 // ComplexType represents a complex type.
80 type ComplexType struct {
84 // IntType represents a signed integer type.
89 // UintType represents a uint type.
90 type UintType struct {
94 // StringType represents a string type.
95 type StringType struct {
99 // UnsafePointerType represents an unsafe.Pointer type.
100 type UnsafePointerType struct {
101 commonType "unsafe.Pointer"
104 // ArrayType represents a fixed array type.
105 type ArrayType struct {
111 // ChanDir represents a channel type's direction.
115 RecvDir ChanDir = 1 << iota
117 BothDir = RecvDir | SendDir
120 // ChanType represents a channel type.
121 type ChanType struct {
127 // FuncType represents a function type.
128 type FuncType struct {
135 // Method on interface type
136 type imethod struct {
142 // InterfaceType represents an interface type.
143 type InterfaceType struct {
144 commonType "interface"
148 // MapType represents a map type.
149 type MapType struct {
155 // PtrType represents a pointer type.
156 type PtrType struct {
161 // SliceType represents a slice type.
162 type SliceType struct {
168 type structField struct {
176 // StructType represents a struct type.
177 type StructType struct {
184 * The compiler knows the exact layout of all the data structures above.
185 * The compiler does not know about the data structures and methods below.
188 // Method represents a single method.
190 PkgPath string // empty for uppercase Name
196 // Type is the runtime representation of a Go type.
197 // Every type implements the methods listed here.
198 // Some types implement additional interfaces;
199 // use a type switch to find out what kind of type a Type is.
200 // Each type in a program has a unique Type, so == on Types
201 // corresponds to Go's type equality.
202 type Type interface {
203 // PkgPath returns the type's package path.
204 // The package path is a full package import path like "container/vector".
205 // PkgPath returns an empty string for unnamed types.
208 // Name returns the type's name within its package.
209 // Name returns an empty string for unnamed types.
212 // String returns a string representation of the type.
213 // The string representation may use shortened package names
214 // (e.g., vector instead of "container/vector") and is not
215 // guaranteed to be unique among types. To test for equality,
216 // compare the Types directly.
219 // Size returns the number of bytes needed to store
220 // a value of the given type; it is analogous to unsafe.Sizeof.
223 // Bits returns the size of the type in bits.
224 // It is intended for use with numeric types and may overflow
225 // when used for composite types.
228 // Align returns the alignment of a value of this type
229 // when allocated in memory.
232 // FieldAlign returns the alignment of a value of this type
233 // when used as a field in a struct.
236 // Kind returns the specific kind of this type.
239 // For non-interface types, Method returns the i'th method with receiver T.
240 // For interface types, Method returns the i'th method in the interface.
241 // NumMethod returns the number of such methods.
244 uncommon() *uncommonType
247 // A Kind represents the specific kind of type that a Type represents.
248 // For numeric types, the Kind gives more information than the Type's
249 // dynamic type. For example, the Type of a float32 is FloatType, but
250 // the Kind is Float32.
252 // The zero Kind is not a valid kind.
284 // High bit says whether type has
285 // embedded pointers,to help garbage collector.
286 const kindMask = 0x7f
288 func (k Kind) String() string {
289 if int(k) < len(kindNames) {
292 return "kind" + strconv.Itoa(int(k))
295 var kindNames = []string{
310 Complex64: "complex64",
311 Complex128: "complex128",
315 Interface: "interface",
321 UnsafePointer: "unsafe.Pointer",
324 func (t *uncommonType) uncommon() *uncommonType {
328 func (t *uncommonType) PkgPath() string {
329 if t == nil || t.pkgPath == nil {
335 func (t *uncommonType) Name() string {
336 if t == nil || t.name == nil {
342 func (t *commonType) String() string { return *t.string }
344 func (t *commonType) Size() uintptr { return t.size }
346 func (t *commonType) Bits() int { return int(t.size * 8) }
348 func (t *commonType) Align() int { return int(t.align) }
350 func (t *commonType) FieldAlign() int { return int(t.fieldAlign) }
352 func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) }
354 func (t *uncommonType) Method(i int) (m Method) {
355 if t == nil || i < 0 || i >= len(t.methods) {
362 if p.pkgPath != nil {
363 m.PkgPath = *p.pkgPath
365 m.Type = runtimeToType(p.typ).(*FuncType)
367 m.Func = &FuncValue{value: value{m.Type, addr(&fn), true}}
371 func (t *uncommonType) NumMethod() int {
375 return len(t.methods)
378 // TODO(rsc): 6g supplies these, but they are not
379 // as efficient as they could be: they have commonType
380 // as the receiver instead of *commonType.
381 func (t *commonType) NumMethod() int { return t.uncommonType.NumMethod() }
383 func (t *commonType) Method(i int) (m Method) { return t.uncommonType.Method(i) }
385 func (t *commonType) PkgPath() string { return t.uncommonType.PkgPath() }
387 func (t *commonType) Name() string { return t.uncommonType.Name() }
389 // Len returns the number of elements in the array.
390 func (t *ArrayType) Len() int { return int(t.len) }
392 // Elem returns the type of the array's elements.
393 func (t *ArrayType) Elem() Type { return runtimeToType(t.elem) }
395 // Dir returns the channel direction.
396 func (t *ChanType) Dir() ChanDir { return ChanDir(t.dir) }
398 // Elem returns the channel's element type.
399 func (t *ChanType) Elem() Type { return runtimeToType(t.elem) }
401 func (d ChanDir) String() string {
410 return "ChanDir" + strconv.Itoa(int(d))
413 // In returns the type of the i'th function input parameter.
414 func (t *FuncType) In(i int) Type {
415 if i < 0 || i >= len(t.in) {
418 return runtimeToType(t.in[i])
421 // DotDotDot returns true if the final function input parameter
422 // is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the
423 // parameter's underlying static type []T.
425 // For concreteness, if t is func(x int, y ... float), then
428 // t.In(0) is the reflect.Type for "int"
429 // t.In(1) is the reflect.Type for "[]float"
430 // t.DotDotDot() == true
432 func (t *FuncType) DotDotDot() bool { return t.dotdotdot }
434 // NumIn returns the number of input parameters.
435 func (t *FuncType) NumIn() int { return len(t.in) }
437 // Out returns the type of the i'th function output parameter.
438 func (t *FuncType) Out(i int) Type {
439 if i < 0 || i >= len(t.out) {
442 return runtimeToType(t.out[i])
445 // NumOut returns the number of function output parameters.
446 func (t *FuncType) NumOut() int { return len(t.out) }
448 // Method returns the i'th interface method.
449 func (t *InterfaceType) Method(i int) (m Method) {
450 if i < 0 || i >= len(t.methods) {
455 if p.pkgPath != nil {
456 m.PkgPath = *p.pkgPath
458 m.Type = runtimeToType(p.typ).(*FuncType)
462 // NumMethod returns the number of interface methods.
463 func (t *InterfaceType) NumMethod() int { return len(t.methods) }
465 // Key returns the map key type.
466 func (t *MapType) Key() Type { return runtimeToType(t.key) }
468 // Elem returns the map element type.
469 func (t *MapType) Elem() Type { return runtimeToType(t.elem) }
471 // Elem returns the pointer element type.
472 func (t *PtrType) Elem() Type { return runtimeToType(t.elem) }
474 // Elem returns the type of the slice's elements.
475 func (t *SliceType) Elem() Type { return runtimeToType(t.elem) }
477 type StructField struct {
478 PkgPath string // empty for uppercase Name
487 // Field returns the i'th struct field.
488 func (t *StructType) Field(i int) (f StructField) {
489 if i < 0 || i >= len(t.fields) {
493 f.Type = runtimeToType(p.typ)
498 if pt, ok := t.(*PtrType); ok {
504 if p.pkgPath != nil {
505 f.PkgPath = *p.pkgPath
515 // TODO(gri): Should there be an error/bool indicator if the index
516 // is wrong for FieldByIndex?
518 // FieldByIndex returns the nested field corresponding to index.
519 func (t *StructType) FieldByIndex(index []int) (f StructField) {
520 for i, x := range index {
523 if pt, ok := ft.(*PtrType); ok {
526 if st, ok := ft.(*StructType); ok {
539 const inf = 1 << 30 // infinity - no struct has that many nesting levels
541 func (t *StructType) fieldByNameFunc(match func(string) bool, mark map[*StructType]bool, depth int) (ff StructField, fd int) {
542 fd = inf // field depth
545 // Struct already seen.
550 var fi int // field index
551 n := 0 // number of matching fields at depth fd
553 for i := range t.fields {
558 // Matching top-level field.
562 if pt, ok := ft.(*PtrType); ok {
566 case match(ft.Name()):
567 // Matching anonymous top-level field.
570 // No top-level field yet; look inside nested structs.
571 if st, ok := ft.(*StructType); ok {
572 f, d = st.fieldByNameFunc(match, mark, depth+1)
579 // Found field at shallower depth.
583 // More than one matching field at the same depth (or d, fd == inf).
584 // Same as no field found at this depth.
587 // Impossible to find a field at lower depth.
594 // Found matching field.
595 if len(ff.Index) <= depth {
596 ff.Index = make([]int, depth+1)
600 // None or more than one matching field found.
604 mark[t] = false, false
608 // FieldByName returns the struct field with the given name
609 // and a boolean to indicate if the field was found.
610 func (t *StructType) FieldByName(name string) (f StructField, present bool) {
611 return t.FieldByNameFunc(func(s string) bool { return s == name })
614 // FieldByNameFunc returns the struct field with a name that satisfies the
615 // match function and a boolean to indicate if the field was found.
616 func (t *StructType) FieldByNameFunc(match func(string) bool) (f StructField, present bool) {
617 if ff, fd := t.fieldByNameFunc(match, make(map[*StructType]bool), 0); fd < inf {
618 ff.Index = ff.Index[0 : fd+1]
619 f, present = ff, true
624 // NumField returns the number of struct fields.
625 func (t *StructType) NumField() int { return len(t.fields) }
627 // Canonicalize a Type.
628 var canonicalType = make(map[string]Type)
630 var canonicalTypeLock sync.Mutex
632 func canonicalize(t Type) Type {
638 if u == nil || u.PkgPath() == "" {
641 s = u.PkgPath() + "." + u.Name()
643 canonicalTypeLock.Lock()
644 if r, ok := canonicalType[s]; ok {
645 canonicalTypeLock.Unlock()
649 canonicalTypeLock.Unlock()
653 // Convert runtime type to reflect type.
654 // Same memory layouts, different method sets.
655 func toType(i interface{}) Type {
656 switch v := i.(type) {
659 case *runtime.BoolType:
660 return (*BoolType)(unsafe.Pointer(v))
661 case *runtime.FloatType:
662 return (*FloatType)(unsafe.Pointer(v))
663 case *runtime.ComplexType:
664 return (*ComplexType)(unsafe.Pointer(v))
665 case *runtime.IntType:
666 return (*IntType)(unsafe.Pointer(v))
667 case *runtime.StringType:
668 return (*StringType)(unsafe.Pointer(v))
669 case *runtime.UintType:
670 return (*UintType)(unsafe.Pointer(v))
671 case *runtime.UnsafePointerType:
672 return (*UnsafePointerType)(unsafe.Pointer(v))
673 case *runtime.ArrayType:
674 return (*ArrayType)(unsafe.Pointer(v))
675 case *runtime.ChanType:
676 return (*ChanType)(unsafe.Pointer(v))
677 case *runtime.FuncType:
678 return (*FuncType)(unsafe.Pointer(v))
679 case *runtime.InterfaceType:
680 return (*InterfaceType)(unsafe.Pointer(v))
681 case *runtime.MapType:
682 return (*MapType)(unsafe.Pointer(v))
683 case *runtime.PtrType:
684 return (*PtrType)(unsafe.Pointer(v))
685 case *runtime.SliceType:
686 return (*SliceType)(unsafe.Pointer(v))
687 case *runtime.StructType:
688 return (*StructType)(unsafe.Pointer(v))
694 // Convert pointer to runtime Type structure to our Type structure.
695 func runtimeToType(v *runtime.Type) Type {
697 switch Kind(v.Kind) {
699 r = (*BoolType)(unsafe.Pointer(v))
700 case Int, Int8, Int16, Int32, Int64:
701 r = (*IntType)(unsafe.Pointer(v))
702 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
703 r = (*UintType)(unsafe.Pointer(v))
704 case Float32, Float64:
705 r = (*FloatType)(unsafe.Pointer(v))
706 case Complex64, Complex128:
707 r = (*ComplexType)(unsafe.Pointer(v))
709 r = (*ArrayType)(unsafe.Pointer(v))
711 r = (*ChanType)(unsafe.Pointer(v))
713 r = (*FuncType)(unsafe.Pointer(v))
715 r = (*InterfaceType)(unsafe.Pointer(v))
717 r = (*MapType)(unsafe.Pointer(v))
719 r = (*PtrType)(unsafe.Pointer(v))
721 r = (*SliceType)(unsafe.Pointer(v))
723 r = (*StringType)(unsafe.Pointer(v))
725 r = (*StructType)(unsafe.Pointer(v))
727 r = (*UnsafePointerType)(unsafe.Pointer(v))
729 panic("runtimeToType")
731 return canonicalize(r)
732 panic("runtimeToType")
735 // ArrayOrSliceType is the common interface implemented
736 // by both ArrayType and SliceType.
737 type ArrayOrSliceType interface {
742 // Typeof returns the reflection Type of the value in the interface{}.
743 func Typeof(i interface{}) Type { return canonicalize(toType(unsafe.Typeof(i))) }