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