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