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