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