~ubuntu-branches/ubuntu/vivid/golang/vivid

« back to all changes in this revision

Viewing changes to src/pkg/reflect/type.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2013-08-20 14:06:23 UTC
  • mfrom: (14.1.23 saucy-proposed)
  • Revision ID: package-import@ubuntu.com-20130820140623-b414jfxi3m0qkmrq
Tags: 2:1.1.2-2ubuntu1
* Merge from Debian unstable (LP: #1211749, #1202027). Remaining changes:
  - 016-armhf-elf-header.patch: Use correct ELF header for armhf binaries.
  - d/control,control.cross: Update Breaks/Replaces for Ubuntu
    versions to ensure smooth upgrades, regenerate control file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
92
92
        // AssignableTo returns true if a value of the type is assignable to type u.
93
93
        AssignableTo(u Type) bool
94
94
 
 
95
        // ConvertibleTo returns true if a value of the type is convertible to type u.
 
96
        ConvertibleTo(u Type) bool
 
97
 
95
98
        // Methods applicable only to some types, depending on Kind.
96
99
        // The methods allowed for each kind are:
97
100
        //
181
184
        // It panics if i is not in the range [0, NumOut()).
182
185
        Out(i int) Type
183
186
 
184
 
        runtimeType() *runtimeType
185
 
        common() *commonType
 
187
        common() *rtype
186
188
        uncommon() *uncommonType
187
189
}
188
190
 
 
191
/*
 
192
 * These data structures are known to the compiler (../../cmd/gc/reflect.c).
 
193
 * A few are known to ../runtime/type.go to convey to debuggers.
 
194
 * They are also known to ../runtime/type.h.
 
195
 */
 
196
 
189
197
// A Kind represents the specific kind of type that a Type represents.
190
198
// The zero Kind is not a valid kind.
191
199
type Kind uint
220
228
        UnsafePointer
221
229
)
222
230
 
223
 
/*
224
 
 * These data structures are known to the compiler (../../cmd/gc/reflect.c).
225
 
 * A few are known to ../runtime/type.go to convey to debuggers.
226
 
 */
227
 
 
228
 
// The compiler can only construct empty interface values at
229
 
// compile time; non-empty interface values get created
230
 
// during initialization.  Type is an empty interface
231
 
// so that the compiler can lay out references as data.
232
 
// The underlying type is *reflect.ArrayType and so on.
233
 
type runtimeType interface{}
234
 
 
235
 
// commonType is the common implementation of most values.
 
231
// rtype is the common implementation of most values.
236
232
// It is embedded in other, public struct types, but always
237
233
// with a unique tag like `reflect:"array"` or `reflect:"ptr"`
238
234
// so that code cannot convert from, say, *arrayType to *ptrType.
239
 
