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