type.go 52 KB

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