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