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