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