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