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