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