]> Cypherpunks.ru repositories - gostls13.git/blob - src/reflect/all_test.go
[dev.typeparams] all: merge master (798ec73) into dev.typeparams
[gostls13.git] / src / reflect / all_test.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package reflect_test
6
7 import (
8         "bytes"
9         "encoding/base64"
10         "flag"
11         "fmt"
12         "go/token"
13         "internal/goarch"
14         "io"
15         "math"
16         "math/rand"
17         "os"
18         . "reflect"
19         "reflect/internal/example1"
20         "reflect/internal/example2"
21         "runtime"
22         "sort"
23         "strconv"
24         "strings"
25         "sync"
26         "sync/atomic"
27         "testing"
28         "time"
29         "unsafe"
30 )
31
32 var sink interface{}
33
34 func TestBool(t *testing.T) {
35         v := ValueOf(true)
36         if v.Bool() != true {
37                 t.Fatal("ValueOf(true).Bool() = false")
38         }
39 }
40
41 type integer int
42 type T struct {
43         a int
44         b float64
45         c string
46         d *int
47 }
48
49 type pair struct {
50         i interface{}
51         s string
52 }
53
54 func assert(t *testing.T, s, want string) {
55         if s != want {
56                 t.Errorf("have %#q want %#q", s, want)
57         }
58 }
59
60 var typeTests = []pair{
61         {struct{ x int }{}, "int"},
62         {struct{ x int8 }{}, "int8"},
63         {struct{ x int16 }{}, "int16"},
64         {struct{ x int32 }{}, "int32"},
65         {struct{ x int64 }{}, "int64"},
66         {struct{ x uint }{}, "uint"},
67         {struct{ x uint8 }{}, "uint8"},
68         {struct{ x uint16 }{}, "uint16"},
69         {struct{ x uint32 }{}, "uint32"},
70         {struct{ x uint64 }{}, "uint64"},
71         {struct{ x float32 }{}, "float32"},
72         {struct{ x float64 }{}, "float64"},
73         {struct{ x int8 }{}, "int8"},
74         {struct{ x (**int8) }{}, "**int8"},
75         {struct{ x (**integer) }{}, "**reflect_test.integer"},
76         {struct{ x ([32]int32) }{}, "[32]int32"},
77         {struct{ x ([]int8) }{}, "[]int8"},
78         {struct{ x (map[string]int32) }{}, "map[string]int32"},
79         {struct{ x (chan<- string) }{}, "chan<- string"},
80         {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
81         {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
82         {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
83         {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
84         {struct {
85                 x struct {
86                         c chan *int32
87                         d float32
88                 }
89         }{},
90                 "struct { c chan *int32; d float32 }",
91         },
92         {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
93         {struct {
94                 x struct {
95                         c func(chan *integer, *int8)
96                 }
97         }{},
98                 "struct { c func(chan *reflect_test.integer, *int8) }",
99         },
100         {struct {
101                 x struct {
102                         a int8
103                         b int32
104                 }
105         }{},
106                 "struct { a int8; b int32 }",
107         },
108         {struct {
109                 x struct {
110                         a int8
111                         b int8
112                         c int32
113                 }
114         }{},
115                 "struct { a int8; b int8; c int32 }",
116         },
117         {struct {
118                 x struct {
119                         a int8
120                         b int8
121                         c int8
122                         d int32
123                 }
124         }{},
125                 "struct { a int8; b int8; c int8; d int32 }",
126         },
127         {struct {
128                 x struct {
129                         a int8
130                         b int8
131                         c int8
132                         d int8
133                         e int32
134                 }
135         }{},
136                 "struct { a int8; b int8; c int8; d int8; e int32 }",
137         },
138         {struct {
139                 x struct {
140                         a int8
141                         b int8
142                         c int8
143                         d int8
144                         e int8
145                         f int32
146                 }
147         }{},
148                 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
149         },
150         {struct {
151                 x struct {
152                         a int8 `reflect:"hi there"`
153                 }
154         }{},
155                 `struct { a int8 "reflect:\"hi there\"" }`,
156         },
157         {struct {
158                 x struct {
159                         a int8 `reflect:"hi \x00there\t\n\"\\"`
160                 }
161         }{},
162                 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
163         },
164         {struct {
165                 x struct {
166                         f func(args ...int)
167                 }
168         }{},
169                 "struct { f func(...int) }",
170         },
171         {struct {
172                 x (interface {
173                         a(func(func(int) int) func(func(int)) int)
174                         b()
175                 })
176         }{},
177                 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
178         },
179         {struct {
180                 x struct {
181                         int32
182                         int64
183                 }
184         }{},
185                 "struct { int32; int64 }",
186         },
187 }
188
189 var valueTests = []pair{
190         {new(int), "132"},
191         {new(int8), "8"},
192         {new(int16), "16"},
193         {new(int32), "32"},
194         {new(int64), "64"},
195         {new(uint), "132"},
196         {new(uint8), "8"},
197         {new(uint16), "16"},
198         {new(uint32), "32"},
199         {new(uint64), "64"},
200         {new(float32), "256.25"},
201         {new(float64), "512.125"},
202         {new(complex64), "532.125+10i"},
203         {new(complex128), "564.25+1i"},
204         {new(string), "stringy cheese"},
205         {new(bool), "true"},
206         {new(*int8), "*int8(0)"},
207         {new(**int8), "**int8(0)"},
208         {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
209         {new(**integer), "**reflect_test.integer(0)"},
210         {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
211         {new(chan<- string), "chan<- string"},
212         {new(func(a int8, b int32)), "func(int8, int32)(0)"},
213         {new(struct {
214                 c chan *int32
215                 d float32
216         }),
217                 "struct { c chan *int32; d float32 }{chan *int32, 0}",
218         },
219         {new(struct{ c func(chan *integer, *int8) }),
220                 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
221         },
222         {new(struct {
223                 a int8
224                 b int32
225         }),
226                 "struct { a int8; b int32 }{0, 0}",
227         },
228         {new(struct {
229                 a int8
230                 b int8
231                 c int32
232         }),
233                 "struct { a int8; b int8; c int32 }{0, 0, 0}",
234         },
235 }
236
237 func testType(t *testing.T, i int, typ Type, want string) {
238         s := typ.String()
239         if s != want {
240                 t.Errorf("#%d: have %#q, want %#q", i, s, want)
241         }
242 }
243
244 func TestTypes(t *testing.T) {
245         for i, tt := range typeTests {
246                 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
247         }
248 }
249
250 func TestSet(t *testing.T) {
251         for i, tt := range valueTests {
252                 v := ValueOf(tt.i)
253                 v = v.Elem()
254                 switch v.Kind() {
255                 case Int:
256                         v.SetInt(132)
257                 case Int8:
258                         v.SetInt(8)
259                 case Int16:
260                         v.SetInt(16)
261                 case Int32:
262                         v.SetInt(32)
263                 case Int64:
264                         v.SetInt(64)
265                 case Uint:
266                         v.SetUint(132)
267                 case Uint8:
268                         v.SetUint(8)
269                 case Uint16:
270                         v.SetUint(16)
271                 case Uint32:
272                         v.SetUint(32)
273                 case Uint64:
274                         v.SetUint(64)
275                 case Float32:
276                         v.SetFloat(256.25)
277                 case Float64:
278                         v.SetFloat(512.125)
279                 case Complex64:
280                         v.SetComplex(532.125 + 10i)
281                 case Complex128:
282                         v.SetComplex(564.25 + 1i)
283                 case String:
284                         v.SetString("stringy cheese")
285                 case Bool:
286                         v.SetBool(true)
287                 }
288                 s := valueToString(v)
289                 if s != tt.s {
290                         t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
291                 }
292         }
293 }
294
295 func TestSetValue(t *testing.T) {
296         for i, tt := range valueTests {
297                 v := ValueOf(tt.i).Elem()
298                 switch v.Kind() {
299                 case Int:
300                         v.Set(ValueOf(int(132)))
301                 case Int8:
302                         v.Set(ValueOf(int8(8)))
303                 case Int16:
304                         v.Set(ValueOf(int16(16)))
305                 case Int32:
306                         v.Set(ValueOf(int32(32)))
307                 case Int64:
308                         v.Set(ValueOf(int64(64)))
309                 case Uint:
310                         v.Set(ValueOf(uint(132)))
311                 case Uint8:
312                         v.Set(ValueOf(uint8(8)))
313                 case Uint16:
314                         v.Set(ValueOf(uint16(16)))
315                 case Uint32:
316                         v.Set(ValueOf(uint32(32)))
317                 case Uint64:
318                         v.Set(ValueOf(uint64(64)))
319                 case Float32:
320                         v.Set(ValueOf(float32(256.25)))
321                 case Float64:
322                         v.Set(ValueOf(512.125))
323                 case Complex64:
324                         v.Set(ValueOf(complex64(532.125 + 10i)))
325                 case Complex128:
326                         v.Set(ValueOf(complex128(564.25 + 1i)))
327                 case String:
328                         v.Set(ValueOf("stringy cheese"))
329                 case Bool:
330                         v.Set(ValueOf(true))
331                 }
332                 s := valueToString(v)
333                 if s != tt.s {
334                         t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
335                 }
336         }
337 }
338
339 func TestCanSetField(t *testing.T) {
340         type embed struct{ x, X int }
341         type Embed struct{ x, X int }
342         type S1 struct {
343                 embed
344                 x, X int
345         }
346         type S2 struct {
347                 *embed
348                 x, X int
349         }
350         type S3 struct {
351                 Embed
352                 x, X int
353         }
354         type S4 struct {
355                 *Embed
356                 x, X int
357         }
358
359         type testCase struct {
360                 // -1 means Addr().Elem() of current value
361                 index  []int
362                 canSet bool
363         }
364         tests := []struct {
365                 val   Value
366                 cases []testCase
367         }{{
368                 val: ValueOf(&S1{}),
369                 cases: []testCase{
370                         {[]int{0}, false},
371                         {[]int{0, -1}, false},
372                         {[]int{0, 0}, false},
373                         {[]int{0, 0, -1}, false},
374                         {[]int{0, -1, 0}, false},
375                         {[]int{0, -1, 0, -1}, false},
376                         {[]int{0, 1}, true},
377                         {[]int{0, 1, -1}, true},
378                         {[]int{0, -1, 1}, true},
379                         {[]int{0, -1, 1, -1}, true},
380                         {[]int{1}, false},
381                         {[]int{1, -1}, false},
382                         {[]int{2}, true},
383                         {[]int{2, -1}, true},
384                 },
385         }, {
386                 val: ValueOf(&S2{embed: &embed{}}),
387                 cases: []testCase{
388                         {[]int{0}, false},
389                         {[]int{0, -1}, false},
390                         {[]int{0, 0}, false},
391                         {[]int{0, 0, -1}, false},
392                         {[]int{0, -1, 0}, false},
393                         {[]int{0, -1, 0, -1}, false},
394                         {[]int{0, 1}, true},
395                         {[]int{0, 1, -1}, true},
396                         {[]int{0, -1, 1}, true},
397                         {[]int{0, -1, 1, -1}, true},
398                         {[]int{1}, false},
399                         {[]int{2}, true},
400                 },
401         }, {
402                 val: ValueOf(&S3{}),
403                 cases: []testCase{
404                         {[]int{0}, true},
405                         {[]int{0, -1}, true},
406                         {[]int{0, 0}, false},
407                         {[]int{0, 0, -1}, false},
408                         {[]int{0, -1, 0}, false},
409                         {[]int{0, -1, 0, -1}, false},
410                         {[]int{0, 1}, true},
411                         {[]int{0, 1, -1}, true},
412                         {[]int{0, -1, 1}, true},
413                         {[]int{0, -1, 1, -1}, true},
414                         {[]int{1}, false},
415                         {[]int{2}, true},
416                 },
417         }, {
418                 val: ValueOf(&S4{Embed: &Embed{}}),
419                 cases: []testCase{
420                         {[]int{0}, true},
421                         {[]int{0, -1}, true},
422                         {[]int{0, 0}, false},
423                         {[]int{0, 0, -1}, false},
424                         {[]int{0, -1, 0}, false},
425                         {[]int{0, -1, 0, -1}, false},
426                         {[]int{0, 1}, true},
427                         {[]int{0, 1, -1}, true},
428                         {[]int{0, -1, 1}, true},
429                         {[]int{0, -1, 1, -1}, true},
430                         {[]int{1}, false},
431                         {[]int{2}, true},
432                 },
433         }}
434
435         for _, tt := range tests {
436                 t.Run(tt.val.Type().Name(), func(t *testing.T) {
437                         for _, tc := range tt.cases {
438                                 f := tt.val
439                                 for _, i := range tc.index {
440                                         if f.Kind() == Ptr {
441                                                 f = f.Elem()
442                                         }
443                                         if i == -1 {
444                                                 f = f.Addr().Elem()
445                                         } else {
446                                                 f = f.Field(i)
447                                         }
448                                 }
449                                 if got := f.CanSet(); got != tc.canSet {
450                                         t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
451                                 }
452                         }
453                 })
454         }
455 }
456
457 var _i = 7
458
459 var valueToStringTests = []pair{
460         {123, "123"},
461         {123.5, "123.5"},
462         {byte(123), "123"},
463         {"abc", "abc"},
464         {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
465         {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
466         {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
467         {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
468         {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
469         {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
470 }
471
472 func TestValueToString(t *testing.T) {
473         for i, test := range valueToStringTests {
474                 s := valueToString(ValueOf(test.i))
475                 if s != test.s {
476                         t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
477                 }
478         }
479 }
480
481 func TestArrayElemSet(t *testing.T) {
482         v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
483         v.Index(4).SetInt(123)
484         s := valueToString(v)
485         const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
486         if s != want {
487                 t.Errorf("[10]int: have %#q want %#q", s, want)
488         }
489
490         v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
491         v.Index(4).SetInt(123)
492         s = valueToString(v)
493         const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
494         if s != want1 {
495                 t.Errorf("[]int: have %#q want %#q", s, want1)
496         }
497 }
498
499 func TestPtrPointTo(t *testing.T) {
500         var ip *int32
501         var i int32 = 1234
502         vip := ValueOf(&ip)
503         vi := ValueOf(&i).Elem()
504         vip.Elem().Set(vi.Addr())
505         if *ip != 1234 {
506                 t.Errorf("got %d, want 1234", *ip)
507         }
508
509         ip = nil
510         vp := ValueOf(&ip).Elem()
511         vp.Set(Zero(vp.Type()))
512         if ip != nil {
513                 t.Errorf("got non-nil (%p), want nil", ip)
514         }
515 }
516
517 func TestPtrSetNil(t *testing.T) {
518         var i int32 = 1234
519         ip := &i
520         vip := ValueOf(&ip)
521         vip.Elem().Set(Zero(vip.Elem().Type()))
522         if ip != nil {
523                 t.Errorf("got non-nil (%d), want nil", *ip)
524         }
525 }
526
527 func TestMapSetNil(t *testing.T) {
528         m := make(map[string]int)
529         vm := ValueOf(&m)
530         vm.Elem().Set(Zero(vm.Elem().Type()))
531         if m != nil {
532                 t.Errorf("got non-nil (%p), want nil", m)
533         }
534 }
535
536 func TestAll(t *testing.T) {
537         testType(t, 1, TypeOf((int8)(0)), "int8")
538         testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
539
540         typ := TypeOf((*struct {
541                 c chan *int32
542                 d float32
543         })(nil))
544         testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
545         etyp := typ.Elem()
546         testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
547         styp := etyp
548         f := styp.Field(0)
549         testType(t, 5, f.Type, "chan *int32")
550
551         f, present := styp.FieldByName("d")
552         if !present {
553                 t.Errorf("FieldByName says present field is absent")
554         }
555         testType(t, 6, f.Type, "float32")
556
557         f, present = styp.FieldByName("absent")
558         if present {
559                 t.Errorf("FieldByName says absent field is present")
560         }
561
562         typ = TypeOf([32]int32{})
563         testType(t, 7, typ, "[32]int32")
564         testType(t, 8, typ.Elem(), "int32")
565
566         typ = TypeOf((map[string]*int32)(nil))
567         testType(t, 9, typ, "map[string]*int32")
568         mtyp := typ
569         testType(t, 10, mtyp.Key(), "string")
570         testType(t, 11, mtyp.Elem(), "*int32")
571
572         typ = TypeOf((chan<- string)(nil))
573         testType(t, 12, typ, "chan<- string")
574         testType(t, 13, typ.Elem(), "string")
575
576         // make sure tag strings are not part of element type
577         typ = TypeOf(struct {
578                 d []uint32 `reflect:"TAG"`
579         }{}).Field(0).Type
580         testType(t, 14, typ, "[]uint32")
581 }
582
583 func TestInterfaceGet(t *testing.T) {
584         var inter struct {
585                 E interface{}
586         }
587         inter.E = 123.456
588         v1 := ValueOf(&inter)
589         v2 := v1.Elem().Field(0)
590         assert(t, v2.Type().String(), "interface {}")
591         i2 := v2.Interface()
592         v3 := ValueOf(i2)
593         assert(t, v3.Type().String(), "float64")
594 }
595
596 func TestInterfaceValue(t *testing.T) {
597         var inter struct {
598                 E interface{}
599         }
600         inter.E = 123.456
601         v1 := ValueOf(&inter)
602         v2 := v1.Elem().Field(0)
603         assert(t, v2.Type().String(), "interface {}")
604         v3 := v2.Elem()
605         assert(t, v3.Type().String(), "float64")
606
607         i3 := v2.Interface()
608         if _, ok := i3.(float64); !ok {
609                 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
610         }
611 }
612
613 func TestFunctionValue(t *testing.T) {
614         var x interface{} = func() {}
615         v := ValueOf(x)
616         if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
617                 t.Fatalf("TestFunction returned wrong pointer")
618         }
619         assert(t, v.Type().String(), "func()")
620 }
621
622 var appendTests = []struct {
623         orig, extra []int
624 }{
625         {make([]int, 2, 4), []int{22}},
626         {make([]int, 2, 4), []int{22, 33, 44}},
627 }
628
629 func sameInts(x, y []int) bool {
630         if len(x) != len(y) {
631                 return false
632         }
633         for i, xx := range x {
634                 if xx != y[i] {
635                         return false
636                 }
637         }
638         return true
639 }
640
641 func TestAppend(t *testing.T) {
642         for i, test := range appendTests {
643                 origLen, extraLen := len(test.orig), len(test.extra)
644                 want := append(test.orig, test.extra...)
645                 // Convert extra from []int to []Value.
646                 e0 := make([]Value, len(test.extra))
647                 for j, e := range test.extra {
648                         e0[j] = ValueOf(e)
649                 }
650                 // Convert extra from []int to *SliceValue.
651                 e1 := ValueOf(test.extra)
652                 // Test Append.
653                 a0 := ValueOf(test.orig)
654                 have0 := Append(a0, e0...).Interface().([]int)
655                 if !sameInts(have0, want) {
656                         t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
657                 }
658                 // Check that the orig and extra slices were not modified.
659                 if len(test.orig) != origLen {
660                         t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
661                 }
662                 if len(test.extra) != extraLen {
663                         t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
664                 }
665                 // Test AppendSlice.
666                 a1 := ValueOf(test.orig)
667                 have1 := AppendSlice(a1, e1).Interface().([]int)
668                 if !sameInts(have1, want) {
669                         t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
670                 }
671                 // Check that the orig and extra slices were not modified.
672                 if len(test.orig) != origLen {
673                         t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
674                 }
675                 if len(test.extra) != extraLen {
676                         t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
677                 }
678         }
679 }
680
681 func TestCopy(t *testing.T) {
682         a := []int{1, 2, 3, 4, 10, 9, 8, 7}
683         b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
684         c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
685         for i := 0; i < len(b); i++ {
686                 if b[i] != c[i] {
687                         t.Fatalf("b != c before test")
688                 }
689         }
690         a1 := a
691         b1 := b
692         aa := ValueOf(&a1).Elem()
693         ab := ValueOf(&b1).Elem()
694         for tocopy := 1; tocopy <= 7; tocopy++ {
695                 aa.SetLen(tocopy)
696                 Copy(ab, aa)
697                 aa.SetLen(8)
698                 for i := 0; i < tocopy; i++ {
699                         if a[i] != b[i] {
700                                 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
701                                         tocopy, i, a[i], i, b[i])
702                         }
703                 }
704                 for i := tocopy; i < len(b); i++ {
705                         if b[i] != c[i] {
706                                 if i < len(a) {
707                                         t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
708                                                 tocopy, i, a[i], i, b[i], i, c[i])
709                                 } else {
710                                         t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
711                                                 tocopy, i, b[i], i, c[i])
712                                 }
713                         } else {
714                                 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
715                         }
716                 }
717         }
718 }
719
720 func TestCopyString(t *testing.T) {
721         t.Run("Slice", func(t *testing.T) {
722                 s := bytes.Repeat([]byte{'_'}, 8)
723                 val := ValueOf(s)
724
725                 n := Copy(val, ValueOf(""))
726                 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
727                         t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
728                 }
729
730                 n = Copy(val, ValueOf("hello"))
731                 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
732                         t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
733                 }
734
735                 n = Copy(val, ValueOf("helloworld"))
736                 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
737                         t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
738                 }
739         })
740         t.Run("Array", func(t *testing.T) {
741                 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
742                 val := ValueOf(&s).Elem()
743
744                 n := Copy(val, ValueOf(""))
745                 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
746                         t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
747                 }
748
749                 n = Copy(val, ValueOf("hello"))
750                 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
751                         t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
752                 }
753
754                 n = Copy(val, ValueOf("helloworld"))
755                 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
756                         t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
757                 }
758         })
759 }
760
761 func TestCopyArray(t *testing.T) {
762         a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
763         b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
764         c := b
765         aa := ValueOf(&a).Elem()
766         ab := ValueOf(&b).Elem()
767         Copy(ab, aa)
768         for i := 0; i < len(a); i++ {
769                 if a[i] != b[i] {
770                         t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
771                 }
772         }
773         for i := len(a); i < len(b); i++ {
774                 if b[i] != c[i] {
775                         t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
776                 } else {
777                         t.Logf("elem %d is okay\n", i)
778                 }
779         }
780 }
781
782 func TestBigUnnamedStruct(t *testing.T) {
783         b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
784         v := ValueOf(b)
785         b1 := v.Interface().(struct {
786                 a, b, c, d int64
787         })
788         if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
789                 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
790         }
791 }
792
793 type big struct {
794         a, b, c, d, e int64
795 }
796
797 func TestBigStruct(t *testing.T) {
798         b := big{1, 2, 3, 4, 5}
799         v := ValueOf(b)
800         b1 := v.Interface().(big)
801         if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
802                 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
803         }
804 }
805
806 type Basic struct {
807         x int
808         y float32
809 }
810
811 type NotBasic Basic
812
813 type DeepEqualTest struct {
814         a, b interface{}
815         eq   bool
816 }
817
818 // Simple functions for DeepEqual tests.
819 var (
820         fn1 func()             // nil.
821         fn2 func()             // nil.
822         fn3 = func() { fn1() } // Not nil.
823 )
824
825 type self struct{}
826
827 type Loop *Loop
828 type Loopy interface{}
829
830 var loop1, loop2 Loop
831 var loopy1, loopy2 Loopy
832 var cycleMap1, cycleMap2, cycleMap3 map[string]interface{}
833
834 type structWithSelfPtr struct {
835         p *structWithSelfPtr
836         s string
837 }
838
839 func init() {
840         loop1 = &loop2
841         loop2 = &loop1
842
843         loopy1 = &loopy2
844         loopy2 = &loopy1
845
846         cycleMap1 = map[string]interface{}{}
847         cycleMap1["cycle"] = cycleMap1
848         cycleMap2 = map[string]interface{}{}
849         cycleMap2["cycle"] = cycleMap2
850         cycleMap3 = map[string]interface{}{}
851         cycleMap3["different"] = cycleMap3
852 }
853
854 var deepEqualTests = []DeepEqualTest{
855         // Equalities
856         {nil, nil, true},
857         {1, 1, true},
858         {int32(1), int32(1), true},
859         {0.5, 0.5, true},
860         {float32(0.5), float32(0.5), true},
861         {"hello", "hello", true},
862         {make([]int, 10), make([]int, 10), true},
863         {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
864         {Basic{1, 0.5}, Basic{1, 0.5}, true},
865         {error(nil), error(nil), true},
866         {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
867         {fn1, fn2, true},
868
869         // Inequalities
870         {1, 2, false},
871         {int32(1), int32(2), false},
872         {0.5, 0.6, false},
873         {float32(0.5), float32(0.6), false},
874         {"hello", "hey", false},
875         {make([]int, 10), make([]int, 11), false},
876         {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
877         {Basic{1, 0.5}, Basic{1, 0.6}, false},
878         {Basic{1, 0}, Basic{2, 0}, false},
879         {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
880         {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
881         {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
882         {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
883         {nil, 1, false},
884         {1, nil, false},
885         {fn1, fn3, false},
886         {fn3, fn3, false},
887         {[][]int{{1}}, [][]int{{2}}, false},
888         {math.NaN(), math.NaN(), false},
889         {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
890         {&[1]float64{math.NaN()}, self{}, true},
891         {[]float64{math.NaN()}, []float64{math.NaN()}, false},
892         {[]float64{math.NaN()}, self{}, true},
893         {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
894         {map[float64]float64{math.NaN(): 1}, self{}, true},
895         {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
896
897         // Nil vs empty: not the same.
898         {[]int{}, []int(nil), false},
899         {[]int{}, []int{}, true},
900         {[]int(nil), []int(nil), true},
901         {map[int]int{}, map[int]int(nil), false},
902         {map[int]int{}, map[int]int{}, true},
903         {map[int]int(nil), map[int]int(nil), true},
904
905         // Mismatched types
906         {1, 1.0, false},
907         {int32(1), int64(1), false},
908         {0.5, "hello", false},
909         {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
910         {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
911         {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
912         {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
913
914         // Possible loops.
915         {&loop1, &loop1, true},
916         {&loop1, &loop2, true},
917         {&loopy1, &loopy1, true},
918         {&loopy1, &loopy2, true},
919         {&cycleMap1, &cycleMap2, true},
920         {&cycleMap1, &cycleMap3, false},
921 }
922
923 func TestDeepEqual(t *testing.T) {
924         for _, test := range deepEqualTests {
925                 if test.b == (self{}) {
926                         test.b = test.a
927                 }
928                 if r := DeepEqual(test.a, test.b); r != test.eq {
929                         t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
930                 }
931         }
932 }
933
934 func TestTypeOf(t *testing.T) {
935         // Special case for nil
936         if typ := TypeOf(nil); typ != nil {
937                 t.Errorf("expected nil type for nil value; got %v", typ)
938         }
939         for _, test := range deepEqualTests {
940                 v := ValueOf(test.a)
941                 if !v.IsValid() {
942                         continue
943                 }
944                 typ := TypeOf(test.a)
945                 if typ != v.Type() {
946                         t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
947                 }
948         }
949 }
950
951 type Recursive struct {
952         x int
953         r *Recursive
954 }
955
956 func TestDeepEqualRecursiveStruct(t *testing.T) {
957         a, b := new(Recursive), new(Recursive)
958         *a = Recursive{12, a}
959         *b = Recursive{12, b}
960         if !DeepEqual(a, b) {
961                 t.Error("DeepEqual(recursive same) = false, want true")
962         }
963 }
964
965 type _Complex struct {
966         a int
967         b [3]*_Complex
968         c *string
969         d map[float64]float64
970 }
971
972 func TestDeepEqualComplexStruct(t *testing.T) {
973         m := make(map[float64]float64)
974         stra, strb := "hello", "hello"
975         a, b := new(_Complex), new(_Complex)
976         *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
977         *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
978         if !DeepEqual(a, b) {
979                 t.Error("DeepEqual(complex same) = false, want true")
980         }
981 }
982
983 func TestDeepEqualComplexStructInequality(t *testing.T) {
984         m := make(map[float64]float64)
985         stra, strb := "hello", "helloo" // Difference is here
986         a, b := new(_Complex), new(_Complex)
987         *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
988         *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
989         if DeepEqual(a, b) {
990                 t.Error("DeepEqual(complex different) = true, want false")
991         }
992 }
993
994 type UnexpT struct {
995         m map[int]int
996 }
997
998 func TestDeepEqualUnexportedMap(t *testing.T) {
999         // Check that DeepEqual can look at unexported fields.
1000         x1 := UnexpT{map[int]int{1: 2}}
1001         x2 := UnexpT{map[int]int{1: 2}}
1002         if !DeepEqual(&x1, &x2) {
1003                 t.Error("DeepEqual(x1, x2) = false, want true")
1004         }
1005
1006         y1 := UnexpT{map[int]int{2: 3}}
1007         if DeepEqual(&x1, &y1) {
1008                 t.Error("DeepEqual(x1, y1) = true, want false")
1009         }
1010 }
1011
1012 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
1013         s := ValueOf(x)
1014         f := s.Type().Field(1)
1015         if f.Offset != offs {
1016                 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1017         }
1018 }
1019
1020 // Check that structure alignment & offsets viewed through reflect agree with those
1021 // from the compiler itself.
1022 func TestAlignment(t *testing.T) {
1023         type T1inner struct {
1024                 a int
1025         }
1026         type T1 struct {
1027                 T1inner
1028                 f int
1029         }
1030         type T2inner struct {
1031                 a, b int
1032         }
1033         type T2 struct {
1034                 T2inner
1035                 f int
1036         }
1037
1038         x := T1{T1inner{2}, 17}
1039         check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1040
1041         x1 := T2{T2inner{2, 3}, 17}
1042         check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1043 }
1044
1045 func Nil(a interface{}, t *testing.T) {
1046         n := ValueOf(a).Field(0)
1047         if !n.IsNil() {
1048                 t.Errorf("%v should be nil", a)
1049         }
1050 }
1051
1052 func NotNil(a interface{}, t *testing.T) {
1053         n := ValueOf(a).Field(0)
1054         if n.IsNil() {
1055                 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1056         }
1057 }
1058
1059 func TestIsNil(t *testing.T) {
1060         // These implement IsNil.
1061         // Wrap in extra struct to hide interface type.
1062         doNil := []interface{}{
1063                 struct{ x *int }{},
1064                 struct{ x interface{} }{},
1065                 struct{ x map[string]int }{},
1066                 struct{ x func() bool }{},
1067                 struct{ x chan int }{},
1068                 struct{ x []string }{},
1069                 struct{ x unsafe.Pointer }{},
1070         }
1071         for _, ts := range doNil {
1072                 ty := TypeOf(ts).Field(0).Type
1073                 v := Zero(ty)
1074                 v.IsNil() // panics if not okay to call
1075         }
1076
1077         // Check the implementations
1078         var pi struct {
1079                 x *int
1080         }
1081         Nil(pi, t)
1082         pi.x = new(int)
1083         NotNil(pi, t)
1084
1085         var si struct {
1086                 x []int
1087         }
1088         Nil(si, t)
1089         si.x = make([]int, 10)
1090         NotNil(si, t)
1091
1092         var ci struct {
1093                 x chan int
1094         }
1095         Nil(ci, t)
1096         ci.x = make(chan int)
1097         NotNil(ci, t)
1098
1099         var mi struct {
1100                 x map[int]int
1101         }
1102         Nil(mi, t)
1103         mi.x = make(map[int]int)
1104         NotNil(mi, t)
1105
1106         var ii struct {
1107                 x interface{}
1108         }
1109         Nil(ii, t)
1110         ii.x = 2
1111         NotNil(ii, t)
1112
1113         var fi struct {
1114                 x func(t *testing.T)
1115         }
1116         Nil(fi, t)
1117         fi.x = TestIsNil
1118         NotNil(fi, t)
1119 }
1120
1121 func TestIsZero(t *testing.T) {
1122         for i, tt := range []struct {
1123                 x    interface{}
1124                 want bool
1125         }{
1126                 // Booleans
1127                 {true, false},
1128                 {false, true},
1129                 // Numeric types
1130                 {int(0), true},
1131                 {int(1), false},
1132                 {int8(0), true},
1133                 {int8(1), false},
1134                 {int16(0), true},
1135                 {int16(1), false},
1136                 {int32(0), true},
1137                 {int32(1), false},
1138                 {int64(0), true},
1139                 {int64(1), false},
1140                 {uint(0), true},
1141                 {uint(1), false},
1142                 {uint8(0), true},
1143                 {uint8(1), false},
1144                 {uint16(0), true},
1145                 {uint16(1), false},
1146                 {uint32(0), true},
1147                 {uint32(1), false},
1148                 {uint64(0), true},
1149                 {uint64(1), false},
1150                 {float32(0), true},
1151                 {float32(1.2), false},
1152                 {float64(0), true},
1153                 {float64(1.2), false},
1154                 {math.Copysign(0, -1), false},
1155                 {complex64(0), true},
1156                 {complex64(1.2), false},
1157                 {complex128(0), true},
1158                 {complex128(1.2), false},
1159                 {complex(math.Copysign(0, -1), 0), false},
1160                 {complex(0, math.Copysign(0, -1)), false},
1161                 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1162                 {uintptr(0), true},
1163                 {uintptr(128), false},
1164                 // Array
1165                 {Zero(TypeOf([5]string{})).Interface(), true},
1166                 {[5]string{"", "", "", "", ""}, true},
1167                 {[5]string{}, true},
1168                 {[5]string{"", "", "", "a", ""}, false},
1169                 // Chan
1170                 {(chan string)(nil), true},
1171                 {make(chan string), false},
1172                 {time.After(1), false},
1173                 // Func
1174                 {(func())(nil), true},
1175                 {New, false},
1176                 // Interface
1177                 {New(TypeOf(new(error)).Elem()).Elem(), true},
1178                 {(io.Reader)(strings.NewReader("")), false},
1179                 // Map
1180                 {(map[string]string)(nil), true},
1181                 {map[string]string{}, false},
1182                 {make(map[string]string), false},
1183                 // Ptr
1184                 {(*func())(nil), true},
1185                 {(*int)(nil), true},
1186                 {new(int), false},
1187                 // Slice
1188                 {[]string{}, false},
1189                 {([]string)(nil), true},
1190                 {make([]string, 0), false},
1191                 // Strings
1192                 {"", true},
1193                 {"not-zero", false},
1194                 // Structs
1195                 {T{}, true},
1196                 {T{123, 456.75, "hello", &_i}, false},
1197                 // UnsafePointer
1198                 {(unsafe.Pointer)(nil), true},
1199                 {(unsafe.Pointer)(new(int)), false},
1200         } {
1201                 var x Value
1202                 if v, ok := tt.x.(Value); ok {
1203                         x = v
1204                 } else {
1205                         x = ValueOf(tt.x)
1206                 }
1207
1208                 b := x.IsZero()
1209                 if b != tt.want {
1210                         t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1211                 }
1212
1213                 if !Zero(TypeOf(tt.x)).IsZero() {
1214                         t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1215                 }
1216         }
1217
1218         func() {
1219                 defer func() {
1220                         if r := recover(); r == nil {
1221                                 t.Error("should panic for invalid value")
1222                         }
1223                 }()
1224                 (Value{}).IsZero()
1225         }()
1226 }
1227
1228 func TestInterfaceExtraction(t *testing.T) {
1229         var s struct {
1230                 W io.Writer
1231         }
1232
1233         s.W = os.Stdout
1234         v := Indirect(ValueOf(&s)).Field(0).Interface()
1235         if v != s.W.(interface{}) {
1236                 t.Error("Interface() on interface: ", v, s.W)
1237         }
1238 }
1239
1240 func TestNilPtrValueSub(t *testing.T) {
1241         var pi *int
1242         if pv := ValueOf(pi); pv.Elem().IsValid() {
1243                 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1244         }
1245 }
1246
1247 func TestMap(t *testing.T) {
1248         m := map[string]int{"a": 1, "b": 2}
1249         mv := ValueOf(m)
1250         if n := mv.Len(); n != len(m) {
1251                 t.Errorf("Len = %d, want %d", n, len(m))
1252         }
1253         keys := mv.MapKeys()
1254         newmap := MakeMap(mv.Type())
1255         for k, v := range m {
1256                 // Check that returned Keys match keys in range.
1257                 // These aren't required to be in the same order.
1258                 seen := false
1259                 for _, kv := range keys {
1260                         if kv.String() == k {
1261                                 seen = true
1262                                 break
1263                         }
1264                 }
1265                 if !seen {
1266                         t.Errorf("Missing key %q", k)
1267                 }
1268
1269                 // Check that value lookup is correct.
1270                 vv := mv.MapIndex(ValueOf(k))
1271                 if vi := vv.Int(); vi != int64(v) {
1272                         t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1273                 }
1274
1275                 // Copy into new map.
1276                 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1277         }
1278         vv := mv.MapIndex(ValueOf("not-present"))
1279         if vv.IsValid() {
1280                 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1281         }
1282
1283         newm := newmap.Interface().(map[string]int)
1284         if len(newm) != len(m) {
1285                 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1286         }
1287
1288         for k, v := range newm {
1289                 mv, ok := m[k]
1290                 if mv != v {
1291                         t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1292                 }
1293         }
1294
1295         newmap.SetMapIndex(ValueOf("a"), Value{})
1296         v, ok := newm["a"]
1297         if ok {
1298                 t.Errorf("newm[\"a\"] = %d after delete", v)
1299         }
1300
1301         mv = ValueOf(&m).Elem()
1302         mv.Set(Zero(mv.Type()))
1303         if m != nil {
1304                 t.Errorf("mv.Set(nil) failed")
1305         }
1306 }
1307
1308 func TestNilMap(t *testing.T) {
1309         var m map[string]int
1310         mv := ValueOf(m)
1311         keys := mv.MapKeys()
1312         if len(keys) != 0 {
1313                 t.Errorf(">0 keys for nil map: %v", keys)
1314         }
1315
1316         // Check that value for missing key is zero.
1317         x := mv.MapIndex(ValueOf("hello"))
1318         if x.Kind() != Invalid {
1319                 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1320         }
1321
1322         // Check big value too.
1323         var mbig map[string][10 << 20]byte
1324         x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1325         if x.Kind() != Invalid {
1326                 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1327         }
1328
1329         // Test that deletes from a nil map succeed.
1330         mv.SetMapIndex(ValueOf("hi"), Value{})
1331 }
1332
1333 func TestChan(t *testing.T) {
1334         for loop := 0; loop < 2; loop++ {
1335                 var c chan int
1336                 var cv Value
1337
1338                 // check both ways to allocate channels
1339                 switch loop {
1340                 case 1:
1341                         c = make(chan int, 1)
1342                         cv = ValueOf(c)
1343                 case 0:
1344                         cv = MakeChan(TypeOf(c), 1)
1345                         c = cv.Interface().(chan int)
1346                 }
1347
1348                 // Send
1349                 cv.Send(ValueOf(2))
1350                 if i := <-c; i != 2 {
1351                         t.Errorf("reflect Send 2, native recv %d", i)
1352                 }
1353
1354                 // Recv
1355                 c <- 3
1356                 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1357                         t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1358                 }
1359
1360                 // TryRecv fail
1361                 val, ok := cv.TryRecv()
1362                 if val.IsValid() || ok {
1363                         t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1364                 }
1365
1366                 // TryRecv success
1367                 c <- 4
1368                 val, ok = cv.TryRecv()
1369                 if !val.IsValid() {
1370                         t.Errorf("TryRecv on ready chan got nil")
1371                 } else if i := val.Int(); i != 4 || !ok {
1372                         t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1373                 }
1374
1375                 // TrySend fail
1376                 c <- 100
1377                 ok = cv.TrySend(ValueOf(5))
1378                 i := <-c
1379                 if ok {
1380                         t.Errorf("TrySend on full chan succeeded: value %d", i)
1381                 }
1382
1383                 // TrySend success
1384                 ok = cv.TrySend(ValueOf(6))
1385                 if !ok {
1386                         t.Errorf("TrySend on empty chan failed")
1387                         select {
1388                         case x := <-c:
1389                                 t.Errorf("TrySend failed but it did send %d", x)
1390                         default:
1391                         }
1392                 } else {
1393                         if i = <-c; i != 6 {
1394                                 t.Errorf("TrySend 6, recv %d", i)
1395                         }
1396                 }
1397
1398                 // Close
1399                 c <- 123
1400                 cv.Close()
1401                 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1402                         t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1403                 }
1404                 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1405                         t.Errorf("after close Recv %d, %t", i.Int(), ok)
1406                 }
1407         }
1408
1409         // check creation of unbuffered channel
1410         var c chan int
1411         cv := MakeChan(TypeOf(c), 0)
1412         c = cv.Interface().(chan int)
1413         if cv.TrySend(ValueOf(7)) {
1414                 t.Errorf("TrySend on sync chan succeeded")
1415         }
1416         if v, ok := cv.TryRecv(); v.IsValid() || ok {
1417                 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1418         }
1419
1420         // len/cap
1421         cv = MakeChan(TypeOf(c), 10)
1422         c = cv.Interface().(chan int)
1423         for i := 0; i < 3; i++ {
1424                 c <- i
1425         }
1426         if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1427                 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1428         }
1429 }
1430
1431 // caseInfo describes a single case in a select test.
1432 type caseInfo struct {
1433         desc      string
1434         canSelect bool
1435         recv      Value
1436         closed    bool
1437         helper    func()
1438         panic     bool
1439 }
1440
1441 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1442
1443 func TestSelect(t *testing.T) {
1444         selectWatch.once.Do(func() { go selectWatcher() })
1445
1446         var x exhaustive
1447         nch := 0
1448         newop := func(n int, cap int) (ch, val Value) {
1449                 nch++
1450                 if nch%101%2 == 1 {
1451                         c := make(chan int, cap)
1452                         ch = ValueOf(c)
1453                         val = ValueOf(n)
1454                 } else {
1455                         c := make(chan string, cap)
1456                         ch = ValueOf(c)
1457                         val = ValueOf(fmt.Sprint(n))
1458                 }
1459                 return
1460         }
1461
1462         for n := 0; x.Next(); n++ {
1463                 if testing.Short() && n >= 1000 {
1464                         break
1465                 }
1466                 if n >= 100000 && !*allselect {
1467                         break
1468                 }
1469                 if n%100000 == 0 && testing.Verbose() {
1470                         println("TestSelect", n)
1471                 }
1472                 var cases []SelectCase
1473                 var info []caseInfo
1474
1475                 // Ready send.
1476                 if x.Maybe() {
1477                         ch, val := newop(len(cases), 1)
1478                         cases = append(cases, SelectCase{
1479                                 Dir:  SelectSend,
1480                                 Chan: ch,
1481                                 Send: val,
1482                         })
1483                         info = append(info, caseInfo{desc: "ready send", canSelect: true})
1484                 }
1485
1486                 // Ready recv.
1487                 if x.Maybe() {
1488                         ch, val := newop(len(cases), 1)
1489                         ch.Send(val)
1490                         cases = append(cases, SelectCase{
1491                                 Dir:  SelectRecv,
1492                                 Chan: ch,
1493                         })
1494                         info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1495                 }
1496
1497                 // Blocking send.
1498                 if x.Maybe() {
1499                         ch, val := newop(len(cases), 0)
1500                         cases = append(cases, SelectCase{
1501                                 Dir:  SelectSend,
1502                                 Chan: ch,
1503                                 Send: val,
1504                         })
1505                         // Let it execute?
1506                         if x.Maybe() {
1507                                 f := func() { ch.Recv() }
1508                                 info = append(info, caseInfo{desc: "blocking send", helper: f})
1509                         } else {
1510                                 info = append(info, caseInfo{desc: "blocking send"})
1511                         }
1512                 }
1513
1514                 // Blocking recv.
1515                 if x.Maybe() {
1516                         ch, val := newop(len(cases), 0)
1517                         cases = append(cases, SelectCase{
1518                                 Dir:  SelectRecv,
1519                                 Chan: ch,
1520                         })
1521                         // Let it execute?
1522                         if x.Maybe() {
1523                                 f := func() { ch.Send(val) }
1524                                 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1525                         } else {
1526                                 info = append(info, caseInfo{desc: "blocking recv"})
1527                         }
1528                 }
1529
1530                 // Zero Chan send.
1531                 if x.Maybe() {
1532                         // Maybe include value to send.
1533                         var val Value
1534                         if x.Maybe() {
1535                                 val = ValueOf(100)
1536                         }
1537                         cases = append(cases, SelectCase{
1538                                 Dir:  SelectSend,
1539                                 Send: val,
1540                         })
1541                         info = append(info, caseInfo{desc: "zero Chan send"})
1542                 }
1543
1544                 // Zero Chan receive.
1545                 if x.Maybe() {
1546                         cases = append(cases, SelectCase{
1547                                 Dir: SelectRecv,
1548                         })
1549                         info = append(info, caseInfo{desc: "zero Chan recv"})
1550                 }
1551
1552                 // nil Chan send.
1553                 if x.Maybe() {
1554                         cases = append(cases, SelectCase{
1555                                 Dir:  SelectSend,
1556                                 Chan: ValueOf((chan int)(nil)),
1557                                 Send: ValueOf(101),
1558                         })
1559                         info = append(info, caseInfo{desc: "nil Chan send"})
1560                 }
1561
1562                 // nil Chan recv.
1563                 if x.Maybe() {
1564                         cases = append(cases, SelectCase{
1565                                 Dir:  SelectRecv,
1566                                 Chan: ValueOf((chan int)(nil)),
1567                         })
1568                         info = append(info, caseInfo{desc: "nil Chan recv"})
1569                 }
1570
1571                 // closed Chan send.
1572                 if x.Maybe() {
1573                         ch := make(chan int)
1574                         close(ch)
1575                         cases = append(cases, SelectCase{
1576                                 Dir:  SelectSend,
1577                                 Chan: ValueOf(ch),
1578                                 Send: ValueOf(101),
1579                         })
1580                         info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1581                 }
1582
1583                 // closed Chan recv.
1584                 if x.Maybe() {
1585                         ch, val := newop(len(cases), 0)
1586                         ch.Close()
1587                         val = Zero(val.Type())
1588                         cases = append(cases, SelectCase{
1589                                 Dir:  SelectRecv,
1590                                 Chan: ch,
1591                         })
1592                         info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1593                 }
1594
1595                 var helper func() // goroutine to help the select complete
1596
1597                 // Add default? Must be last case here, but will permute.
1598                 // Add the default if the select would otherwise
1599                 // block forever, and maybe add it anyway.
1600                 numCanSelect := 0
1601                 canProceed := false
1602                 canBlock := true
1603                 canPanic := false
1604                 helpers := []int{}
1605                 for i, c := range info {
1606                         if c.canSelect {
1607                                 canProceed = true
1608                                 canBlock = false
1609                                 numCanSelect++
1610                                 if c.panic {
1611                                         canPanic = true
1612                                 }
1613                         } else if c.helper != nil {
1614                                 canProceed = true
1615                                 helpers = append(helpers, i)
1616                         }
1617                 }
1618                 if !canProceed || x.Maybe() {
1619                         cases = append(cases, SelectCase{
1620                                 Dir: SelectDefault,
1621                         })
1622                         info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1623                         numCanSelect++
1624                 } else if canBlock {
1625                         // Select needs to communicate with another goroutine.
1626                         cas := &info[helpers[x.Choose(len(helpers))]]
1627                         helper = cas.helper
1628                         cas.canSelect = true
1629                         numCanSelect++
1630                 }
1631
1632                 // Permute cases and case info.
1633                 // Doing too much here makes the exhaustive loop
1634                 // too exhausting, so just do two swaps.
1635                 for loop := 0; loop < 2; loop++ {
1636                         i := x.Choose(len(cases))
1637                         j := x.Choose(len(cases))
1638                         cases[i], cases[j] = cases[j], cases[i]
1639                         info[i], info[j] = info[j], info[i]
1640                 }
1641
1642                 if helper != nil {
1643                         // We wait before kicking off a goroutine to satisfy a blocked select.
1644                         // The pause needs to be big enough to let the select block before
1645                         // we run the helper, but if we lose that race once in a while it's okay: the
1646                         // select will just proceed immediately. Not a big deal.
1647                         // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1648                         pause := 10 * time.Microsecond
1649                         if testing.Short() {
1650                                 pause = 100 * time.Microsecond
1651                         }
1652                         time.AfterFunc(pause, helper)
1653                 }
1654
1655                 // Run select.
1656                 i, recv, recvOK, panicErr := runSelect(cases, info)
1657                 if panicErr != nil && !canPanic {
1658                         t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1659                 }
1660                 if panicErr == nil && canPanic && numCanSelect == 1 {
1661                         t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1662                 }
1663                 if panicErr != nil {
1664                         continue
1665                 }
1666
1667                 cas := info[i]
1668                 if !cas.canSelect {
1669                         recvStr := ""
1670                         if recv.IsValid() {
1671                                 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1672                         }
1673                         t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1674                         continue
1675                 }
1676                 if cas.panic {
1677                         t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1678                         continue
1679                 }
1680
1681                 if cases[i].Dir == SelectRecv {
1682                         if !recv.IsValid() {
1683                                 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1684                         }
1685                         if !cas.recv.IsValid() {
1686                                 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1687                         }
1688                         if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1689                                 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1690                                         t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1691                                 }
1692                                 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1693                         }
1694                 } else {
1695                         if recv.IsValid() || recvOK {
1696                                 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1697                         }
1698                 }
1699         }
1700 }
1701
1702 func TestSelectMaxCases(t *testing.T) {
1703         var sCases []SelectCase
1704         channel := make(chan int)
1705         close(channel)
1706         for i := 0; i < 65536; i++ {
1707                 sCases = append(sCases, SelectCase{
1708                         Dir:  SelectRecv,
1709                         Chan: ValueOf(channel),
1710                 })
1711         }
1712         // Should not panic
1713         _, _, _ = Select(sCases)
1714         sCases = append(sCases, SelectCase{
1715                 Dir:  SelectRecv,
1716                 Chan: ValueOf(channel),
1717         })
1718         defer func() {
1719                 if err := recover(); err != nil {
1720                         if err.(string) != "reflect.Select: too many cases (max 65536)" {
1721                                 t.Fatalf("unexpected error from select call with greater than max supported cases")
1722                         }
1723                 } else {
1724                         t.Fatalf("expected select call to panic with greater than max supported cases")
1725                 }
1726         }()
1727         // Should panic
1728         _, _, _ = Select(sCases)
1729 }
1730
1731 func TestSelectNop(t *testing.T) {
1732         // "select { default: }" should always return the default case.
1733         chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1734         if chosen != 0 {
1735                 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1736         }
1737 }
1738
1739 func BenchmarkSelect(b *testing.B) {
1740         channel := make(chan int)
1741         close(channel)
1742         var cases []SelectCase
1743         for i := 0; i < 8; i++ {
1744                 cases = append(cases, SelectCase{
1745                         Dir:  SelectRecv,
1746                         Chan: ValueOf(channel),
1747                 })
1748         }
1749         for _, numCases := range []int{1, 4, 8} {
1750                 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1751                         b.ReportAllocs()
1752                         for i := 0; i < b.N; i++ {
1753                                 _, _, _ = Select(cases[:numCases])
1754                         }
1755                 })
1756         }
1757 }
1758
1759 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1760 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1761 // an error describing the select and panics the entire test binary.
1762 var selectWatch struct {
1763         sync.Mutex
1764         once sync.Once
1765         now  time.Time
1766         info []caseInfo
1767 }
1768
1769 func selectWatcher() {
1770         for {
1771                 time.Sleep(1 * time.Second)
1772                 selectWatch.Lock()
1773                 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1774                         fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1775                         panic("select stuck")
1776                 }
1777                 selectWatch.Unlock()
1778         }
1779 }
1780
1781 // runSelect runs a single select test.
1782 // It returns the values returned by Select but also returns
1783 // a panic value if the Select panics.
1784 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1785         defer func() {
1786                 panicErr = recover()
1787
1788                 selectWatch.Lock()
1789                 selectWatch.info = nil
1790                 selectWatch.Unlock()
1791         }()
1792
1793         selectWatch.Lock()
1794         selectWatch.now = time.Now()
1795         selectWatch.info = info
1796         selectWatch.Unlock()
1797
1798         chosen, recv, recvOK = Select(cases)
1799         return
1800 }
1801
1802 // fmtSelect formats the information about a single select test.
1803 func fmtSelect(info []caseInfo) string {
1804         var buf bytes.Buffer
1805         fmt.Fprintf(&buf, "\nselect {\n")
1806         for i, cas := range info {
1807                 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1808                 if cas.recv.IsValid() {
1809                         fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1810                 }
1811                 if cas.canSelect {
1812                         fmt.Fprintf(&buf, " canselect")
1813                 }
1814                 if cas.panic {
1815                         fmt.Fprintf(&buf, " panic")
1816                 }
1817                 fmt.Fprintf(&buf, "\n")
1818         }
1819         fmt.Fprintf(&buf, "}")
1820         return buf.String()
1821 }
1822
1823 type two [2]uintptr
1824
1825 // Difficult test for function call because of
1826 // implicit padding between arguments.
1827 func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
1828         return b, c, d, e, f, g, h
1829 }
1830
1831 func TestFunc(t *testing.T) {
1832         ret := ValueOf(dummy).Call([]Value{
1833                 ValueOf(byte(10)),
1834                 ValueOf(20),
1835                 ValueOf(byte(30)),
1836                 ValueOf(two{40, 50}),
1837                 ValueOf(byte(60)),
1838                 ValueOf(float32(70)),
1839                 ValueOf(byte(80)),
1840         })
1841         if len(ret) != 7 {
1842                 t.Fatalf("Call returned %d values, want 7", len(ret))
1843         }
1844
1845         i := byte(ret[0].Uint())
1846         j := int(ret[1].Int())
1847         k := byte(ret[2].Uint())
1848         l := ret[3].Interface().(two)
1849         m := byte(ret[4].Uint())
1850         n := float32(ret[5].Float())
1851         o := byte(ret[6].Uint())
1852
1853         if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1854                 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1855         }
1856
1857         for i, v := range ret {
1858                 if v.CanAddr() {
1859                         t.Errorf("result %d is addressable", i)
1860                 }
1861         }
1862 }
1863
1864 func TestCallConvert(t *testing.T) {
1865         v := ValueOf(new(io.ReadWriter)).Elem()
1866         f := ValueOf(func(r io.Reader) io.Reader { return r })
1867         out := f.Call([]Value{v})
1868         if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
1869                 t.Errorf("expected [nil], got %v", out)
1870         }
1871 }
1872
1873 type emptyStruct struct{}
1874
1875 type nonEmptyStruct struct {
1876         member int
1877 }
1878
1879 func returnEmpty() emptyStruct {
1880         return emptyStruct{}
1881 }
1882
1883 func takesEmpty(e emptyStruct) {
1884 }
1885
1886 func returnNonEmpty(i int) nonEmptyStruct {
1887         return nonEmptyStruct{member: i}
1888 }
1889
1890 func takesNonEmpty(n nonEmptyStruct) int {
1891         return n.member
1892 }
1893
1894 func TestCallWithStruct(t *testing.T) {
1895         r := ValueOf(returnEmpty).Call(nil)
1896         if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1897                 t.Errorf("returning empty struct returned %#v instead", r)
1898         }
1899         r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1900         if len(r) != 0 {
1901                 t.Errorf("takesEmpty returned values: %#v", r)
1902         }
1903         r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1904         if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1905                 t.Errorf("returnNonEmpty returned %#v", r)
1906         }
1907         r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1908         if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1909                 t.Errorf("takesNonEmpty returned %#v", r)
1910         }
1911 }
1912
1913 func TestCallReturnsEmpty(t *testing.T) {
1914         // Issue 21717: past-the-end pointer write in Call with
1915         // nonzero-sized frame and zero-sized return value.
1916         runtime.GC()
1917         var finalized uint32
1918         f := func() (emptyStruct, *[2]int64) {
1919                 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
1920                 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
1921                 return emptyStruct{}, i
1922         }
1923         v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
1924         timeout := time.After(5 * time.Second)
1925         for atomic.LoadUint32(&finalized) == 0 {
1926                 select {
1927                 case <-timeout:
1928                         t.Fatal("finalizer did not run")
1929                 default:
1930                 }
1931                 runtime.Gosched()
1932                 runtime.GC()
1933         }
1934         runtime.KeepAlive(v)
1935 }
1936
1937 func BenchmarkCall(b *testing.B) {
1938         fv := ValueOf(func(a, b string) {})
1939         b.ReportAllocs()
1940         b.RunParallel(func(pb *testing.PB) {
1941                 args := []Value{ValueOf("a"), ValueOf("b")}
1942                 for pb.Next() {
1943                         fv.Call(args)
1944                 }
1945         })
1946 }
1947
1948 type myint int64
1949
1950 func (i *myint) inc() {
1951         *i = *i + 1
1952 }
1953
1954 func BenchmarkCallMethod(b *testing.B) {
1955         b.ReportAllocs()
1956         z := new(myint)
1957
1958         v := ValueOf(z.inc)
1959         for i := 0; i < b.N; i++ {
1960                 v.Call(nil)
1961         }
1962 }
1963
1964 func BenchmarkCallArgCopy(b *testing.B) {
1965         byteArray := func(n int) Value {
1966                 return Zero(ArrayOf(n, TypeOf(byte(0))))
1967         }
1968         sizes := [...]struct {
1969                 fv  Value
1970                 arg Value
1971         }{
1972                 {ValueOf(func(a [128]byte) {}), byteArray(128)},
1973                 {ValueOf(func(a [256]byte) {}), byteArray(256)},
1974                 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
1975                 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
1976                 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
1977         }
1978         for _, size := range sizes {
1979                 bench := func(b *testing.B) {
1980                         args := []Value{size.arg}
1981                         b.SetBytes(int64(size.arg.Len()))
1982                         b.ResetTimer()
1983                         b.RunParallel(func(pb *testing.PB) {
1984                                 for pb.Next() {
1985                                         size.fv.Call(args)
1986                                 }
1987                         })
1988                 }
1989                 name := fmt.Sprintf("size=%v", size.arg.Len())
1990                 b.Run(name, bench)
1991         }
1992 }
1993
1994 func TestMakeFunc(t *testing.T) {
1995         f := dummy
1996         fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1997         ValueOf(&f).Elem().Set(fv)
1998
1999         // Call g with small arguments so that there is
2000         // something predictable (and different from the
2001         // correct results) in those positions on the stack.
2002         g := dummy
2003         g(1, 2, 3, two{4, 5}, 6, 7, 8)
2004
2005         // Call constructed function f.
2006         i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2007         if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2008                 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
2009         }
2010 }
2011
2012 func TestMakeFuncInterface(t *testing.T) {
2013         fn := func(i int) int { return i }
2014         incr := func(in []Value) []Value {
2015                 return []Value{ValueOf(int(in[0].Int() + 1))}
2016         }
2017         fv := MakeFunc(TypeOf(fn), incr)
2018         ValueOf(&fn).Elem().Set(fv)
2019         if r := fn(2); r != 3 {
2020                 t.Errorf("Call returned %d, want 3", r)
2021         }
2022         if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2023                 t.Errorf("Call returned %d, want 15", r)
2024         }
2025         if r := fv.Interface().(func(int) int)(26); r != 27 {
2026                 t.Errorf("Call returned %d, want 27", r)
2027         }
2028 }
2029
2030 func TestMakeFuncVariadic(t *testing.T) {
2031         // Test that variadic arguments are packed into a slice and passed as last arg
2032         fn := func(_ int, is ...int) []int { return nil }
2033         fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2034         ValueOf(&fn).Elem().Set(fv)
2035
2036         r := fn(1, 2, 3)
2037         if r[0] != 2 || r[1] != 3 {
2038                 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2039         }
2040
2041         r = fn(1, []int{2, 3}...)
2042         if r[0] != 2 || r[1] != 3 {
2043                 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2044         }
2045
2046         r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2047         if r[0] != 2 || r[1] != 3 {
2048                 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2049         }
2050
2051         r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2052         if r[0] != 2 || r[1] != 3 {
2053                 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2054         }
2055
2056         f := fv.Interface().(func(int, ...int) []int)
2057
2058         r = f(1, 2, 3)
2059         if r[0] != 2 || r[1] != 3 {
2060                 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2061         }
2062         r = f(1, []int{2, 3}...)
2063         if r[0] != 2 || r[1] != 3 {
2064                 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2065         }
2066 }
2067
2068 // Dummy type that implements io.WriteCloser
2069 type WC struct {
2070 }
2071
2072 func (w *WC) Write(p []byte) (n int, err error) {
2073         return 0, nil
2074 }
2075 func (w *WC) Close() error {
2076         return nil
2077 }
2078
2079 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2080         // reflect.Values returned from the wrapped function should be assignment-converted
2081         // to the types returned by the result of MakeFunc.
2082
2083         // Concrete types should be promotable to interfaces they implement.
2084         var f func() error
2085         f = MakeFunc(TypeOf(f), func([]Value) []Value {
2086                 return []Value{ValueOf(io.EOF)}
2087         }).Interface().(func() error)
2088         f()
2089
2090         // Super-interfaces should be promotable to simpler interfaces.
2091         var g func() io.Writer
2092         g = MakeFunc(TypeOf(g), func([]Value) []Value {
2093                 var w io.WriteCloser = &WC{}
2094                 return []Value{ValueOf(&w).Elem()}
2095         }).Interface().(func() io.Writer)
2096         g()
2097
2098         // Channels should be promotable to directional channels.
2099         var h func() <-chan int
2100         h = MakeFunc(TypeOf(h), func([]Value) []Value {
2101                 return []Value{ValueOf(make(chan int))}
2102         }).Interface().(func() <-chan int)
2103         h()
2104
2105         // Unnamed types should be promotable to named types.
2106         type T struct{ a, b, c int }
2107         var i func() T
2108         i = MakeFunc(TypeOf(i), func([]Value) []Value {
2109                 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2110         }).Interface().(func() T)
2111         i()
2112 }
2113
2114 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2115         // Type doesn't implement the required interface.
2116         shouldPanic("", func() {
2117                 var f func() error
2118                 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2119                         return []Value{ValueOf(int(7))}
2120                 }).Interface().(func() error)
2121                 f()
2122         })
2123         // Assigning to an interface with additional methods.
2124         shouldPanic("", func() {
2125                 var f func() io.ReadWriteCloser
2126                 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2127                         var w io.WriteCloser = &WC{}
2128                         return []Value{ValueOf(&w).Elem()}
2129                 }).Interface().(func() io.ReadWriteCloser)
2130                 f()
2131         })
2132         // Directional channels can't be assigned to bidirectional ones.
2133         shouldPanic("", func() {
2134                 var f func() chan int
2135                 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2136                         var c <-chan int = make(chan int)
2137                         return []Value{ValueOf(c)}
2138                 }).Interface().(func() chan int)
2139                 f()
2140         })
2141         // Two named types which are otherwise identical.
2142         shouldPanic("", func() {
2143                 type T struct{ a, b, c int }
2144                 type U struct{ a, b, c int }
2145                 var f func() T
2146                 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2147                         return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2148                 }).Interface().(func() T)
2149                 f()
2150         })
2151 }
2152
2153 type Point struct {
2154         x, y int
2155 }
2156
2157 // This will be index 0.
2158 func (p Point) AnotherMethod(scale int) int {
2159         return -1
2160 }
2161
2162 // This will be index 1.
2163 func (p Point) Dist(scale int) int {
2164         //println("Point.Dist", p.x, p.y, scale)
2165         return p.x*p.x*scale + p.y*p.y*scale
2166 }
2167
2168 // This will be index 2.
2169 func (p Point) GCMethod(k int) int {
2170         runtime.GC()
2171         return k + p.x
2172 }
2173
2174 // This will be index 3.
2175 func (p Point) NoArgs() {
2176         // Exercise no-argument/no-result paths.
2177 }
2178
2179 // This will be index 4.
2180 func (p Point) TotalDist(points ...Point) int {
2181         tot := 0
2182         for _, q := range points {
2183                 dx := q.x - p.x
2184                 dy := q.y - p.y
2185                 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2186
2187         }
2188         return tot
2189 }
2190
2191 // This will be index 5.
2192 func (p *Point) Int64Method(x int64) int64 {
2193         return x
2194 }
2195
2196 // This will be index 6.
2197 func (p *Point) Int32Method(x int32) int32 {
2198         return x
2199 }
2200
2201 func TestMethod(t *testing.T) {
2202         // Non-curried method of type.
2203         p := Point{3, 4}
2204         i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2205         if i != 250 {
2206                 t.Errorf("Type Method returned %d; want 250", i)
2207         }
2208
2209         m, ok := TypeOf(p).MethodByName("Dist")
2210         if !ok {
2211                 t.Fatalf("method by name failed")
2212         }
2213         i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2214         if i != 275 {
2215                 t.Errorf("Type MethodByName returned %d; want 275", i)
2216         }
2217
2218         m, ok = TypeOf(p).MethodByName("NoArgs")
2219         if !ok {
2220                 t.Fatalf("method by name failed")
2221         }
2222         n := len(m.Func.Call([]Value{ValueOf(p)}))
2223         if n != 0 {
2224                 t.Errorf("NoArgs returned %d values; want 0", n)
2225         }
2226
2227         i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2228         if i != 300 {
2229                 t.Errorf("Pointer Type Method returned %d; want 300", i)
2230         }
2231
2232         m, ok = TypeOf(&p).MethodByName("Dist")
2233         if !ok {
2234                 t.Fatalf("ptr method by name failed")
2235         }
2236         i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2237         if i != 325 {
2238                 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2239         }
2240
2241         m, ok = TypeOf(&p).MethodByName("NoArgs")
2242         if !ok {
2243                 t.Fatalf("method by name failed")
2244         }
2245         n = len(m.Func.Call([]Value{ValueOf(&p)}))
2246         if n != 0 {
2247                 t.Errorf("NoArgs returned %d values; want 0", n)
2248         }
2249
2250         // Curried method of value.
2251         tfunc := TypeOf((func(int) int)(nil))
2252         v := ValueOf(p).Method(1)
2253         if tt := v.Type(); tt != tfunc {
2254                 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2255         }
2256         i = v.Call([]Value{ValueOf(14)})[0].Int()
2257         if i != 350 {
2258                 t.Errorf("Value Method returned %d; want 350", i)
2259         }
2260         v = ValueOf(p).MethodByName("Dist")
2261         if tt := v.Type(); tt != tfunc {
2262                 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2263         }
2264         i = v.Call([]Value{ValueOf(15)})[0].Int()
2265         if i != 375 {
2266                 t.Errorf("Value MethodByName returned %d; want 375", i)
2267         }
2268         v = ValueOf(p).MethodByName("NoArgs")
2269         v.Call(nil)
2270
2271         // Curried method of pointer.
2272         v = ValueOf(&p).Method(1)
2273         if tt := v.Type(); tt != tfunc {
2274                 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2275         }
2276         i = v.Call([]Value{ValueOf(16)})[0].Int()
2277         if i != 400 {
2278                 t.Errorf("Pointer Value Method returned %d; want 400", i)
2279         }
2280         v = ValueOf(&p).MethodByName("Dist")
2281         if tt := v.Type(); tt != tfunc {
2282                 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2283         }
2284         i = v.Call([]Value{ValueOf(17)})[0].Int()
2285         if i != 425 {
2286                 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2287         }
2288         v = ValueOf(&p).MethodByName("NoArgs")
2289         v.Call(nil)
2290
2291         // Curried method of interface value.
2292         // Have to wrap interface value in a struct to get at it.
2293         // Passing it to ValueOf directly would
2294         // access the underlying Point, not the interface.
2295         var x interface {
2296                 Dist(int) int
2297         } = p
2298         pv := ValueOf(&x).Elem()
2299         v = pv.Method(0)
2300         if tt := v.Type(); tt != tfunc {
2301                 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2302         }
2303         i = v.Call([]Value{ValueOf(18)})[0].Int()
2304         if i != 450 {
2305                 t.Errorf("Interface Method returned %d; want 450", i)
2306         }
2307         v = pv.MethodByName("Dist")
2308         if tt := v.Type(); tt != tfunc {
2309                 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2310         }
2311         i = v.Call([]Value{ValueOf(19)})[0].Int()
2312         if i != 475 {
2313                 t.Errorf("Interface MethodByName returned %d; want 475", i)
2314         }
2315 }
2316
2317 func TestMethodValue(t *testing.T) {
2318         p := Point{3, 4}
2319         var i int64
2320
2321         // Curried method of value.
2322         tfunc := TypeOf((func(int) int)(nil))
2323         v := ValueOf(p).Method(1)
2324         if tt := v.Type(); tt != tfunc {
2325                 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2326         }
2327         i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2328         if i != 250 {
2329                 t.Errorf("Value Method returned %d; want 250", i)
2330         }
2331         v = ValueOf(p).MethodByName("Dist")
2332         if tt := v.Type(); tt != tfunc {
2333                 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2334         }
2335         i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2336         if i != 275 {
2337                 t.Errorf("Value MethodByName returned %d; want 275", i)
2338         }
2339         v = ValueOf(p).MethodByName("NoArgs")
2340         ValueOf(v.Interface()).Call(nil)
2341         v.Interface().(func())()
2342
2343         // Curried method of pointer.
2344         v = ValueOf(&p).Method(1)
2345         if tt := v.Type(); tt != tfunc {
2346                 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2347         }
2348         i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2349         if i != 300 {
2350                 t.Errorf("Pointer Value Method returned %d; want 300", i)
2351         }
2352         v = ValueOf(&p).MethodByName("Dist")
2353         if tt := v.Type(); tt != tfunc {
2354                 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2355         }
2356         i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2357         if i != 325 {
2358                 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2359         }
2360         v = ValueOf(&p).MethodByName("NoArgs")
2361         ValueOf(v.Interface()).Call(nil)
2362         v.Interface().(func())()
2363
2364         // Curried method of pointer to pointer.
2365         pp := &p
2366         v = ValueOf(&pp).Elem().Method(1)
2367         if tt := v.Type(); tt != tfunc {
2368                 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2369         }
2370         i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2371         if i != 350 {
2372                 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2373         }
2374         v = ValueOf(&pp).Elem().MethodByName("Dist")
2375         if tt := v.Type(); tt != tfunc {
2376                 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2377         }
2378         i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2379         if i != 375 {
2380                 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2381         }
2382
2383         // Curried method of interface value.
2384         // Have to wrap interface value in a struct to get at it.
2385         // Passing it to ValueOf directly would
2386         // access the underlying Point, not the interface.
2387         var s = struct {
2388                 X interface {
2389                         Dist(int) int
2390                 }
2391         }{p}
2392         pv := ValueOf(s).Field(0)
2393         v = pv.Method(0)
2394         if tt := v.Type(); tt != tfunc {
2395                 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2396         }
2397         i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2398         if i != 400 {
2399                 t.Errorf("Interface Method returned %d; want 400", i)
2400         }
2401         v = pv.MethodByName("Dist")
2402         if tt := v.Type(); tt != tfunc {
2403                 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2404         }
2405         i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2406         if i != 425 {
2407                 t.Errorf("Interface MethodByName returned %d; want 425", i)
2408         }
2409
2410         // For issue #33628: method args are not stored at the right offset
2411         // on amd64p32.
2412         m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2413         if x := m64(123); x != 123 {
2414                 t.Errorf("Int64Method returned %d; want 123", x)
2415         }
2416         m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2417         if x := m32(456); x != 456 {
2418                 t.Errorf("Int32Method returned %d; want 456", x)
2419         }
2420 }
2421
2422 func TestVariadicMethodValue(t *testing.T) {
2423         p := Point{3, 4}
2424         points := []Point{{20, 21}, {22, 23}, {24, 25}}
2425         want := int64(p.TotalDist(points[0], points[1], points[2]))
2426
2427         // Variadic method of type.
2428         tfunc := TypeOf((func(Point, ...Point) int)(nil))
2429         if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2430                 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2431         }
2432
2433         // Curried method of value.
2434         tfunc = TypeOf((func(...Point) int)(nil))
2435         v := ValueOf(p).Method(4)
2436         if tt := v.Type(); tt != tfunc {
2437                 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2438         }
2439         i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2440         if i != want {
2441                 t.Errorf("Variadic Method returned %d; want %d", i, want)
2442         }
2443         i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2444         if i != want {
2445                 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2446         }
2447
2448         f := v.Interface().(func(...Point) int)
2449         i = int64(f(points[0], points[1], points[2]))
2450         if i != want {
2451                 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2452         }
2453         i = int64(f(points...))
2454         if i != want {
2455                 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2456         }
2457 }
2458
2459 type DirectIfaceT struct {
2460         p *int
2461 }
2462
2463 func (d DirectIfaceT) M() int { return *d.p }
2464
2465 func TestDirectIfaceMethod(t *testing.T) {
2466         x := 42
2467         v := DirectIfaceT{&x}
2468         typ := TypeOf(v)
2469         m, ok := typ.MethodByName("M")
2470         if !ok {
2471                 t.Fatalf("cannot find method M")
2472         }
2473         in := []Value{ValueOf(v)}
2474         out := m.Func.Call(in)
2475         if got := out[0].Int(); got != 42 {
2476                 t.Errorf("Call with value receiver got %d, want 42", got)
2477         }
2478
2479         pv := &v
2480         typ = TypeOf(pv)
2481         m, ok = typ.MethodByName("M")
2482         if !ok {
2483                 t.Fatalf("cannot find method M")
2484         }
2485         in = []Value{ValueOf(pv)}
2486         out = m.Func.Call(in)
2487         if got := out[0].Int(); got != 42 {
2488                 t.Errorf("Call with pointer receiver got %d, want 42", got)
2489         }
2490 }
2491
2492 // Reflect version of $GOROOT/test/method5.go
2493
2494 // Concrete types implementing M method.
2495 // Smaller than a word, word-sized, larger than a word.
2496 // Value and pointer receivers.
2497
2498 type Tinter interface {
2499         M(int, byte) (byte, int)
2500 }
2501
2502 type Tsmallv byte
2503
2504 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2505
2506 type Tsmallp byte
2507
2508 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2509
2510 type Twordv uintptr
2511
2512 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2513
2514 type Twordp uintptr
2515
2516 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2517
2518 type Tbigv [2]uintptr
2519
2520 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2521
2522 type Tbigp [2]uintptr
2523
2524 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2525
2526 type tinter interface {
2527         m(int, byte) (byte, int)
2528 }
2529
2530 // Embedding via pointer.
2531
2532 type Tm1 struct {
2533         Tm2
2534 }
2535
2536 type Tm2 struct {
2537         *Tm3
2538 }
2539
2540 type Tm3 struct {
2541         *Tm4
2542 }
2543
2544 type Tm4 struct {
2545 }
2546
2547 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2548
2549 func TestMethod5(t *testing.T) {
2550         CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2551                 b, x := f(1000, 99)
2552                 if b != 99 || x != 1000+inc {
2553                         t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2554                 }
2555         }
2556
2557         CheckV := func(name string, i Value, inc int) {
2558                 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2559                 b := bx[0].Interface()
2560                 x := bx[1].Interface()
2561                 if b != byte(99) || x != 1000+inc {
2562                         t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2563                 }
2564
2565                 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2566         }
2567
2568         var TinterType = TypeOf(new(Tinter)).Elem()
2569
2570         CheckI := func(name string, i interface{}, inc int) {
2571                 v := ValueOf(i)
2572                 CheckV(name, v, inc)
2573                 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2574         }
2575
2576         sv := Tsmallv(1)
2577         CheckI("sv", sv, 1)
2578         CheckI("&sv", &sv, 1)
2579
2580         sp := Tsmallp(2)
2581         CheckI("&sp", &sp, 2)
2582
2583         wv := Twordv(3)
2584         CheckI("wv", wv, 3)
2585         CheckI("&wv", &wv, 3)
2586
2587         wp := Twordp(4)
2588         CheckI("&wp", &wp, 4)
2589
2590         bv := Tbigv([2]uintptr{5, 6})
2591         CheckI("bv", bv, 11)
2592         CheckI("&bv", &bv, 11)
2593
2594         bp := Tbigp([2]uintptr{7, 8})
2595         CheckI("&bp", &bp, 15)
2596
2597         t4 := Tm4{}
2598         t3 := Tm3{&t4}
2599         t2 := Tm2{&t3}
2600         t1 := Tm1{t2}
2601         CheckI("t4", t4, 40)
2602         CheckI("&t4", &t4, 40)
2603         CheckI("t3", t3, 40)
2604         CheckI("&t3", &t3, 40)
2605         CheckI("t2", t2, 40)
2606         CheckI("&t2", &t2, 40)
2607         CheckI("t1", t1, 40)
2608         CheckI("&t1", &t1, 40)
2609
2610         var tnil Tinter
2611         vnil := ValueOf(&tnil).Elem()
2612         shouldPanic("Method", func() { vnil.Method(0) })
2613 }
2614
2615 func TestInterfaceSet(t *testing.T) {
2616         p := &Point{3, 4}
2617
2618         var s struct {
2619                 I interface{}
2620                 P interface {
2621                         Dist(int) int
2622                 }
2623         }
2624         sv := ValueOf(&s).Elem()
2625         sv.Field(0).Set(ValueOf(p))
2626         if q := s.I.(*Point); q != p {
2627                 t.Errorf("i: have %p want %p", q, p)
2628         }
2629
2630         pv := sv.Field(1)
2631         pv.Set(ValueOf(p))
2632         if q := s.P.(*Point); q != p {
2633                 t.Errorf("i: have %p want %p", q, p)
2634         }
2635
2636         i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2637         if i != 250 {
2638                 t.Errorf("Interface Method returned %d; want 250", i)
2639         }
2640 }
2641
2642 type T1 struct {
2643         a string
2644         int
2645 }
2646
2647 func TestAnonymousFields(t *testing.T) {
2648         var field StructField
2649         var ok bool
2650         var t1 T1
2651         type1 := TypeOf(t1)
2652         if field, ok = type1.FieldByName("int"); !ok {
2653                 t.Fatal("no field 'int'")
2654         }
2655         if field.Index[0] != 1 {
2656                 t.Error("field index should be 1; is", field.Index)
2657         }
2658 }
2659
2660 type FTest struct {
2661         s     interface{}
2662         name  string
2663         index []int
2664         value int
2665 }
2666
2667 type D1 struct {
2668         d int
2669 }
2670 type D2 struct {
2671         d int
2672 }
2673
2674 type S0 struct {
2675         A, B, C int
2676         D1
2677         D2
2678 }
2679
2680 type S1 struct {
2681         B int
2682         S0
2683 }
2684
2685 type S2 struct {
2686         A int
2687         *S1
2688 }
2689
2690 type S1x struct {
2691         S1
2692 }
2693
2694 type S1y struct {
2695         S1
2696 }
2697
2698 type S3 struct {
2699         S1x
2700         S2
2701         D, E int
2702         *S1y
2703 }
2704
2705 type S4 struct {
2706         *S4
2707         A int
2708 }
2709
2710 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2711 type S5 struct {
2712         S6
2713         S7
2714         S8
2715 }
2716
2717 type S6 struct {
2718         X int
2719 }
2720
2721 type S7 S6
2722
2723 type S8 struct {
2724         S9
2725 }
2726
2727 type S9 struct {
2728         X int
2729         Y int
2730 }
2731
2732 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2733 type S10 struct {
2734         S11
2735         S12
2736         S13
2737 }
2738
2739 type S11 struct {
2740         S6
2741 }
2742
2743 type S12 struct {
2744         S6
2745 }
2746
2747 type S13 struct {
2748         S8
2749 }
2750
2751 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2752 type S14 struct {
2753         S15
2754         S16
2755 }
2756
2757 type S15 struct {
2758         S11
2759 }
2760
2761 type S16 struct {
2762         S11
2763 }
2764
2765 var fieldTests = []FTest{
2766         {struct{}{}, "", nil, 0},
2767         {struct{}{}, "Foo", nil, 0},
2768         {S0{A: 'a'}, "A", []int{0}, 'a'},
2769         {S0{}, "D", nil, 0},
2770         {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2771         {S1{B: 'b'}, "B", []int{0}, 'b'},
2772         {S1{}, "S0", []int{1}, 0},
2773         {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2774         {S2{A: 'a'}, "A", []int{0}, 'a'},
2775         {S2{}, "S1", []int{1}, 0},
2776         {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2777         {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2778         {S2{}, "D", nil, 0},
2779         {S3{}, "S1", nil, 0},
2780         {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2781         {S3{}, "B", nil, 0},
2782         {S3{D: 'd'}, "D", []int{2}, 0},
2783         {S3{E: 'e'}, "E", []int{3}, 'e'},
2784         {S4{A: 'a'}, "A", []int{1}, 'a'},
2785         {S4{}, "B", nil, 0},
2786         {S5{}, "X", nil, 0},
2787         {S5{}, "Y", []int{2, 0, 1}, 0},
2788         {S10{}, "X", nil, 0},
2789         {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2790         {S14{}, "X", nil, 0},
2791 }
2792
2793 func TestFieldByIndex(t *testing.T) {
2794         for _, test := range fieldTests {
2795                 s := TypeOf(test.s)
2796                 f := s.FieldByIndex(test.index)
2797                 if f.Name != "" {
2798                         if test.index != nil {
2799                                 if f.Name != test.name {
2800                                         t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2801                                 }
2802                         } else {
2803                                 t.Errorf("%s.%s found", s.Name(), f.Name)
2804                         }
2805                 } else if len(test.index) > 0 {
2806                         t.Errorf("%s.%s not found", s.Name(), test.name)
2807                 }
2808
2809                 if test.value != 0 {
2810                         v := ValueOf(test.s).FieldByIndex(test.index)
2811                         if v.IsValid() {
2812                                 if x, ok := v.Interface().(int); ok {
2813                                         if x != test.value {
2814                                                 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2815                                         }
2816                                 } else {
2817                                         t.Errorf("%s%v value not an int", s.Name(), test.index)
2818                                 }
2819                         } else {
2820                                 t.Errorf("%s%v value not found", s.Name(), test.index)
2821                         }
2822                 }
2823         }
2824 }
2825
2826 func TestFieldByName(t *testing.T) {
2827         for _, test := range fieldTests {
2828                 s := TypeOf(test.s)
2829                 f, found := s.FieldByName(test.name)
2830                 if found {
2831                         if test.index != nil {
2832                                 // Verify field depth and index.
2833                                 if len(f.Index) != len(test.index) {
2834                                         t.Errorf("%s.%s depth %d; want %d: %v vs %v", s.Name(), test.name, len(f.Index), len(test.index), f.Index, test.index)
2835                                 } else {
2836                                         for i, x := range f.Index {
2837                                                 if x != test.index[i] {
2838                                                         t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2839                                                 }
2840                                         }
2841                                 }
2842                         } else {
2843                                 t.Errorf("%s.%s found", s.Name(), f.Name)
2844                         }
2845                 } else if len(test.index) > 0 {
2846                         t.Errorf("%s.%s not found", s.Name(), test.name)
2847                 }
2848
2849                 if test.value != 0 {
2850                         v := ValueOf(test.s).FieldByName(test.name)
2851                         if v.IsValid() {
2852                                 if x, ok := v.Interface().(int); ok {
2853                                         if x != test.value {
2854                                                 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2855                                         }
2856                                 } else {
2857                                         t.Errorf("%s.%s value not an int", s.Name(), test.name)
2858                                 }
2859                         } else {
2860                                 t.Errorf("%s.%s value not found", s.Name(), test.name)
2861                         }
2862                 }
2863         }
2864 }
2865
2866 func TestImportPath(t *testing.T) {
2867         tests := []struct {
2868                 t    Type
2869                 path string
2870         }{
2871                 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2872                 {TypeOf(int(0)), ""},
2873                 {TypeOf(int8(0)), ""},
2874                 {TypeOf(int16(0)), ""},
2875                 {TypeOf(int32(0)), ""},
2876                 {TypeOf(int64(0)), ""},
2877                 {TypeOf(uint(0)), ""},
2878                 {TypeOf(uint8(0)), ""},
2879                 {TypeOf(uint16(0)), ""},
2880                 {TypeOf(uint32(0)), ""},
2881                 {TypeOf(uint64(0)), ""},
2882                 {TypeOf(uintptr(0)), ""},
2883                 {TypeOf(float32(0)), ""},
2884                 {TypeOf(float64(0)), ""},
2885                 {TypeOf(complex64(0)), ""},
2886                 {TypeOf(complex128(0)), ""},
2887                 {TypeOf(byte(0)), ""},
2888                 {TypeOf(rune(0)), ""},
2889                 {TypeOf([]byte(nil)), ""},
2890                 {TypeOf([]rune(nil)), ""},
2891                 {TypeOf(string("")), ""},
2892                 {TypeOf((*interface{})(nil)).Elem(), ""},
2893                 {TypeOf((*byte)(nil)), ""},
2894                 {TypeOf((*rune)(nil)), ""},
2895                 {TypeOf((*int64)(nil)), ""},
2896                 {TypeOf(map[string]int{}), ""},
2897                 {TypeOf((*error)(nil)).Elem(), ""},
2898                 {TypeOf((*Point)(nil)), ""},
2899                 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
2900         }
2901         for _, test := range tests {
2902                 if path := test.t.PkgPath(); path != test.path {
2903                         t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2904                 }
2905         }
2906 }
2907
2908 func TestFieldPkgPath(t *testing.T) {
2909         type x int
2910         typ := TypeOf(struct {
2911                 Exported   string
2912                 unexported string
2913                 OtherPkgFields
2914                 int // issue 21702
2915                 *x  // issue 21122
2916         }{})
2917
2918         type pkgpathTest struct {
2919                 index    []int
2920                 pkgPath  string
2921                 embedded bool
2922                 exported bool
2923         }
2924
2925         checkPkgPath := func(name string, s []pkgpathTest) {
2926                 for _, test := range s {
2927                         f := typ.FieldByIndex(test.index)
2928                         if got, want := f.PkgPath, test.pkgPath; got != want {
2929                                 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
2930                         }
2931                         if got, want := f.Anonymous, test.embedded; got != want {
2932                                 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
2933                         }
2934                         if got, want := f.IsExported(), test.exported; got != want {
2935                                 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
2936                         }
2937                 }
2938         }
2939
2940         checkPkgPath("testStruct", []pkgpathTest{
2941                 {[]int{0}, "", false, true},              // Exported
2942                 {[]int{1}, "reflect_test", false, false}, // unexported
2943                 {[]int{2}, "", true, true},               // OtherPkgFields
2944                 {[]int{2, 0}, "", false, true},           // OtherExported
2945                 {[]int{2, 1}, "reflect", false, false},   // otherUnexported
2946                 {[]int{3}, "reflect_test", true, false},  // int
2947                 {[]int{4}, "reflect_test", true, false},  // *x
2948         })
2949
2950         type localOtherPkgFields OtherPkgFields
2951         typ = TypeOf(localOtherPkgFields{})
2952         checkPkgPath("localOtherPkgFields", []pkgpathTest{
2953                 {[]int{0}, "", false, true},         // OtherExported
2954                 {[]int{1}, "reflect", false, false}, // otherUnexported
2955         })
2956 }
2957
2958 func TestMethodPkgPath(t *testing.T) {
2959         type I interface {
2960                 x()
2961                 X()
2962         }
2963         typ := TypeOf((*interface {
2964                 I
2965                 y()
2966                 Y()
2967         })(nil)).Elem()
2968
2969         tests := []struct {
2970                 name     string
2971                 pkgPath  string
2972                 exported bool
2973         }{
2974                 {"X", "", true},
2975                 {"Y", "", true},
2976                 {"x", "reflect_test", false},
2977                 {"y", "reflect_test", false},
2978         }
2979
2980         for _, test := range tests {
2981                 m, _ := typ.MethodByName(test.name)
2982                 if got, want := m.PkgPath, test.pkgPath; got != want {
2983                         t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
2984                 }
2985                 if got, want := m.IsExported(), test.exported; got != want {
2986                         t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
2987                 }
2988         }
2989 }
2990
2991 func TestVariadicType(t *testing.T) {
2992         // Test example from Type documentation.
2993         var f func(x int, y ...float64)
2994         typ := TypeOf(f)
2995         if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2996                 sl := typ.In(1)
2997                 if sl.Kind() == Slice {
2998                         if sl.Elem() == TypeOf(0.0) {
2999                                 // ok
3000                                 return
3001                         }
3002                 }
3003         }
3004
3005         // Failed
3006         t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3007         s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3008         for i := 0; i < typ.NumIn(); i++ {
3009                 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3010         }
3011         t.Error(s)
3012 }
3013
3014 type inner struct {
3015         x int
3016 }
3017
3018 type outer struct {
3019         y int
3020         inner
3021 }
3022
3023 func (*inner) M() {}
3024 func (*outer) M() {}
3025
3026 func TestNestedMethods(t *testing.T) {
3027         typ := TypeOf((*outer)(nil))
3028         if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
3029                 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3030                 for i := 0; i < typ.NumMethod(); i++ {
3031                         m := typ.Method(i)
3032                         t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3033                 }
3034         }
3035 }
3036
3037 type unexp struct{}
3038
3039 func (*unexp) f() (int32, int8) { return 7, 7 }
3040 func (*unexp) g() (int64, int8) { return 8, 8 }
3041
3042 type unexpI interface {
3043         f() (int32, int8)
3044 }
3045
3046 var unexpi unexpI = new(unexp)
3047
3048 func TestUnexportedMethods(t *testing.T) {
3049         typ := TypeOf(unexpi)
3050
3051         if got := typ.NumMethod(); got != 0 {
3052                 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3053         }
3054 }
3055
3056 type InnerInt struct {
3057         X int
3058 }
3059
3060 type OuterInt struct {
3061         Y int
3062         InnerInt
3063 }
3064
3065 func (i *InnerInt) M() int {
3066         return i.X
3067 }
3068
3069 func TestEmbeddedMethods(t *testing.T) {
3070         typ := TypeOf((*OuterInt)(nil))
3071         if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
3072                 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3073                 for i := 0; i < typ.NumMethod(); i++ {
3074                         m := typ.Method(i)
3075                         t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3076                 }
3077         }
3078
3079         i := &InnerInt{3}
3080         if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3081                 t.Errorf("i.M() = %d, want 3", v)
3082         }
3083
3084         o := &OuterInt{1, InnerInt{2}}
3085         if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3086                 t.Errorf("i.M() = %d, want 2", v)
3087         }
3088
3089         f := (*OuterInt).M
3090         if v := f(o); v != 2 {
3091                 t.Errorf("f(o) = %d, want 2", v)
3092         }
3093 }
3094
3095 type FuncDDD func(...interface{}) error
3096
3097 func (f FuncDDD) M() {}
3098
3099 func TestNumMethodOnDDD(t *testing.T) {
3100         rv := ValueOf((FuncDDD)(nil))
3101         if n := rv.NumMethod(); n != 1 {
3102                 t.Fatalf("NumMethod()=%d, want 1", n)
3103         }
3104 }
3105
3106 func TestPtrTo(t *testing.T) {
3107         // This block of code means that the ptrToThis field of the
3108         // reflect data for *unsafe.Pointer is non zero, see
3109         // https://golang.org/issue/19003
3110         var x unsafe.Pointer
3111         var y = &x
3112         var z = &y
3113
3114         var i int
3115
3116         typ := TypeOf(z)
3117         for i = 0; i < 100; i++ {
3118                 typ = PtrTo(typ)
3119         }
3120         for i = 0; i < 100; i++ {
3121                 typ = typ.Elem()
3122         }
3123         if typ != TypeOf(z) {
3124                 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
3125         }
3126 }
3127
3128 func TestPtrToGC(t *testing.T) {
3129         type T *uintptr
3130         tt := TypeOf(T(nil))
3131         pt := PtrTo(tt)
3132         const n = 100
3133         var x []interface{}
3134         for i := 0; i < n; i++ {
3135                 v := New(pt)
3136                 p := new(*uintptr)
3137                 *p = new(uintptr)
3138                 **p = uintptr(i)
3139                 v.Elem().Set(ValueOf(p).Convert(pt))
3140                 x = append(x, v.Interface())
3141         }
3142         runtime.GC()
3143
3144         for i, xi := range x {
3145                 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3146                 if k != uintptr(i) {
3147                         t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3148                 }
3149         }
3150 }
3151
3152 func BenchmarkPtrTo(b *testing.B) {
3153         // Construct a type with a zero ptrToThis.
3154         type T struct{ int }
3155         t := SliceOf(TypeOf(T{}))
3156         ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3157         if !ptrToThis.IsValid() {
3158                 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3159         }
3160         if ptrToThis.Int() != 0 {
3161                 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3162         }
3163         b.ResetTimer()
3164
3165         // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
3166         // every call.
3167         b.RunParallel(func(pb *testing.PB) {
3168                 for pb.Next() {
3169                         PtrTo(t)
3170                 }
3171         })
3172 }
3173
3174 func TestAddr(t *testing.T) {
3175         var p struct {
3176                 X, Y int
3177         }
3178
3179         v := ValueOf(&p)
3180         v = v.Elem()
3181         v = v.Addr()
3182         v = v.Elem()
3183         v = v.Field(0)
3184         v.SetInt(2)
3185         if p.X != 2 {
3186                 t.Errorf("Addr.Elem.Set failed to set value")
3187         }
3188
3189         // Again but take address of the ValueOf value.
3190         // Exercises generation of PtrTypes not present in the binary.
3191         q := &p
3192         v = ValueOf(&q).Elem()
3193         v = v.Addr()
3194         v = v.Elem()
3195         v = v.Elem()
3196         v = v.Addr()
3197         v = v.Elem()
3198         v = v.Field(0)
3199         v.SetInt(3)
3200         if p.X != 3 {
3201                 t.Errorf("Addr.Elem.Set failed to set value")
3202         }
3203
3204         // Starting without pointer we should get changed value
3205         // in interface.
3206         qq := p
3207         v = ValueOf(&qq).Elem()
3208         v0 := v
3209         v = v.Addr()
3210         v = v.Elem()
3211         v = v.Field(0)
3212         v.SetInt(4)
3213         if p.X != 3 { // should be unchanged from last time
3214                 t.Errorf("somehow value Set changed original p")
3215         }
3216         p = v0.Interface().(struct {
3217                 X, Y int
3218         })
3219         if p.X != 4 {
3220                 t.Errorf("Addr.Elem.Set valued to set value in top value")
3221         }
3222
3223         // Verify that taking the address of a type gives us a pointer
3224         // which we can convert back using the usual interface
3225         // notation.
3226         var s struct {
3227                 B *bool
3228         }
3229         ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3230         *(ps.(**bool)) = new(bool)
3231         if s.B == nil {
3232                 t.Errorf("Addr.Interface direct assignment failed")
3233         }
3234 }
3235
3236 func noAlloc(t *testing.T, n int, f func(int)) {
3237         if testing.Short() {
3238                 t.Skip("skipping malloc count in short mode")
3239         }
3240         if runtime.GOMAXPROCS(0) > 1 {
3241                 t.Skip("skipping; GOMAXPROCS>1")
3242         }
3243         i := -1
3244         allocs := testing.AllocsPerRun(n, func() {
3245                 f(i)
3246                 i++
3247         })
3248         if allocs > 0 {
3249                 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3250         }
3251 }
3252
3253 func TestAllocations(t *testing.T) {
3254         noAlloc(t, 100, func(j int) {
3255                 var i interface{}
3256                 var v Value
3257
3258                 // We can uncomment this when compiler escape analysis
3259                 // is good enough to see that the integer assigned to i
3260                 // does not escape and therefore need not be allocated.
3261                 //
3262                 // i = 42 + j
3263                 // v = ValueOf(i)
3264                 // if int(v.Int()) != 42+j {
3265                 //      panic("wrong int")
3266                 // }
3267
3268                 i = func(j int) int { return j }
3269                 v = ValueOf(i)
3270                 if v.Interface().(func(int) int)(j) != j {
3271                         panic("wrong result")
3272                 }
3273         })
3274 }
3275
3276 func TestSmallNegativeInt(t *testing.T) {
3277         i := int16(-1)
3278         v := ValueOf(i)
3279         if v.Int() != -1 {
3280                 t.Errorf("int16(-1).Int() returned %v", v.Int())
3281         }
3282 }
3283
3284 func TestIndex(t *testing.T) {
3285         xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3286         v := ValueOf(xs).Index(3).Interface().(byte)
3287         if v != xs[3] {
3288                 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3289         }
3290         xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3291         v = ValueOf(xa).Index(2).Interface().(byte)
3292         if v != xa[2] {
3293                 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3294         }
3295         s := "0123456789"
3296         v = ValueOf(s).Index(3).Interface().(byte)
3297         if v != s[3] {
3298                 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3299         }
3300 }
3301
3302 func TestSlice(t *testing.T) {
3303         xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3304         v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3305         if len(v) != 2 {
3306                 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3307         }
3308         if cap(v) != 5 {
3309                 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3310         }
3311         if !DeepEqual(v[0:5], xs[3:]) {
3312                 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3313         }
3314         xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3315         v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3316         if len(v) != 3 {
3317                 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3318         }
3319         if cap(v) != 6 {
3320                 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3321         }
3322         if !DeepEqual(v[0:6], xa[2:]) {
3323                 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3324         }
3325         s := "0123456789"
3326         vs := ValueOf(s).Slice(3, 5).Interface().(string)
3327         if vs != s[3:5] {
3328                 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3329         }
3330
3331         rv := ValueOf(&xs).Elem()
3332         rv = rv.Slice(3, 4)
3333         ptr2 := rv.Pointer()
3334         rv = rv.Slice(5, 5)
3335         ptr3 := rv.Pointer()
3336         if ptr3 != ptr2 {
3337                 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
3338         }
3339 }
3340
3341 func TestSlice3(t *testing.T) {
3342         xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3343         v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3344         if len(v) != 2 {
3345                 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3346         }
3347         if cap(v) != 4 {
3348                 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3349         }
3350         if !DeepEqual(v[0:4], xs[3:7:7]) {
3351                 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3352         }
3353         rv := ValueOf(&xs).Elem()
3354         shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3355         shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3356         shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3357
3358         xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3359         v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3360         if len(v) != 3 {
3361                 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3362         }
3363         if cap(v) != 4 {
3364                 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3365         }
3366         if !DeepEqual(v[0:4], xa[2:6:6]) {
3367                 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3368         }
3369         rv = ValueOf(&xa).Elem()
3370         shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3371         shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3372         shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3373
3374         s := "hello world"
3375         rv = ValueOf(&s).Elem()
3376         shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3377
3378         rv = ValueOf(&xs).Elem()
3379         rv = rv.Slice3(3, 5, 7)
3380         ptr2 := rv.Pointer()
3381         rv = rv.Slice3(4, 4, 4)
3382         ptr3 := rv.Pointer()
3383         if ptr3 != ptr2 {
3384                 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
3385         }
3386 }
3387
3388 func TestSetLenCap(t *testing.T) {
3389         xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3390         xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3391
3392         vs := ValueOf(&xs).Elem()
3393         shouldPanic("SetLen", func() { vs.SetLen(10) })
3394         shouldPanic("SetCap", func() { vs.SetCap(10) })
3395         shouldPanic("SetLen", func() { vs.SetLen(-1) })
3396         shouldPanic("SetCap", func() { vs.SetCap(-1) })
3397         shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3398         vs.SetLen(5)
3399         if len(xs) != 5 || cap(xs) != 8 {
3400                 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3401         }
3402         vs.SetCap(6)
3403         if len(xs) != 5 || cap(xs) != 6 {
3404                 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3405         }
3406         vs.SetCap(5)
3407         if len(xs) != 5 || cap(xs) != 5 {
3408                 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3409         }
3410         shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3411         shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3412
3413         va := ValueOf(&xa).Elem()
3414         shouldPanic("SetLen", func() { va.SetLen(8) })
3415         shouldPanic("SetCap", func() { va.SetCap(8) })
3416 }
3417
3418 func TestVariadic(t *testing.T) {
3419         var b bytes.Buffer
3420         V := ValueOf
3421
3422         b.Reset()
3423         V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3424         if b.String() != "hello, 42 world" {
3425                 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3426         }
3427
3428         b.Reset()
3429         V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3430         if b.String() != "hello, 42 world" {
3431                 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3432         }
3433 }
3434
3435 func TestFuncArg(t *testing.T) {
3436         f1 := func(i int, f func(int) int) int { return f(i) }
3437         f2 := func(i int) int { return i + 1 }
3438         r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3439         if r[0].Int() != 101 {
3440                 t.Errorf("function returned %d, want 101", r[0].Int())
3441         }
3442 }
3443
3444 func TestStructArg(t *testing.T) {
3445         type padded struct {
3446                 B string
3447                 C int32
3448         }
3449         var (
3450                 gotA  padded
3451                 gotB  uint32
3452                 wantA = padded{"3", 4}
3453                 wantB = uint32(5)
3454         )
3455         f := func(a padded, b uint32) {
3456                 gotA, gotB = a, b
3457         }
3458         ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3459         if gotA != wantA || gotB != wantB {
3460                 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3461         }
3462 }
3463
3464 var tagGetTests = []struct {
3465         Tag   StructTag
3466         Key   string
3467         Value string
3468 }{
3469         {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3470         {`protobuf:"PB(1,2)"`, `foo`, ``},
3471         {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3472         {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3473         {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3474         {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3475         {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3476 }
3477
3478 func TestTagGet(t *testing.T) {
3479         for _, tt := range tagGetTests {
3480                 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3481                         t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3482                 }
3483         }
3484 }
3485
3486 func TestBytes(t *testing.T) {
3487         type B []byte
3488         x := B{1, 2, 3, 4}
3489         y := ValueOf(x).Bytes()
3490         if !bytes.Equal(x, y) {
3491                 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3492         }
3493         if &x[0] != &y[0] {
3494                 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3495         }
3496 }
3497
3498 func TestSetBytes(t *testing.T) {
3499         type B []byte
3500         var x B
3501         y := []byte{1, 2, 3, 4}
3502         ValueOf(&x).Elem().SetBytes(y)
3503         if !bytes.Equal(x, y) {
3504                 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3505         }
3506         if &x[0] != &y[0] {
3507                 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3508         }
3509 }
3510
3511 type Private struct {
3512         x int
3513         y **int
3514         Z int
3515 }
3516
3517 func (p *Private) m() {
3518 }
3519
3520 type private struct {
3521         Z int
3522         z int
3523         S string
3524         A [1]Private
3525         T []Private
3526 }
3527
3528 func (p *private) P() {
3529 }
3530
3531 type Public struct {
3532         X int
3533         Y **int
3534         private
3535 }
3536
3537 func (p *Public) M() {
3538 }
3539
3540 func TestUnexported(t *testing.T) {
3541         var pub Public
3542         pub.S = "S"
3543         pub.T = pub.A[:]
3544         v := ValueOf(&pub)
3545         isValid(v.Elem().Field(0))
3546         isValid(v.Elem().Field(1))
3547         isValid(v.Elem().Field(2))
3548         isValid(v.Elem().FieldByName("X"))
3549         isValid(v.Elem().FieldByName("Y"))
3550         isValid(v.Elem().FieldByName("Z"))
3551         isValid(v.Type().Method(0).Func)
3552         m, _ := v.Type().MethodByName("M")
3553         isValid(m.Func)
3554         m, _ = v.Type().MethodByName("P")
3555         isValid(m.Func)
3556         isNonNil(v.Elem().Field(0).Interface())
3557         isNonNil(v.Elem().Field(1).Interface())
3558         isNonNil(v.Elem().Field(2).Field(2).Index(0))
3559         isNonNil(v.Elem().FieldByName("X").Interface())
3560         isNonNil(v.Elem().FieldByName("Y").Interface())
3561         isNonNil(v.Elem().FieldByName("Z").Interface())
3562         isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3563         isNonNil(v.Type().Method(0).Func.Interface())
3564         m, _ = v.Type().MethodByName("P")
3565         isNonNil(m.Func.Interface())
3566
3567         var priv Private
3568         v = ValueOf(&priv)
3569         isValid(v.Elem().Field(0))
3570         isValid(v.Elem().Field(1))
3571         isValid(v.Elem().FieldByName("x"))
3572         isValid(v.Elem().FieldByName("y"))
3573         shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3574         shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3575         shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3576         shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3577         shouldPanic("Method", func() { v.Type().Method(0) })
3578 }
3579
3580 func TestSetPanic(t *testing.T) {
3581         ok := func(f func()) { f() }
3582         bad := func(f func()) { shouldPanic("Set", f) }
3583         clear := func(v Value) { v.Set(Zero(v.Type())) }
3584
3585         type t0 struct {
3586                 W int
3587         }
3588
3589         type t1 struct {
3590                 Y int
3591                 t0
3592         }
3593
3594         type T2 struct {
3595                 Z       int
3596                 namedT0 t0
3597         }
3598
3599         type T struct {
3600                 X int
3601                 t1
3602                 T2
3603                 NamedT1 t1
3604                 NamedT2 T2
3605                 namedT1 t1
3606                 namedT2 T2
3607         }
3608
3609         // not addressable
3610         v := ValueOf(T{})
3611         bad(func() { clear(v.Field(0)) })                   // .X
3612         bad(func() { clear(v.Field(1)) })                   // .t1
3613         bad(func() { clear(v.Field(1).Field(0)) })          // .t1.Y
3614         bad(func() { clear(v.Field(1).Field(1)) })          // .t1.t0
3615         bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3616         bad(func() { clear(v.Field(2)) })                   // .T2
3617         bad(func() { clear(v.Field(2).Field(0)) })          // .T2.Z
3618         bad(func() { clear(v.Field(2).Field(1)) })          // .T2.namedT0
3619         bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3620         bad(func() { clear(v.Field(3)) })                   // .NamedT1
3621         bad(func() { clear(v.Field(3).Field(0)) })          // .NamedT1.Y
3622         bad(func() { clear(v.Field(3).Field(1)) })          // .NamedT1.t0
3623         bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3624         bad(func() { clear(v.Field(4)) })                   // .NamedT2
3625         bad(func() { clear(v.Field(4).Field(0)) })          // .NamedT2.Z
3626         bad(func() { clear(v.Field(4).Field(1)) })          // .NamedT2.namedT0
3627         bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3628         bad(func() { clear(v.Field(5)) })                   // .namedT1
3629         bad(func() { clear(v.Field(5).Field(0)) })          // .namedT1.Y
3630         bad(func() { clear(v.Field(5).Field(1)) })          // .namedT1.t0
3631         bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3632         bad(func() { clear(v.Field(6)) })                   // .namedT2
3633         bad(func() { clear(v.Field(6).Field(0)) })          // .namedT2.Z
3634         bad(func() { clear(v.Field(6).Field(1)) })          // .namedT2.namedT0
3635         bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3636
3637         // addressable
3638         v = ValueOf(&T{}).Elem()
3639         ok(func() { clear(v.Field(0)) })                    // .X
3640         bad(func() { clear(v.Field(1)) })                   // .t1
3641         ok(func() { clear(v.Field(1).Field(0)) })           // .t1.Y
3642         bad(func() { clear(v.Field(1).Field(1)) })          // .t1.t0
3643         ok(func() { clear(v.Field(1).Field(1).Field(0)) })  // .t1.t0.W
3644         ok(func() { clear(v.Field(2)) })                    // .T2
3645         ok(func() { clear(v.Field(2).Field(0)) })           // .T2.Z
3646         bad(func() { clear(v.Field(2).Field(1)) })          // .T2.namedT0
3647         bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3648         ok(func() { clear(v.Field(3)) })                    // .NamedT1
3649         ok(func() { clear(v.Field(3).Field(0)) })           // .NamedT1.Y
3650         bad(func() { clear(v.Field(3).Field(1)) })          // .NamedT1.t0
3651         ok(func() { clear(v.Field(3).Field(1).Field(0)) })  // .NamedT1.t0.W
3652         ok(func() { clear(v.Field(4)) })                    // .NamedT2
3653         ok(func() { clear(v.Field(4).Field(0)) })           // .NamedT2.Z
3654         bad(func() { clear(v.Field(4).Field(1)) })          // .NamedT2.namedT0
3655         bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3656         bad(func() { clear(v.Field(5)) })                   // .namedT1
3657         bad(func() { clear(v.Field(5).Field(0)) })          // .namedT1.Y
3658         bad(func() { clear(v.Field(5).Field(1)) })          // .namedT1.t0
3659         bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3660         bad(func() { clear(v.Field(6)) })                   // .namedT2
3661         bad(func() { clear(v.Field(6).Field(0)) })          // .namedT2.Z
3662         bad(func() { clear(v.Field(6).Field(1)) })          // .namedT2.namedT0
3663         bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3664 }
3665
3666 type timp int
3667
3668 func (t timp) W() {}
3669 func (t timp) Y() {}
3670 func (t timp) w() {}
3671 func (t timp) y() {}
3672
3673 func TestCallPanic(t *testing.T) {
3674         type t0 interface {
3675                 W()
3676                 w()
3677         }
3678         type T1 interface {
3679                 Y()
3680                 y()
3681         }
3682         type T2 struct {
3683                 T1
3684                 t0
3685         }
3686         type T struct {
3687                 t0 // 0
3688                 T1 // 1
3689
3690                 NamedT0 t0 // 2
3691                 NamedT1 T1 // 3
3692                 NamedT2 T2 // 4
3693
3694                 namedT0 t0 // 5
3695                 namedT1 T1 // 6
3696                 namedT2 T2 // 7
3697         }
3698         ok := func(f func()) { f() }
3699         badCall := func(f func()) { shouldPanic("Call", f) }
3700         badMethod := func(f func()) { shouldPanic("Method", f) }
3701         call := func(v Value) { v.Call(nil) }
3702
3703         i := timp(0)
3704         v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3705         badCall(func() { call(v.Field(0).Method(0)) })          // .t0.W
3706         badCall(func() { call(v.Field(0).Elem().Method(0)) })   // .t0.W
3707         badCall(func() { call(v.Field(0).Method(1)) })          // .t0.w
3708         badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3709         ok(func() { call(v.Field(1).Method(0)) })               // .T1.Y
3710         ok(func() { call(v.Field(1).Elem().Method(0)) })        // .T1.Y
3711         badCall(func() { call(v.Field(1).Method(1)) })          // .T1.y
3712         badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3713
3714         ok(func() { call(v.Field(2).Method(0)) })               // .NamedT0.W
3715         ok(func() { call(v.Field(2).Elem().Method(0)) })        // .NamedT0.W
3716         badCall(func() { call(v.Field(2).Method(1)) })          // .NamedT0.w
3717         badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3718
3719         ok(func() { call(v.Field(3).Method(0)) })               // .NamedT1.Y
3720         ok(func() { call(v.Field(3).Elem().Method(0)) })        // .NamedT1.Y
3721         badCall(func() { call(v.Field(3).Method(1)) })          // .NamedT1.y
3722         badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3723
3724         ok(func() { call(v.Field(4).Field(0).Method(0)) })             // .NamedT2.T1.Y
3725         ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) })      // .NamedT2.T1.W
3726         badCall(func() { call(v.Field(4).Field(1).Method(0)) })        // .NamedT2.t0.W
3727         badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3728
3729         badCall(func() { call(v.Field(5).Method(0)) })          // .namedT0.W
3730         badCall(func() { call(v.Field(5).Elem().Method(0)) })   // .namedT0.W
3731         badCall(func() { call(v.Field(5).Method(1)) })          // .namedT0.w
3732         badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3733
3734         badCall(func() { call(v.Field(6).Method(0)) })        // .namedT1.Y
3735         badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3736         badCall(func() { call(v.Field(6).Method(0)) })        // .namedT1.y
3737         badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3738
3739         badCall(func() { call(v.Field(7).Field(0).Method(0)) })        // .namedT2.T1.Y
3740         badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3741         badCall(func() { call(v.Field(7).Field(1).Method(0)) })        // .namedT2.t0.W
3742         badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3743 }
3744
3745 func shouldPanic(expect string, f func()) {
3746         defer func() {
3747                 r := recover()
3748                 if r == nil {
3749                         panic("did not panic")
3750                 }
3751                 if expect != "" {
3752                         var s string
3753                         switch r := r.(type) {
3754                         case string:
3755                                 s = r
3756                         case *ValueError:
3757                                 s = r.Error()
3758                         default:
3759                                 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3760                         }
3761                         if !strings.HasPrefix(s, "reflect") {
3762                                 panic(`panic string does not start with "reflect": ` + s)
3763                         }
3764                         if !strings.Contains(s, expect) {
3765                                 panic(`panic string does not contain "` + expect + `": ` + s)
3766                         }
3767                 }
3768         }()
3769         f()
3770 }
3771
3772 func isNonNil(x interface{}) {
3773         if x == nil {
3774                 panic("nil interface")
3775         }
3776 }
3777
3778 func isValid(v Value) {
3779         if !v.IsValid() {
3780                 panic("zero Value")
3781         }
3782 }
3783
3784 func TestAlias(t *testing.T) {
3785         x := string("hello")
3786         v := ValueOf(&x).Elem()
3787         oldvalue := v.Interface()
3788         v.SetString("world")
3789         newvalue := v.Interface()
3790
3791         if oldvalue != "hello" || newvalue != "world" {
3792                 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3793         }
3794 }
3795
3796 var V = ValueOf
3797
3798 func EmptyInterfaceV(x interface{}) Value {
3799         return ValueOf(&x).Elem()
3800 }
3801
3802 func ReaderV(x io.Reader) Value {
3803         return ValueOf(&x).Elem()
3804 }
3805
3806 func ReadWriterV(x io.ReadWriter) Value {
3807         return ValueOf(&x).Elem()
3808 }
3809
3810 type Empty struct{}
3811 type MyStruct struct {
3812         x int `some:"tag"`
3813 }
3814 type MyStruct1 struct {
3815         x struct {
3816                 int `some:"bar"`
3817         }
3818 }
3819 type MyStruct2 struct {
3820         x struct {
3821                 int `some:"foo"`
3822         }
3823 }
3824 type MyString string
3825 type MyBytes []byte
3826 type MyBytesArrayPtr0 *[0]byte
3827 type MyBytesArrayPtr *[4]byte
3828 type MyBytesArray0 [0]byte
3829 type MyBytesArray [4]byte
3830 type MyRunes []int32
3831 type MyFunc func()
3832 type MyByte byte
3833
3834 type IntChan chan int
3835 type IntChanRecv <-chan int
3836 type IntChanSend chan<- int
3837 type BytesChan chan []byte
3838 type BytesChanRecv <-chan []byte
3839 type BytesChanSend chan<- []byte
3840
3841 var convertTests = []struct {
3842         in  Value
3843         out Value
3844 }{
3845         // numbers
3846         /*
3847                 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3848
3849                 package main
3850
3851                 import "fmt"
3852
3853                 var numbers = []string{
3854                         "int8", "uint8", "int16", "uint16",
3855                         "int32", "uint32", "int64", "uint64",
3856                         "int", "uint", "uintptr",
3857                         "float32", "float64",
3858                 }
3859
3860                 func main() {
3861                         // all pairs but in an unusual order,
3862                         // to emit all the int8, uint8 cases
3863                         // before n grows too big.
3864                         n := 1
3865                         for i, f := range numbers {
3866                                 for _, g := range numbers[i:] {
3867                                         fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3868                                         n++
3869                                         if f != g {
3870                                                 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3871                                                 n++
3872                                         }
3873                                 }
3874                         }
3875                 }
3876         */
3877         {V(int8(1)), V(int8(1))},
3878         {V(int8(2)), V(uint8(2))},
3879         {V(uint8(3)), V(int8(3))},
3880         {V(int8(4)), V(int16(4))},
3881         {V(int16(5)), V(int8(5))},
3882         {V(int8(6)), V(uint16(6))},
3883         {V(uint16(7)), V(int8(7))},
3884         {V(int8(8)), V(int32(8))},
3885         {V(int32(9)), V(int8(9))},
3886         {V(int8(10)), V(uint32(10))},
3887         {V(uint32(11)), V(int8(11))},
3888         {V(int8(12)), V(int64(12))},
3889         {V(int64(13)), V(int8(13))},
3890         {V(int8(14)), V(uint64(14))},
3891         {V(uint64(15)), V(int8(15))},
3892         {V(int8(16)), V(int(16))},
3893         {V(int(17)), V(int8(17))},
3894         {V(int8(18)), V(uint(18))},
3895         {V(uint(19)), V(int8(19))},
3896         {V(int8(20)), V(uintptr(20))},
3897         {V(uintptr(21)), V(int8(21))},
3898         {V(int8(22)), V(float32(22))},
3899         {V(float32(23)), V(int8(23))},
3900         {V(int8(24)), V(float64(24))},
3901         {V(float64(25)), V(int8(25))},
3902         {V(uint8(26)), V(uint8(26))},
3903         {V(uint8(27)), V(int16(27))},
3904         {V(int16(28)), V(uint8(28))},
3905         {V(uint8(29)), V(uint16(29))},
3906         {V(uint16(30)), V(uint8(30))},
3907         {V(uint8(31)), V(int32(31))},
3908         {V(int32(32)), V(uint8(32))},
3909         {V(uint8(33)), V(uint32(33))},
3910         {V(uint32(34)), V(uint8(34))},
3911         {V(uint8(35)), V(int64(35))},
3912         {V(int64(36)), V(uint8(36))},
3913         {V(uint8(37)), V(uint64(37))},
3914         {V(uint64(38)), V(uint8(38))},
3915         {V(uint8(39)), V(int(39))},
3916         {V(int(40)), V(uint8(40))},
3917         {V(uint8(41)), V(uint(41))},
3918         {V(uint(42)), V(uint8(42))},
3919         {V(uint8(43)), V(uintptr(43))},
3920         {V(uintptr(44)), V(uint8(44))},
3921         {V(uint8(45)), V(float32(45))},
3922         {V(float32(46)), V(uint8(46))},
3923         {V(uint8(47)), V(float64(47))},
3924         {V(float64(48)), V(uint8(48))},
3925         {V(int16(49)), V(int16(49))},
3926         {V(int16(50)), V(uint16(50))},
3927         {V(uint16(51)), V(int16(51))},
3928         {V(int16(52)), V(int32(52))},
3929         {V(int32(53)), V(int16(53))},
3930         {V(int16(54)), V(uint32(54))},
3931         {V(uint32(55)), V(int16(55))},
3932         {V(int16(56)), V(int64(56))},
3933         {V(int64(57)), V(int16(57))},
3934         {V(int16(58)), V(uint64(58))},
3935         {V(uint64(59)), V(int16(59))},
3936         {V(int16(60)), V(int(60))},
3937         {V(int(61)), V(int16(61))},
3938         {V(int16(62)), V(uint(62))},
3939         {V(uint(63)), V(int16(63))},
3940         {V(int16(64)), V(uintptr(64))},
3941         {V(uintptr(65)), V(int16(65))},
3942         {V(int16(66)), V(float32(66))},
3943         {V(float32(67)), V(int16(67))},
3944         {V(int16(68)), V(float64(68))},
3945         {V(float64(69)), V(int16(69))},
3946         {V(uint16(70)), V(uint16(70))},
3947         {V(uint16(71)), V(int32(71))},
3948         {V(int32(72)), V(uint16(72))},
3949         {V(uint16(73)), V(uint32(73))},
3950         {V(uint32(74)), V(uint16(74))},
3951         {V(uint16(75)), V(int64(75))},
3952         {V(int64(76)), V(uint16(76))},
3953         {V(uint16(77)), V(uint64(77))},
3954         {V(uint64(78)), V(uint16(78))},
3955         {V(uint16(79)), V(int(79))},
3956         {V(int(80)), V(uint16(80))},
3957         {V(uint16(81)), V(uint(81))},
3958         {V(uint(82)), V(uint16(82))},
3959         {V(uint16(83)), V(uintptr(83))},
3960         {V(uintptr(84)), V(uint16(84))},
3961         {V(uint16(85)), V(float32(85))},
3962         {V(float32(86)), V(uint16(86))},
3963         {V(uint16(87)), V(float64(87))},
3964         {V(float64(88)), V(uint16(88))},
3965         {V(int32(89)), V(int32(89))},
3966         {V(int32(90)), V(uint32(90))},
3967         {V(uint32(91)), V(int32(91))},
3968         {V(int32(92)), V(int64(92))},
3969         {V(int64(93)), V(int32(93))},
3970         {V(int32(94)), V(uint64(94))},
3971         {V(uint64(95)), V(int32(95))},
3972         {V(int32(96)), V(int(96))},
3973         {V(int(97)), V(int32(97))},
3974         {V(int32(98)), V(uint(98))},
3975         {V(uint(99)), V(int32(99))},
3976         {V(int32(100)), V(uintptr(100))},
3977         {V(uintptr(101)), V(int32(101))},
3978         {V(int32(102)), V(float32(102))},
3979         {V(float32(103)), V(int32(103))},
3980         {V(int32(104)), V(float64(104))},
3981         {V(float64(105)), V(int32(105))},
3982         {V(uint32(106)), V(uint32(106))},
3983         {V(uint32(107)), V(int64(107))},
3984         {V(int64(108)), V(uint32(108))},
3985         {V(uint32(109)), V(uint64(109))},
3986         {V(uint64(110)), V(uint32(110))},
3987         {V(uint32(111)), V(int(111))},
3988         {V(int(112)), V(uint32(112))},
3989         {V(uint32(113)), V(uint(113))},
3990         {V(uint(114)), V(uint32(114))},
3991         {V(uint32(115)), V(uintptr(115))},
3992         {V(uintptr(116)), V(uint32(116))},
3993         {V(uint32(117)), V(float32(117))},
3994         {V(float32(118)), V(uint32(118))},
3995         {V(uint32(119)), V(float64(119))},
3996         {V(float64(120)), V(uint32(120))},
3997         {V(int64(121)), V(int64(121))},
3998         {V(int64(122)), V(uint64(122))},
3999         {V(uint64(123)), V(int64(123))},
4000         {V(int64(124)), V(int(124))},
4001         {V(int(125)), V(int64(125))},
4002         {V(int64(126)), V(uint(126))},
4003         {V(uint(127)), V(int64(127))},
4004         {V(int64(128)), V(uintptr(128))},
4005         {V(uintptr(129)), V(int64(129))},
4006         {V(int64(130)), V(float32(130))},
4007         {V(float32(131)), V(int64(131))},
4008         {V(int64(132)), V(float64(132))},
4009         {V(float64(133)), V(int64(133))},
4010         {V(uint64(134)), V(uint64(134))},
4011         {V(uint64(135)), V(int(135))},
4012         {V(int(136)), V(uint64(136))},
4013         {V(uint64(137)), V(uint(137))},
4014         {V(uint(138)), V(uint64(138))},
4015         {V(uint64(139)), V(uintptr(139))},
4016         {V(uintptr(140)), V(uint64(140))},
4017         {V(uint64(141)), V(float32(141))},
4018         {V(float32(142)), V(uint64(142))},
4019         {V(uint64(143)), V(float64(143))},
4020         {V(float64(144)), V(uint64(144))},
4021         {V(int(145)), V(int(145))},
4022         {V(int(146)), V(uint(146))},
4023         {V(uint(147)), V(int(147))},
4024         {V(int(148)), V(uintptr(148))},
4025         {V(uintptr(149)), V(int(149))},
4026         {V(int(150)), V(float32(150))},
4027         {V(float32(151)), V(int(151))},
4028         {V(int(152)), V(float64(152))},
4029         {V(float64(153)), V(int(153))},
4030         {V(uint(154)), V(uint(154))},
4031         {V(uint(155)), V(uintptr(155))},
4032         {V(uintptr(156)), V(uint(156))},
4033         {V(uint(157)), V(float32(157))},
4034         {V(float32(158)), V(uint(158))},
4035         {V(uint(159)), V(float64(159))},
4036         {V(float64(160)), V(uint(160))},
4037         {V(uintptr(161)), V(uintptr(161))},
4038         {V(uintptr(162)), V(float32(162))},
4039         {V(float32(163)), V(uintptr(163))},
4040         {V(uintptr(164)), V(float64(164))},
4041         {V(float64(165)), V(uintptr(165))},
4042         {V(float32(166)), V(float32(166))},
4043         {V(float32(167)), V(float64(167))},
4044         {V(float64(168)), V(float32(168))},
4045         {V(float64(169)), V(float64(169))},
4046
4047         // truncation
4048         {V(float64(1.5)), V(int(1))},
4049
4050         // complex
4051         {V(complex64(1i)), V(complex64(1i))},
4052         {V(complex64(2i)), V(complex128(2i))},
4053         {V(complex128(3i)), V(complex64(3i))},
4054         {V(complex128(4i)), V(complex128(4i))},
4055
4056         // string
4057         {V(string("hello")), V(string("hello"))},
4058         {V(string("bytes1")), V([]byte("bytes1"))},
4059         {V([]byte("bytes2")), V(string("bytes2"))},
4060         {V([]byte("bytes3")), V([]byte("bytes3"))},
4061         {V(string("runes♝")), V([]rune("runes♝"))},
4062         {V([]rune("runes♕")), V(string("runes♕"))},
4063         {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4064         {V(int('a')), V(string("a"))},
4065         {V(int8('a')), V(string("a"))},
4066         {V(int16('a')), V(string("a"))},
4067         {V(int32('a')), V(string("a"))},
4068         {V(int64('a')), V(string("a"))},
4069         {V(uint('a')), V(string("a"))},
4070         {V(uint8('a')), V(string("a"))},
4071         {V(uint16('a')), V(string("a"))},
4072         {V(uint32('a')), V(string("a"))},
4073         {V(uint64('a')), V(string("a"))},
4074         {V(uintptr('a')), V(string("a"))},
4075         {V(int(-1)), V(string("\uFFFD"))},
4076         {V(int8(-2)), V(string("\uFFFD"))},
4077         {V(int16(-3)), V(string("\uFFFD"))},
4078         {V(int32(-4)), V(string("\uFFFD"))},
4079         {V(int64(-5)), V(string("\uFFFD"))},
4080         {V(int64(-1 << 32)), V(string("\uFFFD"))},
4081         {V(int64(1 << 32)), V(string("\uFFFD"))},
4082         {V(uint(0x110001)), V(string("\uFFFD"))},
4083         {V(uint32(0x110002)), V(string("\uFFFD"))},
4084         {V(uint64(0x110003)), V(string("\uFFFD"))},
4085         {V(uint64(1 << 32)), V(string("\uFFFD"))},
4086         {V(uintptr(0x110004)), V(string("\uFFFD"))},
4087
4088         // named string
4089         {V(MyString("hello")), V(string("hello"))},
4090         {V(string("hello")), V(MyString("hello"))},
4091         {V(string("hello")), V(string("hello"))},
4092         {V(MyString("hello")), V(MyString("hello"))},
4093         {V(MyString("bytes1")), V([]byte("bytes1"))},
4094         {V([]byte("bytes2")), V(MyString("bytes2"))},
4095         {V([]byte("bytes3")), V([]byte("bytes3"))},
4096         {V(MyString("runes♝")), V([]rune("runes♝"))},
4097         {V([]rune("runes♕")), V(MyString("runes♕"))},
4098         {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4099         {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4100         {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4101         {V(int('a')), V(MyString("a"))},
4102         {V(int8('a')), V(MyString("a"))},
4103         {V(int16('a')), V(MyString("a"))},
4104         {V(int32('a')), V(MyString("a"))},
4105         {V(int64('a')), V(MyString("a"))},
4106         {V(uint('a')), V(MyString("a"))},
4107         {V(uint8('a')), V(MyString("a"))},
4108         {V(uint16('a')), V(MyString("a"))},
4109         {V(uint32('a')), V(MyString("a"))},
4110         {V(uint64('a')), V(MyString("a"))},
4111         {V(uintptr('a')), V(MyString("a"))},
4112         {V(int(-1)), V(MyString("\uFFFD"))},
4113         {V(int8(-2)), V(MyString("\uFFFD"))},
4114         {V(int16(-3)), V(MyString("\uFFFD"))},
4115         {V(int32(-4)), V(MyString("\uFFFD"))},
4116         {V(int64(-5)), V(MyString("\uFFFD"))},
4117         {V(uint(0x110001)), V(MyString("\uFFFD"))},
4118         {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4119         {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4120         {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4121
4122         // named []byte
4123         {V(string("bytes1")), V(MyBytes("bytes1"))},
4124         {V(MyBytes("bytes2")), V(string("bytes2"))},
4125         {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4126         {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4127         {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4128
4129         // named []rune
4130         {V(string("runes♝")), V(MyRunes("runes♝"))},
4131         {V(MyRunes("runes♕")), V(string("runes♕"))},
4132         {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4133         {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4134         {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4135
4136         // slice to array pointer
4137         {V([]byte(nil)), V((*[0]byte)(nil))},
4138         {V([]byte{}), V(new([0]byte))},
4139         {V([]byte{7}), V(&[1]byte{7})},
4140         {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4141         {V(MyBytes([]byte{})), V(new([0]byte))},
4142         {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4143         {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4144         {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4145         {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4146         {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4147         {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4148
4149         {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4150         {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4151         {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4152         {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4153         {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4154         {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4155         {V(new([0]byte)), V(new(MyBytesArray0))},
4156         {V(new(MyBytesArray0)), V(new([0]byte))},
4157         {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4158         {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4159
4160         // named types and equal underlying types
4161         {V(new(int)), V(new(integer))},
4162         {V(new(integer)), V(new(int))},
4163         {V(Empty{}), V(struct{}{})},
4164         {V(new(Empty)), V(new(struct{}))},
4165         {V(struct{}{}), V(Empty{})},
4166         {V(new(struct{})), V(new(Empty))},
4167         {V(Empty{}), V(Empty{})},
4168         {V(MyBytes{}), V([]byte{})},
4169         {V([]byte{}), V(MyBytes{})},
4170         {V((func())(nil)), V(MyFunc(nil))},
4171         {V((MyFunc)(nil)), V((func())(nil))},
4172
4173         // structs with different tags
4174         {V(struct {
4175                 x int `some:"foo"`
4176         }{}), V(struct {
4177                 x int `some:"bar"`
4178         }{})},
4179
4180         {V(struct {
4181                 x int `some:"bar"`
4182         }{}), V(struct {
4183                 x int `some:"foo"`
4184         }{})},
4185
4186         {V(MyStruct{}), V(struct {
4187                 x int `some:"foo"`
4188         }{})},
4189
4190         {V(struct {
4191                 x int `some:"foo"`
4192         }{}), V(MyStruct{})},
4193
4194         {V(MyStruct{}), V(struct {
4195                 x int `some:"bar"`
4196         }{})},
4197
4198         {V(struct {
4199                 x int `some:"bar"`
4200         }{}), V(MyStruct{})},
4201
4202         {V(MyStruct1{}), V(MyStruct2{})},
4203         {V(MyStruct2{}), V(MyStruct1{})},
4204
4205         // can convert *byte and *MyByte
4206         {V((*byte)(nil)), V((*MyByte)(nil))},
4207         {V((*MyByte)(nil)), V((*byte)(nil))},
4208
4209         // cannot convert mismatched array sizes
4210         {V([2]byte{}), V([2]byte{})},
4211         {V([3]byte{}), V([3]byte{})},
4212
4213         // cannot convert other instances
4214         {V((**byte)(nil)), V((**byte)(nil))},
4215         {V((**MyByte)(nil)), V((**MyByte)(nil))},
4216         {V((chan byte)(nil)), V((chan byte)(nil))},
4217         {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4218         {V(([]byte)(nil)), V(([]byte)(nil))},
4219         {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4220         {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4221         {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4222         {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4223         {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4224         {V([2]byte{}), V([2]byte{})},
4225         {V([2]MyByte{}), V([2]MyByte{})},
4226
4227         // other
4228         {V((***int)(nil)), V((***int)(nil))},
4229         {V((***byte)(nil)), V((***byte)(nil))},
4230         {V((***int32)(nil)), V((***int32)(nil))},
4231         {V((***int64)(nil)), V((***int64)(nil))},
4232         {V((chan byte)(nil)), V((chan byte)(nil))},
4233         {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4234         {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4235         {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4236         {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4237         {V([]uint(nil)), V([]uint(nil))},
4238         {V([]int(nil)), V([]int(nil))},
4239         {V(new(interface{})), V(new(interface{}))},
4240         {V(new(io.Reader)), V(new(io.Reader))},
4241         {V(new(io.Writer)), V(new(io.Writer))},
4242
4243         // channels
4244         {V(IntChan(nil)), V((chan<- int)(nil))},
4245         {V(IntChan(nil)), V((<-chan int)(nil))},
4246         {V((chan int)(nil)), V(IntChanRecv(nil))},
4247         {V((chan int)(nil)), V(IntChanSend(nil))},
4248         {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4249         {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4250         {V(IntChanSend(nil)), V((chan<- int)(nil))},
4251         {V((chan<- int)(nil)), V(IntChanSend(nil))},
4252         {V(IntChan(nil)), V((chan int)(nil))},
4253         {V((chan int)(nil)), V(IntChan(nil))},
4254         {V((chan int)(nil)), V((<-chan int)(nil))},
4255         {V((chan int)(nil)), V((chan<- int)(nil))},
4256         {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4257         {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4258         {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4259         {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4260         {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4261         {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4262         {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4263         {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4264         {V(BytesChan(nil)), V((chan []byte)(nil))},
4265         {V((chan []byte)(nil)), V(BytesChan(nil))},
4266         {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4267         {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4268
4269         // cannot convert other instances (channels)
4270         {V(IntChan(nil)), V(IntChan(nil))},
4271         {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4272         {V(IntChanSend(nil)), V(IntChanSend(nil))},
4273         {V(BytesChan(nil)), V(BytesChan(nil))},
4274         {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4275         {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4276
4277         // interfaces
4278         {V(int(1)), EmptyInterfaceV(int(1))},
4279         {V(string("hello")), EmptyInterfaceV(string("hello"))},
4280         {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4281         {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4282         {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4283 }
4284
4285 func TestConvert(t *testing.T) {
4286         canConvert := map[[2]Type]bool{}
4287         all := map[Type]bool{}
4288
4289         for _, tt := range convertTests {
4290                 t1 := tt.in.Type()
4291                 if !t1.ConvertibleTo(t1) {
4292                         t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4293                         continue
4294                 }
4295
4296                 t2 := tt.out.Type()
4297                 if !t1.ConvertibleTo(t2) {
4298                         t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4299                         continue
4300                 }
4301
4302                 all[t1] = true
4303                 all[t2] = true
4304                 canConvert[[2]Type{t1, t2}] = true
4305
4306                 // vout1 represents the in value converted to the in type.
4307                 v1 := tt.in
4308                 if !v1.CanConvert(t1) {
4309                         t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4310                 }
4311                 vout1 := v1.Convert(t1)
4312                 out1 := vout1.Interface()
4313                 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4314                         t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4315                 }
4316
4317                 // vout2 represents the in value converted to the out type.
4318                 if !v1.CanConvert(t2) {
4319                         t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4320                 }
4321                 vout2 := v1.Convert(t2)
4322                 out2 := vout2.Interface()
4323                 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4324                         t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4325                 }
4326                 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4327                         t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4328                 }
4329
4330                 // vout3 represents a new value of the out type, set to vout2.  This makes
4331                 // sure the converted value vout2 is really usable as a regular value.
4332                 vout3 := New(t2).Elem()
4333                 vout3.Set(vout2)
4334                 out3 := vout3.Interface()
4335                 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4336                         t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4337                 }
4338
4339                 if IsRO(v1) {
4340                         t.Errorf("table entry %v is RO, should not be", v1)
4341                 }
4342                 if IsRO(vout1) {
4343                         t.Errorf("self-conversion output %v is RO, should not be", vout1)
4344                 }
4345                 if IsRO(vout2) {
4346                         t.Errorf("conversion output %v is RO, should not be", vout2)
4347                 }
4348                 if IsRO(vout3) {
4349                         t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4350                 }
4351                 if !IsRO(MakeRO(v1).Convert(t1)) {
4352                         t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4353                 }
4354                 if !IsRO(MakeRO(v1).Convert(t2)) {
4355                         t.Errorf("RO conversion output %v is not RO, should be", v1)
4356                 }
4357         }
4358
4359         // Assume that of all the types we saw during the tests,
4360         // if there wasn't an explicit entry for a conversion between
4361         // a pair of types, then it's not to be allowed. This checks for
4362         // things like 'int64' converting to '*int'.
4363         for t1 := range all {
4364                 for t2 := range all {
4365                         expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4366                         if ok := t1.ConvertibleTo(t2); ok != expectOK {
4367                                 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4368                         }
4369                 }
4370         }
4371 }
4372
4373 func TestConvertPanic(t *testing.T) {
4374         s := make([]byte, 4)
4375         p := new([8]byte)
4376         v := ValueOf(s)
4377         pt := TypeOf(p)
4378         if !v.Type().ConvertibleTo(pt) {
4379                 t.Errorf("[]byte should be convertible to *[8]byte")
4380         }
4381         if v.CanConvert(pt) {
4382                 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4383         }
4384         shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4385                 _ = v.Convert(pt)
4386         })
4387 }
4388
4389 var gFloat32 float32
4390
4391 func TestConvertNaNs(t *testing.T) {
4392         const snan uint32 = 0x7f800001
4393         type myFloat32 float32
4394         x := V(myFloat32(math.Float32frombits(snan)))
4395         y := x.Convert(TypeOf(float32(0)))
4396         z := y.Interface().(float32)
4397         if got := math.Float32bits(z); got != snan {
4398                 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4399         }
4400 }
4401
4402 type ComparableStruct struct {
4403         X int
4404 }
4405
4406 type NonComparableStruct struct {
4407         X int
4408         Y map[string]int
4409 }
4410
4411 var comparableTests = []struct {
4412         typ Type
4413         ok  bool
4414 }{
4415         {TypeOf(1), true},
4416         {TypeOf("hello"), true},
4417         {TypeOf(new(byte)), true},
4418         {TypeOf((func())(nil)), false},
4419         {TypeOf([]byte{}), false},
4420         {TypeOf(map[string]int{}), false},
4421         {TypeOf(make(chan int)), true},
4422         {TypeOf(1.5), true},
4423         {TypeOf(false), true},
4424         {TypeOf(1i), true},
4425         {TypeOf(ComparableStruct{}), true},
4426         {TypeOf(NonComparableStruct{}), false},
4427         {TypeOf([10]map[string]int{}), false},
4428         {TypeOf([10]string{}), true},
4429         {TypeOf(new(interface{})).Elem(), true},
4430 }
4431
4432 func TestComparable(t *testing.T) {
4433         for _, tt := range comparableTests {
4434                 if ok := tt.typ.Comparable(); ok != tt.ok {
4435                         t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4436                 }
4437         }
4438 }
4439
4440 func TestOverflow(t *testing.T) {
4441         if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4442                 t.Errorf("%v wrongly overflows float64", 1e300)
4443         }
4444
4445         maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4446         if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4447                 t.Errorf("%v wrongly overflows float32", maxFloat32)
4448         }
4449         ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4450         if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4451                 t.Errorf("%v should overflow float32", ovfFloat32)
4452         }
4453         if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4454                 t.Errorf("%v should overflow float32", -ovfFloat32)
4455         }
4456
4457         maxInt32 := int64(0x7fffffff)
4458         if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4459                 t.Errorf("%v wrongly overflows int32", maxInt32)
4460         }
4461         if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4462                 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4463         }
4464         ovfInt32 := int64(1 << 31)
4465         if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4466                 t.Errorf("%v should overflow int32", ovfInt32)
4467         }
4468
4469         maxUint32 := uint64(0xffffffff)
4470         if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4471                 t.Errorf("%v wrongly overflows uint32", maxUint32)
4472         }
4473         ovfUint32 := uint64(1 << 32)
4474         if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4475                 t.Errorf("%v should overflow uint32", ovfUint32)
4476         }
4477 }
4478
4479 func checkSameType(t *testing.T, x Type, y interface{}) {
4480         if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4481                 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4482         }
4483 }
4484
4485 func TestArrayOf(t *testing.T) {
4486         // check construction and use of type not in binary
4487         tests := []struct {
4488                 n          int
4489                 value      func(i int) interface{}
4490                 comparable bool
4491                 want       string
4492         }{
4493                 {
4494                         n:          0,
4495                         value:      func(i int) interface{} { type Tint int; return Tint(i) },
4496                         comparable: true,
4497                         want:       "[]",
4498                 },
4499                 {
4500                         n:          10,
4501                         value:      func(i int) interface{} { type Tint int; return Tint(i) },
4502                         comparable: true,
4503                         want:       "[0 1 2 3 4 5 6 7 8 9]",
4504                 },
4505                 {
4506                         n:          10,
4507                         value:      func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
4508                         comparable: true,
4509                         want:       "[0 1 2 3 4 5 6 7 8 9]",
4510                 },
4511                 {
4512                         n:          10,
4513                         value:      func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
4514                         comparable: true,
4515                         want:       "[0 1 2 3 4 5 6 7 8 9]",
4516                 },
4517                 {
4518                         n:          10,
4519                         value:      func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
4520                         comparable: true,
4521                         want:       "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4522                 },
4523                 {
4524                         n:          10,
4525                         value:      func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
4526                         comparable: false,
4527                         want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4528                 },
4529                 {
4530                         n:          10,
4531                         value:      func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
4532                         comparable: true,
4533                         want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4534                 },
4535                 {
4536                         n:          10,
4537                         value:      func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4538                         comparable: true,
4539                         want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4540                 },
4541                 {
4542                         n:          10,
4543                         value:      func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4544                         comparable: false,
4545                         want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4546                 },
4547                 {
4548                         n:          10,
4549                         value:      func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4550                         comparable: true,
4551                         want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4552                 },
4553                 {
4554                         n: 10,
4555                         value: func(i int) interface{} {
4556                                 type TstructUV struct {
4557                                         U int
4558                                         V float64
4559                                 }
4560                                 return TstructUV{i, float64(i)}
4561                         },
4562                         comparable: true,
4563                         want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4564                 },
4565         }
4566
4567         for _, table := range tests {
4568                 at := ArrayOf(table.n, TypeOf(table.value(0)))
4569                 v := New(at).Elem()
4570                 vok := New(at).Elem()
4571                 vnot := New(at).Elem()
4572                 for i := 0; i < v.Len(); i++ {
4573                         v.Index(i).Set(ValueOf(table.value(i)))
4574                         vok.Index(i).Set(ValueOf(table.value(i)))
4575                         j := i
4576                         if i+1 == v.Len() {
4577                                 j = i + 1
4578                         }
4579                         vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4580                 }
4581                 s := fmt.Sprint(v.Interface())
4582                 if s != table.want {
4583                         t.Errorf("constructed array = %s, want %s", s, table.want)
4584                 }
4585
4586                 if table.comparable != at.Comparable() {
4587                         t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4588                 }
4589                 if table.comparable {
4590                         if table.n > 0 {
4591                                 if DeepEqual(vnot.Interface(), v.Interface()) {
4592                                         t.Errorf(
4593                                                 "arrays (%#v) compare ok (but should not)",
4594                                                 v.Interface(),
4595                                         )
4596                                 }
4597                         }
4598                         if !DeepEqual(vok.Interface(), v.Interface()) {
4599                                 t.Errorf(
4600                                         "arrays (%#v) compare NOT-ok (but should)",
4601                                         v.Interface(),
4602                                 )
4603                         }
4604                 }
4605         }
4606
4607         // check that type already in binary is found
4608         type T int
4609         checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4610 }
4611
4612 func TestArrayOfGC(t *testing.T) {
4613         type T *uintptr
4614         tt := TypeOf(T(nil))
4615         const n = 100
4616         var x []interface{}
4617         for i := 0; i < n; i++ {
4618                 v := New(ArrayOf(n, tt)).Elem()
4619                 for j := 0; j < v.Len(); j++ {
4620                         p := new(uintptr)
4621                         *p = uintptr(i*n + j)
4622                         v.Index(j).Set(ValueOf(p).Convert(tt))
4623                 }
4624                 x = append(x, v.Interface())
4625         }
4626         runtime.GC()
4627
4628         for i, xi := range x {
4629                 v := ValueOf(xi)
4630                 for j := 0; j < v.Len(); j++ {
4631                         k := v.Index(j).Elem().Interface()
4632                         if k != uintptr(i*n+j) {
4633                                 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4634                         }
4635                 }
4636         }
4637 }
4638
4639 func TestArrayOfAlg(t *testing.T) {
4640         at := ArrayOf(6, TypeOf(byte(0)))
4641         v1 := New(at).Elem()
4642         v2 := New(at).Elem()
4643         if v1.Interface() != v1.Interface() {
4644                 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4645         }
4646         v1.Index(5).Set(ValueOf(byte(1)))
4647         if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4648                 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4649         }
4650
4651         at = ArrayOf(6, TypeOf([]int(nil)))
4652         v1 = New(at).Elem()
4653         shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4654 }
4655
4656 func TestArrayOfGenericAlg(t *testing.T) {
4657         at1 := ArrayOf(5, TypeOf(string("")))
4658         at := ArrayOf(6, at1)
4659         v1 := New(at).Elem()
4660         v2 := New(at).Elem()
4661         if v1.Interface() != v1.Interface() {
4662                 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4663         }
4664
4665         v1.Index(0).Index(0).Set(ValueOf("abc"))
4666         v2.Index(0).Index(0).Set(ValueOf("efg"))
4667         if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4668                 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4669         }
4670
4671         v1.Index(0).Index(0).Set(ValueOf("abc"))
4672         v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4673         if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4674                 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4675         }
4676
4677         // Test hash
4678         m := MakeMap(MapOf(at, TypeOf(int(0))))
4679         m.SetMapIndex(v1, ValueOf(1))
4680         if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4681                 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4682         }
4683 }
4684
4685 func TestArrayOfDirectIface(t *testing.T) {
4686         {
4687                 type T [1]*byte
4688                 i1 := Zero(TypeOf(T{})).Interface()
4689                 v1 := ValueOf(&i1).Elem()
4690                 p1 := v1.InterfaceData()[1]
4691
4692                 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4693                 v2 := ValueOf(&i2).Elem()
4694                 p2 := v2.InterfaceData()[1]
4695
4696                 if p1 != 0 {
4697                         t.Errorf("got p1=%v. want=%v", p1, nil)
4698                 }
4699
4700                 if p2 != 0 {
4701                         t.Errorf("got p2=%v. want=%v", p2, nil)
4702                 }
4703         }
4704         {
4705                 type T [0]*byte
4706                 i1 := Zero(TypeOf(T{})).Interface()
4707                 v1 := ValueOf(&i1).Elem()
4708                 p1 := v1.InterfaceData()[1]
4709
4710                 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4711                 v2 := ValueOf(&i2).Elem()
4712                 p2 := v2.InterfaceData()[1]
4713
4714                 if p1 == 0 {
4715                         t.Errorf("got p1=%v. want=not-%v", p1, nil)
4716                 }
4717
4718                 if p2 == 0 {
4719                         t.Errorf("got p2=%v. want=not-%v", p2, nil)
4720                 }
4721         }
4722 }
4723
4724 // Ensure passing in negative lengths panics.
4725 // See https://golang.org/issue/43603
4726 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4727         shouldPanic("reflect: negative length passed to ArrayOf", func() {
4728                 ArrayOf(-1, TypeOf(byte(0)))
4729         })
4730 }
4731
4732 func TestSliceOf(t *testing.T) {
4733         // check construction and use of type not in binary
4734         type T int
4735         st := SliceOf(TypeOf(T(1)))
4736         if got, want := st.String(), "[]reflect_test.T"; got != want {
4737                 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4738         }
4739         v := MakeSlice(st, 10, 10)
4740         runtime.GC()
4741         for i := 0; i < v.Len(); i++ {
4742                 v.Index(i).Set(ValueOf(T(i)))
4743                 runtime.GC()
4744         }
4745         s := fmt.Sprint(v.Interface())
4746         want := "[0 1 2 3 4 5 6 7 8 9]"
4747         if s != want {
4748                 t.Errorf("constructed slice = %s, want %s", s, want)
4749         }
4750
4751         // check that type already in binary is found
4752         type T1 int
4753         checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4754 }
4755
4756 func TestSliceOverflow(t *testing.T) {
4757         // check that MakeSlice panics when size of slice overflows uint
4758         const S = 1e6
4759         s := uint(S)
4760         l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4761         if l*s >= s {
4762                 t.Fatal("slice size does not overflow")
4763         }
4764         var x [S]byte
4765         st := SliceOf(TypeOf(x))
4766         defer func() {
4767                 err := recover()
4768                 if err == nil {
4769                         t.Fatal("slice overflow does not panic")
4770                 }
4771         }()
4772         MakeSlice(st, int(l), int(l))
4773 }
4774
4775 func TestSliceOfGC(t *testing.T) {
4776         type T *uintptr
4777         tt := TypeOf(T(nil))
4778         st := SliceOf(tt)
4779         const n = 100
4780         var x []interface{}
4781         for i := 0; i < n; i++ {
4782                 v := MakeSlice(st, n, n)
4783                 for j := 0; j < v.Len(); j++ {
4784                         p := new(uintptr)
4785                         *p = uintptr(i*n + j)
4786                         v.Index(j).Set(ValueOf(p).Convert(tt))
4787                 }
4788                 x = append(x, v.Interface())
4789         }
4790         runtime.GC()
4791
4792         for i, xi := range x {
4793                 v := ValueOf(xi)
4794                 for j := 0; j < v.Len(); j++ {
4795                         k := v.Index(j).Elem().Interface()
4796                         if k != uintptr(i*n+j) {
4797                                 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4798                         }
4799                 }
4800         }
4801 }
4802
4803 func TestStructOfFieldName(t *testing.T) {
4804         // invalid field name "1nvalid"
4805         shouldPanic("has invalid name", func() {
4806                 StructOf([]StructField{
4807                         {Name: "Valid", Type: TypeOf("")},
4808                         {Name: "1nvalid", Type: TypeOf("")},
4809                 })
4810         })
4811
4812         // invalid field name "+"
4813         shouldPanic("has invalid name", func() {
4814                 StructOf([]StructField{
4815                         {Name: "Val1d", Type: TypeOf("")},
4816                         {Name: "+", Type: TypeOf("")},
4817                 })
4818         })
4819
4820         // no field name
4821         shouldPanic("has no name", func() {
4822                 StructOf([]StructField{
4823                         {Name: "", Type: TypeOf("")},
4824                 })
4825         })
4826
4827         // verify creation of a struct with valid struct fields
4828         validFields := []StructField{
4829                 {
4830                         Name: "φ",
4831                         Type: TypeOf(""),
4832                 },
4833                 {
4834                         Name: "ValidName",
4835                         Type: TypeOf(""),
4836                 },
4837                 {
4838                         Name: "Val1dNam5",
4839                         Type: TypeOf(""),
4840                 },
4841         }
4842
4843         validStruct := StructOf(validFields)
4844
4845         const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
4846         if got, want := validStruct.String(), structStr; got != want {
4847                 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
4848         }
4849 }
4850
4851 func TestStructOf(t *testing.T) {
4852         // check construction and use of type not in binary
4853         fields := []StructField{
4854                 {
4855                         Name: "S",
4856                         Tag:  "s",
4857                         Type: TypeOf(""),
4858                 },
4859                 {
4860                         Name: "X",
4861                         Tag:  "x",
4862                         Type: TypeOf(byte(0)),
4863                 },
4864                 {
4865                         Name: "Y",
4866                         Type: TypeOf(uint64(0)),
4867                 },
4868                 {
4869                         Name: "Z",
4870                         Type: TypeOf([3]uint16{}),
4871                 },
4872         }
4873
4874         st := StructOf(fields)
4875         v := New(st).Elem()
4876         runtime.GC()
4877         v.FieldByName("X").Set(ValueOf(byte(2)))
4878         v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
4879         runtime.GC()
4880
4881         s := fmt.Sprint(v.Interface())
4882         want := `{ 1 0 [0 0 0]}`
4883         if s != want {
4884                 t.Errorf("constructed struct = %s, want %s", s, want)
4885         }
4886         const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
4887         if got, want := st.String(), stStr; got != want {
4888                 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
4889         }
4890
4891         // check the size, alignment and field offsets
4892         stt := TypeOf(struct {
4893                 String string
4894                 X      byte
4895                 Y      uint64
4896                 Z      [3]uint16
4897         }{})
4898         if st.Size() != stt.Size() {
4899                 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
4900         }
4901         if st.Align() != stt.Align() {
4902                 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
4903         }
4904         if st.FieldAlign() != stt.FieldAlign() {
4905                 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4906         }
4907         for i := 0; i < st.NumField(); i++ {
4908                 o1 := st.Field(i).Offset
4909                 o2 := stt.Field(i).Offset
4910                 if o1 != o2 {
4911                         t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
4912                 }
4913         }
4914
4915         // Check size and alignment with a trailing zero-sized field.
4916         st = StructOf([]StructField{
4917                 {
4918                         Name: "F1",
4919                         Type: TypeOf(byte(0)),
4920                 },
4921                 {
4922                         Name: "F2",
4923                         Type: TypeOf([0]*byte{}),
4924                 },
4925         })
4926         stt = TypeOf(struct {
4927                 G1 byte
4928                 G2 [0]*byte
4929         }{})
4930         if st.Size() != stt.Size() {
4931                 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
4932         }
4933         if st.Align() != stt.Align() {
4934                 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
4935         }
4936         if st.FieldAlign() != stt.FieldAlign() {
4937                 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4938         }
4939         for i := 0; i < st.NumField(); i++ {
4940                 o1 := st.Field(i).Offset
4941                 o2 := stt.Field(i).Offset
4942                 if o1 != o2 {
4943                         t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
4944                 }
4945         }
4946
4947         // check duplicate names
4948         shouldPanic("duplicate field", func() {
4949                 StructOf([]StructField{
4950                         {Name: "string", PkgPath: "p", Type: TypeOf("")},
4951                         {Name: "string", PkgPath: "p", Type: TypeOf("")},
4952                 })
4953         })
4954         shouldPanic("has no name", func() {
4955                 StructOf([]StructField{
4956                         {Type: TypeOf("")},
4957                         {Name: "string", PkgPath: "p", Type: TypeOf("")},
4958                 })
4959         })
4960         shouldPanic("has no name", func() {
4961                 StructOf([]StructField{
4962                         {Type: TypeOf("")},
4963                         {Type: TypeOf("")},
4964                 })
4965         })
4966         // check that type already in binary is found
4967         checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
4968
4969         // gccgo used to fail this test.
4970         type structFieldType interface{}
4971         checkSameType(t,
4972                 StructOf([]StructField{
4973                         {
4974                                 Name: "F",
4975                                 Type: TypeOf((*structFieldType)(nil)).Elem(),
4976                         },
4977                 }),
4978                 struct{ F structFieldType }{})
4979 }
4980
4981 func TestStructOfExportRules(t *testing.T) {
4982         type S1 struct{}
4983         type s2 struct{}
4984         type ΦType struct{}
4985         type φType struct{}
4986
4987         testPanic := func(i int, mustPanic bool, f func()) {
4988                 defer func() {
4989                         err := recover()
4990                         if err == nil && mustPanic {
4991                                 t.Errorf("test-%d did not panic", i)
4992                         }
4993                         if err != nil && !mustPanic {
4994                                 t.Errorf("test-%d panicked: %v\n", i, err)
4995                         }
4996                 }()
4997                 f()
4998         }
4999
5000         tests := []struct {
5001                 field     StructField
5002                 mustPanic bool
5003                 exported  bool
5004         }{
5005                 {
5006                         field:    StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5007                         exported: true,
5008                 },
5009                 {
5010                         field:    StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5011                         exported: true,
5012                 },
5013                 {
5014                         field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5015                         mustPanic: true,
5016                 },
5017                 {
5018                         field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5019                         mustPanic: true,
5020                 },
5021                 {
5022                         field:     StructField{Name: "Name", Type: nil, PkgPath: ""},
5023                         mustPanic: true,
5024                 },
5025                 {
5026                         field:     StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5027                         mustPanic: true,
5028                 },
5029                 {
5030                         field:     StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5031                         mustPanic: true,
5032                 },
5033                 {
5034                         field:     StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5035                         mustPanic: true,
5036                 },
5037                 {
5038                         field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5039                         mustPanic: true,
5040                 },
5041                 {
5042                         field:     StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5043                         mustPanic: true,
5044                 },
5045                 {
5046                         field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5047                 },
5048                 {
5049                         field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5050                 },
5051                 {
5052                         field:    StructField{Name: "S", Type: TypeOf(S1{})},
5053                         exported: true,
5054                 },
5055                 {
5056                         field:    StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5057                         exported: true,
5058                 },
5059                 {
5060                         field:    StructField{Name: "S", Type: TypeOf(s2{})},
5061                         exported: true,
5062                 },
5063                 {
5064                         field:    StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5065                         exported: true,
5066                 },
5067                 {
5068                         field:     StructField{Name: "s", Type: TypeOf(S1{})},
5069                         mustPanic: true,
5070                 },
5071                 {
5072                         field:     StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5073                         mustPanic: true,
5074                 },
5075                 {
5076                         field:     StructField{Name: "s", Type: TypeOf(s2{})},
5077                         mustPanic: true,
5078                 },
5079                 {
5080                         field:     StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5081                         mustPanic: true,
5082                 },
5083                 {
5084                         field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5085                 },
5086                 {
5087                         field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5088                 },
5089                 {
5090                         field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5091                 },
5092                 {
5093                         field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5094                 },
5095                 {
5096                         field:     StructField{Name: "", Type: TypeOf(ΦType{})},
5097                         mustPanic: true,
5098                 },
5099                 {
5100                         field:     StructField{Name: "", Type: TypeOf(φType{})},
5101                         mustPanic: true,
5102                 },
5103                 {
5104                         field:    StructField{Name: "Φ", Type: TypeOf(0)},
5105                         exported: true,
5106                 },
5107                 {
5108                         field:    StructField{Name: "φ", Type: TypeOf(0)},
5109                         exported: false,
5110                 },
5111         }
5112
5113         for i, test := range tests {
5114                 testPanic(i, test.mustPanic, func() {
5115                         typ := StructOf([]StructField{test.field})
5116                         if typ == nil {
5117                                 t.Errorf("test-%d: error creating struct type", i)
5118                                 return
5119                         }
5120                         field := typ.Field(0)
5121                         n := field.Name
5122                         if n == "" {
5123                                 panic("field.Name must not be empty")
5124                         }
5125                         exported := token.IsExported(n)
5126                         if exported != test.exported {
5127                                 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5128                         }
5129                         if field.PkgPath != test.field.PkgPath {
5130                                 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5131                         }
5132                 })
5133         }
5134 }
5135
5136 func TestStructOfGC(t *testing.T) {
5137         type T *uintptr
5138         tt := TypeOf(T(nil))
5139         fields := []StructField{
5140                 {Name: "X", Type: tt},
5141                 {Name: "Y", Type: tt},
5142         }
5143         st := StructOf(fields)
5144
5145         const n = 10000
5146         var x []interface{}
5147         for i := 0; i < n; i++ {
5148                 v := New(st).Elem()
5149                 for j := 0; j < v.NumField(); j++ {
5150                         p := new(uintptr)
5151                         *p = uintptr(i*n + j)
5152                         v.Field(j).Set(ValueOf(p).Convert(tt))
5153                 }
5154                 x = append(x, v.Interface())
5155         }
5156         runtime.GC()
5157
5158         for i, xi := range x {
5159                 v := ValueOf(xi)
5160                 for j := 0; j < v.NumField(); j++ {
5161                         k := v.Field(j).Elem().Interface()
5162                         if k != uintptr(i*n+j) {
5163                                 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5164                         }
5165                 }
5166         }
5167 }
5168
5169 func TestStructOfAlg(t *testing.T) {
5170         st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5171         v1 := New(st).Elem()
5172         v2 := New(st).Elem()
5173         if !DeepEqual(v1.Interface(), v1.Interface()) {
5174                 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5175         }
5176         v1.FieldByName("X").Set(ValueOf(int(1)))
5177         if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5178                 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5179         }
5180
5181         st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5182         v1 = New(st).Elem()
5183         shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5184 }
5185
5186 func TestStructOfGenericAlg(t *testing.T) {
5187         st1 := StructOf([]StructField{
5188                 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5189                 {Name: "Y", Type: TypeOf(string(""))},
5190         })
5191         st := StructOf([]StructField{
5192                 {Name: "S0", Type: st1},
5193                 {Name: "S1", Type: st1},
5194         })
5195
5196         tests := []struct {
5197                 rt  Type
5198                 idx []int
5199         }{
5200                 {
5201                         rt:  st,
5202                         idx: []int{0, 1},
5203                 },
5204                 {
5205                         rt:  st1,
5206                         idx: []int{1},
5207                 },
5208                 {
5209                         rt: StructOf(
5210                                 []StructField{
5211                                         {Name: "XX", Type: TypeOf([0]int{})},
5212                                         {Name: "YY", Type: TypeOf("")},
5213                                 },
5214                         ),
5215                         idx: []int{1},
5216                 },
5217                 {
5218                         rt: StructOf(
5219                                 []StructField{
5220                                         {Name: "XX", Type: TypeOf([0]int{})},
5221                                         {Name: "YY", Type: TypeOf("")},
5222                                         {Name: "ZZ", Type: TypeOf([2]int{})},
5223                                 },
5224                         ),
5225                         idx: []int{1},
5226                 },
5227                 {
5228                         rt: StructOf(
5229                                 []StructField{
5230                                         {Name: "XX", Type: TypeOf([1]int{})},
5231                                         {Name: "YY", Type: TypeOf("")},
5232                                 },
5233                         ),
5234                         idx: []int{1},
5235                 },
5236                 {
5237                         rt: StructOf(
5238                                 []StructField{
5239                                         {Name: "XX", Type: TypeOf([1]int{})},
5240                                         {Name: "YY", Type: TypeOf("")},
5241                                         {Name: "ZZ", Type: TypeOf([1]int{})},
5242                                 },
5243                         ),
5244                         idx: []int{1},
5245                 },
5246                 {
5247                         rt: StructOf(
5248                                 []StructField{
5249                                         {Name: "XX", Type: TypeOf([2]int{})},
5250                                         {Name: "YY", Type: TypeOf("")},
5251                                         {Name: "ZZ", Type: TypeOf([2]int{})},
5252                                 },
5253                         ),
5254                         idx: []int{1},
5255                 },
5256                 {
5257                         rt: StructOf(
5258                                 []StructField{
5259                                         {Name: "XX", Type: TypeOf(int64(0))},
5260                                         {Name: "YY", Type: TypeOf(byte(0))},
5261                                         {Name: "ZZ", Type: TypeOf("")},
5262                                 },
5263                         ),
5264                         idx: []int{2},
5265                 },
5266                 {
5267                         rt: StructOf(
5268                                 []StructField{
5269                                         {Name: "XX", Type: TypeOf(int64(0))},
5270                                         {Name: "YY", Type: TypeOf(int64(0))},
5271                                         {Name: "ZZ", Type: TypeOf("")},
5272                                         {Name: "AA", Type: TypeOf([1]int64{})},
5273                                 },
5274                         ),
5275                         idx: []int{2},
5276                 },
5277         }
5278
5279         for _, table := range tests {
5280                 v1 := New(table.rt).Elem()
5281                 v2 := New(table.rt).Elem()
5282
5283                 if !DeepEqual(v1.Interface(), v1.Interface()) {
5284                         t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5285                 }
5286
5287                 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5288                 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5289                 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5290                         t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5291                 }
5292
5293                 abc := "abc"
5294                 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5295                 val := "+" + abc + "-"
5296                 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5297                 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5298                         t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5299                 }
5300
5301                 // Test hash
5302                 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5303                 m.SetMapIndex(v1, ValueOf(1))
5304                 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5305                         t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5306                 }
5307
5308                 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5309                 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5310                         t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5311                 }
5312
5313                 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5314                         t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5315                 }
5316         }
5317 }
5318
5319 func TestStructOfDirectIface(t *testing.T) {
5320         {
5321                 type T struct{ X [1]*byte }
5322                 i1 := Zero(TypeOf(T{})).Interface()
5323                 v1 := ValueOf(&i1).Elem()
5324                 p1 := v1.InterfaceData()[1]
5325
5326                 i2 := Zero(StructOf([]StructField{
5327                         {
5328                                 Name: "X",
5329                                 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5330                         },
5331                 })).Interface()
5332                 v2 := ValueOf(&i2).Elem()
5333                 p2 := v2.InterfaceData()[1]
5334
5335                 if p1 != 0 {
5336                         t.Errorf("got p1=%v. want=%v", p1, nil)
5337                 }
5338
5339                 if p2 != 0 {
5340                         t.Errorf("got p2=%v. want=%v", p2, nil)
5341                 }
5342         }
5343         {
5344                 type T struct{ X [0]*byte }
5345                 i1 := Zero(TypeOf(T{})).Interface()
5346                 v1 := ValueOf(&i1).Elem()
5347                 p1 := v1.InterfaceData()[1]
5348
5349                 i2 := Zero(StructOf([]StructField{
5350                         {
5351                                 Name: "X",
5352                                 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5353                         },
5354                 })).Interface()
5355                 v2 := ValueOf(&i2).Elem()
5356                 p2 := v2.InterfaceData()[1]
5357
5358                 if p1 == 0 {
5359                         t.Errorf("got p1=%v. want=not-%v", p1, nil)
5360                 }
5361
5362                 if p2 == 0 {
5363                         t.Errorf("got p2=%v. want=not-%v", p2, nil)
5364                 }
5365         }
5366 }
5367
5368 type StructI int
5369
5370 func (i StructI) Get() int { return int(i) }
5371
5372 type StructIPtr int
5373
5374 func (i *StructIPtr) Get() int  { return int(*i) }
5375 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5376
5377 type SettableStruct struct {
5378         SettableField int
5379 }
5380
5381 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5382
5383 type SettablePointer struct {
5384         SettableField *int
5385 }
5386
5387 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5388
5389 func TestStructOfWithInterface(t *testing.T) {
5390         const want = 42
5391         type Iface interface {
5392                 Get() int
5393         }
5394         type IfaceSet interface {
5395                 Set(int)
5396         }
5397         tests := []struct {
5398                 name string
5399                 typ  Type
5400                 val  Value
5401                 impl bool
5402         }{
5403                 {
5404                         name: "StructI",
5405                         typ:  TypeOf(StructI(want)),
5406                         val:  ValueOf(StructI(want)),
5407                         impl: true,
5408                 },
5409                 {
5410                         name: "StructI",
5411                         typ:  PtrTo(TypeOf(StructI(want))),
5412                         val: ValueOf(func() interface{} {
5413                                 v := StructI(want)
5414                                 return &v
5415                         }()),
5416                         impl: true,
5417                 },
5418                 {
5419                         name: "StructIPtr",
5420                         typ:  PtrTo(TypeOf(StructIPtr(want))),
5421                         val: ValueOf(func() interface{} {
5422                                 v := StructIPtr(want)
5423                                 return &v
5424                         }()),
5425                         impl: true,
5426                 },
5427                 {
5428                         name: "StructIPtr",
5429                         typ:  TypeOf(StructIPtr(want)),
5430                         val:  ValueOf(StructIPtr(want)),
5431                         impl: false,
5432                 },
5433                 // {
5434                 //      typ:  TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5435                 //      val:  ValueOf(StructI(want)),
5436                 //      impl: true,
5437                 // },
5438         }
5439
5440         for i, table := range tests {
5441                 for j := 0; j < 2; j++ {
5442                         var fields []StructField
5443                         if j == 1 {
5444                                 fields = append(fields, StructField{
5445                                         Name:    "Dummy",
5446                                         PkgPath: "",
5447                                         Type:    TypeOf(int(0)),
5448                                 })
5449                         }
5450                         fields = append(fields, StructField{
5451                                 Name:      table.name,
5452                                 Anonymous: true,
5453                                 PkgPath:   "",
5454                                 Type:      table.typ,
5455                         })
5456
5457                         // We currently do not correctly implement methods
5458                         // for embedded fields other than the first.
5459                         // Therefore, for now, we expect those methods
5460                         // to not exist.  See issues 15924 and 20824.
5461                         // When those issues are fixed, this test of panic
5462                         // should be removed.
5463                         if j == 1 && table.impl {
5464                                 func() {
5465                                         defer func() {
5466                                                 if err := recover(); err == nil {
5467                                                         t.Errorf("test-%d-%d did not panic", i, j)
5468                                                 }
5469                                         }()
5470                                         _ = StructOf(fields)
5471                                 }()
5472                                 continue
5473                         }
5474
5475                         rt := StructOf(fields)
5476                         rv := New(rt).Elem()
5477                         rv.Field(j).Set(table.val)
5478
5479                         if _, ok := rv.Interface().(Iface); ok != table.impl {
5480                                 if table.impl {
5481                                         t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5482                                 } else {
5483                                         t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5484                                 }
5485                                 continue
5486                         }
5487
5488                         if !table.impl {
5489                                 continue
5490                         }
5491
5492                         v := rv.Interface().(Iface).Get()
5493                         if v != want {
5494                                 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5495                         }
5496
5497                         fct := rv.MethodByName("Get")
5498                         out := fct.Call(nil)
5499                         if !DeepEqual(out[0].Interface(), want) {
5500                                 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5501                         }
5502                 }
5503         }
5504
5505         // Test an embedded nil pointer with pointer methods.
5506         fields := []StructField{{
5507                 Name:      "StructIPtr",
5508                 Anonymous: true,
5509                 Type:      PtrTo(TypeOf(StructIPtr(want))),
5510         }}
5511         rt := StructOf(fields)
5512         rv := New(rt).Elem()
5513         // This should panic since the pointer is nil.
5514         shouldPanic("", func() {
5515                 rv.Interface().(IfaceSet).Set(want)
5516         })
5517
5518         // Test an embedded nil pointer to a struct with pointer methods.
5519
5520         fields = []StructField{{
5521                 Name:      "SettableStruct",
5522                 Anonymous: true,
5523                 Type:      PtrTo(TypeOf(SettableStruct{})),
5524         }}
5525         rt = StructOf(fields)
5526         rv = New(rt).Elem()
5527         // This should panic since the pointer is nil.
5528         shouldPanic("", func() {
5529                 rv.Interface().(IfaceSet).Set(want)
5530         })
5531
5532         // The behavior is different if there is a second field,
5533         // since now an interface value holds a pointer to the struct
5534         // rather than just holding a copy of the struct.
5535         fields = []StructField{
5536                 {
5537                         Name:      "SettableStruct",
5538                         Anonymous: true,
5539                         Type:      PtrTo(TypeOf(SettableStruct{})),
5540                 },
5541                 {
5542                         Name:      "EmptyStruct",
5543                         Anonymous: true,
5544                         Type:      StructOf(nil),
5545                 },
5546         }
5547         // With the current implementation this is expected to panic.
5548         // Ideally it should work and we should be able to see a panic
5549         // if we call the Set method.
5550         shouldPanic("", func() {
5551                 StructOf(fields)
5552         })
5553
5554         // Embed a field that can be stored directly in an interface,
5555         // with a second field.
5556         fields = []StructField{
5557                 {
5558                         Name:      "SettablePointer",
5559                         Anonymous: true,
5560                         Type:      TypeOf(SettablePointer{}),
5561                 },
5562                 {
5563                         Name:      "EmptyStruct",
5564                         Anonymous: true,
5565                         Type:      StructOf(nil),
5566                 },
5567         }
5568         // With the current implementation this is expected to panic.
5569         // Ideally it should work and we should be able to call the
5570         // Set and Get methods.
5571         shouldPanic("", func() {
5572                 StructOf(fields)
5573         })
5574 }
5575
5576 func TestStructOfTooManyFields(t *testing.T) {
5577         // Bug Fix: #25402 - this should not panic
5578         tt := StructOf([]StructField{
5579                 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5580         })
5581
5582         if _, present := tt.MethodByName("After"); !present {
5583                 t.Errorf("Expected method `After` to be found")
5584         }
5585 }
5586
5587 func TestStructOfDifferentPkgPath(t *testing.T) {
5588         fields := []StructField{
5589                 {
5590                         Name:    "f1",
5591                         PkgPath: "p1",
5592                         Type:    TypeOf(int(0)),
5593                 },
5594                 {
5595                         Name:    "f2",
5596                         PkgPath: "p2",
5597                         Type:    TypeOf(int(0)),
5598                 },
5599         }
5600         shouldPanic("different PkgPath", func() {
5601                 StructOf(fields)
5602         })
5603 }
5604
5605 func TestChanOf(t *testing.T) {
5606         // check construction and use of type not in binary
5607         type T string
5608         ct := ChanOf(BothDir, TypeOf(T("")))
5609         v := MakeChan(ct, 2)
5610         runtime.GC()
5611         v.Send(ValueOf(T("hello")))
5612         runtime.GC()
5613         v.Send(ValueOf(T("world")))
5614         runtime.GC()
5615
5616         sv1, _ := v.Recv()
5617         sv2, _ := v.Recv()
5618         s1 := sv1.String()
5619         s2 := sv2.String()
5620         if s1 != "hello" || s2 != "world" {
5621                 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5622         }
5623
5624         // check that type already in binary is found
5625         type T1 int
5626         checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5627
5628         // Check arrow token association in undefined chan types.
5629         var left chan<- chan T
5630         var right chan (<-chan T)
5631         tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5632         tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5633         if tLeft != TypeOf(left) {
5634                 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5635         }
5636         if tRight != TypeOf(right) {
5637                 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5638         }
5639 }
5640
5641 func TestChanOfDir(t *testing.T) {
5642         // check construction and use of type not in binary
5643         type T string
5644         crt := ChanOf(RecvDir, TypeOf(T("")))
5645         cst := ChanOf(SendDir, TypeOf(T("")))
5646
5647         // check that type already in binary is found
5648         type T1 int
5649         checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5650         checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5651
5652         // check String form of ChanDir
5653         if crt.ChanDir().String() != "<-chan" {
5654                 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5655         }
5656         if cst.ChanDir().String() != "chan<-" {
5657                 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5658         }
5659 }
5660
5661 func TestChanOfGC(t *testing.T) {
5662         done := make(chan bool, 1)
5663         go func() {
5664                 select {
5665                 case <-done:
5666                 case <-time.After(5 * time.Second):
5667                         panic("deadlock in TestChanOfGC")
5668                 }
5669         }()
5670
5671         defer func() {
5672                 done <- true
5673         }()
5674
5675         type T *uintptr
5676         tt := TypeOf(T(nil))
5677         ct := ChanOf(BothDir, tt)
5678
5679         // NOTE: The garbage collector handles allocated channels specially,
5680         // so we have to save pointers to channels in x; the pointer code will
5681         // use the gc info in the newly constructed chan type.
5682         const n = 100
5683         var x []interface{}
5684         for i := 0; i < n; i++ {
5685                 v := MakeChan(ct, n)
5686                 for j := 0; j < n; j++ {
5687                         p := new(uintptr)
5688                         *p = uintptr(i*n + j)
5689                         v.Send(ValueOf(p).Convert(tt))
5690                 }
5691                 pv := New(ct)
5692                 pv.Elem().Set(v)
5693                 x = append(x, pv.Interface())
5694         }
5695         runtime.GC()
5696
5697         for i, xi := range x {
5698                 v := ValueOf(xi).Elem()
5699                 for j := 0; j < n; j++ {
5700                         pv, _ := v.Recv()
5701                         k := pv.Elem().Interface()
5702                         if k != uintptr(i*n+j) {
5703                                 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5704                         }
5705                 }
5706         }
5707 }
5708
5709 func TestMapOf(t *testing.T) {
5710         // check construction and use of type not in binary
5711         type K string
5712         type V float64
5713
5714         v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5715         runtime.GC()
5716         v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5717         runtime.GC()
5718
5719         s := fmt.Sprint(v.Interface())
5720         want := "map[a:1]"
5721         if s != want {
5722                 t.Errorf("constructed map = %s, want %s", s, want)
5723         }
5724
5725         // check that type already in binary is found
5726         checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5727
5728         // check that invalid key type panics
5729         shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5730 }
5731
5732 func TestMapOfGCKeys(t *testing.T) {
5733         type T *uintptr
5734         tt := TypeOf(T(nil))
5735         mt := MapOf(tt, TypeOf(false))
5736
5737         // NOTE: The garbage collector handles allocated maps specially,
5738         // so we have to save pointers to maps in x; the pointer code will
5739         // use the gc info in the newly constructed map type.
5740         const n = 100
5741         var x []interface{}
5742         for i := 0; i < n; i++ {
5743                 v := MakeMap(mt)
5744                 for j := 0; j < n; j++ {
5745                         p := new(uintptr)
5746                         *p = uintptr(i*n + j)
5747                         v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5748                 }
5749                 pv := New(mt)
5750                 pv.Elem().Set(v)
5751                 x = append(x, pv.Interface())
5752         }
5753         runtime.GC()
5754
5755         for i, xi := range x {
5756                 v := ValueOf(xi).Elem()
5757                 var out []int
5758                 for _, kv := range v.MapKeys() {
5759                         out = append(out, int(kv.Elem().Interface().(uintptr)))
5760                 }
5761                 sort.Ints(out)
5762                 for j, k := range out {
5763                         if k != i*n+j {
5764                                 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5765                         }
5766                 }
5767         }
5768 }
5769
5770 func TestMapOfGCValues(t *testing.T) {
5771         type T *uintptr
5772         tt := TypeOf(T(nil))
5773         mt := MapOf(TypeOf(1), tt)
5774
5775         // NOTE: The garbage collector handles allocated maps specially,
5776         // so we have to save pointers to maps in x; the pointer code will
5777         // use the gc info in the newly constructed map type.
5778         const n = 100
5779         var x []interface{}
5780         for i := 0; i < n; i++ {
5781                 v := MakeMap(mt)
5782                 for j := 0; j < n; j++ {
5783                         p := new(uintptr)
5784                         *p = uintptr(i*n + j)
5785                         v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5786                 }
5787                 pv := New(mt)
5788                 pv.Elem().Set(v)
5789                 x = append(x, pv.Interface())
5790         }
5791         runtime.GC()
5792
5793         for i, xi := range x {
5794                 v := ValueOf(xi).Elem()
5795                 for j := 0; j < n; j++ {
5796                         k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
5797                         if k != uintptr(i*n+j) {
5798                                 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5799                         }
5800                 }
5801         }
5802 }
5803
5804 func TestTypelinksSorted(t *testing.T) {
5805         var last string
5806         for i, n := range TypeLinks() {
5807                 if n < last {
5808                         t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
5809                 }
5810                 last = n
5811         }
5812 }
5813
5814 func TestFuncOf(t *testing.T) {
5815         // check construction and use of type not in binary
5816         type K string
5817         type V float64
5818
5819         fn := func(args []Value) []Value {
5820                 if len(args) != 1 {
5821                         t.Errorf("args == %v, want exactly one arg", args)
5822                 } else if args[0].Type() != TypeOf(K("")) {
5823                         t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
5824                 } else if args[0].String() != "gopher" {
5825                         t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
5826                 }
5827                 return []Value{ValueOf(V(3.14))}
5828         }
5829         v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
5830
5831         outs := v.Call([]Value{ValueOf(K("gopher"))})
5832         if len(outs) != 1 {
5833                 t.Fatalf("v.Call returned %v, want exactly one result", outs)
5834         } else if outs[0].Type() != TypeOf(V(0)) {
5835                 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
5836         }
5837         f := outs[0].Float()
5838         if f != 3.14 {
5839                 t.Errorf("constructed func returned %f, want %f", f, 3.14)
5840         }
5841
5842         // check that types already in binary are found
5843         type T1 int
5844         testCases := []struct {
5845                 in, out  []Type
5846                 variadic bool
5847                 want     interface{}
5848         }{
5849                 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
5850                 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
5851                 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
5852                 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
5853                 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
5854         }
5855         for _, tt := range testCases {
5856                 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
5857         }
5858
5859         // check that variadic requires last element be a slice.
5860         FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5861         shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5862         shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
5863 }
5864
5865 type B1 struct {
5866         X int
5867         Y int
5868         Z int
5869 }
5870
5871 func BenchmarkFieldByName1(b *testing.B) {
5872         t := TypeOf(B1{})
5873         b.RunParallel(func(pb *testing.PB) {
5874                 for pb.Next() {
5875                         t.FieldByName("Z")
5876                 }
5877         })
5878 }
5879
5880 func BenchmarkFieldByName2(b *testing.B) {
5881         t := TypeOf(S3{})
5882         b.RunParallel(func(pb *testing.PB) {
5883                 for pb.Next() {
5884                         t.FieldByName("B")
5885                 }
5886         })
5887 }
5888
5889 type R0 struct {
5890         *R1
5891         *R2
5892         *R3
5893         *R4
5894 }
5895
5896 type R1 struct {
5897         *R5
5898         *R6
5899         *R7
5900         *R8
5901 }
5902
5903 type R2 R1
5904 type R3 R1
5905 type R4 R1
5906
5907 type R5 struct {
5908         *R9
5909         *R10
5910         *R11
5911         *R12
5912 }
5913
5914 type R6 R5
5915 type R7 R5
5916 type R8 R5
5917
5918 type R9 struct {
5919         *R13
5920         *R14
5921         *R15
5922         *R16
5923 }
5924
5925 type R10 R9
5926 type R11 R9
5927 type R12 R9
5928
5929 type R13 struct {
5930         *R17
5931         *R18
5932         *R19
5933         *R20
5934 }
5935
5936 type R14 R13
5937 type R15 R13
5938 type R16 R13
5939
5940 type R17 struct {
5941         *R21
5942         *R22
5943         *R23
5944         *R24
5945 }
5946
5947 type R18 R17
5948 type R19 R17
5949 type R20 R17
5950
5951 type R21 struct {
5952         X int
5953 }
5954
5955 type R22 R21
5956 type R23 R21
5957 type R24 R21
5958
5959 func TestEmbed(t *testing.T) {
5960         typ := TypeOf(R0{})
5961         f, ok := typ.FieldByName("X")
5962         if ok {
5963                 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
5964         }
5965 }
5966
5967 func BenchmarkFieldByName3(b *testing.B) {
5968         t := TypeOf(R0{})
5969         b.RunParallel(func(pb *testing.PB) {
5970                 for pb.Next() {
5971                         t.FieldByName("X")
5972                 }
5973         })
5974 }
5975
5976 type S struct {
5977         i1 int64
5978         i2 int64
5979 }
5980
5981 func BenchmarkInterfaceBig(b *testing.B) {
5982         v := ValueOf(S{})
5983         b.RunParallel(func(pb *testing.PB) {
5984                 for pb.Next() {
5985                         v.Interface()
5986                 }
5987         })
5988         b.StopTimer()
5989 }
5990
5991 func TestAllocsInterfaceBig(t *testing.T) {
5992         if testing.Short() {
5993                 t.Skip("skipping malloc count in short mode")
5994         }
5995         v := ValueOf(S{})
5996         if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
5997                 t.Error("allocs:", allocs)
5998         }
5999 }
6000
6001 func BenchmarkInterfaceSmall(b *testing.B) {
6002         v := ValueOf(int64(0))
6003         b.RunParallel(func(pb *testing.PB) {
6004                 for pb.Next() {
6005                         v.Interface()
6006                 }
6007         })
6008 }
6009
6010 func TestAllocsInterfaceSmall(t *testing.T) {
6011         if testing.Short() {
6012                 t.Skip("skipping malloc count in short mode")
6013         }
6014         v := ValueOf(int64(0))
6015         if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6016                 t.Error("allocs:", allocs)
6017         }
6018 }
6019
6020 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6021 // The basic usage is:
6022 //
6023 //      for x.Next() {
6024 //              ... code using x.Maybe() or x.Choice(n) to create test cases ...
6025 //      }
6026 //
6027 // Each iteration of the loop returns a different set of results, until all
6028 // possible result sets have been explored. It is okay for different code paths
6029 // to make different method call sequences on x, but there must be no
6030 // other source of non-determinism in the call sequences.
6031 //
6032 // When faced with a new decision, x chooses randomly. Future explorations
6033 // of that path will choose successive values for the result. Thus, stopping
6034 // the loop after a fixed number of iterations gives somewhat stochastic
6035 // testing.
6036 //
6037 // Example:
6038 //
6039 //      for x.Next() {
6040 //              v := make([]bool, x.Choose(4))
6041 //              for i := range v {
6042 //                      v[i] = x.Maybe()
6043 //              }
6044 //              fmt.Println(v)
6045 //      }
6046 //
6047 // prints (in some order):
6048 //
6049 //      []
6050 //      [false]
6051 //      [true]
6052 //      [false false]
6053 //      [false true]
6054 //      ...
6055 //      [true true]
6056 //      [false false false]
6057 //      ...
6058 //      [true true true]
6059 //      [false false false false]
6060 //      ...
6061 //      [true true true true]
6062 //
6063 type exhaustive struct {
6064         r    *rand.Rand
6065         pos  int
6066         last []choice
6067 }
6068
6069 type choice struct {
6070         off int
6071         n   int
6072         max int
6073 }
6074
6075 func (x *exhaustive) Next() bool {
6076         if x.r == nil {
6077                 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6078         }
6079         x.pos = 0
6080         if x.last == nil {
6081                 x.last = []choice{}
6082                 return true
6083         }
6084         for i := len(x.last) - 1; i >= 0; i-- {
6085                 c := &x.last[i]
6086                 if c.n+1 < c.max {
6087                         c.n++
6088                         x.last = x.last[:i+1]
6089                         return true
6090                 }
6091         }
6092         return false
6093 }
6094
6095 func (x *exhaustive) Choose(max int) int {
6096         if x.pos >= len(x.last) {
6097                 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6098         }
6099         c := &x.last[x.pos]
6100         x.pos++
6101         if c.max != max {
6102                 panic("inconsistent use of exhaustive tester")
6103         }
6104         return (c.n + c.off) % max
6105 }
6106
6107 func (x *exhaustive) Maybe() bool {
6108         return x.Choose(2) == 1
6109 }
6110
6111 func GCFunc(args []Value) []Value {
6112         runtime.GC()
6113         return []Value{}
6114 }
6115
6116 func TestReflectFuncTraceback(t *testing.T) {
6117         f := MakeFunc(TypeOf(func() {}), GCFunc)
6118         f.Call([]Value{})
6119 }
6120
6121 func TestReflectMethodTraceback(t *testing.T) {
6122         p := Point{3, 4}
6123         m := ValueOf(p).MethodByName("GCMethod")
6124         i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6125         if i != 8 {
6126                 t.Errorf("Call returned %d; want 8", i)
6127         }
6128 }
6129
6130 func TestSmallZero(t *testing.T) {
6131         type T [10]byte
6132         typ := TypeOf(T{})
6133         if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6134                 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6135         }
6136 }
6137
6138 func TestBigZero(t *testing.T) {
6139         const size = 1 << 10
6140         var v [size]byte
6141         z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6142         for i := 0; i < size; i++ {
6143                 if z[i] != 0 {
6144                         t.Fatalf("Zero object not all zero, index %d", i)
6145                 }
6146         }
6147 }
6148
6149 func TestZeroSet(t *testing.T) {
6150         type T [16]byte
6151         type S struct {
6152                 a uint64
6153                 T T
6154                 b uint64
6155         }
6156         v := S{
6157                 a: 0xaaaaaaaaaaaaaaaa,
6158                 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6159                 b: 0xbbbbbbbbbbbbbbbb,
6160         }
6161         ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6162         if v != (S{
6163                 a: 0xaaaaaaaaaaaaaaaa,
6164                 b: 0xbbbbbbbbbbbbbbbb,
6165         }) {
6166                 t.Fatalf("Setting a field to a Zero value didn't work")
6167         }
6168 }
6169
6170 func TestFieldByIndexNil(t *testing.T) {
6171         type P struct {
6172                 F int
6173         }
6174         type T struct {
6175                 *P
6176         }
6177         v := ValueOf(T{})
6178
6179         v.FieldByName("P") // should be fine
6180
6181         defer func() {
6182                 if err := recover(); err == nil {
6183                         t.Fatalf("no error")
6184                 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6185                         t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6186                 }
6187         }()
6188         v.FieldByName("F") // should panic
6189
6190         t.Fatalf("did not panic")
6191 }
6192
6193 // Given
6194 //      type Outer struct {
6195 //              *Inner
6196 //              ...
6197 //      }
6198 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6199 // The implementation is logically:
6200 //      func (p *Outer) M() {
6201 //              (p.Inner).M()
6202 //      }
6203 // but since the only change here is the replacement of one pointer receiver with another,
6204 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6205 // then jumps to the M method expecting the *Inner receiver.
6206 //
6207 // During reflect.Value.Call, we create an argument frame and the associated data structures
6208 // to describe it to the garbage collector, populate the frame, call reflect.call to
6209 // run a function call using that frame, and then copy the results back out of the frame.
6210 // The reflect.call function does a memmove of the frame structure onto the
6211 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6212 // the frame structure (to preserve the outputs).
6213 //
6214 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6215 // were for the full stack frame. However, in the case where the called function was
6216 // one of these wrappers, the rewritten receiver is almost certainly a different type
6217 // than the original receiver. This is not a problem on the stack, where we use the
6218 // program counter to determine the type information and understand that
6219 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6220 // memory word is now an *Inner. But in the statically typed argument frame created
6221 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6222 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6223 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6224 // memory as if it were an *Outer. If the two have different memory layouts, the
6225 // collection will interpret the memory incorrectly.
6226 //
6227 // One such possible incorrect interpretation is to treat two arbitrary memory words
6228 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6229 // an interface requires dereferencing the itab word, the misinterpretation will try to
6230 // deference Inner.P1, causing a crash during garbage collection.
6231 //
6232 // This came up in a real program in issue 7725.
6233
6234 type Outer struct {
6235         *Inner
6236         R io.Reader
6237 }
6238
6239 type Inner struct {
6240         X  *Outer
6241         P1 uintptr
6242         P2 uintptr
6243 }
6244
6245 func (pi *Inner) M() {
6246         // Clear references to pi so that the only way the
6247         // garbage collection will find the pointer is in the
6248         // argument frame, typed as a *Outer.
6249         pi.X.Inner = nil
6250
6251         // Set up an interface value that will cause a crash.
6252         // P1 = 1 is a non-zero, so the interface looks non-nil.
6253         // P2 = pi ensures that the data word points into the
6254         // allocated heap; if not the collection skips the interface
6255         // value as irrelevant, without dereferencing P1.
6256         pi.P1 = 1
6257         pi.P2 = uintptr(unsafe.Pointer(pi))
6258 }
6259
6260 func TestCallMethodJump(t *testing.T) {
6261         // In reflect.Value.Call, trigger a garbage collection after reflect.call
6262         // returns but before the args frame has been discarded.
6263         // This is a little clumsy but makes the failure repeatable.
6264         *CallGC = true
6265
6266         p := &Outer{Inner: new(Inner)}
6267         p.Inner.X = p
6268         ValueOf(p).Method(0).Call(nil)
6269
6270         // Stop garbage collecting during reflect.call.
6271         *CallGC = false
6272 }
6273
6274 func TestMakeFuncStackCopy(t *testing.T) {
6275         target := func(in []Value) []Value {
6276                 runtime.GC()
6277                 useStack(16)
6278                 return []Value{ValueOf(9)}
6279         }
6280
6281         var concrete func(*int, int) int
6282         fn := MakeFunc(ValueOf(concrete).Type(), target)
6283         ValueOf(&concrete).Elem().Set(fn)
6284         x := concrete(nil, 7)
6285         if x != 9 {
6286                 t.Errorf("have %#q want 9", x)
6287         }
6288 }
6289
6290 // use about n KB of stack
6291 func useStack(n int) {
6292         if n == 0 {
6293                 return
6294         }
6295         var b [1024]byte // makes frame about 1KB
6296         useStack(n - 1 + int(b[99]))
6297 }
6298
6299 type Impl struct{}
6300
6301 func (Impl) F() {}
6302
6303 func TestValueString(t *testing.T) {
6304         rv := ValueOf(Impl{})
6305         if rv.String() != "<reflect_test.Impl Value>" {
6306                 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6307         }
6308
6309         method := rv.Method(0)
6310         if method.String() != "<func() Value>" {
6311                 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6312         }
6313 }
6314
6315 func TestInvalid(t *testing.T) {
6316         // Used to have inconsistency between IsValid() and Kind() != Invalid.
6317         type T struct{ v interface{} }
6318
6319         v := ValueOf(T{}).Field(0)
6320         if v.IsValid() != true || v.Kind() != Interface {
6321                 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6322         }
6323         v = v.Elem()
6324         if v.IsValid() != false || v.Kind() != Invalid {
6325                 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6326         }
6327 }
6328
6329 // Issue 8917.
6330 func TestLargeGCProg(t *testing.T) {
6331         fv := ValueOf(func([256]*byte) {})
6332         fv.Call([]Value{ValueOf([256]*byte{})})
6333 }
6334
6335 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
6336         defer func() {
6337                 recovered = recover()
6338         }()
6339
6340         t.Field(i)
6341         return
6342 }
6343
6344 // Issue 15046.
6345 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6346         typ := TypeOf(struct{ X int }{10})
6347         testIndices := [...]struct {
6348                 i         int
6349                 mustPanic bool
6350         }{
6351                 0: {-2, true},
6352                 1: {0, false},
6353                 2: {1, true},
6354                 3: {1 << 10, true},
6355         }
6356         for i, tt := range testIndices {
6357                 recoveredErr := fieldIndexRecover(typ, tt.i)
6358                 if tt.mustPanic {
6359                         if recoveredErr == nil {
6360                                 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6361                         }
6362                 } else {
6363                         if recoveredErr != nil {
6364                                 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6365                         }
6366                 }
6367         }
6368 }
6369
6370 // Issue 9179.
6371 func TestCallGC(t *testing.T) {
6372         f := func(a, b, c, d, e string) {
6373         }
6374         g := func(in []Value) []Value {
6375                 runtime.GC()
6376                 return nil
6377         }
6378         typ := ValueOf(f).Type()
6379         f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6380         f2("four", "five5", "six666", "seven77", "eight888")
6381 }
6382
6383 // Issue 18635 (function version).
6384 func TestKeepFuncLive(t *testing.T) {
6385         // Test that we keep makeFuncImpl live as long as it is
6386         // referenced on the stack.
6387         typ := TypeOf(func(i int) {})
6388         var f, g func(in []Value) []Value
6389         f = func(in []Value) []Value {
6390                 clobber()
6391                 i := int(in[0].Int())
6392                 if i > 0 {
6393                         // We can't use Value.Call here because
6394                         // runtime.call* will keep the makeFuncImpl
6395                         // alive. However, by converting it to an
6396                         // interface value and calling that,
6397                         // reflect.callReflect is the only thing that
6398                         // can keep the makeFuncImpl live.
6399                         //
6400                         // Alternate between f and g so that if we do
6401                         // reuse the memory prematurely it's more
6402                         // likely to get obviously corrupted.
6403                         MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6404                 }
6405                 return nil
6406         }
6407         g = func(in []Value) []Value {
6408                 clobber()
6409                 i := int(in[0].Int())
6410                 MakeFunc(typ, f).Interface().(func(i int))(i)
6411                 return nil
6412         }
6413         MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6414 }
6415
6416 type UnExportedFirst int
6417
6418 func (i UnExportedFirst) ΦExported()  {}
6419 func (i UnExportedFirst) unexported() {}
6420
6421 // Issue 21177
6422 func TestMethodByNameUnExportedFirst(t *testing.T) {
6423         defer func() {
6424                 if recover() != nil {
6425                         t.Errorf("should not panic")
6426                 }
6427         }()
6428         typ := TypeOf(UnExportedFirst(0))
6429         m, _ := typ.MethodByName("ΦExported")
6430         if m.Name != "ΦExported" {
6431                 t.Errorf("got %s, expected ΦExported", m.Name)
6432         }
6433 }
6434
6435 // Issue 18635 (method version).
6436 type KeepMethodLive struct{}
6437
6438 func (k KeepMethodLive) Method1(i int) {
6439         clobber()
6440         if i > 0 {
6441                 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6442         }
6443 }
6444
6445 func (k KeepMethodLive) Method2(i int) {
6446         clobber()
6447         ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6448 }
6449
6450 func TestKeepMethodLive(t *testing.T) {
6451         // Test that we keep methodValue live as long as it is
6452         // referenced on the stack.
6453         KeepMethodLive{}.Method1(10)
6454 }
6455
6456 // clobber tries to clobber unreachable memory.
6457 func clobber() {
6458         runtime.GC()
6459         for i := 1; i < 32; i++ {
6460                 for j := 0; j < 10; j++ {
6461                         obj := make([]*byte, i)
6462                         sink = obj
6463                 }
6464         }
6465         runtime.GC()
6466 }
6467
6468 func TestFuncLayout(t *testing.T) {
6469         align := func(x uintptr) uintptr {
6470                 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6471         }
6472         var r []byte
6473         if goarch.PtrSize == 4 {
6474                 r = []byte{0, 0, 0, 1}
6475         } else {
6476                 r = []byte{0, 0, 1}
6477         }
6478
6479         type S struct {
6480                 a, b uintptr
6481                 c, d *byte
6482         }
6483
6484         type test struct {
6485                 rcvr, typ                  Type
6486                 size, argsize, retOffset   uintptr
6487                 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6488                 intRegs, floatRegs         int
6489                 floatRegSize               uintptr
6490         }
6491         tests := []test{
6492                 {
6493                         typ:       ValueOf(func(a, b string) string { return "" }).Type(),
6494                         size:      6 * goarch.PtrSize,
6495                         argsize:   4 * goarch.PtrSize,
6496                         retOffset: 4 * goarch.PtrSize,
6497                         stack:     []byte{1, 0, 1, 0, 1},
6498                         gc:        []byte{1, 0, 1, 0, 1},
6499                 },
6500                 {
6501                         typ:       ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6502                         size:      align(align(3*4) + goarch.PtrSize + 2),
6503                         argsize:   align(3*4) + goarch.PtrSize + 2,
6504                         retOffset: align(align(3*4) + goarch.PtrSize + 2),
6505                         stack:     r,
6506                         gc:        r,
6507                 },
6508                 {
6509                         typ:       ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
6510                         size:      4 * goarch.PtrSize,
6511                         argsize:   4 * goarch.PtrSize,
6512                         retOffset: 4 * goarch.PtrSize,
6513                         stack:     []byte{1, 0, 1, 1},
6514                         gc:        []byte{1, 0, 1, 1},
6515                 },
6516                 {
6517                         typ:       ValueOf(func(a S) {}).Type(),
6518                         size:      4 * goarch.PtrSize,
6519                         argsize:   4 * goarch.PtrSize,
6520                         retOffset: 4 * goarch.PtrSize,
6521                         stack:     []byte{0, 0, 1, 1},
6522                         gc:        []byte{0, 0, 1, 1},
6523                 },
6524                 {
6525                         rcvr:      ValueOf((*byte)(nil)).Type(),
6526                         typ:       ValueOf(func(a uintptr, b *int) {}).Type(),
6527                         size:      3 * goarch.PtrSize,
6528                         argsize:   3 * goarch.PtrSize,
6529                         retOffset: 3 * goarch.PtrSize,
6530                         stack:     []byte{1, 0, 1},
6531                         gc:        []byte{1, 0, 1},
6532                 },
6533                 {
6534                         typ:       ValueOf(func(a uintptr) {}).Type(),
6535                         size:      goarch.PtrSize,
6536                         argsize:   goarch.PtrSize,
6537                         retOffset: goarch.PtrSize,
6538                         stack:     []byte{},
6539                         gc:        []byte{},
6540                 },
6541                 {
6542                         typ:       ValueOf(func() uintptr { return 0 }).Type(),
6543                         size:      goarch.PtrSize,
6544                         argsize:   0,
6545                         retOffset: 0,
6546                         stack:     []byte{},
6547                         gc:        []byte{},
6548                 },
6549                 {
6550                         rcvr:      ValueOf(uintptr(0)).Type(),
6551                         typ:       ValueOf(func(a uintptr) {}).Type(),
6552                         size:      2 * goarch.PtrSize,
6553                         argsize:   2 * goarch.PtrSize,
6554                         retOffset: 2 * goarch.PtrSize,
6555                         stack:     []byte{1},
6556                         gc:        []byte{1},
6557                         // Note: this one is tricky, as the receiver is not a pointer. But we
6558                         // pass the receiver by reference to the autogenerated pointer-receiver
6559                         // version of the function.
6560                 },
6561                 // TODO(mknyszek): Add tests for non-zero register count.
6562         }
6563         for _, lt := range tests {
6564                 name := lt.typ.String()
6565                 if lt.rcvr != nil {
6566                         name = lt.rcvr.String() + "." + name
6567                 }
6568                 t.Run(name, func(t *testing.T) {
6569                         defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6570
6571                         typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6572                         if typ.Size() != lt.size {
6573                                 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6574                         }
6575                         if argsize != lt.argsize {
6576                                 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6577                         }
6578                         if retOffset != lt.retOffset {
6579                                 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6580                         }
6581                         if !bytes.Equal(stack, lt.stack) {
6582                                 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6583                         }
6584                         if !bytes.Equal(gc, lt.gc) {
6585                                 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6586                         }
6587                         if !bytes.Equal(inRegs, lt.inRegs) {
6588                                 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6589                         }
6590                         if !bytes.Equal(outRegs, lt.outRegs) {
6591                                 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6592                         }
6593                         if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6594                                 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6595                         }
6596                 })
6597         }
6598 }
6599
6600 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6601         heapBits := GCBits(New(typ).Interface())
6602         if !bytes.Equal(heapBits, bits) {
6603                 _, _, line, _ := runtime.Caller(1)
6604                 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6605         }
6606 }
6607
6608 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6609         // Creating a slice causes the runtime to repeat a bitmap,
6610         // which exercises a different path from making the compiler
6611         // repeat a bitmap for a small array or executing a repeat in
6612         // a GC program.
6613         val := MakeSlice(typ, 0, cap)
6614         data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
6615         heapBits := GCBits(data.Interface())
6616         // Repeat the bitmap for the slice size, trimming scalars in
6617         // the last element.
6618         bits = rep(cap, bits)
6619         for len(bits) > 0 && bits[len(bits)-1] == 0 {
6620                 bits = bits[:len(bits)-1]
6621         }
6622         if !bytes.Equal(heapBits, bits) {
6623                 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6624         }
6625 }
6626
6627 func TestGCBits(t *testing.T) {
6628         verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6629
6630         // Building blocks for types seen by the compiler (like [2]Xscalar).
6631         // The compiler will create the type structures for the derived types,
6632         // including their GC metadata.
6633         type Xscalar struct{ x uintptr }
6634         type Xptr struct{ x *byte }
6635         type Xptrscalar struct {
6636                 *byte
6637                 uintptr
6638         }
6639         type Xscalarptr struct {
6640                 uintptr
6641                 *byte
6642         }
6643         type Xbigptrscalar struct {
6644                 _ [100]*byte
6645                 _ [100]uintptr
6646         }
6647
6648         var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6649         {
6650                 // Building blocks for types constructed by reflect.
6651                 // This code is in a separate block so that code below
6652                 // cannot accidentally refer to these.
6653                 // The compiler must NOT see types derived from these
6654                 // (for example, [2]Scalar must NOT appear in the program),
6655                 // or else reflect will use it instead of having to construct one.
6656                 // The goal is to test the construction.
6657                 type Scalar struct{ x uintptr }
6658                 type Ptr struct{ x *byte }
6659                 type Ptrscalar struct {
6660                         *byte
6661                         uintptr
6662                 }
6663                 type Scalarptr struct {
6664                         uintptr
6665                         *byte
6666                 }
6667                 type Bigptrscalar struct {
6668                         _ [100]*byte
6669                         _ [100]uintptr
6670                 }
6671                 type Int64 int64
6672                 Tscalar = TypeOf(Scalar{})
6673                 Tint64 = TypeOf(Int64(0))
6674                 Tptr = TypeOf(Ptr{})
6675                 Tscalarptr = TypeOf(Scalarptr{})
6676                 Tptrscalar = TypeOf(Ptrscalar{})
6677                 Tbigptrscalar = TypeOf(Bigptrscalar{})
6678         }
6679
6680         empty := []byte{}
6681
6682         verifyGCBits(t, TypeOf(Xscalar{}), empty)
6683         verifyGCBits(t, Tscalar, empty)
6684         verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6685         verifyGCBits(t, Tptr, lit(1))
6686         verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6687         verifyGCBits(t, Tscalarptr, lit(0, 1))
6688         verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6689         verifyGCBits(t, Tptrscalar, lit(1))
6690
6691         verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6692         verifyGCBits(t, ArrayOf(0, Tptr), empty)
6693         verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6694         verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6695         verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6696         verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6697         verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6698         verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6699         verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6700         verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6701         verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6702         verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6703         verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6704         verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6705         verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6706         verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6707         verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6708         verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6709         verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6710         verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6711         verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6712         verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6713         verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6714         verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6715         verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6716         verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6717
6718         verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6719         verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6720         verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6721         verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6722         verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6723         verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6724         verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6725         verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6726         verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6727         verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6728         verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6729         verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6730         verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6731         verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6732         verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6733         verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6734         verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6735         verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6736         verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6737         verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6738         verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6739         verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6740         verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6741         verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6742         verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6743         verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6744
6745         verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6746         verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6747
6748         verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6749         verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6750
6751         verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6752         verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6753
6754         verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6755         verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6756
6757         verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6758         verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6759
6760         hdr := make([]byte, 8/goarch.PtrSize)
6761
6762         verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6763                 verifyGCBits(t, MapBucketOf(k, e), want)
6764                 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6765         }
6766         verifyMapBucket(t,
6767                 Tscalar, Tptr,
6768                 map[Xscalar]Xptr(nil),
6769                 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6770         verifyMapBucket(t,
6771                 Tscalarptr, Tptr,
6772                 map[Xscalarptr]Xptr(nil),
6773                 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6774         verifyMapBucket(t, Tint64, Tptr,
6775                 map[int64]Xptr(nil),
6776                 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
6777         verifyMapBucket(t,
6778                 Tscalar, Tscalar,
6779                 map[Xscalar]Xscalar(nil),
6780                 empty)
6781         verifyMapBucket(t,
6782                 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6783                 map[[2]Xscalarptr][3]Xptrscalar(nil),
6784                 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6785         verifyMapBucket(t,
6786                 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6787                 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6788                 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6789         verifyMapBucket(t,
6790                 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6791                 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6792                 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6793         verifyMapBucket(t,
6794                 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6795                 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6796                 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
6797         verifyMapBucket(t,
6798                 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6799                 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6800                 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6801 }
6802
6803 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
6804 func join(b ...[]byte) []byte    { return bytes.Join(b, nil) }
6805 func lit(x ...byte) []byte       { return x }
6806
6807 func TestTypeOfTypeOf(t *testing.T) {
6808         // Check that all the type constructors return concrete *rtype implementations.
6809         // It's difficult to test directly because the reflect package is only at arm's length.
6810         // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6811         check := func(name string, typ Type) {
6812                 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
6813                         t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
6814                 }
6815         }
6816
6817         type T struct{ int }
6818         check("TypeOf", TypeOf(T{}))
6819
6820         check("ArrayOf", ArrayOf(10, TypeOf(T{})))
6821         check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
6822         check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
6823         check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
6824         check("PtrTo", PtrTo(TypeOf(T{})))
6825         check("SliceOf", SliceOf(TypeOf(T{})))
6826 }
6827
6828 type XM struct{ _ bool }
6829
6830 func (*XM) String() string { return "" }
6831
6832 func TestPtrToMethods(t *testing.T) {
6833         var y struct{ XM }
6834         yp := New(TypeOf(y)).Interface()
6835         _, ok := yp.(fmt.Stringer)
6836         if !ok {
6837                 t.Fatal("does not implement Stringer, but should")
6838         }
6839 }
6840
6841 func TestMapAlloc(t *testing.T) {
6842         m := ValueOf(make(map[int]int, 10))
6843         k := ValueOf(5)
6844         v := ValueOf(7)
6845         allocs := testing.AllocsPerRun(100, func() {
6846                 m.SetMapIndex(k, v)
6847         })
6848         if allocs > 0.5 {
6849                 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
6850         }
6851
6852         const size = 1000
6853         tmp := 0
6854         val := ValueOf(&tmp).Elem()
6855         allocs = testing.AllocsPerRun(100, func() {
6856                 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
6857                 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6858                 for i := 0; i < size/2; i++ {
6859                         val.SetInt(int64(i))
6860                         mv.SetMapIndex(val, val)
6861                 }
6862         })
6863         if allocs > 10 {
6864                 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
6865         }
6866         // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
6867         // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
6868         // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
6869 }
6870
6871 func TestChanAlloc(t *testing.T) {
6872         // Note: for a chan int, the return Value must be allocated, so we
6873         // use a chan *int instead.
6874         c := ValueOf(make(chan *int, 1))
6875         v := ValueOf(new(int))
6876         allocs := testing.AllocsPerRun(100, func() {
6877                 c.Send(v)
6878                 _, _ = c.Recv()
6879         })
6880         if allocs < 0.5 || allocs > 1.5 {
6881                 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
6882         }
6883         // Note: there is one allocation in reflect.recv which seems to be
6884         // a limitation of escape analysis. If that is ever fixed the
6885         // allocs < 0.5 condition will trigger and this test should be fixed.
6886 }
6887
6888 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
6889
6890 type nameTest struct {
6891         v    interface{}
6892         want string
6893 }
6894
6895 var nameTests = []nameTest{
6896         {(*int32)(nil), "int32"},
6897         {(*D1)(nil), "D1"},
6898         {(*[]D1)(nil), ""},
6899         {(*chan D1)(nil), ""},
6900         {(*func() D1)(nil), ""},
6901         {(*<-chan D1)(nil), ""},
6902         {(*chan<- D1)(nil), ""},
6903         {(*interface{})(nil), ""},
6904         {(*interface {
6905                 F()
6906         })(nil), ""},
6907         {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
6908 }
6909
6910 func TestNames(t *testing.T) {
6911         for _, test := range nameTests {
6912                 typ := TypeOf(test.v).Elem()
6913                 if got := typ.Name(); got != test.want {
6914                         t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
6915                 }
6916         }
6917 }
6918
6919 func TestExported(t *testing.T) {
6920         type ΦExported struct{}
6921         type φUnexported struct{}
6922         type BigP *big
6923         type P int
6924         type p *P
6925         type P2 p
6926         type p3 p
6927
6928         type exportTest struct {
6929                 v    interface{}
6930                 want bool
6931         }
6932         exportTests := []exportTest{
6933                 {D1{}, true},
6934                 {(*D1)(nil), true},
6935                 {big{}, false},
6936                 {(*big)(nil), false},
6937                 {(BigP)(nil), true},
6938                 {(*BigP)(nil), true},
6939                 {ΦExported{}, true},
6940                 {φUnexported{}, false},
6941                 {P(0), true},
6942                 {(p)(nil), false},
6943                 {(P2)(nil), true},
6944                 {(p3)(nil), false},
6945         }
6946
6947         for i, test := range exportTests {
6948                 typ := TypeOf(test.v)
6949                 if got := IsExported(typ); got != test.want {
6950                         t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
6951                 }
6952         }
6953 }
6954
6955 func TestTypeStrings(t *testing.T) {
6956         type stringTest struct {
6957                 typ  Type
6958                 want string
6959         }
6960         stringTests := []stringTest{
6961                 {TypeOf(func(int) {}), "func(int)"},
6962                 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
6963                 {TypeOf(XM{}), "reflect_test.XM"},
6964                 {TypeOf(new(XM)), "*reflect_test.XM"},
6965                 {TypeOf(new(XM).String), "func() string"},
6966                 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
6967                 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
6968                 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
6969                 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
6970                 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
6971         }
6972
6973         for i, test := range stringTests {
6974                 if got, want := test.typ.String(), test.want; got != want {
6975                         t.Errorf("type %d String()=%q, want %q", i, got, want)
6976                 }
6977         }
6978 }
6979
6980 func TestOffsetLock(t *testing.T) {
6981         var wg sync.WaitGroup
6982         for i := 0; i < 4; i++ {
6983                 i := i
6984                 wg.Add(1)
6985                 go func() {
6986                         for j := 0; j < 50; j++ {
6987                                 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
6988                         }
6989                         wg.Done()
6990                 }()
6991         }
6992         wg.Wait()
6993 }
6994
6995 func BenchmarkNew(b *testing.B) {
6996         v := TypeOf(XM{})
6997         b.RunParallel(func(pb *testing.PB) {
6998                 for pb.Next() {
6999                         New(v)
7000                 }
7001         })
7002 }
7003
7004 func TestSwapper(t *testing.T) {
7005         type I int
7006         var a, b, c I
7007         type pair struct {
7008                 x, y int
7009         }
7010         type pairPtr struct {
7011                 x, y int
7012                 p    *I
7013         }
7014         type S string
7015
7016         tests := []struct {
7017                 in   interface{}
7018                 i, j int
7019                 want interface{}
7020         }{
7021                 {
7022                         in:   []int{1, 20, 300},
7023                         i:    0,
7024                         j:    2,
7025                         want: []int{300, 20, 1},
7026                 },
7027                 {
7028                         in:   []uintptr{1, 20, 300},
7029                         i:    0,
7030                         j:    2,
7031                         want: []uintptr{300, 20, 1},
7032                 },
7033                 {
7034                         in:   []int16{1, 20, 300},
7035                         i:    0,
7036                         j:    2,
7037                         want: []int16{300, 20, 1},
7038                 },
7039                 {
7040                         in:   []int8{1, 20, 100},
7041                         i:    0,
7042                         j:    2,
7043                         want: []int8{100, 20, 1},
7044                 },
7045                 {
7046                         in:   []*I{&a, &b, &c},
7047                         i:    0,
7048                         j:    2,
7049                         want: []*I{&c, &b, &a},
7050                 },
7051                 {
7052                         in:   []string{"eric", "sergey", "larry"},
7053                         i:    0,
7054                         j:    2,
7055                         want: []string{"larry", "sergey", "eric"},
7056                 },
7057                 {
7058                         in:   []S{"eric", "sergey", "larry"},
7059                         i:    0,
7060                         j:    2,
7061                         want: []S{"larry", "sergey", "eric"},
7062                 },
7063                 {
7064                         in:   []pair{{1, 2}, {3, 4}, {5, 6}},
7065                         i:    0,
7066                         j:    2,
7067                         want: []pair{{5, 6}, {3, 4}, {1, 2}},
7068                 },
7069                 {
7070                         in:   []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7071                         i:    0,
7072                         j:    2,
7073                         want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7074                 },
7075         }
7076
7077         for i, tt := range tests {
7078                 inStr := fmt.Sprint(tt.in)
7079                 Swapper(tt.in)(tt.i, tt.j)
7080                 if !DeepEqual(tt.in, tt.want) {
7081                         t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7082                 }
7083         }
7084 }
7085
7086 // TestUnaddressableField tests that the reflect package will not allow
7087 // a type from another package to be used as a named type with an
7088 // unexported field.
7089 //
7090 // This ensures that unexported fields cannot be modified by other packages.
7091 func TestUnaddressableField(t *testing.T) {
7092         var b Buffer // type defined in reflect, a different package
7093         var localBuffer struct {
7094                 buf []byte
7095         }
7096         lv := ValueOf(&localBuffer).Elem()
7097         rv := ValueOf(b)
7098         shouldPanic("Set", func() {
7099                 lv.Set(rv)
7100         })
7101 }
7102
7103 type Tint int
7104
7105 type Tint2 = Tint
7106
7107 type Talias1 struct {
7108         byte
7109         uint8
7110         int
7111         int32
7112         rune
7113 }
7114
7115 type Talias2 struct {
7116         Tint
7117         Tint2
7118 }
7119
7120 func TestAliasNames(t *testing.T) {
7121         t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7122         out := fmt.Sprintf("%#v", t1)
7123         want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7124         if out != want {
7125                 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7126         }
7127
7128         t2 := Talias2{Tint: 1, Tint2: 2}
7129         out = fmt.Sprintf("%#v", t2)
7130         want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7131         if out != want {
7132                 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7133         }
7134 }
7135
7136 func TestIssue22031(t *testing.T) {
7137         type s []struct{ C int }
7138
7139         type t1 struct{ s }
7140         type t2 struct{ f s }
7141
7142         tests := []Value{
7143                 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7144                 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7145         }
7146
7147         for i, test := range tests {
7148                 if test.CanSet() {
7149                         t.Errorf("%d: CanSet: got true, want false", i)
7150                 }
7151         }
7152 }
7153
7154 type NonExportedFirst int
7155
7156 func (i NonExportedFirst) ΦExported()       {}
7157 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7158
7159 func TestIssue22073(t *testing.T) {
7160         m := ValueOf(NonExportedFirst(0)).Method(0)
7161
7162         if got := m.Type().NumOut(); got != 0 {
7163                 t.Errorf("NumOut: got %v, want 0", got)
7164         }
7165
7166         // Shouldn't panic.
7167         m.Call(nil)
7168 }
7169
7170 func TestMapIterNonEmptyMap(t *testing.T) {
7171         m := map[string]int{"one": 1, "two": 2, "three": 3}
7172         iter := ValueOf(m).MapRange()
7173         if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7174                 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7175         }
7176 }
7177
7178 func TestMapIterNilMap(t *testing.T) {
7179         var m map[string]int
7180         iter := ValueOf(m).MapRange()
7181         if got, want := iterateToString(iter), `[]`; got != want {
7182                 t.Errorf("non-empty result iteratoring nil map: %s", got)
7183         }
7184 }
7185
7186 func TestMapIterSafety(t *testing.T) {
7187         // Using a zero MapIter causes a panic, but not a crash.
7188         func() {
7189                 defer func() { recover() }()
7190                 new(MapIter).Key()
7191                 t.Fatal("Key did not panic")
7192         }()
7193         func() {
7194                 defer func() { recover() }()
7195                 new(MapIter).Value()
7196                 t.Fatal("Value did not panic")
7197         }()
7198         func() {
7199                 defer func() { recover() }()
7200                 new(MapIter).Next()
7201                 t.Fatal("Next did not panic")
7202         }()
7203
7204         // Calling Key/Value on a MapIter before Next
7205         // causes a panic, but not a crash.
7206         var m map[string]int
7207         iter := ValueOf(m).MapRange()
7208
7209         func() {
7210                 defer func() { recover() }()
7211                 iter.Key()
7212                 t.Fatal("Key did not panic")
7213         }()
7214         func() {
7215                 defer func() { recover() }()
7216                 iter.Value()
7217                 t.Fatal("Value did not panic")
7218         }()
7219
7220         // Calling Next, Key, or Value on an exhausted iterator
7221         // causes a panic, but not a crash.
7222         iter.Next() // -> false
7223         func() {
7224                 defer func() { recover() }()
7225                 iter.Key()
7226                 t.Fatal("Key did not panic")
7227         }()
7228         func() {
7229                 defer func() { recover() }()
7230                 iter.Value()
7231                 t.Fatal("Value did not panic")
7232         }()
7233         func() {
7234                 defer func() { recover() }()
7235                 iter.Next()
7236                 t.Fatal("Next did not panic")
7237         }()
7238 }
7239
7240 func TestMapIterNext(t *testing.T) {
7241         // The first call to Next should reflect any
7242         // insertions to the map since the iterator was created.
7243         m := map[string]int{}
7244         iter := ValueOf(m).MapRange()
7245         m["one"] = 1
7246         if got, want := iterateToString(iter), `[one: 1]`; got != want {
7247                 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7248         }
7249 }
7250
7251 func TestMapIterDelete0(t *testing.T) {
7252         // Delete all elements before first iteration.
7253         m := map[string]int{"one": 1, "two": 2, "three": 3}
7254         iter := ValueOf(m).MapRange()
7255         delete(m, "one")
7256         delete(m, "two")
7257         delete(m, "three")
7258         if got, want := iterateToString(iter), `[]`; got != want {
7259                 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7260         }
7261 }
7262
7263 func TestMapIterDelete1(t *testing.T) {
7264         // Delete all elements after first iteration.
7265         m := map[string]int{"one": 1, "two": 2, "three": 3}
7266         iter := ValueOf(m).MapRange()
7267         var got []string
7268         for iter.Next() {
7269                 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7270                 delete(m, "one")
7271                 delete(m, "two")
7272                 delete(m, "three")
7273         }
7274         if len(got) != 1 {
7275                 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7276         }
7277 }
7278
7279 // iterateToString returns the set of elements
7280 // returned by an iterator in readable form.
7281 func iterateToString(it *MapIter) string {
7282         var got []string
7283         for it.Next() {
7284                 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7285                 got = append(got, line)
7286         }
7287         sort.Strings(got)
7288         return "[" + strings.Join(got, ", ") + "]"
7289 }
7290
7291 func TestConvertibleTo(t *testing.T) {
7292         t1 := ValueOf(example1.MyStruct{}).Type()
7293         t2 := ValueOf(example2.MyStruct{}).Type()
7294
7295         // Shouldn't raise stack overflow
7296         if t1.ConvertibleTo(t2) {
7297                 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7298         }
7299 }