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