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