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