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