type commonType struct {
240
 
        size          uintptr      // size in bytes
241
 
        hash          uint32       // hash of type; avoids computation in hash tables
242
 
        _             uint8        // unused/padding
243
 
        align         uint8        // alignment of variable with this type
244
 
        fieldAlign    uint8        // alignment of struct field with this type
245
 
        kind          uint8        // enumeration for C
246
 
        alg           *uintptr     // algorithm table (../runtime/runtime.h:/Alg)
247
 
        string        *string      // string form; unnecessary but undeniably useful
248
 
        *uncommonType              // (relatively) uncommon fields
249
 
        ptrToThis     *runtimeType // pointer to this type, if used in binary or has methods
 
235
type rtype struct {
 
236
        size          uintptr        // size in bytes
 
237
        hash          uint32         // hash of type; avoids computation in hash tables
 
238
        _             uint8          // unused/padding
 
239
        align         uint8          // alignment of variable with this type
 
240
        fieldAlign    uint8          // alignment of struct field with this type
 
241
        kind          uint8          // enumeration for C
 
242
        alg           *uintptr       // algorithm table (../runtime/runtime.h:/Alg)
 
243
        gc            unsafe.Pointer // garbage collection data
 
244
        string        *string        // string form; unnecessary but undeniably useful
 
245
        *uncommonType                // (relatively) uncommon fields
 
246
        ptrToThis     *rtype         // type for pointer to this type, if used in binary or has methods
250
247
}
251
248
 
252
249
// Method on non-interface type
253
250
type method struct {
254
251
        name    *string        // name of method
255
252
        pkgPath *string        // nil for exported Names; otherwise import path
256
 
        mtyp    *runtimeType   // method type (without receiver)
257
 
        typ     *runtimeType   // .(*FuncType) underneath (with receiver)
 
253
        mtyp    *rtype         // method type (without receiver)
 
254
        typ     *rtype         // .(*FuncType) underneath (with receiver)
258
255
        ifn     unsafe.Pointer // fn used in interface call (one-word receiver)
259
256
        tfn     unsafe.Pointer // fn used for normal method call
260
257
}
280
277
 
281
278
// arrayType represents a fixed array type.
282
279
type arrayType struct {
283
 
        commonType `reflect:"array"`
284
 
        elem       *runtimeType // array element type
285
 
        slice      *runtimeType // slice type
286
 
        len        uintptr
 
280
        rtype `reflect:"array"`
 
281
        elem  *rtype // array element type
 
282
        slice *rtype // slice type
 
283
        len   uintptr
287
284
}
288
285
 
289
286
// chanType represents a channel type.
290
287
type chanType struct {
291
 
        commonType `reflect:"chan"`
292
 
        elem       *runtimeType // channel element type
293
 
        dir        uintptr      // channel direction (ChanDir)
 
288
        rtype `reflect:"chan"`
 
289
        elem  *rtype  // channel element type
 
290
        dir   uintptr // channel direction (ChanDir)
294
291
}
295
292
 
296
293
// funcType represents a function type.
297
294
type funcType struct {
298
 
        commonType `reflect:"func"`
299
 
        dotdotdot  bool           // last input parameter is ...
300
 
        in         []*runtimeType // input parameter types
301
 
        out        []*runtimeType // output parameter types
 
295
        rtype     `reflect:"func"`
 
296
        dotdotdot bool     // last input parameter is ...
 
297
        in        []*rtype // input parameter types
 
298
        out       []*rtype // output parameter types
302
299
}
303
300
 
304
301
// imethod represents a method on an interface type
305
302
type imethod struct {
306
 
        name    *string      // name of method
307
 
        pkgPath *string      // nil for exported Names; otherwise import path
308
 
        typ     *runtimeType // .(*FuncType) underneath
 
303
        name    *string // name of method
 
304
        pkgPath *string // nil for exported Names; otherwise import path
 
305
        typ     *rtype  // .(*FuncType) underneath
309
306
}
310
307
 
311
308
// interfaceType represents an interface type.
312
309
type interfaceType struct {
313
 
        commonType `reflect:"interface"`
314
 
        methods    []imethod // sorted by hash
 
310
        rtype   `reflect:"interface"`
 
311
        methods []imethod // sorted by hash
315
312
}
316
313
 
317
314
// mapType represents a map type.
318
315
type mapType struct {
319
 
        commonType `reflect:"map"`
320
 
        key        *runtimeType // map key type
321
 
        elem       *runtimeType // map element (value) type
 
316
        rtype `reflect:"map"`
 
317
        key   *rtype // map key type
 
318
        elem  *rtype // map element (value) type
322
319
}
323
320
 
324
321
// ptrType represents a pointer type.
325
322
type ptrType struct {
326
 
        commonType `reflect:"ptr"`
327
 
        elem       *runtimeType // pointer element (pointed at) type
 
323
        rtype `reflect:"ptr"`
 
324
        elem  *rtype // pointer element (pointed at) type
328
325
}
329
326
 
330
327
// sliceType represents a slice type.
331
328
type sliceType struct {
332
 
        commonType `reflect:"slice"`
333
 
        elem       *runtimeType // slice element type
 
329
        rtype `reflect:"slice"`
 
330
        elem  *rtype // slice element type
334
331
}
335
332
 
336
333
// Struct field
337
334
type structField struct {
338
 
        name    *string      // nil for embedded fields
339
 
        pkgPath *string      // nil for exported Names; otherwise import path
340
 
        typ     *runtimeType // type of field
341
 
        tag     *string      // nil if no tag
342
 
        offset  uintptr      // byte offset of field within struct
 
335
        name    *string // nil for embedded fields
 
336
        pkgPath *string // nil for exported Names; otherwise import path
 
337
        typ     *rtype  // type of field
 
338
        tag     *string // nil if no tag
 
339
        offset  uintptr // byte offset of field within struct
343
340
}
344
341
 
345
342
// structType represents a struct type.
346
343
type structType struct {
347
 
        commonType `reflect:"struct"`
348
 
        fields     []structField // sorted by offset
 
344
        rtype  `reflect:"struct"`
 
345
        fields []structField // sorted by offset
349
346
}
350
347
 
 
348
// NOTE: These are copied from ../runtime/mgc0.h.
 
349
// They must be kept in sync.
 
350
const (
 
351
        _GC_END = iota
 
352
        _GC_PTR
 
353
        _GC_APTR
 
354
        _GC_ARRAY_START
 
355
        _GC_ARRAY_NEXT
 
356
        _GC_CALL
 
357
        _GC_MAP_PTR
 
358
        _GC_CHAN_PTR
 
359
        _GC_STRING
 
360
        _GC_EFACE
 
361
        _GC_IFACE
 
362
        _GC_SLICE
 
363
        _GC_REGION
 
364
        _GC_NUM_INSTR
 
365
)
 
366
 
351
367
/*
352
368
 * The compiler knows the exact layout of all the data structures above.
353
369
 * The compiler does not know about the data structures and methods below.
359
375
        // PkgPath is the package path that qualifies a lower case (unexported)
360
376
        // method name.  It is empty for upper case (exported) method names.
361
377
        // The combination of PkgPath and Name uniquely identifies a method
362
 
        // in a method set. 
 
378
        // in a method set.
363
379
        // See http://golang.org/ref/spec#Uniqueness_of_identifiers
364
380
        Name    string
365
381
        PkgPath string
371
387
 
372
388
// High bit says whether type has
373
389
// embedded pointers,to help garbage collector.
374
 
const kindMask = 0x7f
 
390
const (
 
391
        kindMask       = 0x7f
 
392
        kindNoPointers = 0x80
 
393
)
375
394
 
376
395
func (k Kind) String() string {
377
396
        if int(k) < len(kindNames) {
428
447
        return *t.name
429
448
}
430
449
 
431
 
func (t *commonType) toType() Type {
432
 
        if t == nil {
433
 
                return nil
434
 
        }
435
 
        return t
436
 
}
437
 
 
438
 
func (t *commonType) String() string { return *t.string }
439
 
 
440
 
func (t *commonType) Size() uintptr { return t.size }
441
 
 
442
 
func (t *commonType) Bits() int {
 
450
func (t *rtype) String() string { return *t.string }
 
451
 
 
452
func (t *rtype) Size() uintptr { return t.size }
 
453
 
 
454
func (t *rtype) Bits() int {
443
455
        if t == nil {
444
456
                panic("reflect: Bits of nil Type")
445
457
        }
450
462
        return int(t.size) * 8
451
463
}
452
464
 
453
 
func (t *commonType) Align() int { return int(t.align) }
454
 
 
455
 
func (t *commonType) FieldAlign() int { return int(t.fieldAlign) }
456
 
 
457
 
func (t *commonType) Kind() Kind { return Kind(t.kind & kindMask) }
458
 
 
459
 
func (t *commonType) common() *commonType { return t }
 
465
func (t *rtype) Align() int { return int(t.align) }
 
466
 
 
467
func (t *rtype) FieldAlign() int { return int(t.fieldAlign) }
 
468
 
 
469
func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }
 
470
 
 
471
func (t *rtype) common() *rtype { return t }
460
472
 
461
473
func (t *uncommonType) Method(i int) (m Method) {
462
474
        if t == nil || i < 0 || i >= len(t.methods) {
471
483
                m.PkgPath = *p.pkgPath
472
484
                fl |= flagRO
473
485
        }
474
 
        mt := toCommonType(p.typ)
 
486
        mt := p.typ
475
487
        m.Type = mt
476
 
        fn := p.tfn
 
488
        fn := unsafe.Pointer(&p.tfn)
477
489
        m.Func = Value{mt, fn, fl}
478
490
        m.Index = i
479
491
        return
502
514
 
503
515
// TODO(rsc): 6g supplies these, but they are not
504
516
// as efficient as they could be: they have commonType
505
 
// as the receiver instead of *commonType.
506
 
func (t *commonType) NumMethod() int {
 
517
// as the receiver instead of *rtype.
 
518
func (t *rtype) NumMethod() int {
507
519
        if t.Kind() == Interface {
508
520
                tt := (*interfaceType)(unsafe.Pointer(t))
509
521
                return tt.NumMethod()
511
523
        return t.uncommonType.NumMethod()
512
524
}
513
525
 
514
 
func (t *commonType) Method(i int) (m Method) {
 
526
func (t *rtype) Method(i int) (m Method) {
515
527
        if t.Kind() == Interface {
516
528
                tt := (*interfaceType)(unsafe.Pointer(t))
517
529
                return tt.Method(i)
519
531
        return t.uncommonType.Method(i)
520
532
}
521
533
 
522
 
func (t *commonType) MethodByName(name string) (m Method, ok bool) {
 
534
func (t *rtype) MethodByName(name string) (m Method, ok bool) {
523
535
        if t.Kind() == Interface {
524
536
                tt := (*interfaceType)(unsafe.Pointer(t))
525
537
                return tt.MethodByName(name)
527
539
        return t.uncommonType.MethodByName(name)
528
540
}
529
541
 
530
 
func (t *commonType) PkgPath() string {
 
542
func (t *rtype) PkgPath() string {
531
543
        return t.uncommonType.PkgPath()
532
544
}
533
545
 
534
 
func (t *commonType) Name() string {
 
546
func (t *rtype) Name() string {
535
547
        return t.uncommonType.Name()
536
548
}
537
549
 
538
 
func (t *commonType) ChanDir() ChanDir {
 
550
func (t *rtype) ChanDir() ChanDir {
539
551
        if t.Kind() != Chan {
540
552
                panic("reflect: ChanDir of non-chan type")
541
553
        }
543
555
        return ChanDir(tt.dir)
544
556
}
545
557
 
546
 
func (t *commonType) IsVariadic() bool {
 
558
func (t *rtype) IsVariadic() bool {
547
559
        if t.Kind() != Func {
548
560
                panic("reflect: IsVariadic of non-func type")
549
561
        }
551
563
        return tt.dotdotdot
552
564
}
553
565
 
554
 
func (t *commonType) Elem() Type {
 
566
func (t *rtype) Elem() Type {
555
567
        switch t.Kind() {
556
568
        case Array:
557
569
                tt := (*arrayType)(unsafe.Pointer(t))
572
584
        panic("reflect: Elem of invalid type")
573
585
}
574
586
 
575
 
func (t *commonType) Field(i int) StructField {
 
587
func (t *rtype) Field(i int) StructField {
576
588
        if t.Kind() != Struct {
577
589
                panic("reflect: Field of non-struct type")
578
590
        }
580
592
        return tt.Field(i)
581
593
}
582
594
 
583
 
func (t *commonType) FieldByIndex(index []int) StructField {
 
595
func (t *rtype) FieldByIndex(index []int) StructField {
584
596
        if t.Kind() != Struct {
585
597
                panic("reflect: FieldByIndex of non-struct type")
586
598
        }
588
600
        return tt.FieldByIndex(index)
589
601
}
590
602
 
591
 
func (t *commonType) FieldByName(name string) (StructField, bool) {
 
603
func (t *rtype) FieldByName(name string) (StructField, bool) {
592
604
        if t.Kind() != Struct {
593
605
                panic("reflect: FieldByName of non-struct type")
594
606
        }
596
608
        return tt.FieldByName(name)
597
609
}
598
610
 
599
 
func (t *commonType) FieldByNameFunc(match func(string) bool) (StructField, bool) {
 
611
func (t *rtype) FieldByNameFunc(match func(string) bool) (StructField, bool) {
600
612
        if t.Kind() != Struct {
601
613
                panic("reflect: FieldByNameFunc of non-struct type")
602
614
        }
604
616
        return tt.FieldByNameFunc(match)
605
617
}
606
618
 
607
 
func (t *commonType) In(i int) Type {
 
619
func (t *rtype) In(i int) Type {
608
620
        if t.Kind() != Func {
609
621
                panic("reflect: In of non-func type")
610
622
        }
612
624
        return toType(tt.in[i])
613
625
}
614
626
 
615
 
func (t *commonType) Key() Type {
 
627
func (t *rtype) Key() Type {
616
628
        if t.Kind() != Map {
617
629
                panic("reflect: Key of non-map type")
618
630
        }
620
632
        return toType(tt.key)
621
633
}
622
634
 
623
 
func (t *commonType) Len() int {
 
635
func (t *rtype) Len() int {
624
636
        if t.Kind() != Array {
625
637
                panic("reflect: Len of non-array type")
626
638
        }
628
640
        return int(tt.len)
629
641
}
630
642
 
631
 
func (t *commonType) NumField() int {
 
643
func (t *rtype) NumField() int {
632
644
        if t.Kind() != Struct {
633
645
                panic("reflect: NumField of non-struct type")
634
646
        }
636
648
        return len(tt.fields)
637
649
}
638
650
 
639
 
func (t *commonType) NumIn() int {
 
651
func (t *rtype) NumIn() int {
640
652
        if t.Kind() != Func {
641
653
                panic("reflect: NumIn of non-func type")
642
654
        }
644
656
        return len(tt.in)
645
657
}
646
658
 
647
 
func (t *commonType) NumOut() int {
 
659
func (t *rtype) NumOut() int {
648
660
        if t.Kind() != Func {
649
661
                panic("reflect: NumOut of non-func type")
650
662
        }
652
664
        return len(tt.out)
653
665
}
654
666
 
655
 
func (t *commonType) Out(i int) Type {
 
667
func (t *rtype) Out(i int) Type {
656
668
        if t.Kind() != Func {
657
669
                panic("reflect: Out of non-func type")
658
670
        }
718
730
        Tag       StructTag // field tag string
719
731
        Offset    uintptr   // offset within struct, in bytes
720
732
        Index     []int     // index sequence for Type.FieldByIndex
721
 
        Anonymous bool      // is an anonymous field
 
733
        Anonymous bool      // is an embedded field
722
734
}
723
735
 
724
736
// A StructTag is the tag string in a struct field.
822
834
 
823
835
// FieldByIndex returns the nested field corresponding to index.
824
836
func (t *structType) FieldByIndex(index []int) (f StructField) {
825
 
        f.Type = Type(t.toType())
 
837
        f.Type = toType(&t.rtype)
826
838
        for i, x := range index {
827
839
                if i > 0 {
828
840
                        ft := f.Type
836
848
        return
837
849
}
838
850
 
839
 
const inf = 1 << 30 // infinity - no struct has that many nesting levels
840
 
 
841
 
func (t *structType) fieldByNameFunc(match func(string) bool, mark map[*structType]bool, depth int) (ff StructField, fd int) {
842
 
        fd = inf // field depth
843
 
 
844
 
        if mark[t] {
845
 
                // Struct already seen.
846
 
                return
847
 
        }
848
 
        mark[t] = true
849
 
 
850
 
        var fi int // field index
851
 
        n := 0     // number of matching fields at depth fd
852
 
L:
853
 
        for i := range t.fields {
854
 
                f := t.Field(i)
855
 
                d := inf
856
 
                switch {
857
 
                case match(f.Name):
858
 
                        // Matching top-level field.
859
 
                        d = depth
860
 
                case f.Anonymous:
861
 
                        ft := f.Type
862
 
                        if ft.Kind() == Ptr {
863
 
                                ft = ft.Elem()
864
 
                        }
865
 
                        switch {
866
 
                        case match(ft.Name()):
867
 
                                // Matching anonymous top-level field.
868
 
                                d = depth
869
 
                        case fd > depth:
870
 
                                // No top-level field yet; look inside nested structs.
871
 
                                if ft.Kind() == Struct {
872
 
                                        st := (*structType)(unsafe.Pointer(ft.(*commonType)))
873
 
                                        f, d = st.fieldByNameFunc(match, mark, depth+1)
874
 
                                }
875
 
                        }
876
 
                }
877
 
 
878
 
                switch {
879
 
                case d < fd:
880
 
                        // Found field at shallower depth.
881
 
                        ff, fi, fd = f, i, d
882
 
                        n = 1
883
 
                case d == fd:
884
 
                        // More than one matching field at the same depth (or d, fd == inf).
885
 
                        // Same as no field found at this depth.
886
 
                        n++
887
 
                        if d == depth {
888
 
                                // Impossible to find a field at lower depth.
889
 
                                break L
890
 
                        }
891
 
                }
892
 
        }
893
 
 
894
 
        if n == 1 {
895
 
                // Found matching field.
896
 
                if depth >= len(ff.Index) {
897
 
                        ff.Index = make([]int, depth+1)
898
 
                }
899
 
                if len(ff.Index) > 1 {
900
 
                        ff.Index[depth] = fi
901
 
                }
902
 
        } else {
903
 
                // None or more than one matching field found.
904
 
                fd = inf
905
 
        }
906
 
 
907
 
        delete(mark, t)
 
851
// A fieldScan represents an item on the fieldByNameFunc scan work list.
 
852
type fieldScan struct {
 
853
        typ   *structType
 
854
        index []int
 
855
}
 
856
 
 
857
// FieldByNameFunc returns the struct field with a name that satisfies the
 
858
// match function and a boolean to indicate if the field was found.
 
859
func (t *structType) FieldByNameFunc(match func(string) bool) (result StructField, ok bool) {
 
860
        // This uses the same condition that the Go language does: there must be a unique instance
 
861
        // of the match at a given depth level. If there are multiple instances of a match at the
 
862
        // same depth, they annihilate each other and inhibit any possible match at a lower level.
 
863
        // The algorithm is breadth first search, one depth level at a time.
 
864
 
 
865
        // The current and next slices are work queues:
 
866
        // current lists the fields to visit on this depth level,
 
867
        // and next lists the fields on the next lower level.
 
868
        current := []fieldScan{}
 
869
        next := []fieldScan{{typ: t}}
 
870
 
 
871
        // nextCount records the number of times an embedded type has been
 
872
        // encountered and considered for queueing in the 'next' slice.
 
873
        // We only queue the first one, but we increment the count on each.
 
874
        // If a struct type T can be reached more than once at a given depth level,
 
875
        // then it annihilates itself and need not be considered at all when we
 
876
        // process that next depth level.
 
877
        var nextCount map[*structType]int
 
878
 
 
879
        // visited records the structs that have been considered already.
 
880
        // Embedded pointer fields can create cycles in the graph of
 
881
        // reachable embedded types; visited avoids following those cycles.
 
882
        // It also avoids duplicated effort: if we didn't find the field in an
 
883
        // embedded type T at level 2, we won't find it in one at level 4 either.
 
884
        visited := map[*structType]bool{}
 
885
 
 
886
        for len(next) > 0 {
 
887
                current, next = next, current[:0]
 
888
                count := nextCount
 
889
                nextCount = nil
 
890
 
 
891
                // Process all the fields at this depth, now listed in 'current'.
 
892
                // The loop queues embedded fields found in 'next', for processing during the next
 
893
                // iteration. The multiplicity of the 'current' field counts is recorded
 
894
                // in 'count'; the multiplicity of the 'next' field counts is recorded in 'nextCount'.
 
895
                for _, scan := range current {
 
896
                        t := scan.typ
 
897
                        if visited[t] {
 
898
                                // We've looked through this type before, at a higher level.
 
899
                                // That higher level would shadow the lower level we're now at,
 
900
                                // so this one can't be useful to us. Ignore it.
 
901
                                continue
 
902
                        }
 
903
                        visited[t] = true
 
904
                        for i := range t.fields {
 
905
                                f := &t.fields[i]
 
906
                                // Find name and type for field f.
 
907
                                var fname string
 
908
                                var ntyp *rtype
 
909
                                if f.name != nil {
 
910
                                        fname = *f.name
 
911
                                } else {
 
912
                                        // Anonymous field of type T or *T.
 
913
                                        // Name taken from type.
 
914
                                        ntyp = f.typ
 
915
                                        if ntyp.Kind() == Ptr {
 
916
                                                ntyp = ntyp.Elem().common()
 
917
                                        }
 
918
                                        fname = ntyp.Name()
 
919
                                }
 
920
 
 
921
                                // Does it match?
 
922
                                if match(fname) {
 
923
                                        // Potential match
 
924
                                        if count[t] > 1 || ok {
 
925
                                                // Name appeared multiple times at this level: annihilate.
 
926
                                                return StructField{}, false
 
927
                                        }
 
928
                                        result = t.Field(i)
 
929
                                        result.Index = nil
 
930
                                        result.Index = append(result.Index, scan.index...)
 
931
                                        result.Index = append(result.Index, i)
 
932
                                        ok = true
 
933
                                        continue
 
934
                                }
 
935
 
 
936
                                // Queue embedded struct fields for processing with next level,
 
937
                                // but only if we haven't seen a match yet at this level and only
 
938
                                // if the embedded types haven't already been queued.
 
939
                                if ok || ntyp == nil || ntyp.Kind() != Struct {
 
940
                                        continue
 
941
                                }
 
942
                                styp := (*structType)(unsafe.Pointer(ntyp))
 
943
                                if nextCount[styp] > 0 {
 
944
                                        nextCount[styp] = 2 // exact multiple doesn't matter
 
945
                                        continue
 
946
                                }
 
947
                                if nextCount == nil {
 
948
                                        nextCount = map[*structType]int{}
 
949
                                }
 
950
                                nextCount[styp] = 1
 
951
                                if count[t] > 1 {
 
952
                                        nextCount[styp] = 2 // exact multiple doesn't matter
 
953
                                }
 
954
                                var index []int
 
955
                                index = append(index, scan.index...)
 
956
                                index = append(index, i)
 
957
                                next = append(next, fieldScan{styp, index})
 
958
                        }
 
959
                }
 
960
                if ok {
 
961
                        break
 
962
                }
 
963
        }
908
964
        return
909
965
}
910
966
 
911
967
// FieldByName returns the struct field with the given name
912
968
// and a boolean to indicate if the field was found.
913
969
func (t *structType) FieldByName(name string) (f StructField, present bool) {
 
970
        // Quick check for top-level name, or struct without anonymous fields.
 
971
        hasAnon := false
 
972
        if name != "" {
 
973
                for i := range t.fields {
 
974
                        tf := &t.fields[i]
 
975
                        if tf.name == nil {
 
976
                                hasAnon = true
 
977
                                continue
 
978
                        }
 
979
                        if *tf.name == name {
 
980
                                return t.Field(i), true
 
981
                        }
 
982
                }
 
983
        }
 
984
        if !hasAnon {
 
985
                return
 
986
        }
914
987
        return t.FieldByNameFunc(func(s string) bool { return s == name })
915
988
}
916
989
 
917
 
// FieldByNameFunc returns the struct field with a name that satisfies the
918
 
// match function and a boolean to indicate if the field was found.
919
 
func (t *structType) FieldByNameFunc(match func(string) bool) (f StructField, present bool) {
920
 
        if ff, fd := t.fieldByNameFunc(match, make(map[*structType]bool), 0); fd < inf {
921
 
                ff.Index = ff.Index[0 : fd+1]
922
 
                f, present = ff, true
923
 
        }
924
 
        return
925
 
}
926
 
 
927
 
// Convert runtime type to reflect type.
928
 
func toCommonType(p *runtimeType) *commonType {
929
 
        if p == nil {
930
 
                return nil
931
 
        }
932
 
        return (*p).(*commonType)
933
 
}
934
 
 
935
 
func toType(p *runtimeType) Type {
936
 
        if p == nil {
937
 
                return nil
938
 
        }
939
 
        return (*p).(*commonType)
940
 
}
941
 
 
942
990
// TypeOf returns the reflection Type of the value in the interface{}.
943
991
// TypeOf(nil) returns nil.
944
992
func TypeOf(i interface{}) Type {
949
997
// ptrMap is the cache for PtrTo.
950
998
var ptrMap struct {
951
999
        sync.RWMutex
952
 
        m map[*commonType]*ptrType
953
 
}
954
 
 
955
 
func (t *commonType) runtimeType() *runtimeType {
956
 
        // The runtimeType always precedes the commonType in memory.
957
 
        // Adjust pointer to find it.
958
 
        var rt struct {
959
 
                i  runtimeType
960
 
                ct commonType
961
 
        }
962
 
        return (*runtimeType)(unsafe.Pointer(uintptr(unsafe.Pointer(t)) - unsafe.Offsetof(rt.ct)))
 
1000
        m map[*rtype]*ptrType
 
1001
}
 
1002
 
 
1003
// garbage collection bytecode program for pointer to memory without pointers.
 
1004
// See ../../cmd/gc/reflect.c:/^dgcsym1 and :/^dgcsym.
 
1005
type ptrDataGC struct {
 
1006
        width uintptr // sizeof(ptr)
 
1007
        op    uintptr // _GC_APTR
 
1008
        off   uintptr // 0
 
1009
        end   uintptr // _GC_END
 
1010
}
 
1011
 
 
1012
var ptrDataGCProg = ptrDataGC{
 
1013
        width: unsafe.Sizeof((*byte)(nil)),
 
1014
        op:    _GC_APTR,
 
1015
        off:   0,
 
1016
        end:   _GC_END,
 
1017
}
 
1018
 
 
1019
// garbage collection bytecode program for pointer to memory with pointers.
 
1020
// See ../../cmd/gc/reflect.c:/^dgcsym1 and :/^dgcsym.
 
1021
type ptrGC struct {
 
1022
        width  uintptr        // sizeof(ptr)
 
1023
        op     uintptr        // _GC_PTR
 
1024
        off    uintptr        // 0
 
1025
        elemgc unsafe.Pointer // element gc type
 
1026
        end    uintptr        // _GC_END
963
1027
}
964
1028
 
965
1029
// PtrTo returns the pointer type with element t.
966
1030
// For example, if t represents type Foo, PtrTo(t) represents *Foo.
967
1031
func PtrTo(t Type) Type {
968
 
        return t.(*commonType).ptrTo()
 
1032
        return t.(*rtype).ptrTo()
969
1033
}
970
1034
 
971
 
func (ct *commonType) ptrTo() *commonType {
972
 
        if p := ct.ptrToThis; p != nil {
973
 
                return toCommonType(p)
 
1035
func (t *rtype) ptrTo() *rtype {
 
1036
        if p := t.ptrToThis; p != nil {
 
1037
                return p
974
1038
        }
975
1039
 
976
1040
        // Otherwise, synthesize one.
980
1044
        // the type structures in read-only memory.
981
1045
        ptrMap.RLock()
982
1046
        if m := ptrMap.m; m != nil {
983
 
                if p := m[ct]; p != nil {
 
1047
                if p := m[t]; p != nil {
984
1048
                        ptrMap.RUnlock()
985
 
                        return &p.commonType
 
1049
                        return &p.rtype
986
1050
                }
987
1051
        }
988
1052
        ptrMap.RUnlock()
989
1053
        ptrMap.Lock()
990
1054
        if ptrMap.m == nil {
991
 
                ptrMap.m = make(map[*commonType]*ptrType)
 
1055
                ptrMap.m = make(map[*rtype]*ptrType)
992
1056
        }
993
 
        p := ptrMap.m[ct]
 
1057
        p := ptrMap.m[t]
994
1058
        if p != nil {
995
1059
                // some other goroutine won the race and created it
996
1060
                ptrMap.Unlock()
997
 
                return &p.commonType
998
 
        }
999
 
 
1000
 
        var rt struct {
1001
 
                i runtimeType
1002
 
                ptrType
1003
 
        }
1004
 
        rt.i = &rt.commonType
1005
 
 
1006
 
        // initialize p using *byte's ptrType as a prototype.
1007
 
        p = &rt.ptrType
1008
 
        var ibyte interface{} = (*byte)(nil)
1009
 
        bp := (*ptrType)(unsafe.Pointer((**(**runtimeType)(unsafe.Pointer(&ibyte))).(*commonType)))
1010
 
        *p = *bp
1011
 
 
1012
 
        s := "*" + *ct.string
 
1061
                return &p.rtype
 
1062
        }
 
1063
 
 
1064
        // Create a new ptrType starting with the description
 
1065
        // of an *unsafe.Pointer.
 
1066
        p = new(ptrType)
 
1067
        var iptr interface{} = (*unsafe.Pointer)(nil)
 
1068
        prototype := *(**ptrType)(unsafe.Pointer(&iptr))
 
1069
        *p = *prototype
 
1070
 
 
1071
        s := "*" + *t.string
1013
1072
        p.string = &s
1014
1073
 
1015
1074
        // For the type structures linked into the binary, the
1017
1076
        // Create a good hash for the new string by using
1018
1077
        // the FNV-1 hash's mixing function to combine the
1019
1078
        // old hash and the new "*".
1020
 
        p.hash = ct.hash*16777619 ^ '*'
 
1079
        p.hash = fnv1(t.hash, '*')
1021
1080
 
1022
1081
        p.uncommonType = nil
1023
1082
        p.ptrToThis = nil
1024
 
        p.elem = (*runtimeType)(unsafe.Pointer(uintptr(unsafe.Pointer(ct)) - unsafe.Offsetof(rt.ptrType)))
1025
 
 
1026
 
        ptrMap.m[ct] = p
 
1083
        p.elem = t
 
1084
 
 
1085
        if t.kind&kindNoPointers != 0 {
 
1086
                p.gc = unsafe.Pointer(&ptrDataGCProg)
 
1087
        } else {
 
1088
                p.gc = unsafe.Pointer(&ptrGC{
 
1089
                        width:  p.size,
 
1090
                        op:     _GC_PTR,
 
1091
                        off:    0,
 
1092
                        elemgc: t.gc,
 
1093
                        end:    _GC_END,
 
1094
                })
 
1095
        }
 
1096
        // INCORRECT. Uncomment to check that TestPtrToGC fails when p.gc is wrong.
 
1097
        //p.gc = unsafe.Pointer(&badGC{width: p.size, end: _GC_END})
 
1098
 
 
1099
        ptrMap.m[t] = p
1027
1100
        ptrMap.Unlock()
1028
 
        return &p.commonType
1029
 
}
1030
 
 
1031
 
func (t *commonType) Implements(u Type) bool {
 
1101
        return &p.rtype
 
1102
}
 
1103
 
 
1104
// fnv1 incorporates the list of bytes into the hash x using the FNV-1 hash function.
 
1105
func fnv1(x uint32, list ...byte) uint32 {
 
1106
        for _, b := range list {
 
1107
                x = x*16777619 ^ uint32(b)
 
1108
        }
 
1109
        return x
 
1110
}
 
1111
 
 
1112
func (t *rtype) Implements(u Type) bool {
1032
1113
        if u == nil {
1033
1114
                panic("reflect: nil type passed to Type.Implements")
1034
1115
        }
1035
1116
        if u.Kind() != Interface {
1036
1117
                panic("reflect: non-interface type passed to Type.Implements")
1037
1118
        }
1038
 
        return implements(u.(*commonType), t)
 
1119
        return implements(u.(*rtype), t)
1039
1120
}
1040
1121
 
1041
 
func (t *commonType) AssignableTo(u Type) bool {
 
1122
func (t *rtype) AssignableTo(u Type) bool {
1042
1123
        if u == nil {
1043
1124
                panic("reflect: nil type passed to Type.AssignableTo")
1044
1125
        }
1045
 
        uu := u.(*commonType)
 
1126
        uu := u.(*rtype)
1046
1127
        return directlyAssignable(uu, t) || implements(uu, t)
1047
1128
}
1048
1129
 
 
1130
func (t *rtype) ConvertibleTo(u Type) bool {
 
1131
        if u == nil {
 
1132
                panic("reflect: nil type passed to Type.ConvertibleTo")
 
1133
        }
 
1134
        uu := u.(*rtype)
 
1135
        return convertOp(uu, t) != nil
 
1136
}
 
1137
 
1049
1138
// implements returns true if the type V implements the interface type T.
1050
 
func implements(T, V *commonType) bool {
 
1139
func implements(T, V *rtype) bool {
1051
1140
        if T.Kind() != Interface {
1052
1141
                return false
1053
1142
        }
1105
1194
// http://golang.org/doc/go_spec.html#Assignability
1106
1195
// Ignoring the interface rules (implemented elsewhere)
1107
1196
// and the ideal constant rules (no ideal constants at run time).
1108
 
func directlyAssignable(T, V *commonType) bool {
 
1197
func directlyAssignable(T, V *rtype) bool {
1109
1198
        // x's type V is identical to T?
1110
1199
        if T == V {
1111
1200
                return true
1117
1206
                return false
1118
1207
        }
1119
1208
 
1120
 
        // x's type T and V have identical underlying types.
1121
 
        // Since at least one is unnamed, only the composite types
1122
 
        // need to be considered.
1123
 
        switch T.Kind() {
 
1209
        // x's type T and V must  have identical underlying types.
 
1210
        return haveIdenticalUnderlyingType(T, V)
 
1211
}
 
1212
 
 
1213
func haveIdenticalUnderlyingType(T, V *rtype) bool {
 
1214
        if T == V {
 
1215
                return true
 
1216
        }
 
1217
 
 
1218
        kind := T.Kind()
 
1219
        if kind != V.Kind() {
 
1220
                return false
 
1221
        }
 
1222
 
 
1223
        // Non-composite types of equal kind have same underlying type
 
1224
        // (the predefined instance of the type).
 
1225
        if Bool <= kind && kind <= Complex128 || kind == String || kind == UnsafePointer {
 
1226
                return true
 
1227
        }
 
1228
 
 
1229
        // Composite types.
 
1230
        switch kind {
1124
1231
        case Array:
1125
1232
                return T.Elem() == V.Elem() && T.Len() == V.Len()
1126
1233
 
1178
1285
                for i := range t.fields {
1179
1286
                        tf := &t.fields[i]
1180
1287
                        vf := &v.fields[i]
1181
 
                        if tf.name != vf.name || tf.pkgPath != vf.pkgPath ||
1182
 
                                tf.typ != vf.typ || tf.tag != vf.tag || tf.offset != vf.offset {
 
1288
                        if tf.name != vf.name && (tf.name == nil || vf.name == nil || *tf.name != *vf.name) {
 
1289
                                return false
 
1290
                        }
 
1291
                        if tf.pkgPath != vf.pkgPath && (tf.pkgPath == nil || vf.pkgPath == nil || *tf.pkgPath != *vf.pkgPath) {
 
1292
                                return false
 
1293
                        }
 
1294
                        if tf.typ != vf.typ {
 
1295
                                return false
 
1296
                        }
 
1297
                        if tf.tag != vf.tag && (tf.tag == nil || vf.tag == nil || *tf.tag != *vf.tag) {
 
1298
                                return false
 
1299
                        }
 
1300
                        if tf.offset != vf.offset {
1183
1301
                                return false
1184
1302
                        }
1185
1303
                }
1188
1306
 
1189
1307
        return false
1190
1308
}
 
1309
 
 
1310
// typelinks is implemented in package runtime.
 
1311
// It returns a slice of all the 'typelink' information in the binary,
 
1312
// which is to say a slice of known types, sorted by string.
 
1313
// Note that strings are not unique identifiers for types:
 
1314
// there can be more than one with a given string.
 
1315
// Only types we might want to look up are included:
 
1316
// channels, maps, slices, and arrays.
 
1317
func typelinks() []*rtype
 
1318
 
 
1319
// typesByString returns the subslice of typelinks() whose elements have
 
1320
// the given string representation.
 
1321
// It may be empty (no known types with that string) or may have
 
1322
// multiple elements (multiple types with that string).
 
1323
func typesByString(s string) []*rtype {
 
1324
        typ := typelinks()
 
1325
 
 
1326
        // We are looking for the first index i where the string becomes >= s.
 
1327
        // This is a copy of sort.Search, with f(h) replaced by (*typ[h].string >= s).
 
1328
        i, j := 0, len(typ)
 
1329
        for i < j {
 
1330
                h := i + (j-i)/2 // avoid overflow when computing h
 
1331
                // i ≤ h < j
 
1332
                if !(*typ[h].string >= s) {
 
1333
                        i = h + 1 // preserves f(i-1) == false
 
1334
                } else {
 
1335
                        j = h // preserves f(j) == true
 
1336
                }
 
1337
        }
 
1338
        // i == j, f(i-1) == false, and f(j) (= f(i)) == true  =>  answer is i.
 
1339
 
 
1340
        // Having found the first, linear scan forward to find the last.
 
1341
        // We could do a second binary search, but the caller is going
 
1342
        // to do a linear scan anyway.
 
1343
        j = i
 
1344
        for j < len(typ) && *typ[j].string == s {
 
1345
                j++
 
1346
        }
 
1347
 
 
1348
        // This slice will be empty if the string is not found.
 
1349
        return typ[i:j]
 
1350
}
 
1351
 
 
1352
// The lookupCache caches ChanOf, MapOf, and SliceOf lookups.
 
1353
var lookupCache struct {
 
1354
        sync.RWMutex
 
1355
        m map[cacheKey]*rtype
 
1356
}
 
1357
 
 
1358
// A cacheKey is the key for use in the lookupCache.
 
1359
// Four values describe any of the types we are looking for:
 
1360
// type kind, one or two subtypes, and an extra integer.
 
1361
type cacheKey struct {
 
1362
        kind  Kind
 
1363
        t1    *rtype
 
1364
        t2    *rtype
 
1365
        extra uintptr
 
1366
}
 
1367
 
 
1368
// cacheGet looks for a type under the key k in the lookupCache.
 
1369
// If it finds one, it returns that type.
 
1370
// If not, it returns nil with the cache locked.
 
1371
// The caller is expected to use cachePut to unlock the cache.
 
1372
func cacheGet(k cacheKey) Type {
 
1373
        lookupCache.RLock()
 
1374
        t := lookupCache.m[k]
 
1375
        lookupCache.RUnlock()
 
1376
        if t != nil {
 
1377
                return t
 
1378
        }
 
1379
 
 
1380
        lookupCache.Lock()
 
1381
        t = lookupCache.m[k]
 
1382
        if t != nil {
 
1383
                lookupCache.Unlock()
 
1384
                return t
 
1385
        }
 
1386
 
 
1387
        if lookupCache.m == nil {
 
1388
                lookupCache.m = make(map[cacheKey]*rtype)
 
1389
        }
 
1390
 
 
1391
        return nil
 
1392
}
 
1393
 
 
1394
// cachePut stores the given type in the cache, unlocks the cache,
 
1395
// and returns the type. It is expected that the cache is locked
 
1396
// because cacheGet returned nil.
 
1397
func cachePut(k cacheKey, t *rtype) Type {
 
1398
        lookupCache.m[k] = t
 
1399
        lookupCache.Unlock()
 
1400
        return t
 
1401
}
 
1402
 
 
1403
// garbage collection bytecode program for chan or map.
 
1404
// See ../../cmd/gc/reflect.c:/^dgcsym1 and :/^dgcsym.
 
1405
type chanMapGC struct {
 
1406
        width uintptr // sizeof(map)
 
1407
        op    uintptr // _GC_MAP_PTR or _GC_CHAN_PTR
 
1408
        off   uintptr // 0
 
1409
        typ   *rtype  // map type
 
1410
        end   uintptr // _GC_END
 
1411
}
 
1412
 
 
1413
type badGC struct {
 
1414
        width uintptr
 
1415
        end   uintptr
 
1416
}
 
1417
 
 
1418
// ChanOf returns the channel type with the given direction and element type.
 
1419
// For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int.
 
1420
//
 
1421
// The gc runtime imposes a limit of 64 kB on channel element types.
 
1422
// If t's size is equal to or exceeds this limit, ChanOf panics.
 
1423
func ChanOf(dir ChanDir, t Type) Type {
 
1424
        typ := t.(*rtype)
 
1425
 
 
1426
        // Look in cache.
 
1427
        ckey := cacheKey{Chan, typ, nil, uintptr(dir)}
 
1428
        if ch := cacheGet(ckey); ch != nil {
 
1429
                return ch
 
1430
        }
 
1431
 
 
1432
        // This restriction is imposed by the gc compiler and the runtime.
 
1433
        if typ.size >= 1<<16 {
 
1434
                lookupCache.Unlock()
 
1435
                panic("reflect.ChanOf: element size too large")
 
1436
        }
 
1437
 
 
1438
        // Look in known types.
 
1439
        // TODO: Precedence when constructing string.
 
1440
        var s string
 
1441
        switch dir {
 
1442
        default:
 
1443
                lookupCache.Unlock()
 
1444
                panic("reflect.ChanOf: invalid dir")
 
1445
        case SendDir:
 
1446
                s = "chan<- " + *typ.string
 
1447
        case RecvDir:
 
1448
                s = "<-chan " + *typ.string
 
1449
        case BothDir:
 
1450
                s = "chan " + *typ.string
 
1451
        }
 
1452
        for _, tt := range typesByString(s) {
 
1453
                ch := (*chanType)(unsafe.Pointer(tt))
 
1454
                if ch.elem == typ && ch.dir == uintptr(dir) {
 
1455
                        return cachePut(ckey, tt)
 
1456
                }
 
1457
        }
 
1458
 
 
1459
        // Make a channel type.
 
1460
        var ichan interface{} = (chan unsafe.Pointer)(nil)
 
1461
        prototype := *(**chanType)(unsafe.Pointer(&ichan))
 
1462
        ch := new(chanType)
 
1463
        *ch = *prototype
 
1464
        ch.string = &s
 
1465
        ch.hash = fnv1(typ.hash, 'c', byte(dir))
 
1466
        ch.elem = typ
 
1467
        ch.uncommonType = nil
 
1468
        ch.ptrToThis = nil
 
1469
 
 
1470
        ch.gc = unsafe.Pointer(&chanMapGC{
 
1471
                width: ch.size,
 
1472
                op:    _GC_CHAN_PTR,
 
1473
                off:   0,
 
1474
                typ:   &ch.rtype,
 
1475
                end:   _GC_END,
 
1476
        })
 
1477
 
 
1478
        // INCORRECT. Uncomment to check that TestChanOfGC fails when ch.gc is wrong.
 
1479
        //ch.gc = unsafe.Pointer(&badGC{width: ch.size, end: _GC_END})
 
1480
 
 
1481
        return cachePut(ckey, &ch.rtype)
 
1482
}
 
1483
 
 
1484
func ismapkey(*rtype) bool // implemented in runtime
 
1485
 
 
1486
// MapOf returns the map type with the given key and element types.
 
1487
// For example, if k represents int and e represents string,
 
1488
// MapOf(k, e) represents map[int]string.
 
1489
//
 
1490
// If the key type is not a valid map key type (that is, if it does
 
1491
// not implement Go's == operator), MapOf panics.
 
1492
func MapOf(key, elem Type) Type {
 
1493
        ktyp := key.(*rtype)
 
1494
        etyp := elem.(*rtype)
 
1495
 
 
1496
        if !ismapkey(ktyp) {
 
1497
                panic("reflect.MapOf: invalid key type " + ktyp.String())
 
1498
        }
 
1499
 
 
1500
        // Look in cache.
 
1501
        ckey := cacheKey{Map, ktyp, etyp, 0}
 
1502
        if mt := cacheGet(ckey); mt != nil {
 
1503
                return mt
 
1504
        }
 
1505
 
 
1506
        // Look in known types.
 
1507
        s := "map[" + *ktyp.string + "]" + *etyp.string
 
1508
        for _, tt := range typesByString(s) {
 
1509
                mt := (*mapType)(unsafe.Pointer(tt))
 
1510
                if mt.key == ktyp && mt.elem == etyp {
 
1511
                        return cachePut(ckey, tt)
 
1512
                }
 
1513
        }
 
1514
 
 
1515
        // Make a map type.
 
1516
        var imap interface{} = (map[unsafe.Pointer]unsafe.Pointer)(nil)
 
1517
        prototype := *(**mapType)(unsafe.Pointer(&imap))
 
1518
        mt := new(mapType)
 
1519
        *mt = *prototype
 
1520
        mt.string = &s
 
1521
        mt.hash = fnv1(etyp.hash, 'm', byte(ktyp.hash>>24), byte(ktyp.hash>>16), byte(ktyp.hash>>8), byte(ktyp.hash))
 
1522
        mt.key = ktyp
 
1523
        mt.elem = etyp
 
1524
        mt.uncommonType = nil
 
1525
        mt.ptrToThis = nil
 
1526
 
 
1527
        mt.gc = unsafe.Pointer(&chanMapGC{
 
1528
                width: mt.size,
 
1529
                op:    _GC_MAP_PTR,
 
1530
                off:   0,
 
1531
                typ:   &mt.rtype,
 
1532
                end:   _GC_END,
 
1533
        })
 
1534
 
 
1535
        // INCORRECT. Uncomment to check that TestMapOfGC and TestMapOfGCValues
 
1536
        // fail when mt.gc is wrong.
 
1537
        //mt.gc = unsafe.Pointer(&badGC{width: mt.size, end: _GC_END})
 
1538
 
 
1539
        return cachePut(ckey, &mt.rtype)
 
1540
}
 
1541
 
 
1542
// garbage collection bytecode program for slice of non-zero-length values.
 
1543
// See ../../cmd/gc/reflect.c:/^dgcsym1 and :/^dgcsym.
 
1544
type sliceGC struct {
 
1545
        width  uintptr        // sizeof(slice)
 
1546
        op     uintptr        // _GC_SLICE
 
1547
        off    uintptr        // 0
 
1548
        elemgc unsafe.Pointer // element gc program
 
1549
        end    uintptr        // _GC_END
 
1550
}
 
1551
 
 
1552
// garbage collection bytecode program for slice of zero-length values.
 
1553
// See ../../cmd/gc/reflect.c:/^dgcsym1 and :/^dgcsym.
 
1554
type sliceEmptyGC struct {
 
1555
        width uintptr // sizeof(slice)
 
1556
        op    uintptr // _GC_APTR
 
1557
        off   uintptr // 0
 
1558
        end   uintptr // _GC_END
 
1559
}
 
1560
 
 
1561
var sliceEmptyGCProg = sliceEmptyGC{
 
1562
        width: unsafe.Sizeof([]byte(nil)),
 
1563
        op:    _GC_APTR,
 
1564
        off:   0,
 
1565
        end:   _GC_END,
 
1566
}
 
1567
 
 
1568
// SliceOf returns the slice type with element type t.
 
1569
// For example, if t represents int, SliceOf(t) represents []int.
 
1570
func SliceOf(t Type) Type {
 
1571
        typ := t.(*rtype)
 
1572
 
 
1573
        // Look in cache.
 
1574
        ckey := cacheKey{Slice, typ, nil, 0}
 
1575
        if slice := cacheGet(ckey); slice != nil {
 
1576
                return slice
 
1577
        }
 
1578
 
 
1579
        // Look in known types.
 
1580
        s := "[]" + *typ.string
 
1581
        for _, tt := range typesByString(s) {
 
1582
                slice := (*sliceType)(unsafe.Pointer(tt))
 
1583
                if slice.elem == typ {
 
1584
                        return cachePut(ckey, tt)
 
1585
                }
 
1586
        }
 
1587
 
 
1588
        // Make a slice type.
 
1589
        var islice interface{} = ([]unsafe.Pointer)(nil)
 
1590
        prototype := *(**sliceType)(unsafe.Pointer(&islice))
 
1591
        slice := new(sliceType)
 
1592
        *slice = *prototype
 
1593
        slice.string = &s
 
1594
        slice.hash = fnv1(typ.hash, '[')
 
1595
        slice.elem = typ
 
1596
        slice.uncommonType = nil
 
1597
        slice.ptrToThis = nil
 
1598
 
 
1599
        if typ.size == 0 {
 
1600
                slice.gc = unsafe.Pointer(&sliceEmptyGCProg)
 
1601
        } else {
 
1602
                slice.gc = unsafe.Pointer(&sliceGC{
 
1603
                        width:  slice.size,
 
1604
                        op:     _GC_SLICE,
 
1605
                        off:    0,
 
1606
                        elemgc: typ.gc,
 
1607
                        end:    _GC_END,
 
1608
                })
 
1609
        }
 
1610
 
 
1611
        // INCORRECT. Uncomment to check that TestSliceOfOfGC fails when slice.gc is wrong.
 
1612
        //slice.gc = unsafe.Pointer(&badGC{width: slice.size, end: _GC_END})
 
1613
 
 
1614
        return cachePut(ckey, &slice.rtype)
 
1615
}
 
1616
 
 
1617
// ArrayOf returns the array type with the given count and element type.
 
1618
// For example, if t represents int, ArrayOf(5, t) represents [5]int.
 
1619
//
 
1620
// If the resulting type would be larger than the available address space,
 
1621
// ArrayOf panics.
 
1622
//
 
1623
// TODO(rsc): Unexported for now. Export once the alg field is set correctly
 
1624
// for the type. This may require significant work.
 
1625
func arrayOf(count int, elem Type) Type {
 
1626
        typ := elem.(*rtype)
 
1627
        slice := SliceOf(elem)
 
1628
 
 
1629
        // Look in cache.
 
1630
        ckey := cacheKey{Array, typ, nil, uintptr(count)}
 
1631
        if slice := cacheGet(ckey); slice != nil {
 
1632
                return slice
 
1633
        }
 
1634
 
 
1635
        // Look in known types.
 
1636
        s := "[" + strconv.Itoa(count) + "]" + *typ.string
 
1637
        for _, tt := range typesByString(s) {
 
1638
                slice := (*sliceType)(unsafe.Pointer(tt))
 
1639
                if slice.elem == typ {
 
1640
                        return cachePut(ckey, tt)
 
1641
                }
 
1642
        }
 
1643
 
 
1644
        // Make an array type.
 
1645
        var iarray interface{} = [1]unsafe.Pointer{}
 
1646
        prototype := *(**arrayType)(unsafe.Pointer(&iarray))
 
1647
        array := new(arrayType)
 
1648
        *array = *prototype
 
1649
        array.string = &s
 
1650
        array.hash = fnv1(typ.hash, '[')
 
1651
        for n := uint32(count); n > 0; n >>= 8 {
 
1652
                array.hash = fnv1(array.hash, byte(n))
 
1653
        }
 
1654
        array.hash = fnv1(array.hash, ']')
 
1655
        array.elem = typ
 
1656
        max := ^uintptr(0) / typ.size
 
1657
        if uintptr(count) > max {
 
1658
                panic("reflect.ArrayOf: array size would exceed virtual address space")
 
1659
        }
 
1660
        array.size = typ.size * uintptr(count)
 
1661
        array.align = typ.align
 
1662
        array.fieldAlign = typ.fieldAlign
 
1663
        // TODO: array.alg
 
1664
        // TODO: array.gc
 
1665
        array.uncommonType = nil
 
1666
        array.ptrToThis = nil
 
1667
        array.len = uintptr(count)
 
1668
        array.slice = slice.(*rtype)
 
1669
 
 
1670
        return cachePut(ckey, &array.rtype)
 
1671
}
 
1672
 
 
1673
// toType converts from a *rtype to a Type that can be returned
 
1674
// to the client of package reflect. In gc, the only concern is that
 
1675
// a nil *rtype must be replaced by a nil Type, but in gccgo this
 
1676
// function takes care of ensuring that multiple *rtype for the same
 
1677
// type are coalesced into a single Type.
 
1678
func toType(t *rtype) Type {
 
1679
        if t == nil {
 
1680
                return nil
 
1681
        }
 
1682
        return t
 
1683
}