Debian Codegraph @

libgo/go/internal/reflectlite/type.go

raw
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 reflectlite implements lightweight version of reflect, not using
6 // any package except for "runtime" and "unsafe".
7 package reflectlite
8
9 import (
10 "unsafe"
11 )
12
13 // Type is the representation of a Go type.
14 //
15 // Not all methods apply to all kinds of types. Restrictions,
16 // if any, are noted in the documentation for each method.
17 // Use the Kind method to find out the kind of type before
18 // calling kind-specific methods. Calling a method
19 // inappropriate to the kind of type causes a run-time panic.
20 //
21 // Type values are comparable, such as with the == operator,
22 // so they can be used as map keys.
23 // Two Type values are equal if they represent identical types.
24 type Type interface {
25 // Methods applicable to all types.
26
27 // Name returns the type's name within its package for a defined type.
28 // For other (non-defined) types it returns the empty string.
29 Name() string
30
31 // PkgPath returns a defined type's package path, that is, the import path
32 // that uniquely identifies the package, such as "encoding/base64".
33 // If the type was predeclared (string, error) or not defined (*T, struct{},
34 // []int, or A where A is an alias for a non-defined type), the package path
35 // will be the empty string.
36 PkgPath() string
37
38 // Size returns the number of bytes needed to store
39 // a value of the given type; it is analogous to unsafe.Sizeof.
40 Size() uintptr
41
42 // Kind returns the specific kind of this type.
43 Kind() Kind
44
45 // Implements reports whether the type implements the interface type u.
46 Implements(u Type) bool
47
48 // AssignableTo reports whether a value of the type is assignable to type u.
49 AssignableTo(u Type) bool
50
51 // Comparable reports whether values of this type are comparable.
52 Comparable() bool
53
54 // String returns a string representation of the type.
55 // The string representation may use shortened package names
56 // (e.g., base64 instead of "encoding/base64") and is not
57 // guaranteed to be unique among types. To test for type identity,
58 // compare the Types directly.
59 String() string
60
61 // Elem returns a type's element type.
62 // It panics if the type's Kind is not Ptr.
63 Elem() Type
64
65 common() *rtype
66 uncommon() *uncommonType
67 }
68
69 /*
70 * These data structures are known to the compiler (../../cmd/internal/reflectdata/reflect.go).
71 * A few are known to ../runtime/type.go to convey to debuggers.
72 * They are also known to ../runtime/type.go.
73 */
74
75 // A Kind represents the specific kind of type that a Type represents.
76 // The zero Kind is not a valid kind.
77 type Kind uint
78
79 const (
80 Invalid Kind = iota
81 Bool
82 Int
83 Int8
84 Int16
85 Int32
86 Int64
87 Uint
88 Uint8
89 Uint16
90 Uint32
91 Uint64
92 Uintptr
93 Float32
94 Float64
95 Complex64
96 Complex128
97 Array
98 Chan
99 Func
100 Interface
101 Map
102 Pointer
103 Slice
104 String
105 Struct
106 UnsafePointer
107 )
108
109 const Ptr = Pointer
110
111 // tflag is used by an rtype to signal what extra type information is
112 // available in the memory directly following the rtype value.
113 //
114 // tflag values must be kept in sync with copies in:
115 // go/types.cc
116 // runtime/type.go
117 type tflag uint8
118
119 const (
120 // tflagRegularMemory means that equal and hash functions can treat
121 // this type as a single region of t.size bytes.
122 tflagRegularMemory tflag = 1 << 3
123 )
124
125 // rtype is the common implementation of most values.
126 // It is embedded in other struct types.
127 //
128 // rtype must be kept in sync with ../runtime/type.go:/^type._type.
129 type rtype struct {
130 size uintptr
131 ptrdata uintptr // number of bytes in the type that can contain pointers
132 hash uint32 // hash of type; avoids computation in hash tables
133 tflag tflag // extra type information flags
134 align uint8 // alignment of variable with this type
135 fieldAlign uint8 // alignment of struct field with this type
136 kind uint8 // enumeration for C
137 // function for comparing objects of this type
138 // (ptr to object A, ptr to object B) -> ==?
139 equal func(unsafe.Pointer, unsafe.Pointer) bool
140 gcdata *byte // garbage collection data
141 string *string // string form; unnecessary but undeniably useful
142 *uncommonType // (relatively) uncommon fields
143 ptrToThis *rtype // type for pointer to this type, may be zero
144 }
145
146 // Method on non-interface type
147 type method struct {
148 name *string // name of method
149 pkgPath *string // nil for exported Names; otherwise import path
150 mtyp *rtype // method type (without receiver)
151 typ *rtype // .(*FuncType) underneath (with receiver)
152 tfn unsafe.Pointer // fn used for normal method call
153 }
154
155 // uncommonType is present only for defined types or types with methods
156 // (if T is a defined type, the uncommonTypes for T and *T have methods).
157 // Using a pointer to this struct reduces the overall size required
158 // to describe a non-defined type with no methods.
159 type uncommonType struct {
160 name *string // name of type
161 pkgPath *string // import path; nil for built-in types like int, string
162 methods []method // methods associated with type
163 }
164
165 // chanDir represents a channel type's direction.
166 type chanDir int
167
168 const (
169 recvDir chanDir = 1 << iota // <-chan
170 sendDir // chan<-
171 bothDir = recvDir | sendDir // chan
172 )
173
174 // arrayType represents a fixed array type.
175 type arrayType struct {
176 rtype
177 elem *rtype // array element type
178 slice *rtype // slice type
179 len uintptr
180 }
181
182 // chanType represents a channel type.
183 type chanType struct {
184 rtype
185 elem *rtype // channel element type
186 dir uintptr // channel direction (chanDir)
187 }
188
189 // funcType represents a function type.
190 type funcType struct {
191 rtype
192 dotdotdot bool // last input parameter is ...
193 in []*rtype // input parameter types
194 out []*rtype // output parameter types
195 }
196
197 // imethod represents a method on an interface type
198 type imethod struct {
199 name *string // name of method
200 pkgPath *string // nil for exported Names; otherwise import path
201 typ *rtype // .(*FuncType) underneath
202 }
203
204 // interfaceType represents an interface type.
205 type interfaceType struct {
206 rtype
207 methods []imethod // sorted by hash
208 }
209
210 // mapType represents a map type.
211 type mapType struct {
212 rtype
213 key *rtype // map key type
214 elem *rtype // map element (value) type
215 bucket *rtype // internal bucket structure
216 keysize uint8 // size of key slot
217 valuesize uint8 // size of value slot
218 bucketsize uint16 // size of bucket
219 flags uint32
220 }
221
222 // ptrType represents a pointer type.
223 type ptrType struct {
224 rtype
225 elem *rtype // pointer element (pointed at) type
226 }
227
228 // sliceType represents a slice type.
229 type sliceType struct {
230 rtype
231 elem *rtype // slice element type
232 }
233
234 // Struct field
235 type structField struct {
236 name *string // name is always non-empty
237 pkgPath *string // nil for exported Names; otherwise import path
238 typ *rtype // type of field
239 tag *string // nil if no tag
240 offsetEmbed uintptr // byte offset of field<<1 | isAnonymous
241 }
242
243 func (f *structField) offset() uintptr {
244 return f.offsetEmbed >> 1
245 }
246
247 func (f *structField) embedded() bool {
248 return f.offsetEmbed&1 != 0
249 }
250
251 // structType represents a struct type.
252 type structType struct {
253 rtype
254 fields []structField // sorted by offset
255 }
256
257 /*
258 * The compiler knows the exact layout of all the data structures above.
259 * The compiler does not know about the data structures and methods below.
260 */
261
262 const (
263 kindDirectIface = 1 << 5
264 kindGCProg = 1 << 6 // Type.gc points to GC program
265 kindMask = (1 << 5) - 1
266 )
267
268 // String returns the name of k.
269 func (k Kind) String() string {
270 if int(k) < len(kindNames) {
271 return kindNames[k]
272 }
273 return kindNames[0]
274 }
275
276 var kindNames = []string{
277 Invalid: "invalid",
278 Bool: "bool",
279 Int: "int",
280 Int8: "int8",
281 Int16: "int16",
282 Int32: "int32",
283 Int64: "int64",
284 Uint: "uint",
285 Uint8: "uint8",
286 Uint16: "uint16",
287 Uint32: "uint32",
288 Uint64: "uint64",
289 Uintptr: "uintptr",
290 Float32: "float32",
291 Float64: "float64",
292 Complex64: "complex64",
293 Complex128: "complex128",
294 Array: "array",
295 Chan: "chan",
296 Func: "func",
297 Interface: "interface",
298 Map: "map",
299 Ptr: "ptr",
300 Slice: "slice",
301 String: "string",
302 Struct: "struct",
303 UnsafePointer: "unsafe.Pointer",
304 }
305
306 func (t *uncommonType) exportedMethods() []method {
307 allm := t.methods
308 allExported := true
309 for _, m := range allm {
310 if m.pkgPath != nil {
311 allExported = false
312 break
313 }
314 }
315 var methods []method
316 if allExported {
317 methods = allm
318 } else {
319 methods = make([]method, 0, len(allm))
320 for _, m := range allm {
321 if m.pkgPath == nil {
322 methods = append(methods, m)
323 }
324 }
325 methods = methods[:len(methods):len(methods)]
326 }
327
328 return methods
329 }
330
331 func (t *uncommonType) uncommon() *uncommonType {
332 return t
333 }
334
335 func (t *uncommonType) PkgPath() string {
336 if t == nil || t.pkgPath == nil {
337 return ""
338 }
339 return *t.pkgPath
340 }
341
342 func (t *uncommonType) Name() string {
343 if t == nil || t.name == nil {
344 return ""
345 }
346 return *t.name
347 }
348
349 func (t *rtype) String() string {
350 // For gccgo, strip out quoted strings.
351 s := *t.string
352 var q bool
353 r := make([]byte, len(s))
354 j := 0
355 for i := 0; i < len(s); i++ {
356 if s[i] == '\t' {
357 q = !q
358 } else if !q {
359 r[j] = s[i]
360 j++
361 }
362 }
363 return string(r[:j])
364 }
365
366 func (t *rtype) Size() uintptr { return t.size }
367
368 func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }
369
370 func (t *rtype) pointers() bool { return t.ptrdata != 0 }
371
372 func (t *rtype) common() *rtype { return t }
373
374 func (t *rtype) exportedMethods() []method {
375 ut := t.uncommon()
376 if ut == nil {
377 return nil
378 }
379 return ut.exportedMethods()
380 }
381
382 func (t *rtype) NumMethod() int {
383 if t.Kind() == Interface {
384 tt := (*interfaceType)(unsafe.Pointer(t))
385 return tt.NumMethod()
386 }
387 return len(t.exportedMethods())
388 }
389
390 func (t *rtype) PkgPath() string {
391 return t.uncommonType.PkgPath()
392 }
393
394 func (t *rtype) hasName() bool {
395 return t.uncommonType != nil && t.uncommonType.name != nil
396 }
397
398 func (t *rtype) Name() string {
399 return t.uncommonType.Name()
400 }
401
402 func (t *rtype) chanDir() chanDir {
403 if t.Kind() != Chan {
404 panic("reflect: chanDir of non-chan type")
405 }
406 tt := (*chanType)(unsafe.Pointer(t))
407 return chanDir(tt.dir)
408 }
409
410 func (t *rtype) Elem() Type {
411 switch t.Kind() {
412 case Array:
413 tt := (*arrayType)(unsafe.Pointer(t))
414 return toType(tt.elem)
415 case Chan:
416 tt := (*chanType)(unsafe.Pointer(t))
417 return toType(tt.elem)
418 case Map:
419 tt := (*mapType)(unsafe.Pointer(t))
420 return toType(tt.elem)
421 case Ptr:
422 tt := (*ptrType)(unsafe.Pointer(t))
423 return toType(tt.elem)
424 case Slice:
425 tt := (*sliceType)(unsafe.Pointer(t))
426 return toType(tt.elem)
427 }
428 panic("reflect: Elem of invalid type")
429 }
430
431 func (t *rtype) In(i int) Type {
432 if t.Kind() != Func {
433 panic("reflect: In of non-func type")
434 }
435 tt := (*funcType)(unsafe.Pointer(t))
436 return toType(tt.in[i])
437 }
438
439 func (t *rtype) Key() Type {
440 if t.Kind() != Map {
441 panic("reflect: Key of non-map type")
442 }
443 tt := (*mapType)(unsafe.Pointer(t))
444 return toType(tt.key)
445 }
446
447 func (t *rtype) Len() int {
448 if t.Kind() != Array {
449 panic("reflect: Len of non-array type")
450 }
451 tt := (*arrayType)(unsafe.Pointer(t))
452 return int(tt.len)
453 }
454
455 func (t *rtype) NumField() int {
456 if t.Kind() != Struct {
457 panic("reflect: NumField of non-struct type")
458 }
459 tt := (*structType)(unsafe.Pointer(t))
460 return len(tt.fields)
461 }
462
463 func (t *rtype) NumIn() int {
464 if t.Kind() != Func {
465 panic("reflect: NumIn of non-func type")
466 }
467 tt := (*funcType)(unsafe.Pointer(t))
468 return len(tt.in)
469 }
470
471 func (t *rtype) NumOut() int {
472 if t.Kind() != Func {
473 panic("reflect: NumOut of non-func type")
474 }
475 tt := (*funcType)(unsafe.Pointer(t))
476 return len(tt.out)
477 }
478
479 func (t *rtype) Out(i int) Type {
480 if t.Kind() != Func {
481 panic("reflect: Out of non-func type")
482 }
483 tt := (*funcType)(unsafe.Pointer(t))
484 return toType(tt.out[i])
485 }
486
487 // add returns p+x.
488 //
489 // The whySafe string is ignored, so that the function still inlines
490 // as efficiently as p+x, but all call sites should use the string to
491 // record why the addition is safe, which is to say why the addition
492 // does not cause x to advance to the very end of p's allocation
493 // and therefore point incorrectly at the next block in memory.
494 func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer {
495 return unsafe.Pointer(uintptr(p) + x)
496 }
497
498 // NumMethod returns the number of interface methods in the type's method set.
499 func (t *interfaceType) NumMethod() int { return len(t.methods) }
500
501 // TypeOf returns the reflection Type that represents the dynamic type of i.
502 // If i is a nil interface value, TypeOf returns nil.
503 func TypeOf(i any) Type {
504 eface := *(*emptyInterface)(unsafe.Pointer(&i))
505 return toType(eface.typ)
506 }
507
508 func (t *rtype) Implements(u Type) bool {
509 if u == nil {
510 panic("reflect: nil type passed to Type.Implements")
511 }
512 if u.Kind() != Interface {
513 panic("reflect: non-interface type passed to Type.Implements")
514 }
515 return implements(u.(*rtype), t)
516 }
517
518 func (t *rtype) AssignableTo(u Type) bool {
519 if u == nil {
520 panic("reflect: nil type passed to Type.AssignableTo")
521 }
522 uu := u.(*rtype)
523 return directlyAssignable(uu, t) || implements(uu, t)
524 }
525
526 func (t *rtype) Comparable() bool {
527 switch t.Kind() {
528 case Bool, Int, Int8, Int16, Int32, Int64,
529 Uint, Uint8, Uint16, Uint32, Uint64, Uintptr,
530 Float32, Float64, Complex64, Complex128,
531 Chan, Interface, Ptr, String, UnsafePointer:
532 return true
533
534 case Func, Map, Slice:
535 return false
536
537 case Array:
538 return (*arrayType)(unsafe.Pointer(t)).elem.Comparable()
539
540 case Struct:
541 tt := (*structType)(unsafe.Pointer(t))
542 for i := range tt.fields {
543 if !tt.fields[i].typ.Comparable() {
544 return false
545 }
546 }
547 return true
548
549 default:
550 panic("reflectlite: impossible")
551 }
552 }
553
554 // implements reports whether the type V implements the interface type T.
555 func implements(T, V *rtype) bool {
556 if T.Kind() != Interface {
557 return false
558 }
559 t := (*interfaceType)(unsafe.Pointer(T))
560 if len(t.methods) == 0 {
561 return true
562 }
563
564 // The same algorithm applies in both cases, but the
565 // method tables for an interface type and a concrete type
566 // are different, so the code is duplicated.
567 // In both cases the algorithm is a linear scan over the two
568 // lists - T's methods and V's methods - simultaneously.
569 // Since method tables are stored in a unique sorted order
570 // (alphabetical, with no duplicate method names), the scan
571 // through V's methods must hit a match for each of T's
572 // methods along the way, or else V does not implement T.
573 // This lets us run the scan in overall linear time instead of
574 // the quadratic time a naive search would require.
575 // See also ../runtime/iface.go.
576 if V.Kind() == Interface {
577 v := (*interfaceType)(unsafe.Pointer(V))
578 i := 0
579 for j := 0; j < len(v.methods); j++ {
580 tm := &t.methods[i]
581 vm := &v.methods[j]
582 if *vm.name == *tm.name && (vm.pkgPath == tm.pkgPath || (vm.pkgPath != nil && tm.pkgPath != nil && *vm.pkgPath == *tm.pkgPath)) && rtypeEqual(toType(vm.typ).common(), toType(tm.typ).common()) {
583 if i++; i >= len(t.methods) {
584 return true
585 }
586 }
587 }
588 return false
589 }
590
591 v := V.uncommon()
592 if v == nil {
593 return false
594 }
595 i := 0
596 for j := 0; j < len(v.methods); j++ {
597 tm := &t.methods[i]
598 vm := &v.methods[j]
599 if *vm.name == *tm.name && (vm.pkgPath == tm.pkgPath || (vm.pkgPath != nil && tm.pkgPath != nil && *vm.pkgPath == *tm.pkgPath)) && rtypeEqual(toType(vm.mtyp).common(), toType(tm.typ).common()) {
600 if i++; i >= len(t.methods) {
601 return true
602 }
603 }
604 }
605 return false
606 }
607
608 // directlyAssignable reports whether a value x of type V can be directly
609 // assigned (using memmove) to a value of type T.
610 // https://golang.org/doc/go_spec.html#Assignability
611 // Ignoring the interface rules (implemented elsewhere)
612 // and the ideal constant rules (no ideal constants at run time).
613 func directlyAssignable(T, V *rtype) bool {
614 // x's type V is identical to T?
615 if rtypeEqual(T, V) {
616 return true
617 }
618
619 // Otherwise at least one of T and V must not be defined
620 // and they must have the same kind.
621 if T.hasName() && V.hasName() || T.Kind() != V.Kind() {
622 return false
623 }
624
625 // x's type T and V must have identical underlying types.
626 return haveIdenticalUnderlyingType(T, V, true)
627 }
628
629 func haveIdenticalType(T, V Type, cmpTags bool) bool {
630 if cmpTags {
631 return T == V
632 }
633
634 if T.Name() != V.Name() || T.Kind() != V.Kind() {
635 return false
636 }
637
638 return haveIdenticalUnderlyingType(T.common(), V.common(), false)
639 }
640
641 func haveIdenticalUnderlyingType(T, V *rtype, cmpTags bool) bool {
642 if rtypeEqual(T, V) {
643 return true
644 }
645
646 kind := T.Kind()
647 if kind != V.Kind() {
648 return false
649 }
650
651 // Non-composite types of equal kind have same underlying type
652 // (the predefined instance of the type).
653 if Bool <= kind && kind <= Complex128 || kind == String || kind == UnsafePointer {
654 return true
655 }
656
657 // Composite types.
658 switch kind {
659 case Array:
660 return T.Len() == V.Len() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
661
662 case Chan:
663 // Special case:
664 // x is a bidirectional channel value, T is a channel type,
665 // and x's type V and T have identical element types.
666 if V.chanDir() == bothDir && haveIdenticalType(T.Elem(), V.Elem(), cmpTags) {
667 return true
668 }
669
670 // Otherwise continue test for identical underlying type.
671 return V.chanDir() == T.chanDir() && haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
672
673 case Func:
674 t := (*funcType)(unsafe.Pointer(T))
675 v := (*funcType)(unsafe.Pointer(V))
676 if t.dotdotdot != v.dotdotdot || len(t.in) != len(v.in) || len(t.out) != len(v.out) {
677 return false
678 }
679 for i, typ := range t.in {
680 if !haveIdenticalType(typ, v.in[i], cmpTags) {
681 return false
682 }
683 }
684 for i, typ := range t.out {
685 if !haveIdenticalType(typ, v.out[i], cmpTags) {
686 return false
687 }
688 }
689 return true
690
691 case Interface:
692 t := (*interfaceType)(unsafe.Pointer(T))
693 v := (*interfaceType)(unsafe.Pointer(V))
694 if len(t.methods) == 0 && len(v.methods) == 0 {
695 return true
696 }
697 // Might have the same methods but still
698 // need a run time conversion.
699 return false
700
701 case Map:
702 return haveIdenticalType(T.Key(), V.Key(), cmpTags) && haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
703
704 case Ptr, Slice:
705 return haveIdenticalType(T.Elem(), V.Elem(), cmpTags)
706
707 case Struct:
708 t := (*structType)(unsafe.Pointer(T))
709 v := (*structType)(unsafe.Pointer(V))
710 if len(t.fields) != len(v.fields) {
711 return false
712 }
713 for i := range t.fields {
714 tf := &t.fields[i]
715 vf := &v.fields[i]
716 if tf.name != vf.name && (tf.name == nil || vf.name == nil || *tf.name != *vf.name) {
717 return false
718 }
719 if tf.pkgPath != vf.pkgPath && (tf.pkgPath == nil || vf.pkgPath == nil || *tf.pkgPath != *vf.pkgPath) {
720 return false
721 }
722 if !haveIdenticalType(tf.typ, vf.typ, cmpTags) {
723 return false
724 }
725 if cmpTags && tf.tag != vf.tag && (tf.tag == nil || vf.tag == nil || *tf.tag != *vf.tag) {
726 return false
727 }
728 if tf.offsetEmbed != vf.offsetEmbed {
729 return false
730 }
731 }
732 return true
733 }
734
735 return false
736 }
737
738 // toType converts from a *rtype to a Type that can be returned
739 // to the client of package reflect. In gc, the only concern is that
740 // a nil *rtype must be replaced by a nil Type, but in gccgo this
741 // function takes care of ensuring that multiple *rtype for the same
742 // type are coalesced into a single Type.
743 func toType(t *rtype) Type {
744 if t == nil {
745 return nil
746 }
747 return t
748 }
749
750 // ifaceIndir reports whether t is stored indirectly in an interface value.
751 func ifaceIndir(t *rtype) bool {
752 return t.kind&kindDirectIface == 0
753 }