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