rsc.io/go@v0.0.0-20150416155037-e040fd465409/src/reflect/type.go (about)

     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  //
    14  // See "The Laws of Reflection" for an introduction to reflection in Go:
    15  // http://golang.org/doc/articles/laws_of_reflection.html
    16  package reflect
    17  
    18  import (
    19  	"runtime"
    20  	"strconv"
    21  	"sync"
    22  	"unsafe"
    23  )
    24  
    25  // Type is the representation of a Go type.
    26  //
    27  // Not all methods apply to all kinds of types.  Restrictions,
    28  // if any, are noted in the documentation for each method.
    29  // Use the Kind method to find out the kind of type before
    30  // calling kind-specific methods.  Calling a method
    31  // inappropriate to the kind of type causes a run-time panic.
    32  type Type interface {
    33  	// Methods applicable to all types.
    34  
    35  	// Align returns the alignment in bytes of a value of
    36  	// this type when allocated in memory.
    37  	Align() int
    38  
    39  	// FieldAlign returns the alignment in bytes of a value of
    40  	// this type when used as a field in a struct.
    41  	FieldAlign() int
    42  
    43  	// Method returns the i'th method in the type's method set.
    44  	// It panics if i is not in the range [0, NumMethod()).
    45  	//
    46  	// For a non-interface type T or *T, the returned Method's Type and Func
    47  	// fields describe a function whose first argument is the receiver.
    48  	//
    49  	// For an interface type, the returned Method's Type field gives the
    50  	// method signature, without a receiver, and the Func field is nil.
    51  	Method(int) Method
    52  
    53  	// MethodByName returns the method with that name in the type's
    54  	// method set and a boolean indicating if the method was found.
    55  	//
    56  	// For a non-interface type T or *T, the returned Method's Type and Func
    57  	// fields describe a function whose first argument is the receiver.
    58  	//
    59  	// For an interface type, the returned Method's Type field gives the
    60  	// method signature, without a receiver, and the Func field is nil.
    61  	MethodByName(string) (Method, bool)
    62  
    63  	// NumMethod returns the number of methods in the type's method set.
    64  	NumMethod() int
    65  
    66  	// Name returns the type's name within its package.
    67  	// It returns an empty string for unnamed types.
    68  	Name() string
    69  
    70  	// PkgPath returns a named type's package path, that is, the import path
    71  	// that uniquely identifies the package, such as "encoding/base64".
    72  	// If the type was predeclared (string, error) or unnamed (*T, struct{}, []int),
    73  	// the package path will be the empty string.
    74  	PkgPath() string
    75  
    76  	// Size returns the number of bytes needed to store
    77  	// a value of the given type; it is analogous to unsafe.Sizeof.
    78  	Size() uintptr
    79  
    80  	// String returns a string representation of the type.
    81  	// The string representation may use shortened package names
    82  	// (e.g., base64 instead of "encoding/base64") and is not
    83  	// guaranteed to be unique among types.  To test for equality,
    84  	// compare the Types directly.
    85  	String() string
    86  
    87  	// Kind returns the specific kind of this type.
    88  	Kind() Kind
    89  
    90  	// Implements reports whether the type implements the interface type u.
    91  	Implements(u Type) bool
    92  
    93  	// AssignableTo reports whether a value of the type is assignable to type u.
    94  	AssignableTo(u Type) bool
    95  
    96  	// ConvertibleTo reports whether a value of the type is convertible to type u.
    97  	ConvertibleTo(u Type) bool
    98  
    99  	// Comparable reports whether values of this type are comparable.
   100  	Comparable() bool
   101  
   102  	// Methods applicable only to some types, depending on Kind.
   103  	// The methods allowed for each kind are:
   104  	//
   105  	//	Int*, Uint*, Float*, Complex*: Bits
   106  	//	Array: Elem, Len
   107  	//	Chan: ChanDir, Elem
   108  	//	Func: In, NumIn, Out, NumOut, IsVariadic.
   109  	//	Map: Key, Elem
   110  	//	Ptr: Elem
   111  	//	Slice: Elem
   112  	//	Struct: Field, FieldByIndex, FieldByName, FieldByNameFunc, NumField
   113  
   114  	// Bits returns the size of the type in bits.
   115  	// It panics if the type's Kind is not one of the
   116  	// sized or unsized Int, Uint, Float, or Complex kinds.
   117  	Bits() int
   118  
   119  	// ChanDir returns a channel type's direction.
   120  	// It panics if the type's Kind is not Chan.
   121  	ChanDir() ChanDir
   122  
   123  	// IsVariadic reports whether a function type's final input parameter
   124  	// is a "..." parameter.  If so, t.In(t.NumIn() - 1) returns the parameter's
   125  	// implicit actual type []T.
   126  	//
   127  	// For concreteness, if t represents func(x int, y ... float64), then
   128  	//
   129  	//	t.NumIn() == 2
   130  	//	t.In(0) is the reflect.Type for "int"
   131  	//	t.In(1) is the reflect.Type for "[]float64"
   132  	//	t.IsVariadic() == true
   133  	//
   134  	// IsVariadic panics if the type's Kind is not Func.
   135  	IsVariadic() bool
   136  
   137  	// Elem returns a type's element type.
   138  	// It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
   139  	Elem() Type
   140  
   141  	// Field returns a struct type's i'th field.
   142  	// It panics if the type's Kind is not Struct.
   143  	// It panics if i is not in the range [0, NumField()).
   144  	Field(i int) StructField
   145  
   146  	// FieldByIndex returns the nested field corresponding
   147  	// to the index sequence.  It is equivalent to calling Field
   148  	// successively for each index i.
   149  	// It panics if the type's Kind is not Struct.
   150  	FieldByIndex(index []int) StructField
   151  
   152  	// FieldByName returns the struct field with the given name
   153  	// and a boolean indicating if the field was found.
   154  	FieldByName(name string) (StructField, bool)
   155  
   156  	// FieldByNameFunc returns the first struct field with a name
   157  	// that satisfies the match function and a boolean indicating if
   158  	// the field was found.
   159  	FieldByNameFunc(match func(string) bool) (StructField, bool)
   160  
   161  	// In returns the type of a function type's i'th input parameter.
   162  	// It panics if the type's Kind is not Func.
   163  	// It panics if i is not in the range [0, NumIn()).
   164  	In(i int) Type
   165  
   166  	// Key returns a map type's key type.
   167  	// It panics if the type's Kind is not Map.
   168  	Key() Type
   169  
   170  	// Len returns an array type's length.
   171  	// It panics if the type's Kind is not Array.
   172  	Len() int
   173  
   174  	// NumField returns a struct type's field count.
   175  	// It panics if the type's Kind is not Struct.
   176  	NumField() int
   177  
   178  	// NumIn returns a function type's input parameter count.
   179  	// It panics if the type's Kind is not Func.
   180  	NumIn() int
   181  
   182  	// NumOut returns a function type's output parameter count.
   183  	// It panics if the type's Kind is not Func.
   184  	NumOut() int
   185  
   186  	// Out returns the type of a function type's i'th output parameter.
   187  	// It panics if the type's Kind is not Func.
   188  	// It panics if i is not in the range [0, NumOut()).
   189  	Out(i int) Type
   190  
   191  	common() *rtype
   192  	uncommon() *uncommonType
   193  }
   194  
   195  // BUG(rsc): FieldByName and related functions consider struct field names to be equal
   196  // if the names are equal, even if they are unexported names originating
   197  // in different packages. The practical effect of this is that the result of
   198  // t.FieldByName("x") is not well defined if the struct type t contains
   199  // multiple fields named x (embedded from different packages).
   200  // FieldByName may return one of the fields named x or may report that there are none.
   201  // See golang.org/issue/4876 for more details.
   202  
   203  /*
   204   * These data structures are known to the compiler (../../cmd/internal/gc/reflect.go).
   205   * A few are known to ../runtime/type.go to convey to debuggers.
   206   * They are also known to ../runtime/type.go.
   207   */
   208  
   209  // A Kind represents the specific kind of type that a Type represents.
   210  // The zero Kind is not a valid kind.
   211  type Kind uint
   212  
   213  const (
   214  	Invalid Kind = iota
   215  	Bool
   216  	Int
   217  	Int8
   218  	Int16
   219  	Int32
   220  	Int64
   221  	Uint
   222  	Uint8
   223  	Uint16
   224  	Uint32
   225  	Uint64
   226  	Uintptr
   227  	Float32
   228  	Float64
   229  	Complex64
   230  	Complex128
   231  	Array
   232  	Chan
   233  	Func
   234  	Interface
   235  	Map
   236  	Ptr
   237  	Slice
   238  	String
   239  	Struct
   240  	UnsafePointer
   241  )
   242  
   243  // rtype is the common implementation of most values.
   244  // It is embedded in other, public struct types, but always
   245  // with a unique tag like `reflect:"array"` or `reflect:"ptr"`
   246  // so that code cannot convert from, say, *arrayType to *ptrType.
   247  type rtype struct {
   248  	size          uintptr
   249  	hash          uint32            // hash of type; avoids computation in hash tables
   250  	_             uint8             // unused/padding
   251  	align         uint8             // alignment of variable with this type
   252  	fieldAlign    uint8             // alignment of struct field with this type
   253  	kind          uint8             // enumeration for C
   254  	alg           *typeAlg          // algorithm table
   255  	gc            [2]unsafe.Pointer // garbage collection data
   256  	string        *string           // string form; unnecessary but undeniably useful
   257  	*uncommonType                   // (relatively) uncommon fields
   258  	ptrToThis     *rtype            // type for pointer to this type, if used in binary or has methods
   259  	zero          unsafe.Pointer    // pointer to zero value
   260  }
   261  
   262  // a copy of runtime.typeAlg
   263  type typeAlg struct {
   264  	// function for hashing objects of this type
   265  	// (ptr to object, size, seed) -> hash
   266  	hash func(unsafe.Pointer, uintptr, uintptr) uintptr
   267  	// function for comparing objects of this type
   268  	// (ptr to object A, ptr to object B, size) -> ==?
   269  	equal func(unsafe.Pointer, unsafe.Pointer, uintptr) bool
   270  }
   271  
   272  // Method on non-interface type
   273  type method struct {
   274  	name    *string        // name of method
   275  	pkgPath *string        // nil for exported Names; otherwise import path
   276  	mtyp    *rtype         // method type (without receiver)
   277  	typ     *rtype         // .(*FuncType) underneath (with receiver)
   278  	ifn     unsafe.Pointer // fn used in interface call (one-word receiver)
   279  	tfn     unsafe.Pointer // fn used for normal method call
   280  }
   281  
   282  // uncommonType is present only for types with names or methods
   283  // (if T is a named type, the uncommonTypes for T and *T have methods).
   284  // Using a pointer to this struct reduces the overall size required
   285  // to describe an unnamed type with no methods.
   286  type uncommonType struct {
   287  	name    *string  // name of type
   288  	pkgPath *string  // import path; nil for built-in types like int, string
   289  	methods []method // methods associated with type
   290  }
   291  
   292  // ChanDir represents a channel type's direction.
   293  type ChanDir int
   294  
   295  const (
   296  	RecvDir ChanDir             = 1 << iota // <-chan
   297  	SendDir                                 // chan<-
   298  	BothDir = RecvDir | SendDir             // chan
   299  )
   300  
   301  // arrayType represents a fixed array type.
   302  type arrayType struct {
   303  	rtype `reflect:"array"`
   304  	elem  *rtype // array element type
   305  	slice *rtype // slice type
   306  	len   uintptr
   307  }
   308  
   309  // chanType represents a channel type.
   310  type chanType struct {
   311  	rtype `reflect:"chan"`
   312  	elem  *rtype  // channel element type
   313  	dir   uintptr // channel direction (ChanDir)
   314  }
   315  
   316  // funcType represents a function type.
   317  type funcType struct {
   318  	rtype     `reflect:"func"`
   319  	dotdotdot bool     // last input parameter is ...
   320  	in        []*rtype // input parameter types
   321  	out       []*rtype // output parameter types
   322  }
   323  
   324  // imethod represents a method on an interface type
   325  type imethod struct {
   326  	name    *string // name of method
   327  	pkgPath *string // nil for exported Names; otherwise import path
   328  	typ     *rtype  // .(*FuncType) underneath
   329  }
   330  
   331  // interfaceType represents an interface type.
   332  type interfaceType struct {
   333  	rtype   `reflect:"interface"`
   334  	methods []imethod // sorted by hash
   335  }
   336  
   337  // mapType represents a map type.
   338  type mapType struct {
   339  	rtype         `reflect:"map"`
   340  	key           *rtype // map key type
   341  	elem          *rtype // map element (value) type
   342  	bucket        *rtype // internal bucket structure
   343  	hmap          *rtype // internal map header
   344  	keysize       uint8  // size of key slot
   345  	indirectkey   uint8  // store ptr to key instead of key itself
   346  	valuesize     uint8  // size of value slot
   347  	indirectvalue uint8  // store ptr to value instead of value itself
   348  	bucketsize    uint16 // size of bucket
   349  	reflexivekey  bool   // true if k==k for all keys
   350  }
   351  
   352  // ptrType represents a pointer type.
   353  type ptrType struct {
   354  	rtype `reflect:"ptr"`
   355  	elem  *rtype // pointer element (pointed at) type
   356  }
   357  
   358  // sliceType represents a slice type.
   359  type sliceType struct {
   360  	rtype `reflect:"slice"`
   361  	elem  *rtype // slice element type
   362  }
   363  
   364  // Struct field
   365  type structField struct {
   366  	name    *string // nil for embedded fields
   367  	pkgPath *string // nil for exported Names; otherwise import path
   368  	typ     *rtype  // type of field
   369  	tag     *string // nil if no tag
   370  	offset  uintptr // byte offset of field within struct
   371  }
   372  
   373  // structType represents a struct type.
   374  type structType struct {
   375  	rtype  `reflect:"struct"`
   376  	fields []structField // sorted by offset
   377  }
   378  
   379  /*
   380   * The compiler knows the exact layout of all the data structures above.
   381   * The compiler does not know about the data structures and methods below.
   382   */
   383  
   384  // Method represents a single method.
   385  type Method struct {
   386  	// Name is the method name.
   387  	// PkgPath is the package path that qualifies a lower case (unexported)
   388  	// method name.  It is empty for upper case (exported) method names.
   389  	// The combination of PkgPath and Name uniquely identifies a method
   390  	// in a method set.
   391  	// See http://golang.org/ref/spec#Uniqueness_of_identifiers
   392  	Name    string
   393  	PkgPath string
   394  
   395  	Type  Type  // method type
   396  	Func  Value // func with receiver as first argument
   397  	Index int   // index for Type.Method
   398  }
   399  
   400  const (
   401  	kindDirectIface = 1 << 5
   402  	kindGCProg      = 1 << 6 // Type.gc points to GC program
   403  	kindNoPointers  = 1 << 7
   404  	kindMask        = (1 << 5) - 1
   405  )
   406  
   407  func (k Kind) String() string {
   408  	if int(k) < len(kindNames) {
   409  		return kindNames[k]
   410  	}
   411  	return "kind" + strconv.Itoa(int(k))
   412  }
   413  
   414  var kindNames = []string{
   415  	Invalid:       "invalid",
   416  	Bool:          "bool",
   417  	Int:           "int",
   418  	Int8:          "int8",
   419  	Int16:         "int16",
   420  	Int32:         "int32",
   421  	Int64:         "int64",
   422  	Uint:          "uint",
   423  	Uint8:         "uint8",
   424  	Uint16:        "uint16",
   425  	Uint32:        "uint32",
   426  	Uint64:        "uint64",
   427  	Uintptr:       "uintptr",
   428  	Float32:       "float32",
   429  	Float64:       "float64",
   430  	Complex64:     "complex64",
   431  	Complex128:    "complex128",
   432  	Array:         "array",
   433  	Chan:          "chan",
   434  	Func:          "func",
   435  	Interface:     "interface",
   436  	Map:           "map",
   437  	Ptr:           "ptr",
   438  	Slice:         "slice",
   439  	String:        "string",
   440  	Struct:        "struct",
   441  	UnsafePointer: "unsafe.Pointer",
   442  }
   443  
   444  func (t *uncommonType) uncommon() *uncommonType {
   445  	return t
   446  }
   447  
   448  func (t *uncommonType) PkgPath() string {
   449  	if t == nil || t.pkgPath == nil {
   450  		return ""
   451  	}
   452  	return *t.pkgPath
   453  }
   454  
   455  func (t *uncommonType) Name() string {
   456  	if t == nil || t.name == nil {
   457  		return ""
   458  	}
   459  	return *t.name
   460  }
   461  
   462  func (t *rtype) String() string { return *t.string }
   463  
   464  func (t *rtype) Size() uintptr { return t.size }
   465  
   466  func (t *rtype) Bits() int {
   467  	if t == nil {
   468  		panic("reflect: Bits of nil Type")
   469  	}
   470  	k := t.Kind()
   471  	if k < Int || k > Complex128 {
   472  		panic("reflect: Bits of non-arithmetic Type " + t.String())
   473  	}
   474  	return int(t.size) * 8
   475  }
   476  
   477  func (t *rtype) Align() int { return int(t.align) }
   478  
   479  func (t *rtype) FieldAlign() int { return int(t.fieldAlign) }
   480  
   481  func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }
   482  
   483  func (t *rtype) pointers() bool { return t.kind&kindNoPointers == 0 }
   484  
   485  func (t *rtype) common() *rtype { return t }
   486  
   487  func (t *uncommonType) Method(i int) (m Method) {
   488  	if t == nil || i < 0 || i >= len(t.methods) {
   489  		panic("reflect: Method index out of range")
   490  	}
   491  	p := &t.methods[i]
   492  	if p.name != nil {
   493  		m.Name = *p.name
   494  	}
   495  	fl := flag(Func)
   496  	if p.pkgPath != nil {
   497  		m.PkgPath = *p.pkgPath
   498  		fl |= flagRO
   499  	}
   500  	mt := p.typ
   501  	m.Type = mt
   502  	fn := unsafe.Pointer(&p.tfn)
   503  	m.Func = Value{mt, fn, fl}
   504  	m.Index = i
   505  	return
   506  }
   507  
   508  func (t *uncommonType) NumMethod() int {
   509  	if t == nil {
   510  		return 0
   511  	}
   512  	return len(t.methods)
   513  }
   514  
   515  func (t *uncommonType) MethodByName(name string) (m Method, ok bool) {
   516  	if t == nil {
   517  		return
   518  	}
   519  	var p *method
   520  	for i := range t.methods {
   521  		p = &t.methods[i]
   522  		if p.name != nil && *p.name == name {
   523  			return t.Method(i), true
   524  		}
   525  	}
   526  	return
   527  }
   528  
   529  // TODO(rsc): 6g supplies these, but they are not
   530  // as efficient as they could be: they have commonType
   531  // as the receiver instead of *rtype.
   532  func (t *rtype) NumMethod() int {
   533  	if t.Kind() == Interface {
   534  		tt := (*interfaceType)(unsafe.Pointer(t))
   535  		return tt.NumMethod()
   536  	}
   537  	return t.uncommonType.NumMethod()
   538  }
   539  
   540  func (t *rtype) Method(i int) (m Method) {
   541  	if t.Kind() == Interface {
   542  		tt := (*interfaceType)(unsafe.Pointer(t))
   543  		return tt.Method(i)
   544  	}
   545  	return t.uncommonType.Method(i)
   546  }
   547  
   548  func (t *rtype) MethodByName(name string) (m Method, ok bool) {
   549  	if t.Kind() == Interface {
   550  		tt := (*interfaceType)(unsafe.Pointer(t))
   551  		return tt.MethodByName(name)
   552  	}
   553  	return t.uncommonType.MethodByName(name)
   554  }
   555  
   556  func (t *rtype) PkgPath() string {
   557  	return t.uncommonType.PkgPath()
   558  }
   559  
   560  func (t *rtype) Name() string {
   561  	return t.uncommonType.Name()
   562  }
   563  
   564  func (t *rtype) ChanDir() ChanDir {
   565  	if t.Kind() != Chan {
   566  		panic("reflect: ChanDir of non-chan type")
   567  	}
   568  	tt := (*chanType)(unsafe.Pointer(t))
   569  	return ChanDir(tt.dir)
   570  }
   571  
   572  func (t *rtype) IsVariadic() bool {
   573  	if t.Kind() != Func {
   574  		panic("reflect: IsVariadic of non-func type")
   575  	}
   576  	tt := (*funcType)(unsafe.Pointer(t))
   577  	return tt.dotdotdot
   578  }
   579  
   580  func (t *rtype) Elem() Type {
   581  	switch t.Kind() {
   582  	case Array:
   583  		tt := (*arrayType)(unsafe.Pointer(t))
   584  		return toType(tt.elem)
   585  	case Chan:
   586  		tt := (*chanType)(unsafe.Pointer(t))
   587  		return toType(tt.elem)
   588  	case Map:
   589  		tt := (*mapType)(unsafe.Pointer(t))
   590  		return toType(tt.elem)
   591  	case Ptr:
   592  		tt := (*ptrType)(unsafe.Pointer(t))
   593  		return toType(tt.elem)
   594  	case Slice:
   595  		tt := (*sliceType)(unsafe.Pointer(t))
   596  		return toType(tt.elem)
   597  	}
   598  	panic("reflect: Elem of invalid type")
   599  }
   600  
   601  func (t *rtype) Field(i int) StructField {
   602  	if t.Kind() != Struct {
   603  		panic("reflect: Field of non-struct type")
   604  	}
   605  	tt := (*structType)(unsafe.Pointer(t))
   606  	return tt.Field(i)
   607  }
   608  
   609  func (t *rtype) FieldByIndex(index []int) StructField {
   610  	if t.Kind() != Struct {
   611  		panic("reflect: FieldByIndex of non-struct type")
   612  	}
   613  	tt := (*structType)(unsafe.Pointer(t))
   614  	return tt.FieldByIndex(index)
   615  }
   616  
   617  func (t *rtype) FieldByName(name string) (StructField, bool) {
   618  	if t.Kind() != Struct {
   619  		panic("reflect: FieldByName of non-struct type")
   620  	}
   621  	tt := (*structType)(unsafe.Pointer(t))
   622  	return tt.FieldByName(name)
   623  }
   624  
   625  func (t *rtype) FieldByNameFunc(match func(string) bool) (StructField, bool) {
   626  	if t.Kind() != Struct {
   627  		panic("reflect: FieldByNameFunc of non-struct type")
   628  	}
   629  	tt := (*structType)(unsafe.Pointer(t))
   630  	return tt.FieldByNameFunc(match)
   631  }
   632  
   633  func (t *rtype) In(i int) Type {
   634  	if t.Kind() != Func {
   635  		panic("reflect: In of non-func type")
   636  	}
   637  	tt := (*funcType)(unsafe.Pointer(t))
   638  	return toType(tt.in[i])
   639  }
   640  
   641  func (t *rtype) Key() Type {
   642  	if t.Kind() != Map {
   643  		panic("reflect: Key of non-map type")
   644  	}
   645  	tt := (*mapType)(unsafe.Pointer(t))
   646  	return toType(tt.key)
   647  }
   648  
   649  func (t *rtype) Len() int {
   650  	if t.Kind() != Array {
   651  		panic("reflect: Len of non-array type")
   652  	}
   653  	tt := (*arrayType)(unsafe.Pointer(t))
   654  	return int(tt.len)
   655  }
   656  
   657  func (t *rtype) NumField() int {
   658  	if t.Kind() != Struct {
   659  		panic("reflect: NumField of non-struct type")
   660  	}
   661  	tt := (*structType)(unsafe.Pointer(t))
   662  	return len(tt.fields)
   663  }
   664  
   665  func (t *rtype) NumIn() int {
   666  	if t.Kind() != Func {
   667  		panic("reflect: NumIn of non-func type")
   668  	}
   669  	tt := (*funcType)(unsafe.Pointer(t))
   670  	return len(tt.in)
   671  }
   672  
   673  func (t *rtype) NumOut() int {
   674  	if t.Kind() != Func {
   675  		panic("reflect: NumOut of non-func type")
   676  	}
   677  	tt := (*funcType)(unsafe.Pointer(t))
   678  	return len(tt.out)
   679  }
   680  
   681  func (t *rtype) Out(i int) Type {
   682  	if t.Kind() != Func {
   683  		panic("reflect: Out of non-func type")
   684  	}
   685  	tt := (*funcType)(unsafe.Pointer(t))
   686  	return toType(tt.out[i])
   687  }
   688  
   689  func (d ChanDir) String() string {
   690  	switch d {
   691  	case SendDir:
   692  		return "chan<-"
   693  	case RecvDir:
   694  		return "<-chan"
   695  	case BothDir:
   696  		return "chan"
   697  	}
   698  	return "ChanDir" + strconv.Itoa(int(d))
   699  }
   700  
   701  // Method returns the i'th method in the type's method set.
   702  func (t *interfaceType) Method(i int) (m Method) {
   703  	if i < 0 || i >= len(t.methods) {
   704  		return
   705  	}
   706  	p := &t.methods[i]
   707  	m.Name = *p.name
   708  	if p.pkgPath != nil {
   709  		m.PkgPath = *p.pkgPath
   710  	}
   711  	m.Type = toType(p.typ)
   712  	m.Index = i
   713  	return
   714  }
   715  
   716  // NumMethod returns the number of interface methods in the type's method set.
   717  func (t *interfaceType) NumMethod() int { return len(t.methods) }
   718  
   719  // MethodByName method with the given name in the type's method set.
   720  func (t *interfaceType) MethodByName(name string) (m Method, ok bool) {
   721  	if t == nil {
   722  		return
   723  	}
   724  	var p *imethod
   725  	for i := range t.methods {
   726  		p = &t.methods[i]
   727  		if *p.name == name {
   728  			return t.Method(i), true
   729  		}
   730  	}
   731  	return
   732  }
   733  
   734  // A StructField describes a single field in a struct.
   735  type StructField struct {
   736  	// Name is the field name.
   737  	// PkgPath is the package path that qualifies a lower case (unexported)
   738  	// field name.  It is empty for upper case (exported) field names.
   739  	// See http://golang.org/ref/spec#Uniqueness_of_identifiers
   740  	Name    string
   741  	PkgPath string
   742  
   743  	Type      Type      // field type
   744  	Tag       StructTag // field tag string
   745  	Offset    uintptr   // offset within struct, in bytes
   746  	Index     []int     // index sequence for Type.FieldByIndex
   747  	Anonymous bool      // is an embedded field
   748  }
   749  
   750  // A StructTag is the tag string in a struct field.
   751  //
   752  // By convention, tag strings are a concatenation of
   753  // optionally space-separated key:"value" pairs.
   754  // Each key is a non-empty string consisting of non-control
   755  // characters other than space (U+0020 ' '), quote (U+0022 '"'),
   756  // and colon (U+003A ':').  Each value is quoted using U+0022 '"'
   757  // characters and Go string literal syntax.
   758  type StructTag string
   759  
   760  // Get returns the value associated with key in the tag string.
   761  // If there is no such key in the tag, Get returns the empty string.
   762  // If the tag does not have the conventional format, the value
   763  // returned by Get is unspecified.
   764  func (tag StructTag) Get(key string) string {
   765  	// When modifying this code, also update the validateStructTag code
   766  	// in golang.org/x/tools/cmd/vet/structtag.go.
   767  
   768  	for tag != "" {
   769  		// Skip leading space.
   770  		i := 0
   771  		for i < len(tag) && tag[i] == ' ' {
   772  			i++
   773  		}
   774  		tag = tag[i:]
   775  		if tag == "" {
   776  			break
   777  		}
   778  
   779  		// Scan to colon. A space, a quote or a control character is a syntax error.
   780  		// Strictly speaking, control chars include the range [0x7f, 0x9f], not just
   781  		// [0x00, 0x1f], but in practice, we ignore the multi-byte control characters
   782  		// as it is simpler to inspect the tag's bytes than the tag's runes.
   783  		i = 0
   784  		for i < len(tag) && tag[i] > ' ' && tag[i] != ':' && tag[i] != '"' && tag[i] != 0x7f {
   785  			i++
   786  		}
   787  		if i == 0 || i+1 >= len(tag) || tag[i] != ':' || tag[i+1] != '"' {
   788  			break
   789  		}
   790  		name := string(tag[:i])
   791  		tag = tag[i+1:]
   792  
   793  		// Scan quoted string to find value.
   794  		i = 1
   795  		for i < len(tag) && tag[i] != '"' {
   796  			if tag[i] == '\\' {
   797  				i++
   798  			}
   799  			i++
   800  		}
   801  		if i >= len(tag) {
   802  			break
   803  		}
   804  		qvalue := string(tag[:i+1])
   805  		tag = tag[i+1:]
   806  
   807  		if key == name {
   808  			value, err := strconv.Unquote(qvalue)
   809  			if err != nil {
   810  				break
   811  			}
   812  			return value
   813  		}
   814  	}
   815  	return ""
   816  }
   817  
   818  // Field returns the i'th struct field.
   819  func (t *structType) Field(i int) (f StructField) {
   820  	if i < 0 || i >= len(t.fields) {
   821  		return
   822  	}
   823  	p := &t.fields[i]
   824  	f.Type = toType(p.typ)
   825  	if p.name != nil {
   826  		f.Name = *p.name
   827  	} else {
   828  		t := f.Type
   829  		if t.Kind() == Ptr {
   830  			t = t.Elem()
   831  		}
   832  		f.Name = t.Name()
   833  		f.Anonymous = true
   834  	}
   835  	if p.pkgPath != nil {
   836  		f.PkgPath = *p.pkgPath
   837  	}
   838  	if p.tag != nil {
   839  		f.Tag = StructTag(*p.tag)
   840  	}
   841  	f.Offset = p.offset
   842  
   843  	// NOTE(rsc): This is the only allocation in the interface
   844  	// presented by a reflect.Type.  It would be nice to avoid,
   845  	// at least in the common cases, but we need to make sure
   846  	// that misbehaving clients of reflect cannot affect other
   847  	// uses of reflect.  One possibility is CL 5371098, but we
   848  	// postponed that ugliness until there is a demonstrated
   849  	// need for the performance.  This is issue 2320.
   850  	f.Index = []int{i}
   851  	return
   852  }
   853  
   854  // TODO(gri): Should there be an error/bool indicator if the index
   855  //            is wrong for FieldByIndex?
   856  
   857  // FieldByIndex returns the nested field corresponding to index.
   858  func (t *structType) FieldByIndex(index []int) (f StructField) {
   859  	f.Type = toType(&t.rtype)
   860  	for i, x := range index {
   861  		if i > 0 {
   862  			ft := f.Type
   863  			if ft.Kind() == Ptr && ft.Elem().Kind() == Struct {
   864  				ft = ft.Elem()
   865  			}
   866  			f.Type = ft
   867  		}
   868  		f = f.Type.Field(x)
   869  	}
   870  	return
   871  }
   872  
   873  // A fieldScan represents an item on the fieldByNameFunc scan work list.
   874  type fieldScan struct {
   875  	typ   *structType
   876  	index []int
   877  }
   878  
   879  // FieldByNameFunc returns the struct field with a name that satisfies the
   880  // match function and a boolean to indicate if the field was found.
   881  func (t *structType) FieldByNameFunc(match func(string) bool) (result StructField, ok bool) {
   882  	// This uses the same condition that the Go language does: there must be a unique instance
   883  	// of the match at a given depth level. If there are multiple instances of a match at the
   884  	// same depth, they annihilate each other and inhibit any possible match at a lower level.
   885  	// The algorithm is breadth first search, one depth level at a time.
   886  
   887  	// The current and next slices are work queues:
   888  	// current lists the fields to visit on this depth level,
   889  	// and next lists the fields on the next lower level.
   890  	current := []fieldScan{}
   891  	next := []fieldScan{{typ: t}}
   892  
   893  	// nextCount records the number of times an embedded type has been
   894  	// encountered and considered for queueing in the 'next' slice.
   895  	// We only queue the first one, but we increment the count on each.
   896  	// If a struct type T can be reached more than once at a given depth level,
   897  	// then it annihilates itself and need not be considered at all when we
   898  	// process that next depth level.
   899  	var nextCount map[*structType]int
   900  
   901  	// visited records the structs that have been considered already.
   902  	// Embedded pointer fields can create cycles in the graph of
   903  	// reachable embedded types; visited avoids following those cycles.
   904  	// It also avoids duplicated effort: if we didn't find the field in an
   905  	// embedded type T at level 2, we won't find it in one at level 4 either.
   906  	visited := map[*structType]bool{}
   907  
   908  	for len(next) > 0 {
   909  		current, next = next, current[:0]
   910  		count := nextCount
   911  		nextCount = nil
   912  
   913  		// Process all the fields at this depth, now listed in 'current'.
   914  		// The loop queues embedded fields found in 'next', for processing during the next
   915  		// iteration. The multiplicity of the 'current' field counts is recorded
   916  		// in 'count'; the multiplicity of the 'next' field counts is recorded in 'nextCount'.
   917  		for _, scan := range current {
   918  			t := scan.typ
   919  			if visited[t] {
   920  				// We've looked through this type before, at a higher level.
   921  				// That higher level would shadow the lower level we're now at,
   922  				// so this one can't be useful to us. Ignore it.
   923  				continue
   924  			}
   925  			visited[t] = true
   926  			for i := range t.fields {
   927  				f := &t.fields[i]
   928  				// Find name and type for field f.
   929  				var fname string
   930  				var ntyp *rtype
   931  				if f.name != nil {
   932  					fname = *f.name
   933  				} else {
   934  					// Anonymous field of type T or *T.
   935  					// Name taken from type.
   936  					ntyp = f.typ
   937  					if ntyp.Kind() == Ptr {
   938  						ntyp = ntyp.Elem().common()
   939  					}
   940  					fname = ntyp.Name()
   941  				}
   942  
   943  				// Does it match?
   944  				if match(fname) {
   945  					// Potential match
   946  					if count[t] > 1 || ok {
   947  						// Name appeared multiple times at this level: annihilate.
   948  						return StructField{}, false
   949  					}
   950  					result = t.Field(i)
   951  					result.Index = nil
   952  					result.Index = append(result.Index, scan.index...)
   953  					result.Index = append(result.Index, i)
   954  					ok = true
   955  					continue
   956  				}
   957  
   958  				// Queue embedded struct fields for processing with next level,
   959  				// but only if we haven't seen a match yet at this level and only
   960  				// if the embedded types haven't already been queued.
   961  				if ok || ntyp == nil || ntyp.Kind() != Struct {
   962  					continue
   963  				}
   964  				styp := (*structType)(unsafe.Pointer(ntyp))
   965  				if nextCount[styp] > 0 {
   966  					nextCount[styp] = 2 // exact multiple doesn't matter
   967  					continue
   968  				}
   969  				if nextCount == nil {
   970  					nextCount = map[*structType]int{}
   971  				}
   972  				nextCount[styp] = 1
   973  				if count[t] > 1 {
   974  					nextCount[styp] = 2 // exact multiple doesn't matter
   975  				}
   976  				var index []int
   977  				index = append(index, scan.index...)
   978  				index = append(index, i)
   979  				next = append(next, fieldScan{styp, index})
   980  			}
   981  		}
   982  		if ok {
   983  			break
   984  		}
   985  	}
   986  	return
   987  }
   988  
   989  // FieldByName returns the struct field with the given name
   990  // and a boolean to indicate if the field was found.
   991  func (t *structType) FieldByName(name string) (f StructField, present bool) {
   992  	// Quick check for top-level name, or struct without anonymous fields.
   993  	hasAnon := false
   994  	if name != "" {
   995  		for i := range t.fields {
   996  			tf := &t.fields[i]
   997  			if tf.name == nil {
   998  				hasAnon = true
   999  				continue
  1000  			}
  1001  			if *tf.name == name {
  1002  				return t.Field(i), true
  1003  			}
  1004  		}
  1005  	}
  1006  	if !hasAnon {
  1007  		return
  1008  	}
  1009  	return t.FieldByNameFunc(func(s string) bool { return s == name })
  1010  }
  1011  
  1012  // TypeOf returns the reflection Type that represents the dynamic type of i.
  1013  // If i is a nil interface value, TypeOf returns nil.
  1014  func TypeOf(i interface{}) Type {
  1015  	eface := *(*emptyInterface)(unsafe.Pointer(&i))
  1016  	return toType(eface.typ)
  1017  }
  1018  
  1019  // ptrMap is the cache for PtrTo.
  1020  var ptrMap struct {
  1021  	sync.RWMutex
  1022  	m map[*rtype]*ptrType
  1023  }
  1024  
  1025  // PtrTo returns the pointer type with element t.
  1026  // For example, if t represents type Foo, PtrTo(t) represents *Foo.
  1027  func PtrTo(t Type) Type {
  1028  	return t.(*rtype).ptrTo()
  1029  }
  1030  
  1031  func (t *rtype) ptrTo() *rtype {
  1032  	if p := t.ptrToThis; p != nil {
  1033  		return p
  1034  	}
  1035  
  1036  	// Otherwise, synthesize one.
  1037  	// This only happens for pointers with no methods.
  1038  	// We keep the mapping in a map on the side, because
  1039  	// this operation is rare and a separate map lets us keep
  1040  	// the type structures in read-only memory.
  1041  	ptrMap.RLock()
  1042  	if m := ptrMap.m; m != nil {
  1043  		if p := m[t]; p != nil {
  1044  			ptrMap.RUnlock()
  1045  			return &p.rtype
  1046  		}
  1047  	}
  1048  	ptrMap.RUnlock()
  1049  	ptrMap.Lock()
  1050  	if ptrMap.m == nil {
  1051  		ptrMap.m = make(map[*rtype]*ptrType)
  1052  	}
  1053  	p := ptrMap.m[t]
  1054  	if p != nil {
  1055  		// some other goroutine won the race and created it
  1056  		ptrMap.Unlock()
  1057  		return &p.rtype
  1058  	}
  1059  
  1060  	// Create a new ptrType starting with the description
  1061  	// of an *unsafe.Pointer.
  1062  	p = new(ptrType)
  1063  	var iptr interface{} = (*unsafe.Pointer)(nil)
  1064  	prototype := *(**ptrType)(unsafe.Pointer(&iptr))
  1065  	*p = *prototype
  1066  
  1067  	s := "*" + *t.string
  1068  	p.string = &s
  1069  
  1070  	// For the type structures linked into the binary, the
  1071  	// compiler provides a good hash of the string.
  1072  	// Create a good hash for the new string by using
  1073  	// the FNV-1 hash's mixing function to combine the
  1074  	// old hash and the new "*".
  1075  	p.hash = fnv1(t.hash, '*')
  1076  
  1077  	p.uncommonType = nil
  1078  	p.ptrToThis = nil
  1079  	p.zero = unsafe.Pointer(&make([]byte, p.size)[0])
  1080  	p.elem = t
  1081  
  1082  	ptrMap.m[t] = p
  1083  	ptrMap.Unlock()
  1084  	return &p.rtype
  1085  }
  1086  
  1087  // fnv1 incorporates the list of bytes into the hash x using the FNV-1 hash function.
  1088  func fnv1(x uint32, list ...byte) uint32 {
  1089  	for _, b := range list {
  1090  		x = x*16777619 ^ uint32(b)
  1091  	}
  1092  	return x
  1093  }
  1094  
  1095  func (t *rtype) Implements(u Type) bool {
  1096  	if u == nil {
  1097  		panic("reflect: nil type passed to Type.Implements")
  1098  	}
  1099  	if u.Kind() != Interface {
  1100  		panic("reflect: non-interface type passed to Type.Implements")
  1101  	}
  1102  	return implements(u.(*rtype), t)
  1103  }
  1104  
  1105  func (t *rtype) AssignableTo(u Type) bool {
  1106  	if u == nil {
  1107  		panic("reflect: nil type passed to Type.AssignableTo")
  1108  	}
  1109  	uu := u.(*rtype)
  1110  	return directlyAssignable(uu, t) || implements(uu, t)
  1111  }
  1112  
  1113  func (t *rtype) ConvertibleTo(u Type) bool {
  1114  	if u == nil {
  1115  		panic("reflect: nil type passed to Type.ConvertibleTo")
  1116  	}
  1117  	uu := u.(*rtype)
  1118  	return convertOp(uu, t) != nil
  1119  }
  1120  
  1121  func (t *rtype) Comparable() bool {
  1122  	return t.alg != nil && t.alg.equal != nil
  1123  }
  1124  
  1125  // implements reports whether the type V implements the interface type T.
  1126  func implements(T, V *rtype) bool {
  1127  	if T.Kind() != Interface {
  1128  		return false
  1129  	}
  1130  	t := (*interfaceType)(unsafe.Pointer(T))
  1131  	if len(t.methods) == 0 {
  1132  		return true
  1133  	}
  1134  
  1135  	// The same algorithm applies in both cases, but the
  1136  	// method tables for an interface type and a concrete type
  1137  	// are different, so the code is duplicated.
  1138  	// In both cases the algorithm is a linear scan over the two
  1139  	// lists - T's methods and V's methods - simultaneously.
  1140  	// Since method tables are stored in a unique sorted order
  1141  	// (alphabetical, with no duplicate method names), the scan
  1142  	// through V's methods must hit a match for each of T's
  1143  	// methods along the way, or else V does not implement T.
  1144  	// This lets us run the scan in overall linear time instead of
  1145  	// the quadratic time  a naive search would require.
  1146  	// See also ../runtime/iface.go.
  1147  	if V.Kind() == Interface {
  1148  		v := (*interfaceType)(unsafe.Pointer(V))
  1149  		i := 0
  1150  		for j := 0; j < len(v.methods); j++ {
  1151  			tm := &t.methods[i]
  1152  			vm := &v.methods[j]
  1153  			if *vm.name == *tm.name && vm.pkgPath == tm.pkgPath && vm.typ == tm.typ {
  1154  				if i++; i >= len(t.methods) {
  1155  					return true
  1156  				}
  1157  			}
  1158  		}
  1159  		return false
  1160  	}
  1161  
  1162  	v := V.uncommon()
  1163  	if v == nil {
  1164  		return false
  1165  	}
  1166  	i := 0
  1167  	for j := 0; j < len(v.methods); j++ {
  1168  		tm := &t.methods[i]
  1169  		vm := &v.methods[j]
  1170  		if *vm.name == *tm.name && vm.pkgPath == tm.pkgPath && vm.mtyp == tm.typ {
  1171  			if i++; i >= len(t.methods) {
  1172  				return true
  1173  			}
  1174  		}
  1175  	}
  1176  	return false
  1177  }
  1178  
  1179  // directlyAssignable reports whether a value x of type V can be directly
  1180  // assigned (using memmove) to a value of type T.
  1181  // http://golang.org/doc/go_spec.html#Assignability
  1182  // Ignoring the interface rules (implemented elsewhere)
  1183  // and the ideal constant rules (no ideal constants at run time).
  1184  func directlyAssignable(T, V *rtype) bool {
  1185  	// x's type V is identical to T?
  1186  	if T == V {
  1187  		return true
  1188  	}
  1189  
  1190  	// Otherwise at least one of T and V must be unnamed
  1191  	// and they must have the same kind.
  1192  	if T.Name() != "" && V.Name() != "" || T.Kind() != V.Kind() {
  1193  		return false
  1194  	}
  1195  
  1196  	// x's type T and V must  have identical underlying types.
  1197  	return haveIdenticalUnderlyingType(T, V)
  1198  }
  1199  
  1200  func haveIdenticalUnderlyingType(T, V *rtype) bool {
  1201  	if T == V {
  1202  		return true
  1203  	}
  1204  
  1205  	kind := T.Kind()
  1206  	if kind != V.Kind() {
  1207  		return false
  1208  	}
  1209  
  1210  	// Non-composite types of equal kind have same underlying type
  1211  	// (the predefined instance of the type).
  1212  	if Bool <= kind && kind <= Complex128 || kind == String || kind == UnsafePointer {
  1213  		return true
  1214  	}
  1215  
  1216  	// Composite types.
  1217  	switch kind {
  1218  	case Array:
  1219  		return T.Elem() == V.Elem() && T.Len() == V.Len()
  1220  
  1221  	case Chan:
  1222  		// Special case:
  1223  		// x is a bidirectional channel value, T is a channel type,
  1224  		// and x's type V and T have identical element types.
  1225  		if V.ChanDir() == BothDir && T.Elem() == V.Elem() {
  1226  			return true
  1227  		}
  1228  
  1229  		// Otherwise continue test for identical underlying type.
  1230  		return V.ChanDir() == T.ChanDir() && T.Elem() == V.Elem()
  1231  
  1232  	case Func:
  1233  		t := (*funcType)(unsafe.Pointer(T))
  1234  		v := (*funcType)(unsafe.Pointer(V))
  1235  		if t.dotdotdot != v.dotdotdot || len(t.in) != len(v.in) || len(t.out) != len(v.out) {
  1236  			return false
  1237  		}
  1238  		for i, typ := range t.in {
  1239  			if typ != v.in[i] {
  1240  				return false
  1241  			}
  1242  		}
  1243  		for i, typ := range t.out {
  1244  			if typ != v.out[i] {
  1245  				return false
  1246  			}
  1247  		}
  1248  		return true
  1249  
  1250  	case Interface:
  1251  		t := (*interfaceType)(unsafe.Pointer(T))
  1252  		v := (*interfaceType)(unsafe.Pointer(V))
  1253  		if len(t.methods) == 0 && len(v.methods) == 0 {
  1254  			return true
  1255  		}
  1256  		// Might have the same methods but still
  1257  		// need a run time conversion.
  1258  		return false
  1259  
  1260  	case Map:
  1261  		return T.Key() == V.Key() && T.Elem() == V.Elem()
  1262  
  1263  	case Ptr, Slice:
  1264  		return T.Elem() == V.Elem()
  1265  
  1266  	case Struct:
  1267  		t := (*structType)(unsafe.Pointer(T))
  1268  		v := (*structType)(unsafe.Pointer(V))
  1269  		if len(t.fields) != len(v.fields) {
  1270  			return false
  1271  		}
  1272  		for i := range t.fields {
  1273  			tf := &t.fields[i]
  1274  			vf := &v.fields[i]
  1275  			if tf.name != vf.name && (tf.name == nil || vf.name == nil || *tf.name != *vf.name) {
  1276  				return false
  1277  			}
  1278  			if tf.pkgPath != vf.pkgPath && (tf.pkgPath == nil || vf.pkgPath == nil || *tf.pkgPath != *vf.pkgPath) {
  1279  				return false
  1280  			}
  1281  			if tf.typ != vf.typ {
  1282  				return false
  1283  			}
  1284  			if tf.tag != vf.tag && (tf.tag == nil || vf.tag == nil || *tf.tag != *vf.tag) {
  1285  				return false
  1286  			}
  1287  			if tf.offset != vf.offset {
  1288  				return false
  1289  			}
  1290  		}
  1291  		return true
  1292  	}
  1293  
  1294  	return false
  1295  }
  1296  
  1297  // typelinks is implemented in package runtime.
  1298  // It returns a slice of all the 'typelink' information in the binary,
  1299  // which is to say a slice of known types, sorted by string.
  1300  // Note that strings are not unique identifiers for types:
  1301  // there can be more than one with a given string.
  1302  // Only types we might want to look up are included:
  1303  // channels, maps, slices, and arrays.
  1304  func typelinks() [][]*rtype
  1305  
  1306  // typesByString returns the subslice of typelinks() whose elements have
  1307  // the given string representation.
  1308  // It may be empty (no known types with that string) or may have
  1309  // multiple elements (multiple types with that string).
  1310  func typesByString(s string) []*rtype {
  1311  	typs := typelinks()
  1312  	var ret []*rtype
  1313  
  1314  	for _, typ := range typs {
  1315  		// We are looking for the first index i where the string becomes >= s.
  1316  		// This is a copy of sort.Search, with f(h) replaced by (*typ[h].string >= s).
  1317  		i, j := 0, len(typ)
  1318  		for i < j {
  1319  			h := i + (j-i)/2 // avoid overflow when computing h
  1320  			// i ≤ h < j
  1321  			if !(*typ[h].string >= s) {
  1322  				i = h + 1 // preserves f(i-1) == false
  1323  			} else {
  1324  				j = h // preserves f(j) == true
  1325  			}
  1326  		}
  1327  		// i == j, f(i-1) == false, and f(j) (= f(i)) == true  =>  answer is i.
  1328  
  1329  		// Having found the first, linear scan forward to find the last.
  1330  		// We could do a second binary search, but the caller is going
  1331  		// to do a linear scan anyway.
  1332  		j = i
  1333  		for j < len(typ) && *typ[j].string == s {
  1334  			j++
  1335  		}
  1336  
  1337  		if j > i {
  1338  			if ret == nil {
  1339  				ret = typ[i:j:j]
  1340  			} else {
  1341  				ret = append(ret, typ[i:j]...)
  1342  			}
  1343  		}
  1344  	}
  1345  	return ret
  1346  }
  1347  
  1348  // The lookupCache caches ChanOf, MapOf, and SliceOf lookups.
  1349  var lookupCache struct {
  1350  	sync.RWMutex
  1351  	m map[cacheKey]*rtype
  1352  }
  1353  
  1354  // A cacheKey is the key for use in the lookupCache.
  1355  // Four values describe any of the types we are looking for:
  1356  // type kind, one or two subtypes, and an extra integer.
  1357  type cacheKey struct {
  1358  	kind  Kind
  1359  	t1    *rtype
  1360  	t2    *rtype
  1361  	extra uintptr
  1362  }
  1363  
  1364  // cacheGet looks for a type under the key k in the lookupCache.
  1365  // If it finds one, it returns that type.
  1366  // If not, it returns nil with the cache locked.
  1367  // The caller is expected to use cachePut to unlock the cache.
  1368  func cacheGet(k cacheKey) Type {
  1369  	lookupCache.RLock()
  1370  	t := lookupCache.m[k]
  1371  	lookupCache.RUnlock()
  1372  	if t != nil {
  1373  		return t
  1374  	}
  1375  
  1376  	lookupCache.Lock()
  1377  	t = lookupCache.m[k]
  1378  	if t != nil {
  1379  		lookupCache.Unlock()
  1380  		return t
  1381  	}
  1382  
  1383  	if lookupCache.m == nil {
  1384  		lookupCache.m = make(map[cacheKey]*rtype)
  1385  	}
  1386  
  1387  	return nil
  1388  }
  1389  
  1390  // cachePut stores the given type in the cache, unlocks the cache,
  1391  // and returns the type. It is expected that the cache is locked
  1392  // because cacheGet returned nil.
  1393  func cachePut(k cacheKey, t *rtype) Type {
  1394  	lookupCache.m[k] = t
  1395  	lookupCache.Unlock()
  1396  	return t
  1397  }
  1398  
  1399  // The funcLookupCache caches FuncOf lookups.
  1400  // FuncOf does not share the common lookupCache since cacheKey is not
  1401  // sufficient to represent functions unambiguously.
  1402  var funcLookupCache struct {
  1403  	sync.RWMutex
  1404  	m map[uint32][]*rtype // keyed by hash calculated in FuncOf
  1405  }
  1406  
  1407  // ChanOf returns the channel type with the given direction and element type.
  1408  // For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int.
  1409  //
  1410  // The gc runtime imposes a limit of 64 kB on channel element types.
  1411  // If t's size is equal to or exceeds this limit, ChanOf panics.
  1412  func ChanOf(dir ChanDir, t Type) Type {
  1413  	typ := t.(*rtype)
  1414  
  1415  	// Look in cache.
  1416  	ckey := cacheKey{Chan, typ, nil, uintptr(dir)}
  1417  	if ch := cacheGet(ckey); ch != nil {
  1418  		return ch
  1419  	}
  1420  
  1421  	// This restriction is imposed by the gc compiler and the runtime.
  1422  	if typ.size >= 1<<16 {
  1423  		lookupCache.Unlock()
  1424  		panic("reflect.ChanOf: element size too large")
  1425  	}
  1426  
  1427  	// Look in known types.
  1428  	// TODO: Precedence when constructing string.
  1429  	var s string
  1430  	switch dir {
  1431  	default:
  1432  		lookupCache.Unlock()
  1433  		panic("reflect.ChanOf: invalid dir")
  1434  	case SendDir:
  1435  		s = "chan<- " + *typ.string
  1436  	case RecvDir:
  1437  		s = "<-chan " + *typ.string
  1438  	case BothDir:
  1439  		s = "chan " + *typ.string
  1440  	}
  1441  	for _, tt := range typesByString(s) {
  1442  		ch := (*chanType)(unsafe.Pointer(tt))
  1443  		if ch.elem == typ && ch.dir == uintptr(dir) {
  1444  			return cachePut(ckey, tt)
  1445  		}
  1446  	}
  1447  
  1448  	// Make a channel type.
  1449  	var ichan interface{} = (chan unsafe.Pointer)(nil)
  1450  	prototype := *(**chanType)(unsafe.Pointer(&ichan))
  1451  	ch := new(chanType)
  1452  	*ch = *prototype
  1453  	ch.dir = uintptr(dir)
  1454  	ch.string = &s
  1455  	ch.hash = fnv1(typ.hash, 'c', byte(dir))
  1456  	ch.elem = typ
  1457  	ch.uncommonType = nil
  1458  	ch.ptrToThis = nil
  1459  	ch.zero = unsafe.Pointer(&make([]byte, ch.size)[0])
  1460  
  1461  	return cachePut(ckey, &ch.rtype)
  1462  }
  1463  
  1464  func ismapkey(*rtype) bool // implemented in runtime
  1465  
  1466  // MapOf returns the map type with the given key and element types.
  1467  // For example, if k represents int and e represents string,
  1468  // MapOf(k, e) represents map[int]string.
  1469  //
  1470  // If the key type is not a valid map key type (that is, if it does
  1471  // not implement Go's == operator), MapOf panics.
  1472  func MapOf(key, elem Type) Type {
  1473  	ktyp := key.(*rtype)
  1474  	etyp := elem.(*rtype)
  1475  
  1476  	if !ismapkey(ktyp) {
  1477  		panic("reflect.MapOf: invalid key type " + ktyp.String())
  1478  	}
  1479  
  1480  	// Look in cache.
  1481  	ckey := cacheKey{Map, ktyp, etyp, 0}
  1482  	if mt := cacheGet(ckey); mt != nil {
  1483  		return mt
  1484  	}
  1485  
  1486  	// Look in known types.
  1487  	s := "map[" + *ktyp.string + "]" + *etyp.string
  1488  	for _, tt := range typesByString(s) {
  1489  		mt := (*mapType)(unsafe.Pointer(tt))
  1490  		if mt.key == ktyp && mt.elem == etyp {
  1491  			return cachePut(ckey, tt)
  1492  		}
  1493  	}
  1494  
  1495  	// Make a map type.
  1496  	var imap interface{} = (map[unsafe.Pointer]unsafe.Pointer)(nil)
  1497  	mt := new(mapType)
  1498  	*mt = **(**mapType)(unsafe.Pointer(&imap))
  1499  	mt.string = &s
  1500  	mt.hash = fnv1(etyp.hash, 'm', byte(ktyp.hash>>24), byte(ktyp.hash>>16), byte(ktyp.hash>>8), byte(ktyp.hash))
  1501  	mt.key = ktyp
  1502  	mt.elem = etyp
  1503  	mt.bucket = bucketOf(ktyp, etyp)
  1504  	if ktyp.size > maxKeySize {
  1505  		mt.keysize = uint8(ptrSize)
  1506  		mt.indirectkey = 1
  1507  	} else {
  1508  		mt.keysize = uint8(ktyp.size)
  1509  		mt.indirectkey = 0
  1510  	}
  1511  	if etyp.size > maxValSize {
  1512  		mt.valuesize = uint8(ptrSize)
  1513  		mt.indirectvalue = 1
  1514  	} else {
  1515  		mt.valuesize = uint8(etyp.size)
  1516  		mt.indirectvalue = 0
  1517  	}
  1518  	mt.bucketsize = uint16(mt.bucket.size)
  1519  	mt.reflexivekey = isReflexive(ktyp)
  1520  	mt.uncommonType = nil
  1521  	mt.ptrToThis = nil
  1522  	mt.zero = unsafe.Pointer(&make([]byte, mt.size)[0])
  1523  
  1524  	return cachePut(ckey, &mt.rtype)
  1525  }
  1526  
  1527  // FuncOf returns the function type with the given argument and result types.
  1528  // For example if k represents int and e represents string,
  1529  // FuncOf([]Type{k}, []Type{e}, false) represents func(int) string.
  1530  //
  1531  // The variadic argument controls whether the function is variadic. FuncOf
  1532  // panics if the in[len(in)-1] does not represent a slice and variadic is
  1533  // true.
  1534  func FuncOf(in, out []Type, variadic bool) Type {
  1535  	if variadic && (len(in) == 0 || in[len(in)-1].Kind() != Slice) {
  1536  		panic("reflect.FuncOf: last arg of variadic func must be slice")
  1537  	}
  1538  
  1539  	// Make a func type.
  1540  	var ifunc interface{} = (func())(nil)
  1541  	prototype := *(**funcType)(unsafe.Pointer(&ifunc))
  1542  	ft := new(funcType)
  1543  	*ft = *prototype
  1544  
  1545  	// Build a hash and minimally populate ft.
  1546  	var hash uint32
  1547  	var fin, fout []*rtype
  1548  	for _, in := range in {
  1549  		t := in.(*rtype)
  1550  		fin = append(fin, t)
  1551  		hash = fnv1(hash, byte(t.hash>>24), byte(t.hash>>16), byte(t.hash>>8), byte(t.hash))
  1552  	}
  1553  	if variadic {
  1554  		hash = fnv1(hash, 'v')
  1555  	}
  1556  	hash = fnv1(hash, '.')
  1557  	for _, out := range out {
  1558  		t := out.(*rtype)
  1559  		fout = append(fout, t)
  1560  		hash = fnv1(hash, byte(t.hash>>24), byte(t.hash>>16), byte(t.hash>>8), byte(t.hash))
  1561  	}
  1562  	ft.hash = hash
  1563  	ft.in = fin
  1564  	ft.out = fout
  1565  	ft.dotdotdot = variadic
  1566  
  1567  	// Look in cache.
  1568  	funcLookupCache.RLock()
  1569  	for _, t := range funcLookupCache.m[hash] {
  1570  		if haveIdenticalUnderlyingType(&ft.rtype, t) {
  1571  			funcLookupCache.RUnlock()
  1572  			return t
  1573  		}
  1574  	}
  1575  	funcLookupCache.RUnlock()
  1576  
  1577  	// Not in cache, lock and retry.
  1578  	funcLookupCache.Lock()
  1579  	defer funcLookupCache.Unlock()
  1580  	if funcLookupCache.m == nil {
  1581  		funcLookupCache.m = make(map[uint32][]*rtype)
  1582  	}
  1583  	for _, t := range funcLookupCache.m[hash] {
  1584  		if haveIdenticalUnderlyingType(&ft.rtype, t) {
  1585  			return t
  1586  		}
  1587  	}
  1588  
  1589  	// Look in known types for the same string representation.
  1590  	str := funcStr(ft)
  1591  	for _, tt := range typesByString(str) {
  1592  		if haveIdenticalUnderlyingType(&ft.rtype, tt) {
  1593  			funcLookupCache.m[hash] = append(funcLookupCache.m[hash], tt)
  1594  			return tt
  1595  		}
  1596  	}
  1597  
  1598  	// Populate the remaining fields of ft and store in cache.
  1599  	ft.string = &str
  1600  	ft.uncommonType = nil
  1601  	ft.ptrToThis = nil
  1602  	ft.zero = unsafe.Pointer(&make([]byte, ft.size)[0])
  1603  	funcLookupCache.m[hash] = append(funcLookupCache.m[hash], &ft.rtype)
  1604  
  1605  	return ft
  1606  }
  1607  
  1608  // funcStr builds a string representation of a funcType.
  1609  func funcStr(ft *funcType) string {
  1610  	repr := make([]byte, 0, 64)
  1611  	repr = append(repr, "func("...)
  1612  	for i, t := range ft.in {
  1613  		if i > 0 {
  1614  			repr = append(repr, ", "...)
  1615  		}
  1616  		if ft.dotdotdot && i == len(ft.in)-1 {
  1617  			repr = append(repr, "..."...)
  1618  			repr = append(repr, *(*sliceType)(unsafe.Pointer(t)).elem.string...)
  1619  		} else {
  1620  			repr = append(repr, *t.string...)
  1621  		}
  1622  	}
  1623  	repr = append(repr, ')')
  1624  	if l := len(ft.out); l == 1 {
  1625  		repr = append(repr, ' ')
  1626  	} else if l > 1 {
  1627  		repr = append(repr, " ("...)
  1628  	}
  1629  	for i, t := range ft.out {
  1630  		if i > 0 {
  1631  			repr = append(repr, ", "...)
  1632  		}
  1633  		repr = append(repr, *t.string...)
  1634  	}
  1635  	if len(ft.out) > 1 {
  1636  		repr = append(repr, ')')
  1637  	}
  1638  	return string(repr)
  1639  }
  1640  
  1641  // isReflexive reports whether the == operation on the type is reflexive.
  1642  // That is, x == x for all values x of type t.
  1643  func isReflexive(t *rtype) bool {
  1644  	switch t.Kind() {
  1645  	case Bool, Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr, Chan, Ptr, String, UnsafePointer:
  1646  		return true
  1647  	case Float32, Float64, Complex64, Complex128, Interface:
  1648  		return false
  1649  	case Array:
  1650  		tt := (*arrayType)(unsafe.Pointer(t))
  1651  		return isReflexive(tt.elem)
  1652  	case Struct:
  1653  		tt := (*structType)(unsafe.Pointer(t))
  1654  		for _, f := range tt.fields {
  1655  			if !isReflexive(f.typ) {
  1656  				return false
  1657  			}
  1658  		}
  1659  		return true
  1660  	default:
  1661  		// Func, Map, Slice, Invalid
  1662  		panic("isReflexive called on non-key type " + t.String())
  1663  	}
  1664  }
  1665  
  1666  // gcProg is a helper type for generatation of GC pointer info.
  1667  type gcProg struct {
  1668  	gc       []byte
  1669  	size     uintptr // size of type in bytes
  1670  	hasPtr   bool
  1671  	lastZero uintptr // largest offset of a zero-byte field
  1672  }
  1673  
  1674  func (gc *gcProg) append(v byte) {
  1675  	gc.align(unsafe.Sizeof(uintptr(0)))
  1676  	gc.appendWord(v)
  1677  }
  1678  
  1679  // Appends t's type info to the current program.
  1680  func (gc *gcProg) appendProg(t *rtype) {
  1681  	gc.align(uintptr(t.align))
  1682  	if !t.pointers() {
  1683  		gc.size += t.size
  1684  		if t.size == 0 {
  1685  			gc.lastZero = gc.size
  1686  		}
  1687  		return
  1688  	}
  1689  	switch t.Kind() {
  1690  	default:
  1691  		panic("reflect: non-pointer type marked as having pointers")
  1692  	case Ptr, UnsafePointer, Chan, Func, Map:
  1693  		gc.appendWord(bitsPointer)
  1694  	case Slice:
  1695  		gc.appendWord(bitsPointer)
  1696  		gc.appendWord(bitsScalar)
  1697  		gc.appendWord(bitsScalar)
  1698  	case String:
  1699  		gc.appendWord(bitsPointer)
  1700  		gc.appendWord(bitsScalar)
  1701  	case Array:
  1702  		c := t.Len()
  1703  		e := t.Elem().common()
  1704  		for i := 0; i < c; i++ {
  1705  			gc.appendProg(e)
  1706  		}
  1707  	case Interface:
  1708  		gc.appendWord(bitsPointer)
  1709  		gc.appendWord(bitsPointer)
  1710  	case Struct:
  1711  		oldsize := gc.size
  1712  		c := t.NumField()
  1713  		for i := 0; i < c; i++ {
  1714  			gc.appendProg(t.Field(i).Type.common())
  1715  		}
  1716  		if gc.size > oldsize+t.size {
  1717  			panic("reflect: struct components are larger than the struct itself")
  1718  		}
  1719  		gc.size = oldsize + t.size
  1720  	}
  1721  }
  1722  
  1723  func (gc *gcProg) appendWord(v byte) {
  1724  	ptrsize := unsafe.Sizeof(uintptr(0))
  1725  	if gc.size%ptrsize != 0 {
  1726  		panic("reflect: unaligned GC program")
  1727  	}
  1728  	nptr := gc.size / ptrsize
  1729  	for uintptr(len(gc.gc)) < nptr/2+1 {
  1730  		gc.gc = append(gc.gc, 0x44) // BitsScalar
  1731  	}
  1732  	gc.gc[nptr/2] &= ^(3 << ((nptr%2)*4 + 2))
  1733  	gc.gc[nptr/2] |= v << ((nptr%2)*4 + 2)
  1734  	gc.size += ptrsize
  1735  	if v == bitsPointer {
  1736  		gc.hasPtr = true
  1737  	}
  1738  }
  1739  
  1740  func (gc *gcProg) finalize() (unsafe.Pointer, bool) {
  1741  	if gc.size == 0 {
  1742  		return nil, false
  1743  	}
  1744  	if gc.lastZero == gc.size {
  1745  		gc.size++
  1746  	}
  1747  	ptrsize := unsafe.Sizeof(uintptr(0))
  1748  	gc.align(ptrsize)
  1749  	nptr := gc.size / ptrsize
  1750  	for uintptr(len(gc.gc)) < nptr/2+1 {
  1751  		gc.gc = append(gc.gc, 0x44) // BitsScalar
  1752  	}
  1753  	// If number of words is odd, repeat the mask twice.
  1754  	// Compiler does the same.
  1755  	if nptr%2 != 0 {
  1756  		for i := uintptr(0); i < nptr; i++ {
  1757  			gc.appendWord(extractGCWord(gc.gc, i))
  1758  		}
  1759  	}
  1760  	return unsafe.Pointer(&gc.gc[0]), gc.hasPtr
  1761  }
  1762  
  1763  func extractGCWord(gc []byte, i uintptr) byte {
  1764  	return (gc[i/2] >> ((i%2)*4 + 2)) & 3
  1765  }
  1766  
  1767  func (gc *gcProg) align(a uintptr) {
  1768  	gc.size = align(gc.size, a)
  1769  }
  1770  
  1771  // These constants must stay in sync with ../runtime/mbitmap.go.
  1772  const (
  1773  	bitsScalar  = 1
  1774  	bitsPointer = 2
  1775  )
  1776  
  1777  // Make sure these routines stay in sync with ../../runtime/hashmap.go!
  1778  // These types exist only for GC, so we only fill out GC relevant info.
  1779  // Currently, that's just size and the GC program.  We also fill in string
  1780  // for possible debugging use.
  1781  const (
  1782  	bucketSize = 8
  1783  	maxKeySize = 128
  1784  	maxValSize = 128
  1785  )
  1786  
  1787  func bucketOf(ktyp, etyp *rtype) *rtype {
  1788  	// See comment on hmap.overflow in ../runtime/hashmap.go.
  1789  	var kind uint8
  1790  	if ktyp.kind&kindNoPointers != 0 && etyp.kind&kindNoPointers != 0 &&
  1791  		ktyp.size <= maxKeySize && etyp.size <= maxValSize {
  1792  		kind = kindNoPointers
  1793  	}
  1794  
  1795  	if ktyp.size > maxKeySize {
  1796  		ktyp = PtrTo(ktyp).(*rtype)
  1797  	}
  1798  	if etyp.size > maxValSize {
  1799  		etyp = PtrTo(etyp).(*rtype)
  1800  	}
  1801  	ptrsize := unsafe.Sizeof(uintptr(0))
  1802  
  1803  	var gc gcProg
  1804  	// topbits
  1805  	for i := 0; i < int(bucketSize*unsafe.Sizeof(uint8(0))/ptrsize); i++ {
  1806  		gc.append(bitsScalar)
  1807  	}
  1808  	// keys
  1809  	for i := 0; i < bucketSize; i++ {
  1810  		gc.appendProg(ktyp)
  1811  	}
  1812  	// values
  1813  	for i := 0; i < bucketSize; i++ {
  1814  		gc.appendProg(etyp)
  1815  	}
  1816  	// overflow
  1817  	gc.append(bitsPointer)
  1818  	if runtime.GOARCH == "amd64p32" {
  1819  		gc.append(bitsScalar)
  1820  	}
  1821  
  1822  	b := new(rtype)
  1823  	b.size = gc.size
  1824  	b.kind = kind
  1825  	b.gc[0], _ = gc.finalize()
  1826  	s := "bucket(" + *ktyp.string + "," + *etyp.string + ")"
  1827  	b.string = &s
  1828  	return b
  1829  }
  1830  
  1831  // SliceOf returns the slice type with element type t.
  1832  // For example, if t represents int, SliceOf(t) represents []int.
  1833  func SliceOf(t Type) Type {
  1834  	typ := t.(*rtype)
  1835  
  1836  	// Look in cache.
  1837  	ckey := cacheKey{Slice, typ, nil, 0}
  1838  	if slice := cacheGet(ckey); slice != nil {
  1839  		return slice
  1840  	}
  1841  
  1842  	// Look in known types.
  1843  	s := "[]" + *typ.string
  1844  	for _, tt := range typesByString(s) {
  1845  		slice := (*sliceType)(unsafe.Pointer(tt))
  1846  		if slice.elem == typ {
  1847  			return cachePut(ckey, tt)
  1848  		}
  1849  	}
  1850  
  1851  	// Make a slice type.
  1852  	var islice interface{} = ([]unsafe.Pointer)(nil)
  1853  	prototype := *(**sliceType)(unsafe.Pointer(&islice))
  1854  	slice := new(sliceType)
  1855  	*slice = *prototype
  1856  	slice.string = &s
  1857  	slice.hash = fnv1(typ.hash, '[')
  1858  	slice.elem = typ
  1859  	slice.uncommonType = nil
  1860  	slice.ptrToThis = nil
  1861  	slice.zero = unsafe.Pointer(&make([]byte, slice.size)[0])
  1862  
  1863  	return cachePut(ckey, &slice.rtype)
  1864  }
  1865  
  1866  // ArrayOf returns the array type with the given count and element type.
  1867  // For example, if t represents int, ArrayOf(5, t) represents [5]int.
  1868  //
  1869  // If the resulting type would be larger than the available address space,
  1870  // ArrayOf panics.
  1871  //
  1872  // TODO(rsc): Unexported for now. Export once the alg field is set correctly
  1873  // for the type. This may require significant work.
  1874  //
  1875  // TODO(rsc): TestArrayOf is also disabled. Re-enable.
  1876  func arrayOf(count int, elem Type) Type {
  1877  	typ := elem.(*rtype)
  1878  	slice := SliceOf(elem)
  1879  
  1880  	// Look in cache.
  1881  	ckey := cacheKey{Array, typ, nil, uintptr(count)}
  1882  	if slice := cacheGet(ckey); slice != nil {
  1883  		return slice
  1884  	}
  1885  
  1886  	// Look in known types.
  1887  	s := "[" + strconv.Itoa(count) + "]" + *typ.string
  1888  	for _, tt := range typesByString(s) {
  1889  		slice := (*sliceType)(unsafe.Pointer(tt))
  1890  		if slice.elem == typ {
  1891  			return cachePut(ckey, tt)
  1892  		}
  1893  	}
  1894  
  1895  	// Make an array type.
  1896  	var iarray interface{} = [1]unsafe.Pointer{}
  1897  	prototype := *(**arrayType)(unsafe.Pointer(&iarray))
  1898  	array := new(arrayType)
  1899  	*array = *prototype
  1900  	// TODO: Set extra kind bits correctly.
  1901  	array.string = &s
  1902  	array.hash = fnv1(typ.hash, '[')
  1903  	for n := uint32(count); n > 0; n >>= 8 {
  1904  		array.hash = fnv1(array.hash, byte(n))
  1905  	}
  1906  	array.hash = fnv1(array.hash, ']')
  1907  	array.elem = typ
  1908  	max := ^uintptr(0) / typ.size
  1909  	if uintptr(count) > max {
  1910  		panic("reflect.ArrayOf: array size would exceed virtual address space")
  1911  	}
  1912  	array.size = typ.size * uintptr(count)
  1913  	array.align = typ.align
  1914  	array.fieldAlign = typ.fieldAlign
  1915  	// TODO: array.alg
  1916  	// TODO: array.gc
  1917  	// TODO:
  1918  	array.uncommonType = nil
  1919  	array.ptrToThis = nil
  1920  	array.zero = unsafe.Pointer(&make([]byte, array.size)[0])
  1921  	array.len = uintptr(count)
  1922  	array.slice = slice.(*rtype)
  1923  
  1924  	return cachePut(ckey, &array.rtype)
  1925  }
  1926  
  1927  // toType converts from a *rtype to a Type that can be returned
  1928  // to the client of package reflect. In gc, the only concern is that
  1929  // a nil *rtype must be replaced by a nil Type, but in gccgo this
  1930  // function takes care of ensuring that multiple *rtype for the same
  1931  // type are coalesced into a single Type.
  1932  func toType(t *rtype) Type {
  1933  	if t == nil {
  1934  		return nil
  1935  	}
  1936  	return t
  1937  }
  1938  
  1939  type layoutKey struct {
  1940  	t    *rtype // function signature
  1941  	rcvr *rtype // receiver type, or nil if none
  1942  }
  1943  
  1944  type layoutType struct {
  1945  	t         *rtype
  1946  	argSize   uintptr // size of arguments
  1947  	retOffset uintptr // offset of return values.
  1948  	stack     *bitVector
  1949  	framePool *sync.Pool
  1950  }
  1951  
  1952  var layoutCache struct {
  1953  	sync.RWMutex
  1954  	m map[layoutKey]layoutType
  1955  }
  1956  
  1957  // funcLayout computes a struct type representing the layout of the
  1958  // function arguments and return values for the function type t.
  1959  // If rcvr != nil, rcvr specifies the type of the receiver.
  1960  // The returned type exists only for GC, so we only fill out GC relevant info.
  1961  // Currently, that's just size and the GC program.  We also fill in
  1962  // the name for possible debugging use.
  1963  func funcLayout(t *rtype, rcvr *rtype) (frametype *rtype, argSize, retOffset uintptr, stack *bitVector, framePool *sync.Pool) {
  1964  	if t.Kind() != Func {
  1965  		panic("reflect: funcLayout of non-func type")
  1966  	}
  1967  	if rcvr != nil && rcvr.Kind() == Interface {
  1968  		panic("reflect: funcLayout with interface receiver " + rcvr.String())
  1969  	}
  1970  	k := layoutKey{t, rcvr}
  1971  	layoutCache.RLock()
  1972  	if x := layoutCache.m[k]; x.t != nil {
  1973  		layoutCache.RUnlock()
  1974  		return x.t, x.argSize, x.retOffset, x.stack, x.framePool
  1975  	}
  1976  	layoutCache.RUnlock()
  1977  	layoutCache.Lock()
  1978  	if x := layoutCache.m[k]; x.t != nil {
  1979  		layoutCache.Unlock()
  1980  		return x.t, x.argSize, x.retOffset, x.stack, x.framePool
  1981  	}
  1982  
  1983  	tt := (*funcType)(unsafe.Pointer(t))
  1984  
  1985  	// compute gc program & stack bitmap for arguments
  1986  	stack = new(bitVector)
  1987  	var gc gcProg
  1988  	var offset uintptr
  1989  	if rcvr != nil {
  1990  		// Reflect uses the "interface" calling convention for
  1991  		// methods, where receivers take one word of argument
  1992  		// space no matter how big they actually are.
  1993  		if ifaceIndir(rcvr) {
  1994  			// we pass a pointer to the receiver.
  1995  			gc.append(bitsPointer)
  1996  			stack.append2(bitsPointer)
  1997  		} else if rcvr.pointers() {
  1998  			// rcvr is a one-word pointer object.  Its gc program
  1999  			// is just what we need here.
  2000  			gc.append(bitsPointer)
  2001  			stack.append2(bitsPointer)
  2002  		} else {
  2003  			gc.append(bitsScalar)
  2004  			stack.append2(bitsScalar)
  2005  		}
  2006  		offset += ptrSize
  2007  	}
  2008  	for _, arg := range tt.in {
  2009  		gc.appendProg(arg)
  2010  		addTypeBits(stack, &offset, arg)
  2011  	}
  2012  	argSize = gc.size
  2013  	if runtime.GOARCH == "amd64p32" {
  2014  		gc.align(8)
  2015  	}
  2016  	gc.align(ptrSize)
  2017  	retOffset = gc.size
  2018  	for _, res := range tt.out {
  2019  		gc.appendProg(res)
  2020  		// stack map does not need result bits
  2021  	}
  2022  	gc.align(ptrSize)
  2023  
  2024  	// build dummy rtype holding gc program
  2025  	x := new(rtype)
  2026  	x.size = gc.size
  2027  	var hasPtr bool
  2028  	x.gc[0], hasPtr = gc.finalize()
  2029  	if !hasPtr {
  2030  		x.kind |= kindNoPointers
  2031  	}
  2032  	var s string
  2033  	if rcvr != nil {
  2034  		s = "methodargs(" + *rcvr.string + ")(" + *t.string + ")"
  2035  	} else {
  2036  		s = "funcargs(" + *t.string + ")"
  2037  	}
  2038  	x.string = &s
  2039  
  2040  	// cache result for future callers
  2041  	if layoutCache.m == nil {
  2042  		layoutCache.m = make(map[layoutKey]layoutType)
  2043  	}
  2044  	framePool = &sync.Pool{New: func() interface{} {
  2045  		return unsafe_New(x)
  2046  	}}
  2047  	layoutCache.m[k] = layoutType{
  2048  		t:         x,
  2049  		argSize:   argSize,
  2050  		retOffset: retOffset,
  2051  		stack:     stack,
  2052  		framePool: framePool,
  2053  	}
  2054  	layoutCache.Unlock()
  2055  	return x, argSize, retOffset, stack, framePool
  2056  }
  2057  
  2058  // ifaceIndir reports whether t is stored indirectly in an interface value.
  2059  func ifaceIndir(t *rtype) bool {
  2060  	return t.kind&kindDirectIface == 0
  2061  }
  2062  
  2063  // Layout matches runtime.BitVector (well enough).
  2064  type bitVector struct {
  2065  	n    uint32 // number of bits
  2066  	data []byte
  2067  }
  2068  
  2069  // append a bit pair to the bitmap.
  2070  func (bv *bitVector) append2(bits uint8) {
  2071  	// assume bv.n is a multiple of 2, since append2 is the only operation.
  2072  	if bv.n%8 == 0 {
  2073  		bv.data = append(bv.data, 0)
  2074  	}
  2075  	bv.data[bv.n/8] |= bits << (bv.n % 8)
  2076  	bv.n += 2
  2077  }
  2078  
  2079  func addTypeBits(bv *bitVector, offset *uintptr, t *rtype) {
  2080  	*offset = align(*offset, uintptr(t.align))
  2081  	if !t.pointers() {
  2082  		*offset += t.size
  2083  		return
  2084  	}
  2085  
  2086  	switch Kind(t.kind & kindMask) {
  2087  	case Chan, Func, Map, Ptr, Slice, String, UnsafePointer:
  2088  		// 1 pointer at start of representation
  2089  		for bv.n < 2*uint32(*offset/uintptr(ptrSize)) {
  2090  			bv.append2(bitsScalar)
  2091  		}
  2092  		bv.append2(bitsPointer)
  2093  
  2094  	case Interface:
  2095  		// 2 pointers
  2096  		for bv.n < 2*uint32(*offset/uintptr(ptrSize)) {
  2097  			bv.append2(bitsScalar)
  2098  		}
  2099  		bv.append2(bitsPointer)
  2100  		bv.append2(bitsPointer)
  2101  
  2102  	case Array:
  2103  		// repeat inner type
  2104  		tt := (*arrayType)(unsafe.Pointer(t))
  2105  		for i := 0; i < int(tt.len); i++ {
  2106  			addTypeBits(bv, offset, tt.elem)
  2107  		}
  2108  
  2109  	case Struct:
  2110  		// apply fields
  2111  		tt := (*structType)(unsafe.Pointer(t))
  2112  		start := *offset
  2113  		for i := range tt.fields {
  2114  			f := &tt.fields[i]
  2115  			off := start + f.offset
  2116  			addTypeBits(bv, &off, f.typ)
  2117  		}
  2118  	}
  2119  
  2120  	*offset += t.size
  2121  }