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