Remove the types float and complex.
[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 // The reflect package implements run-time reflection, allowing a program to
6 // manipulate objects with arbitrary types. The typical use is to take a
7 // value with static type interface{} and extract its dynamic type
8 // information by calling Typeof, which returns an object with interface
9 // type Type. That contains a pointer to a struct of type *StructType,
10 // *IntType, etc. representing the details of the underlying type. A type
11 // switch or type assertion can reveal which.
12 //
13 // A call to NewValue creates a Value representing the run-time data; it
14 // contains a *StructValue, *IntValue, etc. MakeZero takes a Type and
15 // returns a Value representing a zero value for that type.
16 package reflect
17
18 import (
19 "runtime"
20 "strconv"
21 "sync"
22 "unsafe"
23 )
24
25 /*
26 * Copy of data structures from ../runtime/type.go.
27 * For comments, see the ones in that file.
28 *
29 * These data structures are known to the compiler and the runtime.
30 *
31 * Putting these types in runtime instead of reflect means that
32 * reflect doesn't need to be autolinked into every binary, which
33 * simplifies bootstrapping and package dependencies.
34 * Unfortunately, it also means that reflect needs its own
35 * copy in order to access the private fields.
36 */
37
38 // commonType is the common implementation of most values.
39 // It is embedded in other, public struct types, but always
40 // with a unique tag like "uint" or "float" so that the client cannot
41 // convert from, say, *UintType to *FloatType.
42
43 type commonType struct {
44 kind uint8
45 align int8
46 fieldAlign uint8
47 size uintptr
48 hash uint32
49 hashfn func(unsafe.Pointer, uintptr)
50 equalfn func(unsafe.Pointer, unsafe.Pointer, uintptr)
51 string *string
52 *uncommonType
53 }
54
55 type method struct {
56 name *string
57 pkgPath *string
58 mtyp *runtime.Type
59 typ *runtime.Type
60 tfn unsafe.Pointer
61 }
62
63 type uncommonType struct {
64 name *string
65 pkgPath *string
66 methods []method
67 }
68
69 // BoolType represents a boolean type.
70 type BoolType struct {
71 commonType "bool"
72 }
73
74 // FloatType represents a float type.
75 type FloatType struct {
76 commonType "float"
77 }
78
79 // ComplexType represents a complex type.
80 type ComplexType struct {
81 commonType "complex"
82 }
83
84 // IntType represents a signed integer type.
85 type IntType struct {
86 commonType "int"
87 }
88
89 // UintType represents a uint type.
90 type UintType struct {
91 commonType "uint"
92 }
93
94 // StringType represents a string type.
95 type StringType struct {
96 commonType "string"
97 }
98
99 // UnsafePointerType represents an unsafe.Pointer type.
100 type UnsafePointerType struct {
101 commonType "unsafe.Pointer"
102 }
103
104 // ArrayType represents a fixed array type.
105 type ArrayType struct {
106 commonType "array"
107 elem *runtime.Type
108 len uintptr
109 }
110
111 // ChanDir represents a channel type's direction.
112 type ChanDir int
113
114 const (
115 RecvDir ChanDir = 1 << iota
116 SendDir
117 BothDir = RecvDir | SendDir
118 )
119
120 // ChanType represents a channel type.
121 type ChanType struct {
122 commonType "chan"
123 elem *runtime.Type
124 dir uintptr
125 }
126
127 // FuncType represents a function type.
128 type FuncType struct {
129 commonType "func"
130 dotdotdot bool
131 in []*runtime.Type
132 out []*runtime.Type
133 }
134
135 // Method on interface type
136 type imethod struct {
137 name *string
138 pkgPath *string
139 typ *runtime.Type
140 }
141
142 // InterfaceType represents an interface type.
143 type InterfaceType struct {
144 commonType "interface"
145 methods []imethod
146 }
147
148 // MapType represents a map type.
149 type MapType struct {
150 commonType "map"
151 key *runtime.Type
152 elem *runtime.Type
153 }
154
155 // PtrType represents a pointer type.
156 type PtrType struct {
157 commonType "ptr"
158 elem *runtime.Type
159 }
160
161 // SliceType represents a slice type.
162 type SliceType struct {
163 commonType "slice"
164 elem *runtime.Type
165 }
166
167 // Struct field
168 type structField struct {
169 name *string
170 pkgPath *string
171 typ *runtime.Type
172 tag *string
173 offset uintptr
174 }
175
176 // StructType represents a struct type.
177 type StructType struct {
178 commonType "struct"
179 fields []structField
180 }
181
182
183 /*
184 * The compiler knows the exact layout of all the data structures above.
185 * The compiler does not know about the data structures and methods below.
186 */
187
188 // Method represents a single method.
189 type Method struct {
190 PkgPath string // empty for uppercase Name
191 Name string
192 Type *FuncType
193 Func *FuncValue
194 }
195
196 // Type is the runtime representation of a Go type.
197 // Every type implements the methods listed here.
198 // Some types implement additional interfaces;
199 // use a type switch to find out what kind of type a Type is.
200 // Each type in a program has a unique Type, so == on Types
201 // corresponds to Go's type equality.
202 type Type interface {
203 // PkgPath returns the type's package path.
204 // The package path is a full package import path like "container/vector".
205 // PkgPath returns an empty string for unnamed types.
206 PkgPath() string
207
208 // Name returns the type's name within its package.
209 // Name returns an empty string for unnamed types.
210 Name() string
211
212 // String returns a string representation of the type.
213 // The string representation may use shortened package names
214 // (e.g., vector instead of "container/vector") and is not
215 // guaranteed to be unique among types. To test for equality,
216 // compare the Types directly.
217 String() string
218
219 // Size returns the number of bytes needed to store
220 // a value of the given type; it is analogous to unsafe.Sizeof.
221 Size() uintptr
222
223 // Bits returns the size of the type in bits.
224 // It is intended for use with numeric types and may overflow
225 // when used for composite types.
226 Bits() int
227
228 // Align returns the alignment of a value of this type
229 // when allocated in memory.
230 Align() int
231
232 // FieldAlign returns the alignment of a value of this type
233 // when used as a field in a struct.
234 FieldAlign() int
235
236 // Kind returns the specific kind of this type.
237 Kind() Kind
238
239 // For non-interface types, Method returns the i'th method with receiver T.
240 // For interface types, Method returns the i'th method in the interface.
241 // NumMethod returns the number of such methods.
242 Method(int) Method
243 NumMethod() int
244 uncommon() *uncommonType
245 }
246
247 // A Kind represents the specific kind of type that a Type represents.
248 // For numeric types, the Kind gives more information than the Type's
249 // dynamic type. For example, the Type of a float32 is FloatType, but
250 // the Kind is Float32.
251 //
252 // The zero Kind is not a valid kind.
253 type Kind uint8
254
255 const (
256 Bool Kind = 1 + iota
257 Int
258 Int8
259 Int16
260 Int32
261 Int64
262 Uint
263 Uint8
264 Uint16
265 Uint32
266 Uint64
267 Uintptr
268 Float32
269 Float64
270 Complex64
271 Complex128
272 Array
273 Chan
274 Func
275 Interface
276 Map
277 Ptr
278 Slice
279 String
280 Struct
281 UnsafePointer
282 )
283
284 // High bit says whether type has
285 // embedded pointers,to help garbage collector.
286 const kindMask = 0x7f
287
288 func (k Kind) String() string {
289 if int(k) < len(kindNames) {
290 return kindNames[k]
291 }
292 return "kind" + strconv.Itoa(int(k))
293 }
294
295 var kindNames = []string{
296 Bool: "bool",
297 Int: "int",
298 Int8: "int8",
299 Int16: "int16",
300 Int32: "int32",
301 Int64: "int64",
302 Uint: "uint",
303 Uint8: "uint8",
304 Uint16: "uint16",
305 Uint32: "uint32",
306 Uint64: "uint64",
307 Uintptr: "uintptr",
308 Float32: "float32",
309 Float64: "float64",
310 Complex64: "complex64",
311 Complex128: "complex128",
312 Array: "array",
313 Chan: "chan",
314 Func: "func",
315 Interface: "interface",
316 Map: "map",
317 Ptr: "ptr",
318 Slice: "slice",
319 String: "string",
320 Struct: "struct",
321 UnsafePointer: "unsafe.Pointer",
322 }
323
324 func (t *uncommonType) uncommon() *uncommonType {
325 return t
326 }
327
328 func (t *uncommonType) PkgPath() string {
329 if t == nil || t.pkgPath == nil {
330 return ""
331 }
332 return *t.pkgPath
333 }
334
335 func (t *uncommonType) Name() string {
336 if t == nil || t.name == nil {
337 return ""
338 }
339 return *t.name
340 }
341
342 func (t *commonType) String() string { return *t.string }
343
344 func (t *commonType) Size() uintptr { return t.size }
345
346 func (t *commonType) Bits() int { return int(t.size * 8) }
347
348 func (t *commonType) Align() int { return int(t.align) }
349
350 func (t *commonType) FieldAlign() int { return int(t.fieldAlign) }
351
352 func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) }
353
354 func (t *uncommonType) Method(i int) (m Method) {
355 if t == nil || i < 0 || i >= len(t.methods) {
356 return
357 }
358 p := &t.methods[i]
359 if p.name != nil {
360 m.Name = *p.name
361 }
362 if p.pkgPath != nil {
363 m.PkgPath = *p.pkgPath
364 }
365 m.Type = runtimeToType(p.typ).(*FuncType)
366 fn := p.tfn
367 m.Func = &FuncValue{value: value{m.Type, addr(&fn), true}}
368 return
369 }
370
371 func (t *uncommonType) NumMethod() int {
372 if t == nil {
373 return 0
374 }
375 return len(t.methods)
376 }
377
378 // TODO(rsc): 6g supplies these, but they are not
379 // as efficient as they could be: they have commonType
380 // as the receiver instead of *commonType.
381 func (t *commonType) NumMethod() int { return t.uncommonType.NumMethod() }
382
383 func (t *commonType) Method(i int) (m Method) { return t.uncommonType.Method(i) }
384
385 func (t *commonType) PkgPath() string { return t.uncommonType.PkgPath() }
386
387 func (t *commonType) Name() string { return t.uncommonType.Name() }
388
389 // Len returns the number of elements in the array.
390 func (t *ArrayType) Len() int { return int(t.len) }
391
392 // Elem returns the type of the array's elements.
393 func (t *ArrayType) Elem() Type { return runtimeToType(t.elem) }
394
395 // Dir returns the channel direction.
396 func (t *ChanType) Dir() ChanDir { return ChanDir(t.dir) }
397
398 // Elem returns the channel's element type.
399 func (t *ChanType) Elem() Type { return runtimeToType(t.elem) }
400
401 func (d ChanDir) String() string {
402 switch d {
403 case SendDir:
404 return "chan<-"
405 case RecvDir:
406 return "<-chan"
407 case BothDir:
408 return "chan"
409 }
410 return "ChanDir" + strconv.Itoa(int(d))
411 }
412
413 // In returns the type of the i'th function input parameter.
414 func (t *FuncType) In(i int) Type {
415 if i < 0 || i >= len(t.in) {
416 return nil
417 }
418 return runtimeToType(t.in[i])
419 }
420
421 // DotDotDot returns true if the final function input parameter
422 // is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the
423 // parameter's underlying static type []T.
424 //
425 // For concreteness, if t is func(x int, y ... float), then
426 //
427 // t.NumIn() == 2
428 // t.In(0) is the reflect.Type for "int"
429 // t.In(1) is the reflect.Type for "[]float"
430 // t.DotDotDot() == true
431 //
432 func (t *FuncType) DotDotDot() bool { return t.dotdotdot }
433
434 // NumIn returns the number of input parameters.
435 func (t *FuncType) NumIn() int { return len(t.in) }
436
437 // Out returns the type of the i'th function output parameter.
438 func (t *FuncType) Out(i int) Type {
439 if i < 0 || i >= len(t.out) {
440 return nil
441 }
442 return runtimeToType(t.out[i])
443 }
444
445 // NumOut returns the number of function output parameters.
446 func (t *FuncType) NumOut() int { return len(t.out) }
447
448 // Method returns the i'th interface method.
449 func (t *InterfaceType) Method(i int) (m Method) {
450 if i < 0 || i >= len(t.methods) {
451 return
452 }
453 p := &t.methods[i]
454 m.Name = *p.name
455 if p.pkgPath != nil {
456 m.PkgPath = *p.pkgPath
457 }
458 m.Type = runtimeToType(p.typ).(*FuncType)
459 return
460 }
461
462 // NumMethod returns the number of interface methods.
463 func (t *InterfaceType) NumMethod() int { return len(t.methods) }
464
465 // Key returns the map key type.
466 func (t *MapType) Key() Type { return runtimeToType(t.key) }
467
468 // Elem returns the map element type.
469 func (t *MapType) Elem() Type { return runtimeToType(t.elem) }
470
471 // Elem returns the pointer element type.
472 func (t *PtrType) Elem() Type { return runtimeToType(t.elem) }
473
474 // Elem returns the type of the slice's elements.
475 func (t *SliceType) Elem() Type { return runtimeToType(t.elem) }
476
477 type StructField struct {
478 PkgPath string // empty for uppercase Name
479 Name string
480 Type Type
481 Tag string
482 Offset uintptr
483 Index []int
484 Anonymous bool
485 }
486
487 // Field returns the i'th struct field.
488 func (t *StructType) Field(i int) (f StructField) {
489 if i < 0 || i >= len(t.fields) {
490 return
491 }
492 p := t.fields[i]
493 f.Type = runtimeToType(p.typ)
494 if p.name != nil {
495 f.Name = *p.name
496 } else {
497 t := f.Type
498 if pt, ok := t.(*PtrType); ok {
499 t = pt.Elem()
500 }
501 f.Name = t.Name()
502 f.Anonymous = true
503 }
504 if p.pkgPath != nil {
505 f.PkgPath = *p.pkgPath
506 }
507 if p.tag != nil {
508 f.Tag = *p.tag
509 }
510 f.Offset = p.offset
511 f.Index = []int{i}
512 return
513 }
514
515 // TODO(gri): Should there be an error/bool indicator if the index
516 // is wrong for FieldByIndex?
517
518 // FieldByIndex returns the nested field corresponding to index.
519 func (t *StructType) FieldByIndex(index []int) (f StructField) {
520 for i, x := range index {
521 if i > 0 {
522 ft := f.Type
523 if pt, ok := ft.(*PtrType); ok {
524 ft = pt.Elem()
525 }
526 if st, ok := ft.(*StructType); ok {
527 t = st
528 } else {
529 var f0 StructField
530 f = f0
531 return
532 }
533 }
534 f = t.Field(x)
535 }
536 return
537 }
538
539 const inf = 1 << 30 // infinity - no struct has that many nesting levels
540
541 func (t *StructType) fieldByNameFunc(match func(string) bool, mark map[*StructType]bool, depth int) (ff StructField, fd int) {
542 fd = inf // field depth
543
544 if mark[t] {
545 // Struct already seen.
546 return
547 }
548 mark[t] = true
549
550 var fi int // field index
551 n := 0 // number of matching fields at depth fd
552 L:
553 for i := range t.fields {
554 f := t.Field(i)
555 d := inf
556 switch {
557 case match(f.Name):
558 // Matching top-level field.
559 d = depth
560 case f.Anonymous:
561 ft := f.Type
562 if pt, ok := ft.(*PtrType); ok {
563 ft = pt.Elem()
564 }
565 switch {
566 case match(ft.Name()):
567 // Matching anonymous top-level field.
568 d = depth
569 case fd > depth:
570 // No top-level field yet; look inside nested structs.
571 if st, ok := ft.(*StructType); ok {
572 f, d = st.fieldByNameFunc(match, mark, depth+1)
573 }
574 }
575 }
576
577 switch {
578 case d < fd:
579 // Found field at shallower depth.
580 ff, fi, fd = f, i, d
581 n = 1
582 case d == fd:
583 // More than one matching field at the same depth (or d, fd == inf).
584 // Same as no field found at this depth.
585 n++
586 if d == depth {
587 // Impossible to find a field at lower depth.
588 break L
589 }
590 }
591 }
592
593 if n == 1 {
594 // Found matching field.
595 if len(ff.Index) <= depth {
596 ff.Index = make([]int, depth+1)
597 }
598 ff.Index[depth] = fi
599 } else {
600 // None or more than one matching field found.
601 fd = inf
602 }
603
604 mark[t] = false, false
605 return
606 }
607
608 // FieldByName returns the struct field with the given name
609 // and a boolean to indicate if the field was found.
610 func (t *StructType) FieldByName(name string) (f StructField, present bool) {
611 return t.FieldByNameFunc(func(s string) bool { return s == name })
612 }
613
614 // FieldByNameFunc returns the struct field with a name that satisfies the
615 // match function and a boolean to indicate if the field was found.
616 func (t *StructType) FieldByNameFunc(match func(string) bool) (f StructField, present bool) {
617 if ff, fd := t.fieldByNameFunc(match, make(map[*StructType]bool), 0); fd < inf {
618 ff.Index = ff.Index[0 : fd+1]
619 f, present = ff, true
620 }
621 return
622 }
623
624 // NumField returns the number of struct fields.
625 func (t *StructType) NumField() int { return len(t.fields) }
626
627 // Canonicalize a Type.
628 var canonicalType = make(map[string]Type)
629
630 var canonicalTypeLock sync.Mutex
631
632 func canonicalize(t Type) Type {
633 if t == nil {
634 return nil
635 }
636 u := t.uncommon()
637 var s string
638 if u == nil || u.PkgPath() == "" {
639 s = t.String()
640 } else {
641 s = u.PkgPath() + "." + u.Name()
642 }
643 canonicalTypeLock.Lock()
644 if r, ok := canonicalType[s]; ok {
645 canonicalTypeLock.Unlock()
646 return r
647 }
648 canonicalType[s] = t
649 canonicalTypeLock.Unlock()
650 return t
651 }
652
653 // Convert runtime type to reflect type.
654 // Same memory layouts, different method sets.
655 func toType(i interface{}) Type {
656 switch v := i.(type) {
657 case nil:
658 return nil
659 case *runtime.BoolType:
660 return (*BoolType)(unsafe.Pointer(v))
661 case *runtime.FloatType:
662 return (*FloatType)(unsafe.Pointer(v))
663 case *runtime.ComplexType:
664 return (*ComplexType)(unsafe.Pointer(v))
665 case *runtime.IntType:
666 return (*IntType)(unsafe.Pointer(v))
667 case *runtime.StringType:
668 return (*StringType)(unsafe.Pointer(v))
669 case *runtime.UintType:
670 return (*UintType)(unsafe.Pointer(v))
671 case *runtime.UnsafePointerType:
672 return (*UnsafePointerType)(unsafe.Pointer(v))
673 case *runtime.ArrayType:
674 return (*ArrayType)(unsafe.Pointer(v))
675 case *runtime.ChanType:
676 return (*ChanType)(unsafe.Pointer(v))
677 case *runtime.FuncType:
678 return (*FuncType)(unsafe.Pointer(v))
679 case *runtime.InterfaceType:
680 return (*InterfaceType)(unsafe.Pointer(v))
681 case *runtime.MapType:
682 return (*MapType)(unsafe.Pointer(v))
683 case *runtime.PtrType:
684 return (*PtrType)(unsafe.Pointer(v))
685 case *runtime.SliceType:
686 return (*SliceType)(unsafe.Pointer(v))
687 case *runtime.StructType:
688 return (*StructType)(unsafe.Pointer(v))
689 }
690 println(i)
691 panic("toType")
692 }
693
694 // Convert pointer to runtime Type structure to our Type structure.
695 func runtimeToType(v *runtime.Type) Type {
696 var r Type
697 switch Kind(v.Kind) {
698 case Bool:
699 r = (*BoolType)(unsafe.Pointer(v))
700 case Int, Int8, Int16, Int32, Int64:
701 r = (*IntType)(unsafe.Pointer(v))
702 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
703 r = (*UintType)(unsafe.Pointer(v))
704 case Float32, Float64:
705 r = (*FloatType)(unsafe.Pointer(v))
706 case Complex64, Complex128:
707 r = (*ComplexType)(unsafe.Pointer(v))
708 case Array:
709 r = (*ArrayType)(unsafe.Pointer(v))
710 case Chan:
711 r = (*ChanType)(unsafe.Pointer(v))
712 case Func:
713 r = (*FuncType)(unsafe.Pointer(v))
714 case Interface:
715 r = (*InterfaceType)(unsafe.Pointer(v))
716 case Map:
717 r = (*MapType)(unsafe.Pointer(v))
718 case Ptr:
719 r = (*PtrType)(unsafe.Pointer(v))
720 case Slice:
721 r = (*SliceType)(unsafe.Pointer(v))
722 case String:
723 r = (*StringType)(unsafe.Pointer(v))
724 case Struct:
725 r = (*StructType)(unsafe.Pointer(v))
726 case UnsafePointer:
727 r = (*UnsafePointerType)(unsafe.Pointer(v))
728 default:
729 panic("runtimeToType")
730 }
731 return canonicalize(r)
732 panic("runtimeToType")
733 }
734
735 // ArrayOrSliceType is the common interface implemented
736 // by both ArrayType and SliceType.
737 type ArrayOrSliceType interface {
738 Type
739 Elem() Type
740 }
741
742 // Typeof returns the reflection Type of the value in the interface{}.
743 func Typeof(i interface{}) Type { return canonicalize(toType(unsafe.Typeof(i))) }