github.com/3JoB/go-reflect@v1.0.1/all_test.go (about)

     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  	"io"
    13  	"math"
    14  	"math/rand"
    15  	"os"
    16  	"runtime"
    17  	"sort"
    18  	"strconv"
    19  	"strings"
    20  	"sync"
    21  	"sync/atomic"
    22  	"testing"
    23  	"time"
    24  	"unicode"
    25  	"unicode/utf8"
    26  	"unsafe"
    27  
    28  	. "github.com/3JoB/go-reflect"
    29  )
    30  
    31  const (
    32  	PtrSize = 8
    33  )
    34  
    35  var sink any
    36  
    37  func TestBool(t *testing.T) {
    38  	v := ValueOf(true)
    39  	if !v.Bool() {
    40  		t.Fatal("ValueOf(true).Bool() = false")
    41  	}
    42  }
    43  
    44  type integer int
    45  
    46  type T struct {
    47  	a int
    48  	b float64
    49  	c string
    50  	d *int
    51  }
    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  	{i: struct{ x int }{}, s: "int"},
    66  	{i: struct{ x int8 }{}, s: "int8"},
    67  	{i: struct{ x int16 }{}, s: "int16"},
    68  	{i: struct{ x int32 }{}, s: "int32"},
    69  	{i: struct{ x int64 }{}, s: "int64"},
    70  	{i: struct{ x uint }{}, s: "uint"},
    71  	{i: struct{ x uint8 }{}, s: "uint8"},
    72  	{i: struct{ x uint16 }{}, s: "uint16"},
    73  	{i: struct{ x uint32 }{}, s: "uint32"},
    74  	{i: struct{ x uint64 }{}, s: "uint64"},
    75  	{i: struct{ x float32 }{}, s: "float32"},
    76  	{i: struct{ x float64 }{}, s: "float64"},
    77  	{i: struct{ x int8 }{}, s: "int8"},
    78  	{i: struct{ x (**int8) }{}, s: "**int8"},
    79  	{i: struct{ x (**integer) }{}, s: "**reflect_test.integer"},
    80  	{i: struct{ x ([32]int32) }{}, s: "[32]int32"},
    81  	{i: struct{ x ([]int8) }{}, s: "[]int8"},
    82  	{i: struct{ x (map[string]int32) }{}, s: "map[string]int32"},
    83  	{i: struct{ x (chan<- string) }{}, s: "chan<- string"},
    84  	{i: struct {
    85  		x struct {
    86  			c chan *int32
    87  			d float32
    88  		}
    89  	}{},
    90  		s: "struct { c chan *int32; d float32 }",
    91  	},
    92  	{i: struct{ x (func(a int8, b int32)) }{}, s: "func(int8, int32)"},
    93  	{i: struct {
    94  		x struct {
    95  			c func(chan *integer, *int8)
    96  		}
    97  	}{},
    98  		s: "struct { c func(chan *reflect_test.integer, *int8) }",
    99  	},
   100  	{i: struct {
   101  		x struct {
   102  			a int8
   103  			b int32
   104  		}
   105  	}{},
   106  		s: "struct { a int8; b int32 }",
   107  	},
   108  	{i: struct {
   109  		x struct {
   110  			a int8
   111  			b int8
   112  			c int32
   113  		}
   114  	}{},
   115  		s: "struct { a int8; b int8; c int32 }",
   116  	},
   117  	{i: struct {
   118  		x struct {
   119  			a int8
   120  			b int8
   121  			c int8
   122  			d int32
   123  		}
   124  	}{},
   125  		s: "struct { a int8; b int8; c int8; d int32 }",
   126  	},
   127  	{i: struct {
   128  		x struct {
   129  			a int8
   130  			b int8
   131  			c int8
   132  			d int8
   133  			e int32
   134  		}
   135  	}{},
   136  		s: "struct { a int8; b int8; c int8; d int8; e int32 }",
   137  	},
   138  	{i: struct {
   139  		x struct {
   140  			a int8
   141  			b int8
   142  			c int8
   143  			d int8
   144  			e int8
   145  			f int32
   146  		}
   147  	}{},
   148  		s: "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
   149  	},
   150  	{i: struct {
   151  		x struct {
   152  			a int8 `reflect:"hi there"`
   153  		}
   154  	}{},
   155  		s: `struct { a int8 "reflect:\"hi there\"" }`,
   156  	},
   157  	{i: struct {
   158  		x struct {
   159  			a int8 `reflect:"hi \x00there\t\n\"\\"`
   160  		}
   161  	}{},
   162  		s: `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
   163  	},
   164  	{i: struct {
   165  		x struct {
   166  			f func(args ...int)
   167  		}
   168  	}{},
   169  		s: "struct { f func(...int) }",
   170  	},
   171  	{i: struct {
   172  		x (interface {
   173  			a(func(func(int) int) func(func(int)) int)
   174  			b()
   175  		})
   176  	}{},
   177  		s: "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
   178  	},
   179  	{i: struct {
   180  		x struct {
   181  			int32
   182  			int64
   183  		}
   184  	}{},
   185  		s: "struct { int32; int64 }",
   186  	},
   187  }
   188  
   189  var valueTests = []pair{
   190  	{i: new(int), s: "132"},
   191  	{i: new(int8), s: "8"},
   192  	{i: new(int16), s: "16"},
   193  	{i: new(int32), s: "32"},
   194  	{i: new(int64), s: "64"},
   195  	{i: new(uint), s: "132"},
   196  	{i: new(uint8), s: "8"},
   197  	{i: new(uint16), s: "16"},
   198  	{i: new(uint32), s: "32"},
   199  	{i: new(uint64), s: "64"},
   200  	{i: new(float32), s: "256.25"},
   201  	{i: new(float64), s: "512.125"},
   202  	{i: new(complex64), s: "532.125+10i"},
   203  	{i: new(complex128), s: "564.25+1i"},
   204  	{i: new(string), s: "stringy cheese"},
   205  	{i: new(bool), s: "true"},
   206  	{i: new(*int8), s: "*int8(0)"},
   207  	{i: new(**int8), s: "**int8(0)"},
   208  	{i: new([5]int32), s: "[5]int32{0, 0, 0, 0, 0}"},
   209  	{i: new(**integer), s: "**reflect_test.integer(0)"},
   210  	{i: new(map[string]int32), s: "map[string]int32{<can't iterate on maps>}"},
   211  	{i: new(chan<- string), s: "chan<- string"},
   212  	{i: new(func(a int8, b int32)), s: "func(int8, int32)(0)"},
   213  	{i: new(struct {
   214  		c chan *int32
   215  		d float32
   216  	}),
   217  		s: "struct { c chan *int32; d float32 }{chan *int32, 0}",
   218  	},
   219  	{i: new(struct{ c func(chan *integer, *int8) }),
   220  		s: "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
   221  	},
   222  	{i: new(struct {
   223  		a int8
   224  		b int32
   225  	}),
   226  		s: "struct { a int8; b int32 }{0, 0}",
   227  	},
   228  	{i: new(struct {
   229  		a int8
   230  		b int8
   231  		c int32
   232  	}),
   233  		s: "struct { a int8; b int8; c int32 }{0, 0, 0}",
   234  	},
   235  }
   236  
   237  func testType(t *testing.T, i int, typ Type, want string) {
   238  	s := typ.String()
   239  	if s != want {
   240  		t.Errorf("#%d: have %#q, want %#q", i, s, want)
   241  	}
   242  }
   243  
   244  func TestTypes(t *testing.T) {
   245  	for i, tt := range typeTests {
   246  		testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
   247  	}
   248  }
   249  
   250  func TestSet(t *testing.T) {
   251  	for i, tt := range valueTests {
   252  		v := ValueOf(tt.i)
   253  		v = v.Elem()
   254  		switch v.Kind() {
   255  		case Int:
   256  			v.SetInt(132)
   257  		case Int8:
   258  			v.SetInt(8)
   259  		case Int16:
   260  			v.SetInt(16)
   261  		case Int32:
   262  			v.SetInt(32)
   263  		case Int64:
   264  			v.SetInt(64)
   265  		case Uint:
   266  			v.SetUint(132)
   267  		case Uint8:
   268  			v.SetUint(8)
   269  		case Uint16:
   270  			v.SetUint(16)
   271  		case Uint32:
   272  			v.SetUint(32)
   273  		case Uint64:
   274  			v.SetUint(64)
   275  		case Float32:
   276  			v.SetFloat(256.25)
   277  		case Float64:
   278  			v.SetFloat(512.125)
   279  		case Complex64:
   280  			v.SetComplex(532.125 + 10i)
   281  		case Complex128:
   282  			v.SetComplex(564.25 + 1i)
   283  		case String:
   284  			v.SetString("stringy cheese")
   285  		case Bool:
   286  			v.SetBool(true)
   287  		}
   288  		s := valueToString(v)
   289  		if s != tt.s {
   290  			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
   291  		}
   292  	}
   293  }
   294  
   295  func TestSetValue(t *testing.T) {
   296  	for i, tt := range valueTests {
   297  		v := ValueOf(tt.i).Elem()
   298  		switch v.Kind() {
   299  		case Int:
   300  			v.Set(ValueOf(int(132)))
   301  		case Int8:
   302  			v.Set(ValueOf(int8(8)))
   303  		case Int16:
   304  			v.Set(ValueOf(int16(16)))
   305  		case Int32:
   306  			v.Set(ValueOf(int32(32)))
   307  		case Int64:
   308  			v.Set(ValueOf(int64(64)))
   309  		case Uint:
   310  			v.Set(ValueOf(uint(132)))
   311  		case Uint8:
   312  			v.Set(ValueOf(uint8(8)))
   313  		case Uint16:
   314  			v.Set(ValueOf(uint16(16)))
   315  		case Uint32:
   316  			v.Set(ValueOf(uint32(32)))
   317  		case Uint64:
   318  			v.Set(ValueOf(uint64(64)))
   319  		case Float32:
   320  			v.Set(ValueOf(float32(256.25)))
   321  		case Float64:
   322  			v.Set(ValueOf(512.125))
   323  		case Complex64:
   324  			v.Set(ValueOf(complex64(532.125 + 10i)))
   325  		case Complex128:
   326  			v.Set(ValueOf(complex128(564.25 + 1i)))
   327  		case String:
   328  			v.Set(ValueOf("stringy cheese"))
   329  		case Bool:
   330  			v.Set(ValueOf(true))
   331  		}
   332  		s := valueToString(v)
   333  		if s != tt.s {
   334  			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
   335  		}
   336  	}
   337  }
   338  
   339  func TestCanSetField(t *testing.T) {
   340  	type embed struct{ x, X int }
   341  	type Embed struct{ x, X int }
   342  	type S1 struct {
   343  		embed
   344  		x, X int
   345  	}
   346  	type S2 struct {
   347  		*embed
   348  		x, X int
   349  	}
   350  	type S3 struct {
   351  		Embed
   352  		x, X int
   353  	}
   354  	type S4 struct {
   355  		*Embed
   356  		x, X int
   357  	}
   358  
   359  	type testCase struct {
   360  		index  []int
   361  		canSet bool
   362  	}
   363  	tests := []struct {
   364  		val   Value
   365  		cases []testCase
   366  	}{{
   367  		val: ValueOf(&S1{}),
   368  		cases: []testCase{
   369  			{index: []int{0}, canSet: false},
   370  			{index: []int{0, 0}, canSet: false},
   371  			{index: []int{0, 1}, canSet: true},
   372  			{index: []int{1}, canSet: false},
   373  			{index: []int{2}, canSet: true},
   374  		},
   375  	}, {
   376  		val: ValueOf(&S2{embed: &embed{}}),
   377  		cases: []testCase{
   378  			{index: []int{0}, canSet: false},
   379  			{index: []int{0, 0}, canSet: false},
   380  			{index: []int{0, 1}, canSet: true},
   381  			{index: []int{1}, canSet: false},
   382  			{index: []int{2}, canSet: true},
   383  		},
   384  	}, {
   385  		val: ValueOf(&S3{}),
   386  		cases: []testCase{
   387  			{index: []int{0}, canSet: true},
   388  			{index: []int{0, 0}, canSet: false},
   389  			{index: []int{0, 1}, canSet: true},
   390  			{index: []int{1}, canSet: false},
   391  			{index: []int{2}, canSet: true},
   392  		},
   393  	}, {
   394  		val: ValueOf(&S4{Embed: &Embed{}}),
   395  		cases: []testCase{
   396  			{index: []int{0}, canSet: true},
   397  			{index: []int{0, 0}, canSet: false},
   398  			{index: []int{0, 1}, canSet: true},
   399  			{index: []int{1}, canSet: false},
   400  			{index: []int{2}, canSet: true},
   401  		},
   402  	}}
   403  
   404  	for _, tt := range tests {
   405  		t.Run(tt.val.Type().Name(), func(t *testing.T) {
   406  			for _, tc := range tt.cases {
   407  				f := tt.val
   408  				for _, i := range tc.index {
   409  					if f.Kind() == Ptr {
   410  						f = f.Elem()
   411  					}
   412  					f = f.Field(i)
   413  				}
   414  				if got := f.CanSet(); got != tc.canSet {
   415  					t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
   416  				}
   417  			}
   418  		})
   419  	}
   420  }
   421  
   422  var _i = 7
   423  
   424  var valueToStringTests = []pair{
   425  	{i: 123, s: "123"},
   426  	{i: 123.5, s: "123.5"},
   427  	{i: byte(123), s: "123"},
   428  	{i: "abc", s: "abc"},
   429  	{i: T{a: 123, b: 456.75, c: "hello", d: &_i}, s: "reflect_test.T{123, 456.75, hello, *int(&7)}"},
   430  	{i: new(chan *T), s: "*chan *reflect_test.T(&chan *reflect_test.T)"},
   431  	{i: [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, s: "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
   432  	{i: &[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, s: "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
   433  	{i: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, s: "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
   434  	{i: &[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, s: "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
   435  }
   436  
   437  func TestValueToString(t *testing.T) {
   438  	for i, test := range valueToStringTests {
   439  		s := valueToString(ValueOf(test.i))
   440  		if s != test.s {
   441  			t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
   442  		}
   443  	}
   444  }
   445  
   446  func TestArrayElemSet(t *testing.T) {
   447  	v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
   448  	v.Index(4).SetInt(123)
   449  	s := valueToString(v)
   450  	const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
   451  	if s != want {
   452  		t.Errorf("[10]int: have %#q want %#q", s, want)
   453  	}
   454  
   455  	v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
   456  	v.Index(4).SetInt(123)
   457  	s = valueToString(v)
   458  	const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
   459  	if s != want1 {
   460  		t.Errorf("[]int: have %#q want %#q", s, want1)
   461  	}
   462  }
   463  
   464  func TestPtrPointTo(t *testing.T) {
   465  	var ip *int32
   466  	var i int32 = 1234
   467  	vip := ValueOf(&ip)
   468  	vi := ValueOf(&i).Elem()
   469  	vip.Elem().Set(vi.Addr())
   470  	if *ip != 1234 {
   471  		t.Errorf("got %d, want 1234", *ip)
   472  	}
   473  
   474  	ip = nil
   475  	vp := ValueOf(&ip).Elem()
   476  	vp.Set(Zero(vp.Type()))
   477  	if ip != nil {
   478  		t.Errorf("got non-nil (%p), want nil", ip)
   479  	}
   480  }
   481  
   482  func TestPtrSetNil(t *testing.T) {
   483  	var i int32 = 1234
   484  	ip := &i
   485  	vip := ValueOf(&ip)
   486  	vip.Elem().Set(Zero(vip.Elem().Type()))
   487  	if ip != nil {
   488  		t.Errorf("got non-nil (%d), want nil", *ip)
   489  	}
   490  }
   491  
   492  func TestMapSetNil(t *testing.T) {
   493  	m := make(map[string]int)
   494  	vm := ValueOf(&m)
   495  	vm.Elem().Set(Zero(vm.Elem().Type()))
   496  	if m != nil {
   497  		t.Errorf("got non-nil (%p), want nil", m)
   498  	}
   499  }
   500  
   501  func TestAll(t *testing.T) {
   502  	testType(t, 1, TypeOf((int8)(0)), "int8")
   503  	testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
   504  
   505  	typ := TypeOf((*struct {
   506  		c chan *int32
   507  		d float32
   508  	})(nil))
   509  	testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
   510  	etyp := typ.Elem()
   511  	testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
   512  	styp := etyp
   513  	f := styp.Field(0)
   514  	testType(t, 5, f.Type, "chan *int32")
   515  
   516  	f, present := styp.FieldByName("d")
   517  	if !present {
   518  		t.Errorf("FieldByName says present field is absent")
   519  	}
   520  	testType(t, 6, f.Type, "float32")
   521  
   522  	f, present = styp.FieldByName("absent")
   523  	if present {
   524  		t.Errorf("FieldByName says absent field is present")
   525  	}
   526  
   527  	typ = TypeOf([32]int32{})
   528  	testType(t, 7, typ, "[32]int32")
   529  	testType(t, 8, typ.Elem(), "int32")
   530  
   531  	typ = TypeOf((map[string]*int32)(nil))
   532  	testType(t, 9, typ, "map[string]*int32")
   533  	mtyp := typ
   534  	testType(t, 10, mtyp.Key(), "string")
   535  	testType(t, 11, mtyp.Elem(), "*int32")
   536  
   537  	typ = TypeOf((chan<- string)(nil))
   538  	testType(t, 12, typ, "chan<- string")
   539  	testType(t, 13, typ.Elem(), "string")
   540  
   541  	// make sure tag strings are not part of element type
   542  	typ = TypeOf(struct {
   543  		d []uint32 `reflect:"TAG"`
   544  	}{}).Field(0).Type
   545  	testType(t, 14, typ, "[]uint32")
   546  }
   547  
   548  func TestInterfaceGet(t *testing.T) {
   549  	var inter struct {
   550  		E any
   551  	}
   552  	inter.E = 123.456
   553  	v1 := ValueOf(&inter)
   554  	v2 := v1.Elem().Field(0)
   555  	assert(t, v2.Type().String(), "interface {}")
   556  	i2 := v2.Interface()
   557  	v3 := ValueOf(i2)
   558  	assert(t, v3.Type().String(), "float64")
   559  }
   560  
   561  func TestInterfaceValue(t *testing.T) {
   562  	var inter struct {
   563  		E any
   564  	}
   565  	inter.E = 123.456
   566  	v1 := ValueOf(&inter)
   567  	v2 := v1.Elem().Field(0)
   568  	assert(t, v2.Type().String(), "interface {}")
   569  	v3 := v2.Elem()
   570  	assert(t, v3.Type().String(), "float64")
   571  
   572  	i3 := v2.Interface()
   573  	if _, ok := i3.(float64); !ok {
   574  		t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
   575  	}
   576  }
   577  
   578  func TestFunctionValue(t *testing.T) {
   579  	var x any = func() {}
   580  	v := ValueOf(x)
   581  	if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
   582  		t.Fatalf("TestFunction returned wrong pointer")
   583  	}
   584  	assert(t, v.Type().String(), "func()")
   585  }
   586  
   587  var appendTests = []struct {
   588  	orig, extra []int
   589  }{
   590  	{orig: make([]int, 2, 4), extra: []int{22}},
   591  	{orig: make([]int, 2, 4), extra: []int{22, 33, 44}},
   592  }
   593  
   594  func sameInts(x, y []int) bool {
   595  	if len(x) != len(y) {
   596  		return false
   597  	}
   598  	for i, xx := range x {
   599  		if xx != y[i] {
   600  			return false
   601  		}
   602  	}
   603  	return true
   604  }
   605  
   606  func TestAppend(t *testing.T) {
   607  	for i, test := range appendTests {
   608  		origLen, extraLen := len(test.orig), len(test.extra)
   609  		want := append(test.orig, test.extra...)
   610  		// Convert extra from []int to []Value.
   611  		e0 := make([]Value, len(test.extra))
   612  		for j, e := range test.extra {
   613  			e0[j] = ValueOf(e)
   614  		}
   615  		// Convert extra from []int to *SliceValue.
   616  		e1 := ValueOf(test.extra)
   617  		// Test Append.
   618  		a0 := ValueOf(test.orig)
   619  		have0 := Append(a0, e0...).Interface().([]int)
   620  		if !sameInts(have0, want) {
   621  			t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
   622  		}
   623  		// Check that the orig and extra slices were not modified.
   624  		if len(test.orig) != origLen {
   625  			t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
   626  		}
   627  		if len(test.extra) != extraLen {
   628  			t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
   629  		}
   630  		// Test AppendSlice.
   631  		a1 := ValueOf(test.orig)
   632  		have1 := AppendSlice(a1, e1).Interface().([]int)
   633  		if !sameInts(have1, want) {
   634  			t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
   635  		}
   636  		// Check that the orig and extra slices were not modified.
   637  		if len(test.orig) != origLen {
   638  			t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
   639  		}
   640  		if len(test.extra) != extraLen {
   641  			t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
   642  		}
   643  	}
   644  }
   645  
   646  func TestCopy(t *testing.T) {
   647  	a := []int{1, 2, 3, 4, 10, 9, 8, 7}
   648  	b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   649  	c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   650  	for i := 0; i < len(b); i++ {
   651  		if b[i] != c[i] {
   652  			t.Fatalf("b != c before test")
   653  		}
   654  	}
   655  	a1 := a
   656  	b1 := b
   657  	aa := ValueOf(&a1).Elem()
   658  	ab := ValueOf(&b1).Elem()
   659  	for tocopy := 1; tocopy <= 7; tocopy++ {
   660  		aa.SetLen(tocopy)
   661  		Copy(ab, aa)
   662  		aa.SetLen(8)
   663  		for i := 0; i < tocopy; i++ {
   664  			if a[i] != b[i] {
   665  				t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
   666  					tocopy, i, a[i], i, b[i])
   667  			}
   668  		}
   669  		for i := tocopy; i < len(b); i++ {
   670  			if b[i] != c[i] {
   671  				if i < len(a) {
   672  					t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
   673  						tocopy, i, a[i], i, b[i], i, c[i])
   674  				} else {
   675  					t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
   676  						tocopy, i, b[i], i, c[i])
   677  				}
   678  			} else {
   679  				t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
   680  			}
   681  		}
   682  	}
   683  }
   684  
   685  func TestCopyString(t *testing.T) {
   686  	t.Run("Slice", func(t *testing.T) {
   687  		s := bytes.Repeat([]byte{'_'}, 8)
   688  		val := ValueOf(s)
   689  
   690  		n := Copy(val, ValueOf(""))
   691  		if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
   692  			t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
   693  		}
   694  
   695  		n = Copy(val, ValueOf("hello"))
   696  		if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
   697  			t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
   698  		}
   699  
   700  		n = Copy(val, ValueOf("helloworld"))
   701  		if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
   702  			t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
   703  		}
   704  	})
   705  	t.Run("Array", func(t *testing.T) {
   706  		s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
   707  		val := ValueOf(&s).Elem()
   708  
   709  		n := Copy(val, ValueOf(""))
   710  		if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
   711  			t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
   712  		}
   713  
   714  		n = Copy(val, ValueOf("hello"))
   715  		if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
   716  			t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
   717  		}
   718  
   719  		n = Copy(val, ValueOf("helloworld"))
   720  		if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
   721  			t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
   722  		}
   723  	})
   724  }
   725  
   726  func TestCopyArray(t *testing.T) {
   727  	a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
   728  	b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
   729  	c := b
   730  	aa := ValueOf(&a).Elem()
   731  	ab := ValueOf(&b).Elem()
   732  	Copy(ab, aa)
   733  	for i := 0; i < len(a); i++ {
   734  		if a[i] != b[i] {
   735  			t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
   736  		}
   737  	}
   738  	for i := len(a); i < len(b); i++ {
   739  		if b[i] != c[i] {
   740  			t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
   741  		} else {
   742  			t.Logf("elem %d is okay\n", i)
   743  		}
   744  	}
   745  }
   746  
   747  func TestBigUnnamedStruct(t *testing.T) {
   748  	b := struct{ a, b, c, d int64 }{a: 1, b: 2, c: 3, d: 4}
   749  	v := ValueOf(b)
   750  	b1 := v.Interface().(struct {
   751  		a, b, c, d int64
   752  	})
   753  	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
   754  		t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
   755  	}
   756  }
   757  
   758  type big struct {
   759  	a, b, c, d, e int64
   760  }
   761  
   762  func TestBigStruct(t *testing.T) {
   763  	b := big{a: 1, b: 2, c: 3, d: 4, e: 5}
   764  	v := ValueOf(b)
   765  	b1 := v.Interface().(big)
   766  	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
   767  		t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
   768  	}
   769  }
   770  
   771  type Basic struct {
   772  	x int
   773  	y float32
   774  }
   775  
   776  type NotBasic Basic
   777  
   778  type DeepEqualTest struct {
   779  	a, b any
   780  	eq   bool
   781  }
   782  
   783  // Simple functions for DeepEqual tests.
   784  var (
   785  	fn1 func()             // nil.
   786  	fn2 func()             // nil.
   787  	fn3 = func() { fn1() } // Not nil.
   788  )
   789  
   790  type self struct{}
   791  
   792  type Loop *Loop
   793  
   794  type Loopy any
   795  
   796  var loop1, loop2 Loop
   797  var loopy1, loopy2 Loopy
   798  
   799  func init() {
   800  	loop1 = &loop2
   801  	loop2 = &loop1
   802  
   803  	loopy1 = &loopy2
   804  	loopy2 = &loopy1
   805  }
   806  
   807  var deepEqualTests = []DeepEqualTest{
   808  	// Equalities
   809  	{a: nil, b: nil, eq: true},
   810  	{a: 1, b: 1, eq: true},
   811  	{a: int32(1), b: int32(1), eq: true},
   812  	{a: 0.5, b: 0.5, eq: true},
   813  	{a: float32(0.5), b: float32(0.5), eq: true},
   814  	{a: "hello", b: "hello", eq: true},
   815  	{a: make([]int, 10), b: make([]int, 10), eq: true},
   816  	{a: &[3]int{1, 2, 3}, b: &[3]int{1, 2, 3}, eq: true},
   817  	{a: Basic{x: 1, y: 0.5}, b: Basic{x: 1, y: 0.5}, eq: true},
   818  	{a: error(nil), b: error(nil), eq: true},
   819  	{a: map[int]string{1: "one", 2: "two"}, b: map[int]string{2: "two", 1: "one"}, eq: true},
   820  	{a: fn1, b: fn2, eq: true},
   821  
   822  	// Inequalities
   823  	{a: 1, b: 2, eq: false},
   824  	{a: int32(1), b: int32(2), eq: false},
   825  	{a: 0.5, b: 0.6, eq: false},
   826  	{a: float32(0.5), b: float32(0.6), eq: false},
   827  	{a: "hello", b: "hey", eq: false},
   828  	{a: make([]int, 10), b: make([]int, 11), eq: false},
   829  	{a: &[3]int{1, 2, 3}, b: &[3]int{1, 2, 4}, eq: false},
   830  	{a: Basic{x: 1, y: 0.5}, b: Basic{x: 1, y: 0.6}, eq: false},
   831  	{a: Basic{x: 1, y: 0}, b: Basic{x: 2, y: 0}, eq: false},
   832  	{a: map[int]string{1: "one", 3: "two"}, b: map[int]string{2: "two", 1: "one"}, eq: false},
   833  	{a: map[int]string{1: "one", 2: "txo"}, b: map[int]string{2: "two", 1: "one"}, eq: false},
   834  	{a: map[int]string{1: "one"}, b: map[int]string{2: "two", 1: "one"}, eq: false},
   835  	{a: map[int]string{2: "two", 1: "one"}, b: map[int]string{1: "one"}, eq: false},
   836  	{a: nil, b: 1, eq: false},
   837  	{a: 1, b: nil, eq: false},
   838  	{a: fn1, b: fn3, eq: false},
   839  	{a: fn3, b: fn3, eq: false},
   840  	{a: [][]int{{1}}, b: [][]int{{2}}, eq: false},
   841  	{a: math.NaN(), b: math.NaN(), eq: false},
   842  	{a: &[1]float64{math.NaN()}, b: &[1]float64{math.NaN()}, eq: false},
   843  	{a: &[1]float64{math.NaN()}, b: self{}, eq: true},
   844  	{a: []float64{math.NaN()}, b: []float64{math.NaN()}, eq: false},
   845  	{a: []float64{math.NaN()}, b: self{}, eq: true},
   846  	{a: map[float64]float64{math.NaN(): 1}, b: map[float64]float64{1: 2}, eq: false},
   847  	{a: map[float64]float64{math.NaN(): 1}, b: self{}, eq: true},
   848  
   849  	// Nil vs empty: not the same.
   850  	{a: []int{}, b: []int(nil), eq: false},
   851  	{a: []int{}, b: []int{}, eq: true},
   852  	{a: []int(nil), b: []int(nil), eq: true},
   853  	{a: map[int]int{}, b: map[int]int(nil), eq: false},
   854  	{a: map[int]int{}, b: map[int]int{}, eq: true},
   855  	{a: map[int]int(nil), b: map[int]int(nil), eq: true},
   856  
   857  	// Mismatched types
   858  	{a: 1, b: 1.0, eq: false},
   859  	{a: int32(1), b: int64(1), eq: false},
   860  	{a: 0.5, b: "hello", eq: false},
   861  	{a: []int{1, 2, 3}, b: [3]int{1, 2, 3}, eq: false},
   862  	{a: &[3]any{1, 2, 4}, b: &[3]any{1, 2, "s"}, eq: false},
   863  	{a: Basic{x: 1, y: 0.5}, b: NotBasic{x: 1, y: 0.5}, eq: false},
   864  	{a: map[uint]string{1: "one", 2: "two"}, b: map[int]string{2: "two", 1: "one"}, eq: false},
   865  
   866  	// Possible loops.
   867  	{a: &loop1, b: &loop1, eq: true},
   868  	{a: &loop1, b: &loop2, eq: true},
   869  	{a: &loopy1, b: &loopy1, eq: true},
   870  	{a: &loopy1, b: &loopy2, eq: true},
   871  }
   872  
   873  func TestDeepEqual(t *testing.T) {
   874  	for _, test := range deepEqualTests {
   875  		if test.b == (self{}) {
   876  			test.b = test.a
   877  		}
   878  		if r := DeepEqual(test.a, test.b); r != test.eq {
   879  			t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
   880  		}
   881  	}
   882  }
   883  
   884  func TestTypeOf(t *testing.T) {
   885  	// Special case for nil
   886  	if typ := TypeOf(nil); typ != nil {
   887  		t.Errorf("expected nil type for nil value; got %v", typ)
   888  	}
   889  	for _, test := range deepEqualTests {
   890  		v := ValueOf(test.a)
   891  		if !v.IsValid() {
   892  			continue
   893  		}
   894  		typ := TypeOf(test.a)
   895  		if typ != v.Type() {
   896  			t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
   897  		}
   898  	}
   899  }
   900  
   901  type Recursive struct {
   902  	x int
   903  	r *Recursive
   904  }
   905  
   906  func TestDeepEqualRecursiveStruct(t *testing.T) {
   907  	a, b := new(Recursive), new(Recursive)
   908  	*a = Recursive{x: 12, r: a}
   909  	*b = Recursive{x: 12, r: b}
   910  	if !DeepEqual(a, b) {
   911  		t.Error("DeepEqual(recursive same) = false, want true")
   912  	}
   913  }
   914  
   915  type _Complex struct {
   916  	a int
   917  	b [3]*_Complex
   918  	c *string
   919  	d map[float64]float64
   920  }
   921  
   922  func TestDeepEqualComplexStruct(t *testing.T) {
   923  	m := make(map[float64]float64)
   924  	stra, strb := "hello", "hello"
   925  	a, b := new(_Complex), new(_Complex)
   926  	*a = _Complex{a: 5, b: [3]*_Complex{a, b, a}, c: &stra, d: m}
   927  	*b = _Complex{a: 5, b: [3]*_Complex{b, a, a}, c: &strb, d: m}
   928  	if !DeepEqual(a, b) {
   929  		t.Error("DeepEqual(complex same) = false, want true")
   930  	}
   931  }
   932  
   933  func TestDeepEqualComplexStructInequality(t *testing.T) {
   934  	m := make(map[float64]float64)
   935  	stra, strb := "hello", "helloo" // Difference is here
   936  	a, b := new(_Complex), new(_Complex)
   937  	*a = _Complex{a: 5, b: [3]*_Complex{a, b, a}, c: &stra, d: m}
   938  	*b = _Complex{a: 5, b: [3]*_Complex{b, a, a}, c: &strb, d: m}
   939  	if DeepEqual(a, b) {
   940  		t.Error("DeepEqual(complex different) = true, want false")
   941  	}
   942  }
   943  
   944  type UnexpT struct {
   945  	m map[int]int
   946  }
   947  
   948  func TestDeepEqualUnexportedMap(t *testing.T) {
   949  	// Check that DeepEqual can look at unexported fields.
   950  	x1 := UnexpT{m: map[int]int{1: 2}}
   951  	x2 := UnexpT{m: map[int]int{1: 2}}
   952  	if !DeepEqual(&x1, &x2) {
   953  		t.Error("DeepEqual(x1, x2) = false, want true")
   954  	}
   955  
   956  	y1 := UnexpT{m: map[int]int{2: 3}}
   957  	if DeepEqual(&x1, &y1) {
   958  		t.Error("DeepEqual(x1, y1) = true, want false")
   959  	}
   960  }
   961  
   962  func check2ndField(x any, offs uintptr, t *testing.T) {
   963  	s := ValueOf(x)
   964  	f := s.Type().Field(1)
   965  	if f.Offset != offs {
   966  		t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
   967  	}
   968  }
   969  
   970  // Check that structure alignment & offsets viewed through reflect agree with those
   971  // from the compiler itself.
   972  func TestAlignment(t *testing.T) {
   973  	type T1inner struct {
   974  		a int
   975  	}
   976  	type T1 struct {
   977  		T1inner
   978  		f int
   979  	}
   980  	type T2inner struct {
   981  		a, b int
   982  	}
   983  	type T2 struct {
   984  		T2inner
   985  		f int
   986  	}
   987  
   988  	x := T1{T1inner: T1inner{a: 2}, f: 17}
   989  	check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
   990  
   991  	x1 := T2{T2inner: T2inner{a: 2, b: 3}, f: 17}
   992  	check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
   993  }
   994  
   995  func Nil(a any, t *testing.T) {
   996  	n := ValueOf(a).Field(0)
   997  	if !n.IsNil() {
   998  		t.Errorf("%v should be nil", a)
   999  	}
  1000  }
  1001  
  1002  func NotNil(a any, t *testing.T) {
  1003  	n := ValueOf(a).Field(0)
  1004  	if n.IsNil() {
  1005  		t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
  1006  	}
  1007  }
  1008  
  1009  func TestIsNil(t *testing.T) {
  1010  	// These implement IsNil.
  1011  	// Wrap in extra struct to hide interface type.
  1012  	doNil := []any{
  1013  		struct{ x *int }{},
  1014  		struct{ x any }{},
  1015  		struct{ x map[string]int }{},
  1016  		struct{ x func() bool }{},
  1017  		struct{ x chan int }{},
  1018  		struct{ x []string }{},
  1019  		struct{ x unsafe.Pointer }{},
  1020  	}
  1021  	for _, ts := range doNil {
  1022  		ty := TypeOf(ts).Field(0).Type
  1023  		v := Zero(ty)
  1024  		v.IsNil() // panics if not okay to call
  1025  	}
  1026  
  1027  	// Check the implementations
  1028  	var pi struct {
  1029  		x *int
  1030  	}
  1031  	Nil(pi, t)
  1032  	pi.x = new(int)
  1033  	NotNil(pi, t)
  1034  
  1035  	var si struct {
  1036  		x []int
  1037  	}
  1038  	Nil(si, t)
  1039  	si.x = make([]int, 10)
  1040  	NotNil(si, t)
  1041  
  1042  	var ci struct {
  1043  		x chan int
  1044  	}
  1045  	Nil(ci, t)
  1046  	ci.x = make(chan int)
  1047  	NotNil(ci, t)
  1048  
  1049  	var mi struct {
  1050  		x map[int]int
  1051  	}
  1052  	Nil(mi, t)
  1053  	mi.x = make(map[int]int)
  1054  	NotNil(mi, t)
  1055  
  1056  	var ii struct {
  1057  		x any
  1058  	}
  1059  	Nil(ii, t)
  1060  	ii.x = 2
  1061  	NotNil(ii, t)
  1062  
  1063  	var fi struct {
  1064  		x func(t *testing.T)
  1065  	}
  1066  	Nil(fi, t)
  1067  	fi.x = TestIsNil
  1068  	NotNil(fi, t)
  1069  }
  1070  
  1071  func TestInterfaceExtraction(t *testing.T) {
  1072  	var s struct {
  1073  		W io.Writer
  1074  	}
  1075  
  1076  	s.W = os.Stdout
  1077  	v := Indirect(ValueOf(&s)).Field(0).Interface()
  1078  	if v != s.W.(any) {
  1079  		t.Error("Interface() on interface: ", v, s.W)
  1080  	}
  1081  }
  1082  
  1083  func TestNilPtrValueSub(t *testing.T) {
  1084  	var pi *int
  1085  	if pv := ValueOf(pi); pv.Elem().IsValid() {
  1086  		t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
  1087  	}
  1088  }
  1089  
  1090  func TestMap(t *testing.T) {
  1091  	m := map[string]int{"a": 1, "b": 2}
  1092  	mv := ValueOf(m)
  1093  	if n := mv.Len(); n != len(m) {
  1094  		t.Errorf("Len = %d, want %d", n, len(m))
  1095  	}
  1096  	keys := mv.MapKeys()
  1097  	newmap := MakeMap(mv.Type())
  1098  	for k, v := range m {
  1099  		// Check that returned Keys match keys in range.
  1100  		// These aren't required to be in the same order.
  1101  		seen := false
  1102  		for _, kv := range keys {
  1103  			if kv.String() == k {
  1104  				seen = true
  1105  				break
  1106  			}
  1107  		}
  1108  		if !seen {
  1109  			t.Errorf("Missing key %q", k)
  1110  		}
  1111  
  1112  		// Check that value lookup is correct.
  1113  		vv := mv.MapIndex(ValueOf(k))
  1114  		if vi := vv.Int(); vi != int64(v) {
  1115  			t.Errorf("Key %q: have value %d, want %d", k, vi, v)
  1116  		}
  1117  
  1118  		// Copy into new map.
  1119  		newmap.SetMapIndex(ValueOf(k), ValueOf(v))
  1120  	}
  1121  	vv := mv.MapIndex(ValueOf("not-present"))
  1122  	if vv.IsValid() {
  1123  		t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
  1124  	}
  1125  
  1126  	newm := newmap.Interface().(map[string]int)
  1127  	if len(newm) != len(m) {
  1128  		t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
  1129  	}
  1130  
  1131  	for k, v := range newm {
  1132  		mv, ok := m[k]
  1133  		if mv != v {
  1134  			t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
  1135  		}
  1136  	}
  1137  
  1138  	newmap.SetMapIndex(ValueOf("a"), Value{})
  1139  	v, ok := newm["a"]
  1140  	if ok {
  1141  		t.Errorf("newm[\"a\"] = %d after delete", v)
  1142  	}
  1143  
  1144  	mv = ValueOf(&m).Elem()
  1145  	mv.Set(Zero(mv.Type()))
  1146  	if m != nil {
  1147  		t.Errorf("mv.Set(nil) failed")
  1148  	}
  1149  }
  1150  
  1151  func TestNilMap(t *testing.T) {
  1152  	var m map[string]int
  1153  	mv := ValueOf(m)
  1154  	keys := mv.MapKeys()
  1155  	if len(keys) != 0 {
  1156  		t.Errorf(">0 keys for nil map: %v", keys)
  1157  	}
  1158  
  1159  	// Check that value for missing key is zero.
  1160  	x := mv.MapIndex(ValueOf("hello"))
  1161  	if x.Kind() != Invalid {
  1162  		t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
  1163  	}
  1164  
  1165  	// Check big value too.
  1166  	var mbig map[string][10 << 20]byte
  1167  	x = ValueOf(mbig).MapIndex(ValueOf("hello"))
  1168  	if x.Kind() != Invalid {
  1169  		t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
  1170  	}
  1171  
  1172  	// Test that deletes from a nil map succeed.
  1173  	mv.SetMapIndex(ValueOf("hi"), Value{})
  1174  }
  1175  
  1176  func TestChan(t *testing.T) {
  1177  	for loop := 0; loop < 2; loop++ {
  1178  		var c chan int
  1179  		var cv Value
  1180  
  1181  		// check both ways to allocate channels
  1182  		switch loop {
  1183  		case 1:
  1184  			c = make(chan int, 1)
  1185  			cv = ValueOf(c)
  1186  		case 0:
  1187  			cv = MakeChan(TypeOf(c), 1)
  1188  			c = cv.Interface().(chan int)
  1189  		}
  1190  
  1191  		// Send
  1192  		cv.Send(ValueOf(2))
  1193  		if i := <-c; i != 2 {
  1194  			t.Errorf("reflect Send 2, native recv %d", i)
  1195  		}
  1196  
  1197  		// Recv
  1198  		c <- 3
  1199  		if i, ok := cv.Recv(); i.Int() != 3 || !ok {
  1200  			t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
  1201  		}
  1202  
  1203  		// TryRecv fail
  1204  		val, ok := cv.TryRecv()
  1205  		if val.IsValid() || ok {
  1206  			t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
  1207  		}
  1208  
  1209  		// TryRecv success
  1210  		c <- 4
  1211  		val, ok = cv.TryRecv()
  1212  		if !val.IsValid() {
  1213  			t.Errorf("TryRecv on ready chan got nil")
  1214  		} else if i := val.Int(); i != 4 || !ok {
  1215  			t.Errorf("native send 4, TryRecv %d, %t", i, ok)
  1216  		}
  1217  
  1218  		// TrySend fail
  1219  		c <- 100
  1220  		ok = cv.TrySend(ValueOf(5))
  1221  		i := <-c
  1222  		if ok {
  1223  			t.Errorf("TrySend on full chan succeeded: value %d", i)
  1224  		}
  1225  
  1226  		// TrySend success
  1227  		ok = cv.TrySend(ValueOf(6))
  1228  		if !ok {
  1229  			t.Errorf("TrySend on empty chan failed")
  1230  			select {
  1231  			case x := <-c:
  1232  				t.Errorf("TrySend failed but it did send %d", x)
  1233  			default:
  1234  			}
  1235  		} else {
  1236  			if i = <-c; i != 6 {
  1237  				t.Errorf("TrySend 6, recv %d", i)
  1238  			}
  1239  		}
  1240  
  1241  		// Close
  1242  		c <- 123
  1243  		cv.Close()
  1244  		if i, ok := cv.Recv(); i.Int() != 123 || !ok {
  1245  			t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
  1246  		}
  1247  		if i, ok := cv.Recv(); i.Int() != 0 || ok {
  1248  			t.Errorf("after close Recv %d, %t", i.Int(), ok)
  1249  		}
  1250  	}
  1251  
  1252  	// check creation of unbuffered channel
  1253  	var c chan int
  1254  	cv := MakeChan(TypeOf(c), 0)
  1255  	c = cv.Interface().(chan int)
  1256  	if cv.TrySend(ValueOf(7)) {
  1257  		t.Errorf("TrySend on sync chan succeeded")
  1258  	}
  1259  	if v, ok := cv.TryRecv(); v.IsValid() || ok {
  1260  		t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
  1261  	}
  1262  
  1263  	// len/cap
  1264  	cv = MakeChan(TypeOf(c), 10)
  1265  	c = cv.Interface().(chan int)
  1266  	for i := 0; i < 3; i++ {
  1267  		c <- i
  1268  	}
  1269  	if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
  1270  		t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
  1271  	}
  1272  }
  1273  
  1274  // caseInfo describes a single case in a select test.
  1275  type caseInfo struct {
  1276  	desc      string
  1277  	canSelect bool
  1278  	recv      Value
  1279  	closed    bool
  1280  	helper    func()
  1281  	panic     bool
  1282  }
  1283  
  1284  var allselect = flag.Bool("allselect", false, "exhaustive select test")
  1285  
  1286  func TestSelect(t *testing.T) {
  1287  	selectWatch.once.Do(func() { go selectWatcher() })
  1288  
  1289  	var x exhaustive
  1290  	nch := 0
  1291  	newop := func(n int, cap int) (ch, val Value) {
  1292  		nch++
  1293  		if nch%101%2 == 1 {
  1294  			c := make(chan int, cap)
  1295  			ch = ValueOf(c)
  1296  			val = ValueOf(n)
  1297  		} else {
  1298  			c := make(chan string, cap)
  1299  			ch = ValueOf(c)
  1300  			val = ValueOf(fmt.Sprint(n))
  1301  		}
  1302  		return
  1303  	}
  1304  
  1305  	for n := 0; x.Next(); n++ {
  1306  		if testing.Short() && n >= 1000 {
  1307  			break
  1308  		}
  1309  		if n >= 100000 && !*allselect {
  1310  			break
  1311  		}
  1312  		if n%100000 == 0 && testing.Verbose() {
  1313  			println("TestSelect", n)
  1314  		}
  1315  		var cases []SelectCase
  1316  		var info []caseInfo
  1317  
  1318  		// Ready send.
  1319  		if x.Maybe() {
  1320  			ch, val := newop(len(cases), 1)
  1321  			cases = append(cases, SelectCase{
  1322  				Dir:  SelectSend,
  1323  				Chan: ch,
  1324  				Send: val,
  1325  			})
  1326  			info = append(info, caseInfo{desc: "ready send", canSelect: true})
  1327  		}
  1328  
  1329  		// Ready recv.
  1330  		if x.Maybe() {
  1331  			ch, val := newop(len(cases), 1)
  1332  			ch.Send(val)
  1333  			cases = append(cases, SelectCase{
  1334  				Dir:  SelectRecv,
  1335  				Chan: ch,
  1336  			})
  1337  			info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
  1338  		}
  1339  
  1340  		// Blocking send.
  1341  		if x.Maybe() {
  1342  			ch, val := newop(len(cases), 0)
  1343  			cases = append(cases, SelectCase{
  1344  				Dir:  SelectSend,
  1345  				Chan: ch,
  1346  				Send: val,
  1347  			})
  1348  			// Let it execute?
  1349  			if x.Maybe() {
  1350  				f := func() { ch.Recv() }
  1351  				info = append(info, caseInfo{desc: "blocking send", helper: f})
  1352  			} else {
  1353  				info = append(info, caseInfo{desc: "blocking send"})
  1354  			}
  1355  		}
  1356  
  1357  		// Blocking recv.
  1358  		if x.Maybe() {
  1359  			ch, val := newop(len(cases), 0)
  1360  			cases = append(cases, SelectCase{
  1361  				Dir:  SelectRecv,
  1362  				Chan: ch,
  1363  			})
  1364  			// Let it execute?
  1365  			if x.Maybe() {
  1366  				f := func() { ch.Send(val) }
  1367  				info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
  1368  			} else {
  1369  				info = append(info, caseInfo{desc: "blocking recv"})
  1370  			}
  1371  		}
  1372  
  1373  		// Zero Chan send.
  1374  		if x.Maybe() {
  1375  			// Maybe include value to send.
  1376  			var val Value
  1377  			if x.Maybe() {
  1378  				val = ValueOf(100)
  1379  			}
  1380  			cases = append(cases, SelectCase{
  1381  				Dir:  SelectSend,
  1382  				Send: val,
  1383  			})
  1384  			info = append(info, caseInfo{desc: "zero Chan send"})
  1385  		}
  1386  
  1387  		// Zero Chan receive.
  1388  		if x.Maybe() {
  1389  			cases = append(cases, SelectCase{
  1390  				Dir: SelectRecv,
  1391  			})
  1392  			info = append(info, caseInfo{desc: "zero Chan recv"})
  1393  		}
  1394  
  1395  		// nil Chan send.
  1396  		if x.Maybe() {
  1397  			cases = append(cases, SelectCase{
  1398  				Dir:  SelectSend,
  1399  				Chan: ValueOf((chan int)(nil)),
  1400  				Send: ValueOf(101),
  1401  			})
  1402  			info = append(info, caseInfo{desc: "nil Chan send"})
  1403  		}
  1404  
  1405  		// nil Chan recv.
  1406  		if x.Maybe() {
  1407  			cases = append(cases, SelectCase{
  1408  				Dir:  SelectRecv,
  1409  				Chan: ValueOf((chan int)(nil)),
  1410  			})
  1411  			info = append(info, caseInfo{desc: "nil Chan recv"})
  1412  		}
  1413  
  1414  		// closed Chan send.
  1415  		if x.Maybe() {
  1416  			ch := make(chan int)
  1417  			close(ch)
  1418  			cases = append(cases, SelectCase{
  1419  				Dir:  SelectSend,
  1420  				Chan: ValueOf(ch),
  1421  				Send: ValueOf(101),
  1422  			})
  1423  			info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
  1424  		}
  1425  
  1426  		// closed Chan recv.
  1427  		if x.Maybe() {
  1428  			ch, val := newop(len(cases), 0)
  1429  			ch.Close()
  1430  			val = Zero(val.Type())
  1431  			cases = append(cases, SelectCase{
  1432  				Dir:  SelectRecv,
  1433  				Chan: ch,
  1434  			})
  1435  			info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
  1436  		}
  1437  
  1438  		var helper func() // goroutine to help the select complete
  1439  
  1440  		// Add default? Must be last case here, but will permute.
  1441  		// Add the default if the select would otherwise
  1442  		// block forever, and maybe add it anyway.
  1443  		numCanSelect := 0
  1444  		canProceed := false
  1445  		canBlock := true
  1446  		canPanic := false
  1447  		helpers := []int{}
  1448  		for i, c := range info {
  1449  			if c.canSelect {
  1450  				canProceed = true
  1451  				canBlock = false
  1452  				numCanSelect++
  1453  				if c.panic {
  1454  					canPanic = true
  1455  				}
  1456  			} else if c.helper != nil {
  1457  				canProceed = true
  1458  				helpers = append(helpers, i)
  1459  			}
  1460  		}
  1461  		if !canProceed || x.Maybe() {
  1462  			cases = append(cases, SelectCase{
  1463  				Dir: SelectDefault,
  1464  			})
  1465  			info = append(info, caseInfo{desc: "default", canSelect: canBlock})
  1466  			numCanSelect++
  1467  		} else if canBlock {
  1468  			// Select needs to communicate with another goroutine.
  1469  			cas := &info[helpers[x.Choose(len(helpers))]]
  1470  			helper = cas.helper
  1471  			cas.canSelect = true
  1472  			numCanSelect++
  1473  		}
  1474  
  1475  		// Permute cases and case info.
  1476  		// Doing too much here makes the exhaustive loop
  1477  		// too exhausting, so just do two swaps.
  1478  		for loop := 0; loop < 2; loop++ {
  1479  			i := x.Choose(len(cases))
  1480  			j := x.Choose(len(cases))
  1481  			cases[i], cases[j] = cases[j], cases[i]
  1482  			info[i], info[j] = info[j], info[i]
  1483  		}
  1484  
  1485  		if helper != nil {
  1486  			// We wait before kicking off a goroutine to satisfy a blocked select.
  1487  			// The pause needs to be big enough to let the select block before
  1488  			// we run the helper, but if we lose that race once in a while it's okay: the
  1489  			// select will just proceed immediately. Not a big deal.
  1490  			// For short tests we can grow [sic] the timeout a bit without fear of taking too long
  1491  			pause := 10 * time.Microsecond
  1492  			if testing.Short() {
  1493  				pause = 100 * time.Microsecond
  1494  			}
  1495  			time.AfterFunc(pause, helper)
  1496  		}
  1497  
  1498  		// Run select.
  1499  		i, recv, recvOK, panicErr := runSelect(cases, info)
  1500  		if panicErr != nil && !canPanic {
  1501  			t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
  1502  		}
  1503  		if panicErr == nil && canPanic && numCanSelect == 1 {
  1504  			t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
  1505  		}
  1506  		if panicErr != nil {
  1507  			continue
  1508  		}
  1509  
  1510  		cas := info[i]
  1511  		if !cas.canSelect {
  1512  			recvStr := ""
  1513  			if recv.IsValid() {
  1514  				recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
  1515  			}
  1516  			t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
  1517  			continue
  1518  		}
  1519  		if cas.panic {
  1520  			t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
  1521  			continue
  1522  		}
  1523  
  1524  		if cases[i].Dir == SelectRecv {
  1525  			if !recv.IsValid() {
  1526  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
  1527  			}
  1528  			if !cas.recv.IsValid() {
  1529  				t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
  1530  			}
  1531  			if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
  1532  				if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
  1533  					t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
  1534  				}
  1535  				t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
  1536  			}
  1537  		} else {
  1538  			if recv.IsValid() || recvOK {
  1539  				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
  1540  			}
  1541  		}
  1542  	}
  1543  }
  1544  
  1545  // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
  1546  // If the selectWatcher notices that the select has been blocked for >1 second, it prints
  1547  // an error describing the select and panics the entire test binary.
  1548  var selectWatch struct {
  1549  	sync.Mutex
  1550  	once sync.Once
  1551  	now  time.Time
  1552  	info []caseInfo
  1553  }
  1554  
  1555  func selectWatcher() {
  1556  	for {
  1557  		time.Sleep(1 * time.Second)
  1558  		selectWatch.Lock()
  1559  		if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
  1560  			fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
  1561  			panic("select stuck")
  1562  		}
  1563  		selectWatch.Unlock()
  1564  	}
  1565  }
  1566  
  1567  // runSelect runs a single select test.
  1568  // It returns the values returned by Select but also returns
  1569  // a panic value if the Select panics.
  1570  func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
  1571  	defer func() {
  1572  		panicErr = recover()
  1573  
  1574  		selectWatch.Lock()
  1575  		selectWatch.info = nil
  1576  		selectWatch.Unlock()
  1577  	}()
  1578  
  1579  	selectWatch.Lock()
  1580  	selectWatch.now = time.Now()
  1581  	selectWatch.info = info
  1582  	selectWatch.Unlock()
  1583  
  1584  	chosen, recv, recvOK = Select(cases)
  1585  	return
  1586  }
  1587  
  1588  // fmtSelect formats the information about a single select test.
  1589  func fmtSelect(info []caseInfo) string {
  1590  	var buf bytes.Buffer
  1591  	fmt.Fprint(&buf, "\nselect {\n")
  1592  	for i, cas := range info {
  1593  		fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
  1594  		if cas.recv.IsValid() {
  1595  			fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
  1596  		}
  1597  		if cas.canSelect {
  1598  			fmt.Fprint(&buf, " canselect")
  1599  		}
  1600  		if cas.panic {
  1601  			fmt.Fprint(&buf, " panic")
  1602  		}
  1603  		fmt.Fprint(&buf, "\n")
  1604  	}
  1605  	fmt.Fprint(&buf, "}")
  1606  	return buf.String()
  1607  }
  1608  
  1609  type two [2]uintptr
  1610  
  1611  // Difficult test for function call because of
  1612  // implicit padding between arguments.
  1613  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) {
  1614  	return b, c, d, e, f, g, h
  1615  }
  1616  
  1617  func TestFunc(t *testing.T) {
  1618  	ret := ValueOf(dummy).Call([]Value{
  1619  		ValueOf(byte(10)),
  1620  		ValueOf(20),
  1621  		ValueOf(byte(30)),
  1622  		ValueOf(two{40, 50}),
  1623  		ValueOf(byte(60)),
  1624  		ValueOf(float32(70)),
  1625  		ValueOf(byte(80)),
  1626  	})
  1627  	if len(ret) != 7 {
  1628  		t.Fatalf("Call returned %d values, want 7", len(ret))
  1629  	}
  1630  
  1631  	i := byte(ret[0].Uint())
  1632  	j := int(ret[1].Int())
  1633  	k := byte(ret[2].Uint())
  1634  	l := ret[3].Interface().(two)
  1635  	m := byte(ret[4].Uint())
  1636  	n := float32(ret[5].Float())
  1637  	o := byte(ret[6].Uint())
  1638  
  1639  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1640  		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)
  1641  	}
  1642  
  1643  	for i, v := range ret {
  1644  		if v.CanAddr() {
  1645  			t.Errorf("result %d is addressable", i)
  1646  		}
  1647  	}
  1648  }
  1649  
  1650  func TestCallConvert(t *testing.T) {
  1651  	v := ValueOf(new(io.ReadWriter)).Elem()
  1652  	f := ValueOf(func(r io.Reader) io.Reader { return r })
  1653  	out := f.Call([]Value{v})
  1654  	if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
  1655  		t.Errorf("expected [nil], got %v", out)
  1656  	}
  1657  }
  1658  
  1659  type emptyStruct struct{}
  1660  
  1661  type nonEmptyStruct struct {
  1662  	member int
  1663  }
  1664  
  1665  func returnEmpty() emptyStruct {
  1666  	return emptyStruct{}
  1667  }
  1668  
  1669  func takesEmpty(e emptyStruct) {}
  1670  
  1671  func returnNonEmpty(i int) nonEmptyStruct {
  1672  	return nonEmptyStruct{member: i}
  1673  }
  1674  
  1675  func takesNonEmpty(n nonEmptyStruct) int {
  1676  	return n.member
  1677  }
  1678  
  1679  func TestCallWithStruct(t *testing.T) {
  1680  	r := ValueOf(returnEmpty).Call(nil)
  1681  	if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
  1682  		t.Errorf("returning empty struct returned %#v instead", r)
  1683  	}
  1684  	r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
  1685  	if len(r) != 0 {
  1686  		t.Errorf("takesEmpty returned values: %#v", r)
  1687  	}
  1688  	r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
  1689  	if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
  1690  		t.Errorf("returnNonEmpty returned %#v", r)
  1691  	}
  1692  	r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
  1693  	if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
  1694  		t.Errorf("takesNonEmpty returned %#v", r)
  1695  	}
  1696  }
  1697  
  1698  func TestCallReturnsEmpty(t *testing.T) {
  1699  	// Issue 21717: past-the-end pointer write in Call with
  1700  	// nonzero-sized frame and zero-sized return value.
  1701  	runtime.GC()
  1702  	var finalized uint32
  1703  	f := func() (emptyStruct, *[2]int64) {
  1704  		i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
  1705  		runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
  1706  		return emptyStruct{}, i
  1707  	}
  1708  	v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
  1709  	timeout := time.After(5 * time.Second)
  1710  	for atomic.LoadUint32(&finalized) == 0 {
  1711  		select {
  1712  		case <-timeout:
  1713  			t.Fatal("finalizer did not run")
  1714  		default:
  1715  		}
  1716  		runtime.Gosched()
  1717  		runtime.GC()
  1718  	}
  1719  	runtime.KeepAlive(v)
  1720  }
  1721  
  1722  func BenchmarkCall(b *testing.B) {
  1723  	fv := ValueOf(func(a, b string) {})
  1724  	b.ReportAllocs()
  1725  	b.RunParallel(func(pb *testing.PB) {
  1726  		args := []Value{ValueOf("a"), ValueOf("b")}
  1727  		for pb.Next() {
  1728  			fv.Call(args)
  1729  		}
  1730  	})
  1731  }
  1732  
  1733  func BenchmarkCallArgCopy(b *testing.B) {
  1734  	byteArray := func(n int) Value {
  1735  		return Zero(ArrayOf(n, TypeOf(byte(0))))
  1736  	}
  1737  	sizes := [...]struct {
  1738  		fv  Value
  1739  		arg Value
  1740  	}{
  1741  		{fv: ValueOf(func(a [128]byte) {}), arg: byteArray(128)},
  1742  		{fv: ValueOf(func(a [256]byte) {}), arg: byteArray(256)},
  1743  		{fv: ValueOf(func(a [1024]byte) {}), arg: byteArray(1024)},
  1744  		{fv: ValueOf(func(a [4096]byte) {}), arg: byteArray(4096)},
  1745  		{fv: ValueOf(func(a [65536]byte) {}), arg: byteArray(65536)},
  1746  	}
  1747  	for _, size := range sizes {
  1748  		bench := func(b *testing.B) {
  1749  			args := []Value{size.arg}
  1750  			b.SetBytes(int64(size.arg.Len()))
  1751  			b.ResetTimer()
  1752  			b.RunParallel(func(pb *testing.PB) {
  1753  				for pb.Next() {
  1754  					size.fv.Call(args)
  1755  				}
  1756  			})
  1757  		}
  1758  		name := fmt.Sprintf("size=%v", size.arg.Len())
  1759  		b.Run(name, bench)
  1760  	}
  1761  }
  1762  
  1763  func TestMakeFunc(t *testing.T) {
  1764  	f := dummy
  1765  	fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
  1766  	ValueOf(&f).Elem().Set(fv)
  1767  
  1768  	// Call g with small arguments so that there is
  1769  	// something predictable (and different from the
  1770  	// correct results) in those positions on the stack.
  1771  	g := dummy
  1772  	g(1, 2, 3, two{4, 5}, 6, 7, 8)
  1773  
  1774  	// Call constructed function f.
  1775  	i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
  1776  	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1777  		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)
  1778  	}
  1779  }
  1780  
  1781  func TestMakeFuncInterface(t *testing.T) {
  1782  	fn := func(i int) int { return i }
  1783  	incr := func(in []Value) []Value {
  1784  		return []Value{ValueOf(int(in[0].Int() + 1))}
  1785  	}
  1786  	fv := MakeFunc(TypeOf(fn), incr)
  1787  	ValueOf(&fn).Elem().Set(fv)
  1788  	if r := fn(2); r != 3 {
  1789  		t.Errorf("Call returned %d, want 3", r)
  1790  	}
  1791  	if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
  1792  		t.Errorf("Call returned %d, want 15", r)
  1793  	}
  1794  	if r := fv.Interface().(func(int) int)(26); r != 27 {
  1795  		t.Errorf("Call returned %d, want 27", r)
  1796  	}
  1797  }
  1798  
  1799  func TestMakeFuncVariadic(t *testing.T) {
  1800  	// Test that variadic arguments are packed into a slice and passed as last arg
  1801  	fn := func(_ int, is ...int) []int { return nil }
  1802  	fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
  1803  	ValueOf(&fn).Elem().Set(fv)
  1804  
  1805  	r := fn(1, 2, 3)
  1806  	if r[0] != 2 || r[1] != 3 {
  1807  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1808  	}
  1809  
  1810  	r = fn(1, []int{2, 3}...)
  1811  	if r[0] != 2 || r[1] != 3 {
  1812  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1813  	}
  1814  
  1815  	r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
  1816  	if r[0] != 2 || r[1] != 3 {
  1817  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1818  	}
  1819  
  1820  	r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
  1821  	if r[0] != 2 || r[1] != 3 {
  1822  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1823  	}
  1824  
  1825  	f := fv.Interface().(func(int, ...int) []int)
  1826  
  1827  	r = f(1, 2, 3)
  1828  	if r[0] != 2 || r[1] != 3 {
  1829  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1830  	}
  1831  	r = f(1, []int{2, 3}...)
  1832  	if r[0] != 2 || r[1] != 3 {
  1833  		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1834  	}
  1835  }
  1836  
  1837  type Point struct {
  1838  	x, y int
  1839  }
  1840  
  1841  // This will be index 0.
  1842  func (p Point) AnotherMethod(scale int) int {
  1843  	return -1
  1844  }
  1845  
  1846  // This will be index 1.
  1847  func (p Point) Dist(scale int) int {
  1848  	// println("Point.Dist", p.x, p.y, scale)
  1849  	return p.x*p.x*scale + p.y*p.y*scale
  1850  }
  1851  
  1852  // This will be index 2.
  1853  func (p Point) GCMethod(k int) int {
  1854  	runtime.GC()
  1855  	return k + p.x
  1856  }
  1857  
  1858  // This will be index 3.
  1859  func (p Point) NoArgs() {
  1860  	// Exercise no-argument/no-result paths.
  1861  }
  1862  
  1863  // This will be index 4.
  1864  func (p Point) TotalDist(points ...Point) int {
  1865  	tot := 0
  1866  	for _, q := range points {
  1867  		dx := q.x - p.x
  1868  		dy := q.y - p.y
  1869  		tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
  1870  	}
  1871  	return tot
  1872  }
  1873  
  1874  func TestMethod(t *testing.T) {
  1875  	// Non-curried method of type.
  1876  	p := Point{x: 3, y: 4}
  1877  	i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
  1878  	if i != 250 {
  1879  		t.Errorf("Type Method returned %d; want 250", i)
  1880  	}
  1881  
  1882  	m, ok := TypeOf(p).MethodByName("Dist")
  1883  	if !ok {
  1884  		t.Fatalf("method by name failed")
  1885  	}
  1886  	i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
  1887  	if i != 275 {
  1888  		t.Errorf("Type MethodByName returned %d; want 275", i)
  1889  	}
  1890  
  1891  	m, ok = TypeOf(p).MethodByName("NoArgs")
  1892  	if !ok {
  1893  		t.Fatalf("method by name failed")
  1894  	}
  1895  	n := len(m.Func.Call([]Value{ValueOf(p)}))
  1896  	if n != 0 {
  1897  		t.Errorf("NoArgs returned %d values; want 0", n)
  1898  	}
  1899  
  1900  	i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
  1901  	if i != 300 {
  1902  		t.Errorf("Pointer Type Method returned %d; want 300", i)
  1903  	}
  1904  
  1905  	m, ok = TypeOf(&p).MethodByName("Dist")
  1906  	if !ok {
  1907  		t.Fatalf("ptr method by name failed")
  1908  	}
  1909  	i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
  1910  	if i != 325 {
  1911  		t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
  1912  	}
  1913  
  1914  	m, ok = TypeOf(&p).MethodByName("NoArgs")
  1915  	if !ok {
  1916  		t.Fatalf("method by name failed")
  1917  	}
  1918  	n = len(m.Func.Call([]Value{ValueOf(&p)}))
  1919  	if n != 0 {
  1920  		t.Errorf("NoArgs returned %d values; want 0", n)
  1921  	}
  1922  
  1923  	// Curried method of value.
  1924  	tfunc := TypeOf((func(int) int)(nil))
  1925  	v := ValueOf(p).Method(1)
  1926  	if tt := v.Type(); tt != tfunc {
  1927  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1928  	}
  1929  	i = v.Call([]Value{ValueOf(14)})[0].Int()
  1930  	if i != 350 {
  1931  		t.Errorf("Value Method returned %d; want 350", i)
  1932  	}
  1933  	v = ValueOf(p).MethodByName("Dist")
  1934  	if tt := v.Type(); tt != tfunc {
  1935  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1936  	}
  1937  	i = v.Call([]Value{ValueOf(15)})[0].Int()
  1938  	if i != 375 {
  1939  		t.Errorf("Value MethodByName returned %d; want 375", i)
  1940  	}
  1941  	v = ValueOf(p).MethodByName("NoArgs")
  1942  	v.Call(nil)
  1943  
  1944  	// Curried method of pointer.
  1945  	v = ValueOf(&p).Method(1)
  1946  	if tt := v.Type(); tt != tfunc {
  1947  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1948  	}
  1949  	i = v.Call([]Value{ValueOf(16)})[0].Int()
  1950  	if i != 400 {
  1951  		t.Errorf("Pointer Value Method returned %d; want 400", i)
  1952  	}
  1953  	v = ValueOf(&p).MethodByName("Dist")
  1954  	if tt := v.Type(); tt != tfunc {
  1955  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1956  	}
  1957  	i = v.Call([]Value{ValueOf(17)})[0].Int()
  1958  	if i != 425 {
  1959  		t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
  1960  	}
  1961  	v = ValueOf(&p).MethodByName("NoArgs")
  1962  	v.Call(nil)
  1963  
  1964  	// Curried method of interface value.
  1965  	// Have to wrap interface value in a struct to get at it.
  1966  	// Passing it to ValueOf directly would
  1967  	// access the underlying Point, not the interface.
  1968  	var x interface {
  1969  		Dist(int) int
  1970  	} = p
  1971  	pv := ValueOf(&x).Elem()
  1972  	v = pv.Method(0)
  1973  	if tt := v.Type(); tt != tfunc {
  1974  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1975  	}
  1976  	i = v.Call([]Value{ValueOf(18)})[0].Int()
  1977  	if i != 450 {
  1978  		t.Errorf("Interface Method returned %d; want 450", i)
  1979  	}
  1980  	v = pv.MethodByName("Dist")
  1981  	if tt := v.Type(); tt != tfunc {
  1982  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1983  	}
  1984  	i = v.Call([]Value{ValueOf(19)})[0].Int()
  1985  	if i != 475 {
  1986  		t.Errorf("Interface MethodByName returned %d; want 475", i)
  1987  	}
  1988  }
  1989  
  1990  func TestMethodValue(t *testing.T) {
  1991  	p := Point{x: 3, y: 4}
  1992  	var i int64
  1993  
  1994  	// Curried method of value.
  1995  	tfunc := TypeOf((func(int) int)(nil))
  1996  	v := ValueOf(p).Method(1)
  1997  	if tt := v.Type(); tt != tfunc {
  1998  		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1999  	}
  2000  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
  2001  	if i != 250 {
  2002  		t.Errorf("Value Method returned %d; want 250", i)
  2003  	}
  2004  	v = ValueOf(p).MethodByName("Dist")
  2005  	if tt := v.Type(); tt != tfunc {
  2006  		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  2007  	}
  2008  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
  2009  	if i != 275 {
  2010  		t.Errorf("Value MethodByName returned %d; want 275", i)
  2011  	}
  2012  	v = ValueOf(p).MethodByName("NoArgs")
  2013  	ValueOf(v.Interface()).Call(nil)
  2014  	v.Interface().(func())()
  2015  
  2016  	// Curried method of pointer.
  2017  	v = ValueOf(&p).Method(1)
  2018  	if tt := v.Type(); tt != tfunc {
  2019  		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  2020  	}
  2021  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
  2022  	if i != 300 {
  2023  		t.Errorf("Pointer Value Method returned %d; want 300", i)
  2024  	}
  2025  	v = ValueOf(&p).MethodByName("Dist")
  2026  	if tt := v.Type(); tt != tfunc {
  2027  		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  2028  	}
  2029  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
  2030  	if i != 325 {
  2031  		t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
  2032  	}
  2033  	v = ValueOf(&p).MethodByName("NoArgs")
  2034  	ValueOf(v.Interface()).Call(nil)
  2035  	v.Interface().(func())()
  2036  
  2037  	// Curried method of pointer to pointer.
  2038  	pp := &p
  2039  	v = ValueOf(&pp).Elem().Method(1)
  2040  	if tt := v.Type(); tt != tfunc {
  2041  		t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
  2042  	}
  2043  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
  2044  	if i != 350 {
  2045  		t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
  2046  	}
  2047  	v = ValueOf(&pp).Elem().MethodByName("Dist")
  2048  	if tt := v.Type(); tt != tfunc {
  2049  		t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  2050  	}
  2051  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
  2052  	if i != 375 {
  2053  		t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
  2054  	}
  2055  
  2056  	// Curried method of interface value.
  2057  	// Have to wrap interface value in a struct to get at it.
  2058  	// Passing it to ValueOf directly would
  2059  	// access the underlying Point, not the interface.
  2060  	var s = struct {
  2061  		X interface {
  2062  			Dist(int) int
  2063  		}
  2064  	}{X: p}
  2065  	pv := ValueOf(s).Field(0)
  2066  	v = pv.Method(0)
  2067  	if tt := v.Type(); tt != tfunc {
  2068  		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  2069  	}
  2070  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
  2071  	if i != 400 {
  2072  		t.Errorf("Interface Method returned %d; want 400", i)
  2073  	}
  2074  	v = pv.MethodByName("Dist")
  2075  	if tt := v.Type(); tt != tfunc {
  2076  		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  2077  	}
  2078  	i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
  2079  	if i != 425 {
  2080  		t.Errorf("Interface MethodByName returned %d; want 425", i)
  2081  	}
  2082  }
  2083  
  2084  func TestVariadicMethodValue(t *testing.T) {
  2085  	p := Point{x: 3, y: 4}
  2086  	points := []Point{{x: 20, y: 21}, {x: 22, y: 23}, {x: 24, y: 25}}
  2087  	want := int64(p.TotalDist(points[0], points[1], points[2]))
  2088  
  2089  	// Curried method of value.
  2090  	tfunc := TypeOf((func(...Point) int)(nil))
  2091  	v := ValueOf(p).Method(4)
  2092  	if tt := v.Type(); tt != tfunc {
  2093  		t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
  2094  	}
  2095  	i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
  2096  	if i != want {
  2097  		t.Errorf("Variadic Method returned %d; want %d", i, want)
  2098  	}
  2099  	i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
  2100  	if i != want {
  2101  		t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
  2102  	}
  2103  
  2104  	f := v.Interface().(func(...Point) int)
  2105  	i = int64(f(points[0], points[1], points[2]))
  2106  	if i != want {
  2107  		t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
  2108  	}
  2109  	i = int64(f(points...))
  2110  	if i != want {
  2111  		t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
  2112  	}
  2113  }
  2114  
  2115  // Reflect version of $GOROOT/test/method5.go
  2116  
  2117  // Concrete types implementing M method.
  2118  // Smaller than a word, word-sized, larger than a word.
  2119  // Value and pointer receivers.
  2120  
  2121  type Tinter interface {
  2122  	M(int, byte) (byte, int)
  2123  }
  2124  
  2125  type Tsmallv byte
  2126  
  2127  func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  2128  
  2129  type Tsmallp byte
  2130  
  2131  func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  2132  
  2133  type Twordv uintptr
  2134  
  2135  func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  2136  
  2137  type Twordp uintptr
  2138  
  2139  func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  2140  
  2141  type Tbigv [2]uintptr
  2142  
  2143  func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  2144  
  2145  type Tbigp [2]uintptr
  2146  
  2147  func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  2148  
  2149  type tinter interface {
  2150  	m(int, byte) (byte, int)
  2151  }
  2152  
  2153  // Embedding via pointer.
  2154  
  2155  type Tm1 struct {
  2156  	Tm2
  2157  }
  2158  
  2159  type Tm2 struct {
  2160  	*Tm3
  2161  }
  2162  
  2163  type Tm3 struct {
  2164  	*Tm4
  2165  }
  2166  
  2167  type Tm4 struct {
  2168  }
  2169  
  2170  func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
  2171  
  2172  func TestMethod5(t *testing.T) {
  2173  	CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
  2174  		b, x := f(1000, 99)
  2175  		if b != 99 || x != 1000+inc {
  2176  			t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  2177  		}
  2178  	}
  2179  
  2180  	CheckV := func(name string, i Value, inc int) {
  2181  		bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
  2182  		b := bx[0].Interface()
  2183  		x := bx[1].Interface()
  2184  		if b != byte(99) || x != 1000+inc {
  2185  			t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  2186  		}
  2187  
  2188  		CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
  2189  	}
  2190  
  2191  	var TinterType = TypeOf(new(Tinter)).Elem()
  2192  
  2193  	CheckI := func(name string, i any, inc int) {
  2194  		v := ValueOf(i)
  2195  		CheckV(name, v, inc)
  2196  		CheckV("(i="+name+")", v.Convert(TinterType), inc)
  2197  	}
  2198  
  2199  	sv := Tsmallv(1)
  2200  	CheckI("sv", sv, 1)
  2201  	CheckI("&sv", &sv, 1)
  2202  
  2203  	sp := Tsmallp(2)
  2204  	CheckI("&sp", &sp, 2)
  2205  
  2206  	wv := Twordv(3)
  2207  	CheckI("wv", wv, 3)
  2208  	CheckI("&wv", &wv, 3)
  2209  
  2210  	wp := Twordp(4)
  2211  	CheckI("&wp", &wp, 4)
  2212  
  2213  	bv := Tbigv([2]uintptr{5, 6})
  2214  	CheckI("bv", bv, 11)
  2215  	CheckI("&bv", &bv, 11)
  2216  
  2217  	bp := Tbigp([2]uintptr{7, 8})
  2218  	CheckI("&bp", &bp, 15)
  2219  
  2220  	t4 := Tm4{}
  2221  	t3 := Tm3{Tm4: &t4}
  2222  	t2 := Tm2{Tm3: &t3}
  2223  	t1 := Tm1{Tm2: t2}
  2224  	CheckI("t4", t4, 40)
  2225  	CheckI("&t4", &t4, 40)
  2226  	CheckI("t3", t3, 40)
  2227  	CheckI("&t3", &t3, 40)
  2228  	CheckI("t2", t2, 40)
  2229  	CheckI("&t2", &t2, 40)
  2230  	CheckI("t1", t1, 40)
  2231  	CheckI("&t1", &t1, 40)
  2232  
  2233  	var tnil Tinter
  2234  	vnil := ValueOf(&tnil).Elem()
  2235  	shouldPanic(func() { vnil.Method(0) })
  2236  }
  2237  
  2238  func TestInterfaceSet(t *testing.T) {
  2239  	p := &Point{x: 3, y: 4}
  2240  
  2241  	var s struct {
  2242  		I any
  2243  		P interface {
  2244  			Dist(int) int
  2245  		}
  2246  	}
  2247  	sv := ValueOf(&s).Elem()
  2248  	sv.Field(0).Set(ValueOf(p))
  2249  	if q := s.I.(*Point); q != p {
  2250  		t.Errorf("i: have %p want %p", q, p)
  2251  	}
  2252  
  2253  	pv := sv.Field(1)
  2254  	pv.Set(ValueOf(p))
  2255  	if q := s.P.(*Point); q != p {
  2256  		t.Errorf("i: have %p want %p", q, p)
  2257  	}
  2258  
  2259  	i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
  2260  	if i != 250 {
  2261  		t.Errorf("Interface Method returned %d; want 250", i)
  2262  	}
  2263  }
  2264  
  2265  type T1 struct {
  2266  	a string
  2267  	int
  2268  }
  2269  
  2270  func TestAnonymousFields(t *testing.T) {
  2271  	var field StructField
  2272  	var ok bool
  2273  	var t1 T1
  2274  	type1 := TypeOf(t1)
  2275  	if field, ok = type1.FieldByName("int"); !ok {
  2276  		t.Fatal("no field 'int'")
  2277  	}
  2278  	if field.Index[0] != 1 {
  2279  		t.Error("field index should be 1; is", field.Index)
  2280  	}
  2281  }
  2282  
  2283  type FTest struct {
  2284  	s     any
  2285  	name  string
  2286  	index []int
  2287  	value int
  2288  }
  2289  
  2290  type D1 struct {
  2291  	d int
  2292  }
  2293  
  2294  type D2 struct {
  2295  	d int
  2296  }
  2297  
  2298  type S0 struct {
  2299  	A, B, C int
  2300  	D1
  2301  	D2
  2302  }
  2303  
  2304  type S1 struct {
  2305  	B int
  2306  	S0
  2307  }
  2308  
  2309  type S2 struct {
  2310  	A int
  2311  	*S1
  2312  }
  2313  
  2314  type S1x struct {
  2315  	S1
  2316  }
  2317  
  2318  type S1y struct {
  2319  	S1
  2320  }
  2321  
  2322  type S3 struct {
  2323  	S1x
  2324  	S2
  2325  	D, E int
  2326  	*S1y
  2327  }
  2328  
  2329  type S4 struct {
  2330  	*S4
  2331  	A int
  2332  }
  2333  
  2334  // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
  2335  type S5 struct {
  2336  	S6
  2337  	S7
  2338  	S8
  2339  }
  2340  
  2341  type S6 struct {
  2342  	X int
  2343  }
  2344  
  2345  type S7 S6
  2346  
  2347  type S8 struct {
  2348  	S9
  2349  }
  2350  
  2351  type S9 struct {
  2352  	X int
  2353  	Y int
  2354  }
  2355  
  2356  // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
  2357  type S10 struct {
  2358  	S11
  2359  	S12
  2360  	S13
  2361  }
  2362  
  2363  type S11 struct {
  2364  	S6
  2365  }
  2366  
  2367  type S12 struct {
  2368  	S6
  2369  }
  2370  
  2371  type S13 struct {
  2372  	S8
  2373  }
  2374  
  2375  // The X in S15.S11.S1 and S16.S11.S1 annihilate.
  2376  type S14 struct {
  2377  	S15
  2378  	S16
  2379  }
  2380  
  2381  type S15 struct {
  2382  	S11
  2383  }
  2384  
  2385  type S16 struct {
  2386  	S11
  2387  }
  2388  
  2389  var fieldTests = []FTest{
  2390  	{s: struct{}{}, name: "", index: nil, value: 0},
  2391  	{s: struct{}{}, name: "Foo", index: nil, value: 0},
  2392  	{s: S0{A: 'a'}, name: "A", index: []int{0}, value: 'a'},
  2393  	{s: S0{}, name: "D", index: nil, value: 0},
  2394  	{s: S1{S0: S0{A: 'a'}}, name: "A", index: []int{1, 0}, value: 'a'},
  2395  	{s: S1{B: 'b'}, name: "B", index: []int{0}, value: 'b'},
  2396  	{s: S1{}, name: "S0", index: []int{1}, value: 0},
  2397  	{s: S1{S0: S0{C: 'c'}}, name: "C", index: []int{1, 2}, value: 'c'},
  2398  	{s: S2{A: 'a'}, name: "A", index: []int{0}, value: 'a'},
  2399  	{s: S2{}, name: "S1", index: []int{1}, value: 0},
  2400  	{s: S2{S1: &S1{B: 'b'}}, name: "B", index: []int{1, 0}, value: 'b'},
  2401  	{s: S2{S1: &S1{S0: S0{C: 'c'}}}, name: "C", index: []int{1, 1, 2}, value: 'c'},
  2402  	{s: S2{}, name: "D", index: nil, value: 0},
  2403  	{s: S3{}, name: "S1", index: nil, value: 0},
  2404  	{s: S3{S2: S2{A: 'a'}}, name: "A", index: []int{1, 0}, value: 'a'},
  2405  	{s: S3{}, name: "B", index: nil, value: 0},
  2406  	{s: S3{D: 'd'}, name: "D", index: []int{2}, value: 0},
  2407  	{s: S3{E: 'e'}, name: "E", index: []int{3}, value: 'e'},
  2408  	{s: S4{A: 'a'}, name: "A", index: []int{1}, value: 'a'},
  2409  	{s: S4{}, name: "B", index: nil, value: 0},
  2410  	{s: S5{}, name: "X", index: nil, value: 0},
  2411  	{s: S5{}, name: "Y", index: []int{2, 0, 1}, value: 0},
  2412  	{s: S10{}, name: "X", index: nil, value: 0},
  2413  	{s: S10{}, name: "Y", index: []int{2, 0, 0, 1}, value: 0},
  2414  	{s: S14{}, name: "X", index: nil, value: 0},
  2415  }
  2416  
  2417  func TestFieldByIndex(t *testing.T) {
  2418  	for _, test := range fieldTests {
  2419  		s := TypeOf(test.s)
  2420  		f := s.FieldByIndex(test.index)
  2421  		if f.Name != "" {
  2422  			if test.index != nil {
  2423  				if f.Name != test.name {
  2424  					t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
  2425  				}
  2426  			} else {
  2427  				t.Errorf("%s.%s found", s.Name(), f.Name)
  2428  			}
  2429  		} else if len(test.index) > 0 {
  2430  			t.Errorf("%s.%s not found", s.Name(), test.name)
  2431  		}
  2432  
  2433  		if test.value != 0 {
  2434  			v := ValueOf(test.s).FieldByIndex(test.index)
  2435  			if v.IsValid() {
  2436  				if x, ok := v.Interface().(int); ok {
  2437  					if x != test.value {
  2438  						t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
  2439  					}
  2440  				} else {
  2441  					t.Errorf("%s%v value not an int", s.Name(), test.index)
  2442  				}
  2443  			} else {
  2444  				t.Errorf("%s%v value not found", s.Name(), test.index)
  2445  			}
  2446  		}
  2447  	}
  2448  }
  2449  
  2450  func TestFieldByName(t *testing.T) {
  2451  	for _, test := range fieldTests {
  2452  		s := TypeOf(test.s)
  2453  		f, found := s.FieldByName(test.name)
  2454  		if found {
  2455  			if test.index != nil {
  2456  				// Verify field depth and index.
  2457  				if len(f.Index) != len(test.index) {
  2458  					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)
  2459  				} else {
  2460  					for i, x := range f.Index {
  2461  						if x != test.index[i] {
  2462  							t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
  2463  						}
  2464  					}
  2465  				}
  2466  			} else {
  2467  				t.Errorf("%s.%s found", s.Name(), f.Name)
  2468  			}
  2469  		} else if len(test.index) > 0 {
  2470  			t.Errorf("%s.%s not found", s.Name(), test.name)
  2471  		}
  2472  
  2473  		if test.value != 0 {
  2474  			v := ValueOf(test.s).FieldByName(test.name)
  2475  			if v.IsValid() {
  2476  				if x, ok := v.Interface().(int); ok {
  2477  					if x != test.value {
  2478  						t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
  2479  					}
  2480  				} else {
  2481  					t.Errorf("%s.%s value not an int", s.Name(), test.name)
  2482  				}
  2483  			} else {
  2484  				t.Errorf("%s.%s value not found", s.Name(), test.name)
  2485  			}
  2486  		}
  2487  	}
  2488  }
  2489  
  2490  func TestImportPath(t *testing.T) {
  2491  	tests := []struct {
  2492  		t    Type
  2493  		path string
  2494  	}{
  2495  		{t: TypeOf(&base64.Encoding{}).Elem(), path: "encoding/base64"},
  2496  		{t: TypeOf(int(0)), path: ""},
  2497  		{t: TypeOf(int8(0)), path: ""},
  2498  		{t: TypeOf(int16(0)), path: ""},
  2499  		{t: TypeOf(int32(0)), path: ""},
  2500  		{t: TypeOf(int64(0)), path: ""},
  2501  		{t: TypeOf(uint(0)), path: ""},
  2502  		{t: TypeOf(uint8(0)), path: ""},
  2503  		{t: TypeOf(uint16(0)), path: ""},
  2504  		{t: TypeOf(uint32(0)), path: ""},
  2505  		{t: TypeOf(uint64(0)), path: ""},
  2506  		{t: TypeOf(uintptr(0)), path: ""},
  2507  		{t: TypeOf(float32(0)), path: ""},
  2508  		{t: TypeOf(float64(0)), path: ""},
  2509  		{t: TypeOf(complex64(0)), path: ""},
  2510  		{t: TypeOf(complex128(0)), path: ""},
  2511  		{t: TypeOf(byte(0)), path: ""},
  2512  		{t: TypeOf(rune(0)), path: ""},
  2513  		{t: TypeOf([]byte(nil)), path: ""},
  2514  		{t: TypeOf([]rune(nil)), path: ""},
  2515  		{t: TypeOf(string("")), path: ""},
  2516  		{t: TypeOf((*any)(nil)).Elem(), path: ""},
  2517  		{t: TypeOf((*byte)(nil)), path: ""},
  2518  		{t: TypeOf((*rune)(nil)), path: ""},
  2519  		{t: TypeOf((*int64)(nil)), path: ""},
  2520  		{t: TypeOf(map[string]int{}), path: ""},
  2521  		{t: TypeOf((*error)(nil)).Elem(), path: ""},
  2522  		{t: TypeOf((*Point)(nil)), path: ""},
  2523  		{t: TypeOf((*Point)(nil)).Elem(), path: "github.com/goccy/go-reflect_test"},
  2524  	}
  2525  	for _, test := range tests {
  2526  		if path := test.t.PkgPath(); path != test.path {
  2527  			t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
  2528  		}
  2529  	}
  2530  }
  2531  
  2532  func TestVariadicType(t *testing.T) {
  2533  	// Test example from Type documentation.
  2534  	var f func(x int, y ...float64)
  2535  	typ := TypeOf(f)
  2536  	if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
  2537  		sl := typ.In(1)
  2538  		if sl.Kind() == Slice {
  2539  			if sl.Elem() == TypeOf(0.0) {
  2540  				// ok
  2541  				return
  2542  			}
  2543  		}
  2544  	}
  2545  
  2546  	// Failed
  2547  	t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
  2548  	s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
  2549  	for i := 0; i < typ.NumIn(); i++ {
  2550  		s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
  2551  	}
  2552  	t.Error(s)
  2553  }
  2554  
  2555  type inner struct {
  2556  	x int
  2557  }
  2558  
  2559  type outer struct {
  2560  	y int
  2561  	inner
  2562  }
  2563  
  2564  func (*inner) M() {}
  2565  
  2566  func (*outer) M() {}
  2567  
  2568  func TestNestedMethods(t *testing.T) {
  2569  	typ := TypeOf((*outer)(nil))
  2570  	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
  2571  		t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
  2572  		for i := 0; i < typ.NumMethod(); i++ {
  2573  			m := typ.Method(i)
  2574  			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2575  		}
  2576  	}
  2577  }
  2578  
  2579  type unexp struct{}
  2580  
  2581  func (*unexp) f() (int32, int8) { return 7, 7 }
  2582  
  2583  func (*unexp) g() (int64, int8) { return 8, 8 }
  2584  
  2585  type unexpI interface {
  2586  	f() (int32, int8)
  2587  }
  2588  
  2589  var unexpi unexpI = new(unexp)
  2590  
  2591  func TestUnexportedMethods(t *testing.T) {
  2592  	typ := TypeOf(unexpi)
  2593  
  2594  	if got := typ.NumMethod(); got != 0 {
  2595  		t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
  2596  	}
  2597  }
  2598  
  2599  type InnerInt struct {
  2600  	X int
  2601  }
  2602  
  2603  type OuterInt struct {
  2604  	Y int
  2605  	InnerInt
  2606  }
  2607  
  2608  func (i *InnerInt) M() int {
  2609  	return i.X
  2610  }
  2611  
  2612  func TestEmbeddedMethods(t *testing.T) {
  2613  	typ := TypeOf((*OuterInt)(nil))
  2614  	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
  2615  		t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
  2616  		for i := 0; i < typ.NumMethod(); i++ {
  2617  			m := typ.Method(i)
  2618  			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2619  		}
  2620  	}
  2621  
  2622  	i := &InnerInt{X: 3}
  2623  	if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
  2624  		t.Errorf("i.M() = %d, want 3", v)
  2625  	}
  2626  
  2627  	o := &OuterInt{Y: 1, InnerInt: InnerInt{X: 2}}
  2628  	if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
  2629  		t.Errorf("i.M() = %d, want 2", v)
  2630  	}
  2631  
  2632  	f := (*OuterInt).M
  2633  	if v := f(o); v != 2 {
  2634  		t.Errorf("f(o) = %d, want 2", v)
  2635  	}
  2636  }
  2637  
  2638  type FuncDDD func(...any) error
  2639  
  2640  func (f FuncDDD) M() {}
  2641  
  2642  func TestNumMethodOnDDD(t *testing.T) {
  2643  	rv := ValueOf((FuncDDD)(nil))
  2644  	if n := rv.NumMethod(); n != 1 {
  2645  		t.Fatalf("NumMethod()=%d, want 1", n)
  2646  	}
  2647  }
  2648  
  2649  func TestPtrTo(t *testing.T) {
  2650  	// This block of code means that the ptrToThis field of the
  2651  	// reflect data for *unsafe.Pointer is non zero, see
  2652  	// https://golang.org/issue/19003
  2653  	var x unsafe.Pointer
  2654  	var y = &x
  2655  	var z = &y
  2656  
  2657  	var i int
  2658  
  2659  	typ := TypeOf(z)
  2660  	for i = 0; i < 100; i++ {
  2661  		typ = PtrTo(typ)
  2662  	}
  2663  	for i = 0; i < 100; i++ {
  2664  		typ = typ.Elem()
  2665  	}
  2666  	if typ != TypeOf(z) {
  2667  		t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
  2668  	}
  2669  }
  2670  
  2671  func TestPtrToGC(t *testing.T) {
  2672  	type T *uintptr
  2673  	tt := TypeOf(T(nil))
  2674  	pt := PtrTo(tt)
  2675  	const n = 100
  2676  	var x []any
  2677  	for i := 0; i < n; i++ {
  2678  		v := New(pt)
  2679  		p := new(*uintptr)
  2680  		*p = new(uintptr)
  2681  		**p = uintptr(i)
  2682  		v.Elem().Set(ValueOf(p).Convert(pt))
  2683  		x = append(x, v.Interface())
  2684  	}
  2685  	runtime.GC()
  2686  
  2687  	for i, xi := range x {
  2688  		k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
  2689  		if k != uintptr(i) {
  2690  			t.Errorf("lost x[%d] = %d, want %d", i, k, i)
  2691  		}
  2692  	}
  2693  }
  2694  
  2695  func BenchmarkPtrTo(b *testing.B) {
  2696  	// Construct a type with a zero ptrToThis.
  2697  	type T struct{ int }
  2698  	t := SliceOf(TypeOf(T{}))
  2699  	ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
  2700  	if !ptrToThis.IsValid() {
  2701  		b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
  2702  	}
  2703  	if ptrToThis.Int() != 0 {
  2704  		b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
  2705  	}
  2706  	b.ResetTimer()
  2707  
  2708  	// Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
  2709  	// every call.
  2710  	b.RunParallel(func(pb *testing.PB) {
  2711  		for pb.Next() {
  2712  			PtrTo(t)
  2713  		}
  2714  	})
  2715  }
  2716  
  2717  func TestAddr(t *testing.T) {
  2718  	var p struct {
  2719  		X, Y int
  2720  	}
  2721  
  2722  	v := ValueOf(&p)
  2723  	v = v.Elem()
  2724  	v = v.Addr()
  2725  	v = v.Elem()
  2726  	v = v.Field(0)
  2727  	v.SetInt(2)
  2728  	if p.X != 2 {
  2729  		t.Errorf("Addr.Elem.Set failed to set value")
  2730  	}
  2731  
  2732  	// Again but take address of the ValueOf value.
  2733  	// Exercises generation of PtrTypes not present in the binary.
  2734  	q := &p
  2735  	v = ValueOf(&q).Elem()
  2736  	v = v.Addr()
  2737  	v = v.Elem()
  2738  	v = v.Elem()
  2739  	v = v.Addr()
  2740  	v = v.Elem()
  2741  	v = v.Field(0)
  2742  	v.SetInt(3)
  2743  	if p.X != 3 {
  2744  		t.Errorf("Addr.Elem.Set failed to set value")
  2745  	}
  2746  
  2747  	// Starting without pointer we should get changed value
  2748  	// in interface.
  2749  	qq := p
  2750  	v = ValueOf(&qq).Elem()
  2751  	v0 := v
  2752  	v = v.Addr()
  2753  	v = v.Elem()
  2754  	v = v.Field(0)
  2755  	v.SetInt(4)
  2756  	if p.X != 3 { // should be unchanged from last time
  2757  		t.Errorf("somehow value Set changed original p")
  2758  	}
  2759  	p = v0.Interface().(struct {
  2760  		X, Y int
  2761  	})
  2762  	if p.X != 4 {
  2763  		t.Errorf("Addr.Elem.Set valued to set value in top value")
  2764  	}
  2765  
  2766  	// Verify that taking the address of a type gives us a pointer
  2767  	// which we can convert back using the usual interface
  2768  	// notation.
  2769  	var s struct {
  2770  		B *bool
  2771  	}
  2772  	ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
  2773  	*(ps.(**bool)) = new(bool)
  2774  	if s.B == nil {
  2775  		t.Errorf("Addr.Interface direct assignment failed")
  2776  	}
  2777  }
  2778  
  2779  func noAlloc(t *testing.T, n int, f func(int)) {
  2780  	if testing.Short() {
  2781  		t.Skip("skipping malloc count in short mode")
  2782  	}
  2783  	if runtime.GOMAXPROCS(0) > 1 {
  2784  		t.Skip("skipping; GOMAXPROCS>1")
  2785  	}
  2786  	i := -1
  2787  	allocs := testing.AllocsPerRun(n, func() {
  2788  		f(i)
  2789  		i++
  2790  	})
  2791  	if allocs > 0 {
  2792  		t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
  2793  	}
  2794  }
  2795  
  2796  func TestAllocations(t *testing.T) {
  2797  	noAlloc(t, 100, func(j int) {
  2798  		var i any
  2799  		var v Value
  2800  
  2801  		// We can uncomment this when compiler escape analysis
  2802  		// is good enough to see that the integer assigned to i
  2803  		// does not escape and therefore need not be allocated.
  2804  		//
  2805  		// i = 42 + j
  2806  		// v = ValueOf(i)
  2807  		// if int(v.Int()) != 42+j {
  2808  		// 	panic("wrong int")
  2809  		// }
  2810  
  2811  		i = func(j int) int { return j }
  2812  		v = ValueOf(i)
  2813  		if v.Interface().(func(int) int)(j) != j {
  2814  			panic("wrong result")
  2815  		}
  2816  	})
  2817  }
  2818  
  2819  func TestSmallNegativeInt(t *testing.T) {
  2820  	i := int16(-1)
  2821  	v := ValueOf(i)
  2822  	if v.Int() != -1 {
  2823  		t.Errorf("int16(-1).Int() returned %v", v.Int())
  2824  	}
  2825  }
  2826  
  2827  func TestIndex(t *testing.T) {
  2828  	xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
  2829  	v := ValueOf(xs).Index(3).Interface().(byte)
  2830  	if v != xs[3] {
  2831  		t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
  2832  	}
  2833  	xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
  2834  	v = ValueOf(xa).Index(2).Interface().(byte)
  2835  	if v != xa[2] {
  2836  		t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
  2837  	}
  2838  	s := "0123456789"
  2839  	v = ValueOf(s).Index(3).Interface().(byte)
  2840  	if v != s[3] {
  2841  		t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
  2842  	}
  2843  }
  2844  
  2845  func TestSlice(t *testing.T) {
  2846  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2847  	v := ValueOf(xs).Slice(3, 5).Interface().([]int)
  2848  	if len(v) != 2 {
  2849  		t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
  2850  	}
  2851  	if cap(v) != 5 {
  2852  		t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
  2853  	}
  2854  	if !DeepEqual(v[0:5], xs[3:]) {
  2855  		t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
  2856  	}
  2857  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2858  	v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
  2859  	if len(v) != 3 {
  2860  		t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
  2861  	}
  2862  	if cap(v) != 6 {
  2863  		t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
  2864  	}
  2865  	if !DeepEqual(v[0:6], xa[2:]) {
  2866  		t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
  2867  	}
  2868  	s := "0123456789"
  2869  	vs := ValueOf(s).Slice(3, 5).Interface().(string)
  2870  	if vs != s[3:5] {
  2871  		t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
  2872  	}
  2873  
  2874  	rv := ValueOf(&xs).Elem()
  2875  	rv = rv.Slice(3, 4)
  2876  	ptr2 := rv.Pointer()
  2877  	rv = rv.Slice(5, 5)
  2878  	ptr3 := rv.Pointer()
  2879  	if ptr3 != ptr2 {
  2880  		t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
  2881  	}
  2882  }
  2883  
  2884  func TestSlice3(t *testing.T) {
  2885  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2886  	v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
  2887  	if len(v) != 2 {
  2888  		t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
  2889  	}
  2890  	if cap(v) != 4 {
  2891  		t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
  2892  	}
  2893  	if !DeepEqual(v[0:4], xs[3:7:7]) {
  2894  		t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
  2895  	}
  2896  	rv := ValueOf(&xs).Elem()
  2897  	shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2898  	shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2899  	shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2900  
  2901  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2902  	v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
  2903  	if len(v) != 3 {
  2904  		t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
  2905  	}
  2906  	if cap(v) != 4 {
  2907  		t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
  2908  	}
  2909  	if !DeepEqual(v[0:4], xa[2:6:6]) {
  2910  		t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
  2911  	}
  2912  	rv = ValueOf(&xa).Elem()
  2913  	shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2914  	shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2915  	shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2916  
  2917  	s := "hello world"
  2918  	rv = ValueOf(&s).Elem()
  2919  	shouldPanic(func() { rv.Slice3(1, 2, 3) })
  2920  
  2921  	rv = ValueOf(&xs).Elem()
  2922  	rv = rv.Slice3(3, 5, 7)
  2923  	ptr2 := rv.Pointer()
  2924  	rv = rv.Slice3(4, 4, 4)
  2925  	ptr3 := rv.Pointer()
  2926  	if ptr3 != ptr2 {
  2927  		t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
  2928  	}
  2929  }
  2930  
  2931  func TestSetLenCap(t *testing.T) {
  2932  	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2933  	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2934  
  2935  	vs := ValueOf(&xs).Elem()
  2936  	shouldPanic(func() { vs.SetLen(10) })
  2937  	shouldPanic(func() { vs.SetCap(10) })
  2938  	shouldPanic(func() { vs.SetLen(-1) })
  2939  	shouldPanic(func() { vs.SetCap(-1) })
  2940  	shouldPanic(func() { vs.SetCap(6) }) // smaller than len
  2941  	vs.SetLen(5)
  2942  	if len(xs) != 5 || cap(xs) != 8 {
  2943  		t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
  2944  	}
  2945  	vs.SetCap(6)
  2946  	if len(xs) != 5 || cap(xs) != 6 {
  2947  		t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
  2948  	}
  2949  	vs.SetCap(5)
  2950  	if len(xs) != 5 || cap(xs) != 5 {
  2951  		t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
  2952  	}
  2953  	shouldPanic(func() { vs.SetCap(4) }) // smaller than len
  2954  	shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
  2955  
  2956  	va := ValueOf(&xa).Elem()
  2957  	shouldPanic(func() { va.SetLen(8) })
  2958  	shouldPanic(func() { va.SetCap(8) })
  2959  }
  2960  
  2961  func TestVariadic(t *testing.T) {
  2962  	var b bytes.Buffer
  2963  	V := ValueOf
  2964  
  2965  	b.Reset()
  2966  	V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
  2967  	if b.String() != "hello, 42 world" {
  2968  		t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
  2969  	}
  2970  
  2971  	b.Reset()
  2972  	V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
  2973  	if b.String() != "hello, 42 world" {
  2974  		t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
  2975  	}
  2976  }
  2977  
  2978  func TestFuncArg(t *testing.T) {
  2979  	f1 := func(i int, f func(int) int) int { return f(i) }
  2980  	f2 := func(i int) int { return i + 1 }
  2981  	r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
  2982  	if r[0].Int() != 101 {
  2983  		t.Errorf("function returned %d, want 101", r[0].Int())
  2984  	}
  2985  }
  2986  
  2987  func TestStructArg(t *testing.T) {
  2988  	type padded struct {
  2989  		B string
  2990  		C int32
  2991  	}
  2992  	var (
  2993  		gotA  padded
  2994  		gotB  uint32
  2995  		wantA = padded{B: "3", C: 4}
  2996  		wantB = uint32(5)
  2997  	)
  2998  	f := func(a padded, b uint32) {
  2999  		gotA, gotB = a, b
  3000  	}
  3001  	ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
  3002  	if gotA != wantA || gotB != wantB {
  3003  		t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
  3004  	}
  3005  }
  3006  
  3007  var tagGetTests = []struct {
  3008  	Tag   StructTag
  3009  	Key   string
  3010  	Value string
  3011  }{
  3012  	{Tag: `protobuf:"PB(1,2)"`, Key: `protobuf`, Value: `PB(1,2)`},
  3013  	{Tag: `protobuf:"PB(1,2)"`, Key: `foo`, Value: ``},
  3014  	{Tag: `protobuf:"PB(1,2)"`, Key: `rotobuf`, Value: ``},
  3015  	{Tag: `protobuf:"PB(1,2)" json:"name"`, Key: `json`, Value: `name`},
  3016  	{Tag: `protobuf:"PB(1,2)" json:"name"`, Key: `protobuf`, Value: `PB(1,2)`},
  3017  	{Tag: `k0:"values contain spaces" k1:"and\ttabs"`, Key: "k0", Value: "values contain spaces"},
  3018  	{Tag: `k0:"values contain spaces" k1:"and\ttabs"`, Key: "k1", Value: "and\ttabs"},
  3019  }
  3020  
  3021  func TestTagGet(t *testing.T) {
  3022  	for _, tt := range tagGetTests {
  3023  		if v := tt.Tag.Get(tt.Key); v != tt.Value {
  3024  			t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
  3025  		}
  3026  	}
  3027  }
  3028  
  3029  func TestBytes(t *testing.T) {
  3030  	type B []byte
  3031  	x := B{1, 2, 3, 4}
  3032  	y := ValueOf(x).Bytes()
  3033  	if !bytes.Equal(x, y) {
  3034  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  3035  	}
  3036  	if &x[0] != &y[0] {
  3037  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  3038  	}
  3039  }
  3040  
  3041  func TestSetBytes(t *testing.T) {
  3042  	type B []byte
  3043  	var x B
  3044  	y := []byte{1, 2, 3, 4}
  3045  	ValueOf(&x).Elem().SetBytes(y)
  3046  	if !bytes.Equal(x, y) {
  3047  		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  3048  	}
  3049  	if &x[0] != &y[0] {
  3050  		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  3051  	}
  3052  }
  3053  
  3054  type Private struct {
  3055  	x int
  3056  	y **int
  3057  	Z int
  3058  }
  3059  
  3060  func (p *Private) m() {}
  3061  
  3062  type private struct {
  3063  	Z int
  3064  	z int
  3065  	S string
  3066  	A [1]Private
  3067  	T []Private
  3068  }
  3069  
  3070  func (p *private) P() {}
  3071  
  3072  type Public struct {
  3073  	X int
  3074  	Y **int
  3075  	private
  3076  }
  3077  
  3078  func (p *Public) M() {}
  3079  
  3080  func TestUnexported(t *testing.T) {
  3081  	var pub Public
  3082  	pub.S = "S"
  3083  	pub.T = pub.A[:]
  3084  	v := ValueOf(&pub)
  3085  	isValid(v.Elem().Field(0))
  3086  	isValid(v.Elem().Field(1))
  3087  	isValid(v.Elem().Field(2))
  3088  	isValid(v.Elem().FieldByName("X"))
  3089  	isValid(v.Elem().FieldByName("Y"))
  3090  	isValid(v.Elem().FieldByName("Z"))
  3091  	isValid(v.Type().Method(0).Func)
  3092  	m, _ := v.Type().MethodByName("M")
  3093  	isValid(m.Func)
  3094  	m, _ = v.Type().MethodByName("P")
  3095  	isValid(m.Func)
  3096  	isNonNil(v.Elem().Field(0).Interface())
  3097  	isNonNil(v.Elem().Field(1).Interface())
  3098  	isNonNil(v.Elem().Field(2).Field(2).Index(0))
  3099  	isNonNil(v.Elem().FieldByName("X").Interface())
  3100  	isNonNil(v.Elem().FieldByName("Y").Interface())
  3101  	isNonNil(v.Elem().FieldByName("Z").Interface())
  3102  	isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
  3103  	isNonNil(v.Type().Method(0).Func.Interface())
  3104  	m, _ = v.Type().MethodByName("P")
  3105  	isNonNil(m.Func.Interface())
  3106  
  3107  	var priv Private
  3108  	v = ValueOf(&priv)
  3109  	isValid(v.Elem().Field(0))
  3110  	isValid(v.Elem().Field(1))
  3111  	isValid(v.Elem().FieldByName("x"))
  3112  	isValid(v.Elem().FieldByName("y"))
  3113  	shouldPanic(func() { v.Elem().Field(0).Interface() })
  3114  	shouldPanic(func() { v.Elem().Field(1).Interface() })
  3115  	shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
  3116  	shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
  3117  	shouldPanic(func() { v.Type().Method(0) })
  3118  }
  3119  
  3120  func TestSetPanic(t *testing.T) {
  3121  	ok := func(f func()) { f() }
  3122  	bad := shouldPanic
  3123  	clear := func(v Value) { v.Set(Zero(v.Type())) }
  3124  
  3125  	type t0 struct {
  3126  		W int
  3127  	}
  3128  
  3129  	type t1 struct {
  3130  		Y int
  3131  		t0
  3132  	}
  3133  
  3134  	type T2 struct {
  3135  		Z       int
  3136  		namedT0 t0
  3137  	}
  3138  
  3139  	type T struct {
  3140  		X int
  3141  		t1
  3142  		T2
  3143  		NamedT1 t1
  3144  		NamedT2 T2
  3145  		namedT1 t1
  3146  		namedT2 T2
  3147  	}
  3148  
  3149  	// not addressable
  3150  	v := ValueOf(T{})
  3151  	bad(func() { clear(v.Field(0)) })                   // .X
  3152  	bad(func() { clear(v.Field(1)) })                   // .t1
  3153  	bad(func() { clear(v.Field(1).Field(0)) })          // .t1.Y
  3154  	bad(func() { clear(v.Field(1).Field(1)) })          // .t1.t0
  3155  	bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
  3156  	bad(func() { clear(v.Field(2)) })                   // .T2
  3157  	bad(func() { clear(v.Field(2).Field(0)) })          // .T2.Z
  3158  	bad(func() { clear(v.Field(2).Field(1)) })          // .T2.namedT0
  3159  	bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
  3160  	bad(func() { clear(v.Field(3)) })                   // .NamedT1
  3161  	bad(func() { clear(v.Field(3).Field(0)) })          // .NamedT1.Y
  3162  	bad(func() { clear(v.Field(3).Field(1)) })          // .NamedT1.t0
  3163  	bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
  3164  	bad(func() { clear(v.Field(4)) })                   // .NamedT2
  3165  	bad(func() { clear(v.Field(4).Field(0)) })          // .NamedT2.Z
  3166  	bad(func() { clear(v.Field(4).Field(1)) })          // .NamedT2.namedT0
  3167  	bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
  3168  	bad(func() { clear(v.Field(5)) })                   // .namedT1
  3169  	bad(func() { clear(v.Field(5).Field(0)) })          // .namedT1.Y
  3170  	bad(func() { clear(v.Field(5).Field(1)) })          // .namedT1.t0
  3171  	bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
  3172  	bad(func() { clear(v.Field(6)) })                   // .namedT2
  3173  	bad(func() { clear(v.Field(6).Field(0)) })          // .namedT2.Z
  3174  	bad(func() { clear(v.Field(6).Field(1)) })          // .namedT2.namedT0
  3175  	bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
  3176  
  3177  	// addressable
  3178  	v = ValueOf(&T{}).Elem()
  3179  	ok(func() { clear(v.Field(0)) })                    // .X
  3180  	bad(func() { clear(v.Field(1)) })                   // .t1
  3181  	ok(func() { clear(v.Field(1).Field(0)) })           // .t1.Y
  3182  	bad(func() { clear(v.Field(1).Field(1)) })          // .t1.t0
  3183  	ok(func() { clear(v.Field(1).Field(1).Field(0)) })  // .t1.t0.W
  3184  	ok(func() { clear(v.Field(2)) })                    // .T2
  3185  	ok(func() { clear(v.Field(2).Field(0)) })           // .T2.Z
  3186  	bad(func() { clear(v.Field(2).Field(1)) })          // .T2.namedT0
  3187  	bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
  3188  	ok(func() { clear(v.Field(3)) })                    // .NamedT1
  3189  	ok(func() { clear(v.Field(3).Field(0)) })           // .NamedT1.Y
  3190  	bad(func() { clear(v.Field(3).Field(1)) })          // .NamedT1.t0
  3191  	ok(func() { clear(v.Field(3).Field(1).Field(0)) })  // .NamedT1.t0.W
  3192  	ok(func() { clear(v.Field(4)) })                    // .NamedT2
  3193  	ok(func() { clear(v.Field(4).Field(0)) })           // .NamedT2.Z
  3194  	bad(func() { clear(v.Field(4).Field(1)) })          // .NamedT2.namedT0
  3195  	bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
  3196  	bad(func() { clear(v.Field(5)) })                   // .namedT1
  3197  	bad(func() { clear(v.Field(5).Field(0)) })          // .namedT1.Y
  3198  	bad(func() { clear(v.Field(5).Field(1)) })          // .namedT1.t0
  3199  	bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
  3200  	bad(func() { clear(v.Field(6)) })                   // .namedT2
  3201  	bad(func() { clear(v.Field(6).Field(0)) })          // .namedT2.Z
  3202  	bad(func() { clear(v.Field(6).Field(1)) })          // .namedT2.namedT0
  3203  	bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
  3204  }
  3205  
  3206  type timp int
  3207  
  3208  func (t timp) W() {}
  3209  
  3210  func (t timp) Y() {}
  3211  
  3212  func (t timp) w() {}
  3213  
  3214  func (t timp) y() {}
  3215  
  3216  func TestCallPanic(t *testing.T) {
  3217  	type t0 interface {
  3218  		W()
  3219  		w()
  3220  	}
  3221  	type T1 interface {
  3222  		Y()
  3223  		y()
  3224  	}
  3225  	type T2 struct {
  3226  		T1
  3227  		t0
  3228  	}
  3229  	type T struct {
  3230  		t0 // 0
  3231  		T1 // 1
  3232  
  3233  		NamedT0 t0 // 2
  3234  		NamedT1 T1 // 3
  3235  		NamedT2 T2 // 4
  3236  
  3237  		namedT0 t0 // 5
  3238  		namedT1 T1 // 6
  3239  		namedT2 T2 // 7
  3240  	}
  3241  	ok := func(f func()) { f() }
  3242  	bad := shouldPanic
  3243  	call := func(v Value) { v.Call(nil) }
  3244  
  3245  	i := timp(0)
  3246  	v := ValueOf(T{t0: i, T1: i, NamedT0: i, NamedT1: i, NamedT2: T2{T1: i, t0: i}, namedT0: i, namedT1: i, namedT2: T2{T1: i, t0: i}})
  3247  	// ok(func() { call(v.Field(0).Method(0)) })         // .t0.W
  3248  	// bad(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
  3249  	// bad(func() { call(v.Field(0).Method(1)) })        // .t0.w
  3250  	// bad(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
  3251  	ok(func() { call(v.Field(1).Method(0)) })         // .T1.Y
  3252  	ok(func() { call(v.Field(1).Elem().Method(0)) })  // .T1.Y
  3253  	bad(func() { call(v.Field(1).Method(1)) })        // .T1.y
  3254  	bad(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
  3255  
  3256  	ok(func() { call(v.Field(2).Method(0)) })         // .NamedT0.W
  3257  	ok(func() { call(v.Field(2).Elem().Method(0)) })  // .NamedT0.W
  3258  	bad(func() { call(v.Field(2).Method(1)) })        // .NamedT0.w
  3259  	bad(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
  3260  
  3261  	ok(func() { call(v.Field(3).Method(0)) })         // .NamedT1.Y
  3262  	ok(func() { call(v.Field(3).Elem().Method(0)) })  // .NamedT1.Y
  3263  	bad(func() { call(v.Field(3).Method(1)) })        // .NamedT1.y
  3264  	bad(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
  3265  
  3266  	ok(func() { call(v.Field(4).Field(0).Method(0)) })        // .NamedT2.T1.Y
  3267  	ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
  3268  	// ok(func() { call(v.Field(4).Field(1).Method(0)) })         // .NamedT2.t0.W
  3269  	// bad(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
  3270  
  3271  	bad(func() { call(v.Field(5).Method(0)) })        // .namedT0.W
  3272  	bad(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
  3273  	bad(func() { call(v.Field(5).Method(1)) })        // .namedT0.w
  3274  	bad(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
  3275  
  3276  	bad(func() { call(v.Field(6).Method(0)) })        // .namedT1.Y
  3277  	bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
  3278  	bad(func() { call(v.Field(6).Method(0)) })        // .namedT1.y
  3279  	bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
  3280  
  3281  	bad(func() { call(v.Field(7).Field(0).Method(0)) })        // .namedT2.T1.Y
  3282  	bad(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
  3283  	// bad(func() { call(v.Field(7).Field(1).Method(0)) })        // .namedT2.t0.W
  3284  	// bad(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
  3285  }
  3286  
  3287  func shouldPanic(f func()) {
  3288  	defer func() {
  3289  		if recover() == nil {
  3290  			panic("did not panic")
  3291  		}
  3292  	}()
  3293  	f()
  3294  }
  3295  
  3296  func isNonNil(x any) {
  3297  	if x == nil {
  3298  		panic("nil interface")
  3299  	}
  3300  }
  3301  
  3302  func isValid(v Value) {
  3303  	if !v.IsValid() {
  3304  		panic("zero Value")
  3305  	}
  3306  }
  3307  
  3308  func TestAlias(t *testing.T) {
  3309  	x := string("hello")
  3310  	v := ValueOf(&x).Elem()
  3311  	oldvalue := v.Interface()
  3312  	v.SetString("world")
  3313  	newvalue := v.Interface()
  3314  
  3315  	if oldvalue != "hello" || newvalue != "world" {
  3316  		t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
  3317  	}
  3318  }
  3319  
  3320  var V = ValueOf
  3321  
  3322  func EmptyInterfaceV(x any) Value {
  3323  	return ValueOf(&x).Elem()
  3324  }
  3325  
  3326  func ReaderV(x io.Reader) Value {
  3327  	return ValueOf(&x).Elem()
  3328  }
  3329  
  3330  func ReadWriterV(x io.ReadWriter) Value {
  3331  	return ValueOf(&x).Elem()
  3332  }
  3333  
  3334  type Empty struct{}
  3335  
  3336  type MyStruct struct {
  3337  	x int `some:"tag"`
  3338  }
  3339  
  3340  type MyString string
  3341  
  3342  type MyBytes []byte
  3343  
  3344  type MyRunes []int32
  3345  
  3346  type MyFunc func()
  3347  
  3348  type MyByte byte
  3349  
  3350  var convertTests = []struct {
  3351  	in  Value
  3352  	out Value
  3353  }{
  3354  	// numbers
  3355  	/*
  3356  		Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
  3357  
  3358  		package main
  3359  
  3360  		import "fmt"
  3361  
  3362  		var numbers = []string{
  3363  			"int8", "uint8", "int16", "uint16",
  3364  			"int32", "uint32", "int64", "uint64",
  3365  			"int", "uint", "uintptr",
  3366  			"float32", "float64",
  3367  		}
  3368  
  3369  		func main() {
  3370  			// all pairs but in an unusual order,
  3371  			// to emit all the int8, uint8 cases
  3372  			// before n grows too big.
  3373  			n := 1
  3374  			for i, f := range numbers {
  3375  				for _, g := range numbers[i:] {
  3376  					fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
  3377  					n++
  3378  					if f != g {
  3379  						fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
  3380  						n++
  3381  					}
  3382  				}
  3383  			}
  3384  		}
  3385  	*/
  3386  	{in: V(int8(1)), out: V(int8(1))},
  3387  	{in: V(int8(2)), out: V(uint8(2))},
  3388  	{in: V(uint8(3)), out: V(int8(3))},
  3389  	{in: V(int8(4)), out: V(int16(4))},
  3390  	{in: V(int16(5)), out: V(int8(5))},
  3391  	{in: V(int8(6)), out: V(uint16(6))},
  3392  	{in: V(uint16(7)), out: V(int8(7))},
  3393  	{in: V(int8(8)), out: V(int32(8))},
  3394  	{in: V(int32(9)), out: V(int8(9))},
  3395  	{in: V(int8(10)), out: V(uint32(10))},
  3396  	{in: V(uint32(11)), out: V(int8(11))},
  3397  	{in: V(int8(12)), out: V(int64(12))},
  3398  	{in: V(int64(13)), out: V(int8(13))},
  3399  	{in: V(int8(14)), out: V(uint64(14))},
  3400  	{in: V(uint64(15)), out: V(int8(15))},
  3401  	{in: V(int8(16)), out: V(int(16))},
  3402  	{in: V(int(17)), out: V(int8(17))},
  3403  	{in: V(int8(18)), out: V(uint(18))},
  3404  	{in: V(uint(19)), out: V(int8(19))},
  3405  	{in: V(int8(20)), out: V(uintptr(20))},
  3406  	{in: V(uintptr(21)), out: V(int8(21))},
  3407  	{in: V(int8(22)), out: V(float32(22))},
  3408  	{in: V(float32(23)), out: V(int8(23))},
  3409  	{in: V(int8(24)), out: V(float64(24))},
  3410  	{in: V(float64(25)), out: V(int8(25))},
  3411  	{in: V(uint8(26)), out: V(uint8(26))},
  3412  	{in: V(uint8(27)), out: V(int16(27))},
  3413  	{in: V(int16(28)), out: V(uint8(28))},
  3414  	{in: V(uint8(29)), out: V(uint16(29))},
  3415  	{in: V(uint16(30)), out: V(uint8(30))},
  3416  	{in: V(uint8(31)), out: V(int32(31))},
  3417  	{in: V(int32(32)), out: V(uint8(32))},
  3418  	{in: V(uint8(33)), out: V(uint32(33))},
  3419  	{in: V(uint32(34)), out: V(uint8(34))},
  3420  	{in: V(uint8(35)), out: V(int64(35))},
  3421  	{in: V(int64(36)), out: V(uint8(36))},
  3422  	{in: V(uint8(37)), out: V(uint64(37))},
  3423  	{in: V(uint64(38)), out: V(uint8(38))},
  3424  	{in: V(uint8(39)), out: V(int(39))},
  3425  	{in: V(int(40)), out: V(uint8(40))},
  3426  	{in: V(uint8(41)), out: V(uint(41))},
  3427  	{in: V(uint(42)), out: V(uint8(42))},
  3428  	{in: V(uint8(43)), out: V(uintptr(43))},
  3429  	{in: V(uintptr(44)), out: V(uint8(44))},
  3430  	{in: V(uint8(45)), out: V(float32(45))},
  3431  	{in: V(float32(46)), out: V(uint8(46))},
  3432  	{in: V(uint8(47)), out: V(float64(47))},
  3433  	{in: V(float64(48)), out: V(uint8(48))},
  3434  	{in: V(int16(49)), out: V(int16(49))},
  3435  	{in: V(int16(50)), out: V(uint16(50))},
  3436  	{in: V(uint16(51)), out: V(int16(51))},
  3437  	{in: V(int16(52)), out: V(int32(52))},
  3438  	{in: V(int32(53)), out: V(int16(53))},
  3439  	{in: V(int16(54)), out: V(uint32(54))},
  3440  	{in: V(uint32(55)), out: V(int16(55))},
  3441  	{in: V(int16(56)), out: V(int64(56))},
  3442  	{in: V(int64(57)), out: V(int16(57))},
  3443  	{in: V(int16(58)), out: V(uint64(58))},
  3444  	{in: V(uint64(59)), out: V(int16(59))},
  3445  	{in: V(int16(60)), out: V(int(60))},
  3446  	{in: V(int(61)), out: V(int16(61))},
  3447  	{in: V(int16(62)), out: V(uint(62))},
  3448  	{in: V(uint(63)), out: V(int16(63))},
  3449  	{in: V(int16(64)), out: V(uintptr(64))},
  3450  	{in: V(uintptr(65)), out: V(int16(65))},
  3451  	{in: V(int16(66)), out: V(float32(66))},
  3452  	{in: V(float32(67)), out: V(int16(67))},
  3453  	{in: V(int16(68)), out: V(float64(68))},
  3454  	{in: V(float64(69)), out: V(int16(69))},
  3455  	{in: V(uint16(70)), out: V(uint16(70))},
  3456  	{in: V(uint16(71)), out: V(int32(71))},
  3457  	{in: V(int32(72)), out: V(uint16(72))},
  3458  	{in: V(uint16(73)), out: V(uint32(73))},
  3459  	{in: V(uint32(74)), out: V(uint16(74))},
  3460  	{in: V(uint16(75)), out: V(int64(75))},
  3461  	{in: V(int64(76)), out: V(uint16(76))},
  3462  	{in: V(uint16(77)), out: V(uint64(77))},
  3463  	{in: V(uint64(78)), out: V(uint16(78))},
  3464  	{in: V(uint16(79)), out: V(int(79))},
  3465  	{in: V(int(80)), out: V(uint16(80))},
  3466  	{in: V(uint16(81)), out: V(uint(81))},
  3467  	{in: V(uint(82)), out: V(uint16(82))},
  3468  	{in: V(uint16(83)), out: V(uintptr(83))},
  3469  	{in: V(uintptr(84)), out: V(uint16(84))},
  3470  	{in: V(uint16(85)), out: V(float32(85))},
  3471  	{in: V(float32(86)), out: V(uint16(86))},
  3472  	{in: V(uint16(87)), out: V(float64(87))},
  3473  	{in: V(float64(88)), out: V(uint16(88))},
  3474  	{in: V(int32(89)), out: V(int32(89))},
  3475  	{in: V(int32(90)), out: V(uint32(90))},
  3476  	{in: V(uint32(91)), out: V(int32(91))},
  3477  	{in: V(int32(92)), out: V(int64(92))},
  3478  	{in: V(int64(93)), out: V(int32(93))},
  3479  	{in: V(int32(94)), out: V(uint64(94))},
  3480  	{in: V(uint64(95)), out: V(int32(95))},
  3481  	{in: V(int32(96)), out: V(int(96))},
  3482  	{in: V(int(97)), out: V(int32(97))},
  3483  	{in: V(int32(98)), out: V(uint(98))},
  3484  	{in: V(uint(99)), out: V(int32(99))},
  3485  	{in: V(int32(100)), out: V(uintptr(100))},
  3486  	{in: V(uintptr(101)), out: V(int32(101))},
  3487  	{in: V(int32(102)), out: V(float32(102))},
  3488  	{in: V(float32(103)), out: V(int32(103))},
  3489  	{in: V(int32(104)), out: V(float64(104))},
  3490  	{in: V(float64(105)), out: V(int32(105))},
  3491  	{in: V(uint32(106)), out: V(uint32(106))},
  3492  	{in: V(uint32(107)), out: V(int64(107))},
  3493  	{in: V(int64(108)), out: V(uint32(108))},
  3494  	{in: V(uint32(109)), out: V(uint64(109))},
  3495  	{in: V(uint64(110)), out: V(uint32(110))},
  3496  	{in: V(uint32(111)), out: V(int(111))},
  3497  	{in: V(int(112)), out: V(uint32(112))},
  3498  	{in: V(uint32(113)), out: V(uint(113))},
  3499  	{in: V(uint(114)), out: V(uint32(114))},
  3500  	{in: V(uint32(115)), out: V(uintptr(115))},
  3501  	{in: V(uintptr(116)), out: V(uint32(116))},
  3502  	{in: V(uint32(117)), out: V(float32(117))},
  3503  	{in: V(float32(118)), out: V(uint32(118))},
  3504  	{in: V(uint32(119)), out: V(float64(119))},
  3505  	{in: V(float64(120)), out: V(uint32(120))},
  3506  	{in: V(int64(121)), out: V(int64(121))},
  3507  	{in: V(int64(122)), out: V(uint64(122))},
  3508  	{in: V(uint64(123)), out: V(int64(123))},
  3509  	{in: V(int64(124)), out: V(int(124))},
  3510  	{in: V(int(125)), out: V(int64(125))},
  3511  	{in: V(int64(126)), out: V(uint(126))},
  3512  	{in: V(uint(127)), out: V(int64(127))},
  3513  	{in: V(int64(128)), out: V(uintptr(128))},
  3514  	{in: V(uintptr(129)), out: V(int64(129))},
  3515  	{in: V(int64(130)), out: V(float32(130))},
  3516  	{in: V(float32(131)), out: V(int64(131))},
  3517  	{in: V(int64(132)), out: V(float64(132))},
  3518  	{in: V(float64(133)), out: V(int64(133))},
  3519  	{in: V(uint64(134)), out: V(uint64(134))},
  3520  	{in: V(uint64(135)), out: V(int(135))},
  3521  	{in: V(int(136)), out: V(uint64(136))},
  3522  	{in: V(uint64(137)), out: V(uint(137))},
  3523  	{in: V(uint(138)), out: V(uint64(138))},
  3524  	{in: V(uint64(139)), out: V(uintptr(139))},
  3525  	{in: V(uintptr(140)), out: V(uint64(140))},
  3526  	{in: V(uint64(141)), out: V(float32(141))},
  3527  	{in: V(float32(142)), out: V(uint64(142))},
  3528  	{in: V(uint64(143)), out: V(float64(143))},
  3529  	{in: V(float64(144)), out: V(uint64(144))},
  3530  	{in: V(int(145)), out: V(int(145))},
  3531  	{in: V(int(146)), out: V(uint(146))},
  3532  	{in: V(uint(147)), out: V(int(147))},
  3533  	{in: V(int(148)), out: V(uintptr(148))},
  3534  	{in: V(uintptr(149)), out: V(int(149))},
  3535  	{in: V(int(150)), out: V(float32(150))},
  3536  	{in: V(float32(151)), out: V(int(151))},
  3537  	{in: V(int(152)), out: V(float64(152))},
  3538  	{in: V(float64(153)), out: V(int(153))},
  3539  	{in: V(uint(154)), out: V(uint(154))},
  3540  	{in: V(uint(155)), out: V(uintptr(155))},
  3541  	{in: V(uintptr(156)), out: V(uint(156))},
  3542  	{in: V(uint(157)), out: V(float32(157))},
  3543  	{in: V(float32(158)), out: V(uint(158))},
  3544  	{in: V(uint(159)), out: V(float64(159))},
  3545  	{in: V(float64(160)), out: V(uint(160))},
  3546  	{in: V(uintptr(161)), out: V(uintptr(161))},
  3547  	{in: V(uintptr(162)), out: V(float32(162))},
  3548  	{in: V(float32(163)), out: V(uintptr(163))},
  3549  	{in: V(uintptr(164)), out: V(float64(164))},
  3550  	{in: V(float64(165)), out: V(uintptr(165))},
  3551  	{in: V(float32(166)), out: V(float32(166))},
  3552  	{in: V(float32(167)), out: V(float64(167))},
  3553  	{in: V(float64(168)), out: V(float32(168))},
  3554  	{in: V(float64(169)), out: V(float64(169))},
  3555  
  3556  	// truncation
  3557  	{in: V(float64(1.5)), out: V(int(1))},
  3558  
  3559  	// complex
  3560  	{in: V(complex64(1i)), out: V(complex64(1i))},
  3561  	{in: V(complex64(2i)), out: V(complex128(2i))},
  3562  	{in: V(complex128(3i)), out: V(complex64(3i))},
  3563  	{in: V(complex128(4i)), out: V(complex128(4i))},
  3564  
  3565  	// string
  3566  	{in: V(string("hello")), out: V(string("hello"))},
  3567  	{in: V(string("bytes1")), out: V([]byte("bytes1"))},
  3568  	{in: V([]byte("bytes2")), out: V(string("bytes2"))},
  3569  	{in: V([]byte("bytes3")), out: V([]byte("bytes3"))},
  3570  	{in: V(string("runes♝")), out: V([]rune("runes♝"))},
  3571  	{in: V([]rune("runes♕")), out: V(string("runes♕"))},
  3572  	{in: V([]rune("runes🙈🙉🙊")), out: V([]rune("runes🙈🙉🙊"))},
  3573  	{in: V(int('a')), out: V(string("a"))},
  3574  	{in: V(int8('a')), out: V(string("a"))},
  3575  	{in: V(int16('a')), out: V(string("a"))},
  3576  	{in: V(int32('a')), out: V(string("a"))},
  3577  	{in: V(int64('a')), out: V(string("a"))},
  3578  	{in: V(uint('a')), out: V(string("a"))},
  3579  	{in: V(uint8('a')), out: V(string("a"))},
  3580  	{in: V(uint16('a')), out: V(string("a"))},
  3581  	{in: V(uint32('a')), out: V(string("a"))},
  3582  	{in: V(uint64('a')), out: V(string("a"))},
  3583  	{in: V(uintptr('a')), out: V(string("a"))},
  3584  	{in: V(int(-1)), out: V(string("\uFFFD"))},
  3585  	{in: V(int8(-2)), out: V(string("\uFFFD"))},
  3586  	{in: V(int16(-3)), out: V(string("\uFFFD"))},
  3587  	{in: V(int32(-4)), out: V(string("\uFFFD"))},
  3588  	{in: V(int64(-5)), out: V(string("\uFFFD"))},
  3589  	{in: V(uint(0x110001)), out: V(string("\uFFFD"))},
  3590  	{in: V(uint32(0x110002)), out: V(string("\uFFFD"))},
  3591  	{in: V(uint64(0x110003)), out: V(string("\uFFFD"))},
  3592  	{in: V(uintptr(0x110004)), out: V(string("\uFFFD"))},
  3593  
  3594  	// named string
  3595  	{in: V(MyString("hello")), out: V(string("hello"))},
  3596  	{in: V(string("hello")), out: V(MyString("hello"))},
  3597  	{in: V(string("hello")), out: V(string("hello"))},
  3598  	{in: V(MyString("hello")), out: V(MyString("hello"))},
  3599  	{in: V(MyString("bytes1")), out: V([]byte("bytes1"))},
  3600  	{in: V([]byte("bytes2")), out: V(MyString("bytes2"))},
  3601  	{in: V([]byte("bytes3")), out: V([]byte("bytes3"))},
  3602  	{in: V(MyString("runes♝")), out: V([]rune("runes♝"))},
  3603  	{in: V([]rune("runes♕")), out: V(MyString("runes♕"))},
  3604  	{in: V([]rune("runes🙈🙉🙊")), out: V([]rune("runes🙈🙉🙊"))},
  3605  	{in: V([]rune("runes🙈🙉🙊")), out: V(MyRunes("runes🙈🙉🙊"))},
  3606  	{in: V(MyRunes("runes🙈🙉🙊")), out: V([]rune("runes🙈🙉🙊"))},
  3607  	{in: V(int('a')), out: V(MyString("a"))},
  3608  	{in: V(int8('a')), out: V(MyString("a"))},
  3609  	{in: V(int16('a')), out: V(MyString("a"))},
  3610  	{in: V(int32('a')), out: V(MyString("a"))},
  3611  	{in: V(int64('a')), out: V(MyString("a"))},
  3612  	{in: V(uint('a')), out: V(MyString("a"))},
  3613  	{in: V(uint8('a')), out: V(MyString("a"))},
  3614  	{in: V(uint16('a')), out: V(MyString("a"))},
  3615  	{in: V(uint32('a')), out: V(MyString("a"))},
  3616  	{in: V(uint64('a')), out: V(MyString("a"))},
  3617  	{in: V(uintptr('a')), out: V(MyString("a"))},
  3618  	{in: V(int(-1)), out: V(MyString("\uFFFD"))},
  3619  	{in: V(int8(-2)), out: V(MyString("\uFFFD"))},
  3620  	{in: V(int16(-3)), out: V(MyString("\uFFFD"))},
  3621  	{in: V(int32(-4)), out: V(MyString("\uFFFD"))},
  3622  	{in: V(int64(-5)), out: V(MyString("\uFFFD"))},
  3623  	{in: V(uint(0x110001)), out: V(MyString("\uFFFD"))},
  3624  	{in: V(uint32(0x110002)), out: V(MyString("\uFFFD"))},
  3625  	{in: V(uint64(0x110003)), out: V(MyString("\uFFFD"))},
  3626  	{in: V(uintptr(0x110004)), out: V(MyString("\uFFFD"))},
  3627  
  3628  	// named []byte
  3629  	{in: V(string("bytes1")), out: V(MyBytes("bytes1"))},
  3630  	{in: V(MyBytes("bytes2")), out: V(string("bytes2"))},
  3631  	{in: V(MyBytes("bytes3")), out: V(MyBytes("bytes3"))},
  3632  	{in: V(MyString("bytes1")), out: V(MyBytes("bytes1"))},
  3633  	{in: V(MyBytes("bytes2")), out: V(MyString("bytes2"))},
  3634  
  3635  	// named []rune
  3636  	{in: V(string("runes♝")), out: V(MyRunes("runes♝"))},
  3637  	{in: V(MyRunes("runes♕")), out: V(string("runes♕"))},
  3638  	{in: V(MyRunes("runes🙈🙉🙊")), out: V(MyRunes("runes🙈🙉🙊"))},
  3639  	{in: V(MyString("runes♝")), out: V(MyRunes("runes♝"))},
  3640  	{in: V(MyRunes("runes♕")), out: V(MyString("runes♕"))},
  3641  
  3642  	// named types and equal underlying types
  3643  	{in: V(new(int)), out: V(new(integer))},
  3644  	{in: V(new(integer)), out: V(new(int))},
  3645  	{in: V(Empty{}), out: V(struct{}{})},
  3646  	{in: V(new(Empty)), out: V(new(struct{}))},
  3647  	{in: V(struct{}{}), out: V(Empty{})},
  3648  	{in: V(new(struct{})), out: V(new(Empty))},
  3649  	{in: V(Empty{}), out: V(Empty{})},
  3650  	{in: V(MyBytes{}), out: V([]byte{})},
  3651  	{in: V([]byte{}), out: V(MyBytes{})},
  3652  	{in: V((func())(nil)), out: V(MyFunc(nil))},
  3653  	{in: V((MyFunc)(nil)), out: V((func())(nil))},
  3654  
  3655  	// structs with different tags
  3656  	{in: V(struct {
  3657  		x int `some:"foo"`
  3658  	}{}), out: V(struct {
  3659  		x int `some:"bar"`
  3660  	}{})},
  3661  
  3662  	{in: V(struct {
  3663  		x int `some:"bar"`
  3664  	}{}), out: V(struct {
  3665  		x int `some:"foo"`
  3666  	}{})},
  3667  
  3668  	{in: V(MyStruct{}), out: V(struct {
  3669  		x int `some:"foo"`
  3670  	}{})},
  3671  
  3672  	{in: V(struct {
  3673  		x int `some:"foo"`
  3674  	}{}), out: V(MyStruct{})},
  3675  
  3676  	{in: V(MyStruct{}), out: V(struct {
  3677  		x int `some:"bar"`
  3678  	}{})},
  3679  
  3680  	{in: V(struct {
  3681  		x int `some:"bar"`
  3682  	}{}), out: V(MyStruct{})},
  3683  
  3684  	// can convert *byte and *MyByte
  3685  	{in: V((*byte)(nil)), out: V((*MyByte)(nil))},
  3686  	{in: V((*MyByte)(nil)), out: V((*byte)(nil))},
  3687  
  3688  	// cannot convert mismatched array sizes
  3689  	{in: V([2]byte{}), out: V([2]byte{})},
  3690  	{in: V([3]byte{}), out: V([3]byte{})},
  3691  
  3692  	// cannot convert other instances
  3693  	{in: V((**byte)(nil)), out: V((**byte)(nil))},
  3694  	{in: V((**MyByte)(nil)), out: V((**MyByte)(nil))},
  3695  	{in: V((chan byte)(nil)), out: V((chan byte)(nil))},
  3696  	{in: V((chan MyByte)(nil)), out: V((chan MyByte)(nil))},
  3697  	{in: V(([]byte)(nil)), out: V(([]byte)(nil))},
  3698  	{in: V(([]MyByte)(nil)), out: V(([]MyByte)(nil))},
  3699  	{in: V((map[int]byte)(nil)), out: V((map[int]byte)(nil))},
  3700  	{in: V((map[int]MyByte)(nil)), out: V((map[int]MyByte)(nil))},
  3701  	{in: V((map[byte]int)(nil)), out: V((map[byte]int)(nil))},
  3702  	{in: V((map[MyByte]int)(nil)), out: V((map[MyByte]int)(nil))},
  3703  	{in: V([2]byte{}), out: V([2]byte{})},
  3704  	{in: V([2]MyByte{}), out: V([2]MyByte{})},
  3705  
  3706  	// other
  3707  	{in: V((***int)(nil)), out: V((***int)(nil))},
  3708  	{in: V((***byte)(nil)), out: V((***byte)(nil))},
  3709  	{in: V((***int32)(nil)), out: V((***int32)(nil))},
  3710  	{in: V((***int64)(nil)), out: V((***int64)(nil))},
  3711  	{in: V((chan int)(nil)), out: V((<-chan int)(nil))},
  3712  	{in: V((chan int)(nil)), out: V((chan<- int)(nil))},
  3713  	{in: V((chan string)(nil)), out: V((<-chan string)(nil))},
  3714  	{in: V((chan string)(nil)), out: V((chan<- string)(nil))},
  3715  	{in: V((chan byte)(nil)), out: V((chan byte)(nil))},
  3716  	{in: V((chan MyByte)(nil)), out: V((chan MyByte)(nil))},
  3717  	{in: V((map[int]bool)(nil)), out: V((map[int]bool)(nil))},
  3718  	{in: V((map[int]byte)(nil)), out: V((map[int]byte)(nil))},
  3719  	{in: V((map[uint]bool)(nil)), out: V((map[uint]bool)(nil))},
  3720  	{in: V([]uint(nil)), out: V([]uint(nil))},
  3721  	{in: V([]int(nil)), out: V([]int(nil))},
  3722  	{in: V(new(any)), out: V(new(any))},
  3723  	{in: V(new(io.Reader)), out: V(new(io.Reader))},
  3724  	{in: V(new(io.Writer)), out: V(new(io.Writer))},
  3725  
  3726  	// interfaces
  3727  	{in: V(int(1)), out: EmptyInterfaceV(int(1))},
  3728  	{in: V(string("hello")), out: EmptyInterfaceV(string("hello"))},
  3729  	{in: V(new(bytes.Buffer)), out: ReaderV(new(bytes.Buffer))},
  3730  	{in: ReadWriterV(new(bytes.Buffer)), out: ReaderV(new(bytes.Buffer))},
  3731  	{in: V(new(bytes.Buffer)), out: ReadWriterV(new(bytes.Buffer))},
  3732  }
  3733  
  3734  func TestConvert(t *testing.T) {
  3735  	canConvert := map[[2]Type]bool{}
  3736  	all := map[Type]bool{}
  3737  
  3738  	for _, tt := range convertTests {
  3739  		t1 := tt.in.Type()
  3740  		if !t1.ConvertibleTo(t1) {
  3741  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
  3742  			continue
  3743  		}
  3744  
  3745  		t2 := tt.out.Type()
  3746  		if !t1.ConvertibleTo(t2) {
  3747  			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
  3748  			continue
  3749  		}
  3750  
  3751  		all[t1] = true
  3752  		all[t2] = true
  3753  		canConvert[[2]Type{t1, t2}] = true
  3754  
  3755  		// vout1 represents the in value converted to the in type.
  3756  		v1 := tt.in
  3757  		vout1 := v1.Convert(t1)
  3758  		out1 := vout1.Interface()
  3759  		if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
  3760  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
  3761  		}
  3762  
  3763  		// vout2 represents the in value converted to the out type.
  3764  		vout2 := v1.Convert(t2)
  3765  		out2 := vout2.Interface()
  3766  		if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
  3767  			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
  3768  		}
  3769  
  3770  		// vout3 represents a new value of the out type, set to vout2.  This makes
  3771  		// sure the converted value vout2 is really usable as a regular value.
  3772  		vout3 := New(t2).Elem()
  3773  		vout3.Set(vout2)
  3774  		out3 := vout3.Interface()
  3775  		if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
  3776  			t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
  3777  		}
  3778  	}
  3779  
  3780  	// Assume that of all the types we saw during the tests,
  3781  	// if there wasn't an explicit entry for a conversion between
  3782  	// a pair of types, then it's not to be allowed. This checks for
  3783  	// things like 'int64' converting to '*int'.
  3784  	for t1 := range all {
  3785  		for t2 := range all {
  3786  			expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
  3787  			if ok := t1.ConvertibleTo(t2); ok != expectOK {
  3788  				t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
  3789  			}
  3790  		}
  3791  	}
  3792  }
  3793  
  3794  type ComparableStruct struct {
  3795  	X int
  3796  }
  3797  
  3798  type NonComparableStruct struct {
  3799  	X int
  3800  	Y map[string]int
  3801  }
  3802  
  3803  var comparableTests = []struct {
  3804  	typ Type
  3805  	ok  bool
  3806  }{
  3807  	{typ: TypeOf(1), ok: true},
  3808  	{typ: TypeOf("hello"), ok: true},
  3809  	{typ: TypeOf(new(byte)), ok: true},
  3810  	{typ: TypeOf((func())(nil)), ok: false},
  3811  	{typ: TypeOf([]byte{}), ok: false},
  3812  	{typ: TypeOf(map[string]int{}), ok: false},
  3813  	{typ: TypeOf(make(chan int)), ok: true},
  3814  	{typ: TypeOf(1.5), ok: true},
  3815  	{typ: TypeOf(false), ok: true},
  3816  	{typ: TypeOf(1i), ok: true},
  3817  	{typ: TypeOf(ComparableStruct{}), ok: true},
  3818  	{typ: TypeOf(NonComparableStruct{}), ok: false},
  3819  	{typ: TypeOf([10]map[string]int{}), ok: false},
  3820  	{typ: TypeOf([10]string{}), ok: true},
  3821  	{typ: TypeOf(new(any)).Elem(), ok: true},
  3822  }
  3823  
  3824  func TestComparable(t *testing.T) {
  3825  	for _, tt := range comparableTests {
  3826  		if ok := tt.typ.Comparable(); ok != tt.ok {
  3827  			t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
  3828  		}
  3829  	}
  3830  }
  3831  
  3832  func TestOverflow(t *testing.T) {
  3833  	if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
  3834  		t.Errorf("%v wrongly overflows float64", 1e300)
  3835  	}
  3836  
  3837  	maxFloat32 := float64((1<<24 - 1) << (127 - 23))
  3838  	if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
  3839  		t.Errorf("%v wrongly overflows float32", maxFloat32)
  3840  	}
  3841  	ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
  3842  	if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
  3843  		t.Errorf("%v should overflow float32", ovfFloat32)
  3844  	}
  3845  	if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
  3846  		t.Errorf("%v should overflow float32", -ovfFloat32)
  3847  	}
  3848  
  3849  	maxInt32 := int64(0x7fffffff)
  3850  	if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
  3851  		t.Errorf("%v wrongly overflows int32", maxInt32)
  3852  	}
  3853  	if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
  3854  		t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
  3855  	}
  3856  	ovfInt32 := int64(1 << 31)
  3857  	if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
  3858  		t.Errorf("%v should overflow int32", ovfInt32)
  3859  	}
  3860  
  3861  	maxUint32 := uint64(0xffffffff)
  3862  	if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
  3863  		t.Errorf("%v wrongly overflows uint32", maxUint32)
  3864  	}
  3865  	ovfUint32 := uint64(1 << 32)
  3866  	if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
  3867  		t.Errorf("%v should overflow uint32", ovfUint32)
  3868  	}
  3869  }
  3870  
  3871  func checkSameType(t *testing.T, x Type, y any) {
  3872  	if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
  3873  		t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
  3874  	}
  3875  }
  3876  
  3877  func TestArrayOf(t *testing.T) {
  3878  	// check construction and use of type not in binary
  3879  	tests := []struct {
  3880  		n          int
  3881  		value      func(i int) any
  3882  		comparable bool
  3883  		want       string
  3884  	}{
  3885  		{
  3886  			n:          0,
  3887  			value:      func(i int) any { type Tint int; return Tint(i) },
  3888  			comparable: true,
  3889  			want:       "[]",
  3890  		},
  3891  		{
  3892  			n:          10,
  3893  			value:      func(i int) any { type Tint int; return Tint(i) },
  3894  			comparable: true,
  3895  			want:       "[0 1 2 3 4 5 6 7 8 9]",
  3896  		},
  3897  		{
  3898  			n:          10,
  3899  			value:      func(i int) any { type Tfloat float64; return Tfloat(i) },
  3900  			comparable: true,
  3901  			want:       "[0 1 2 3 4 5 6 7 8 9]",
  3902  		},
  3903  		{
  3904  			n:          10,
  3905  			value:      func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
  3906  			comparable: true,
  3907  			want:       "[0 1 2 3 4 5 6 7 8 9]",
  3908  		},
  3909  		{
  3910  			n:          10,
  3911  			value:      func(i int) any { type Tstruct struct{ V int }; return Tstruct{V: i} },
  3912  			comparable: true,
  3913  			want:       "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
  3914  		},
  3915  		{
  3916  			n:          10,
  3917  			value:      func(i int) any { type Tint int; return []Tint{Tint(i)} },
  3918  			comparable: false,
  3919  			want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
  3920  		},
  3921  		{
  3922  			n:          10,
  3923  			value:      func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
  3924  			comparable: true,
  3925  			want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
  3926  		},
  3927  		{
  3928  			n:          10,
  3929  			value:      func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{V: [1]int{i}} },
  3930  			comparable: true,
  3931  			want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
  3932  		},
  3933  		{
  3934  			n:          10,
  3935  			value:      func(i int) any { type Tstruct struct{ V []int }; return Tstruct{V: []int{i}} },
  3936  			comparable: false,
  3937  			want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
  3938  		},
  3939  		{
  3940  			n:          10,
  3941  			value:      func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{U: i, V: i} },
  3942  			comparable: true,
  3943  			want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
  3944  		},
  3945  		{
  3946  			n: 10,
  3947  			value: func(i int) any {
  3948  				type TstructUV struct {
  3949  					U int
  3950  					V float64
  3951  				}
  3952  				return TstructUV{U: i, V: float64(i)}
  3953  			},
  3954  			comparable: true,
  3955  			want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
  3956  		},
  3957  	}
  3958  
  3959  	for _, table := range tests {
  3960  		at := ArrayOf(table.n, TypeOf(table.value(0)))
  3961  		v := New(at).Elem()
  3962  		vok := New(at).Elem()
  3963  		vnot := New(at).Elem()
  3964  		for i := 0; i < v.Len(); i++ {
  3965  			v.Index(i).Set(ValueOf(table.value(i)))
  3966  			vok.Index(i).Set(ValueOf(table.value(i)))
  3967  			j := i
  3968  			if i+1 == v.Len() {
  3969  				j = i + 1
  3970  			}
  3971  			vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
  3972  		}
  3973  		s := fmt.Sprint(v.Interface())
  3974  		if s != table.want {
  3975  			t.Errorf("constructed array = %s, want %s", s, table.want)
  3976  		}
  3977  
  3978  		if table.comparable != at.Comparable() {
  3979  			t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
  3980  		}
  3981  		if table.comparable {
  3982  			if table.n > 0 {
  3983  				if DeepEqual(vnot.Interface(), v.Interface()) {
  3984  					t.Errorf(
  3985  						"arrays (%#v) compare ok (but should not)",
  3986  						v.Interface(),
  3987  					)
  3988  				}
  3989  			}
  3990  			if !DeepEqual(vok.Interface(), v.Interface()) {
  3991  				t.Errorf(
  3992  					"arrays (%#v) compare NOT-ok (but should)",
  3993  					v.Interface(),
  3994  				)
  3995  			}
  3996  		}
  3997  	}
  3998  
  3999  	// check that type already in binary is found
  4000  	type T int
  4001  	checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
  4002  }
  4003  
  4004  func TestArrayOfGC(t *testing.T) {
  4005  	type T *uintptr
  4006  	tt := TypeOf(T(nil))
  4007  	const n = 100
  4008  	var x []any
  4009  	for i := 0; i < n; i++ {
  4010  		v := New(ArrayOf(n, tt)).Elem()
  4011  		for j := 0; j < v.Len(); j++ {
  4012  			p := new(uintptr)
  4013  			*p = uintptr(i*n + j)
  4014  			v.Index(j).Set(ValueOf(p).Convert(tt))
  4015  		}
  4016  		x = append(x, v.Interface())
  4017  	}
  4018  	runtime.GC()
  4019  
  4020  	for i, xi := range x {
  4021  		v := ValueOf(xi)
  4022  		for j := 0; j < v.Len(); j++ {
  4023  			k := v.Index(j).Elem().Interface()
  4024  			if k != uintptr(i*n+j) {
  4025  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  4026  			}
  4027  		}
  4028  	}
  4029  }
  4030  
  4031  func TestArrayOfAlg(t *testing.T) {
  4032  	at := ArrayOf(6, TypeOf(byte(0)))
  4033  	v1 := New(at).Elem()
  4034  	v2 := New(at).Elem()
  4035  	if v1.Interface() != v1.Interface() {
  4036  		t.Errorf("constructed array %v not equal to itself", v1.Interface())
  4037  	}
  4038  	v1.Index(5).Set(ValueOf(byte(1)))
  4039  	if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
  4040  		t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
  4041  	}
  4042  
  4043  	at = ArrayOf(6, TypeOf([]int(nil)))
  4044  	v1 = New(at).Elem()
  4045  	shouldPanic(func() { _ = v1.Interface() == v1.Interface() })
  4046  }
  4047  
  4048  func TestArrayOfGenericAlg(t *testing.T) {
  4049  	at1 := ArrayOf(5, TypeOf(string("")))
  4050  	at := ArrayOf(6, at1)
  4051  	v1 := New(at).Elem()
  4052  	v2 := New(at).Elem()
  4053  	if v1.Interface() != v1.Interface() {
  4054  		t.Errorf("constructed array %v not equal to itself", v1.Interface())
  4055  	}
  4056  
  4057  	v1.Index(0).Index(0).Set(ValueOf("abc"))
  4058  	v2.Index(0).Index(0).Set(ValueOf("efg"))
  4059  	if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
  4060  		t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
  4061  	}
  4062  
  4063  	v1.Index(0).Index(0).Set(ValueOf("abc"))
  4064  	v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
  4065  	if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
  4066  		t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
  4067  	}
  4068  
  4069  	// Test hash
  4070  	m := MakeMap(MapOf(at, TypeOf(int(0))))
  4071  	m.SetMapIndex(v1, ValueOf(1))
  4072  	if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
  4073  		t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
  4074  	}
  4075  }
  4076  
  4077  func TestArrayOfDirectIface(t *testing.T) {
  4078  	{
  4079  		type T [1]*byte
  4080  		i1 := Zero(TypeOf(T{})).Interface()
  4081  		v1 := ValueOf(&i1).Elem()
  4082  		p1 := v1.InterfaceData()[1]
  4083  
  4084  		i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
  4085  		v2 := ValueOf(&i2).Elem()
  4086  		p2 := v2.InterfaceData()[1]
  4087  
  4088  		if p1 != 0 {
  4089  			t.Errorf("got p1=%v. want=%v", p1, nil)
  4090  		}
  4091  
  4092  		if p2 != 0 {
  4093  			t.Errorf("got p2=%v. want=%v", p2, nil)
  4094  		}
  4095  	}
  4096  	{
  4097  		type T [0]*byte
  4098  		i1 := Zero(TypeOf(T{})).Interface()
  4099  		v1 := ValueOf(&i1).Elem()
  4100  		p1 := v1.InterfaceData()[1]
  4101  
  4102  		i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
  4103  		v2 := ValueOf(&i2).Elem()
  4104  		p2 := v2.InterfaceData()[1]
  4105  
  4106  		if p1 == 0 {
  4107  			t.Errorf("got p1=%v. want=not-%v", p1, nil)
  4108  		}
  4109  
  4110  		if p2 == 0 {
  4111  			t.Errorf("got p2=%v. want=not-%v", p2, nil)
  4112  		}
  4113  	}
  4114  }
  4115  
  4116  func TestSliceOf(t *testing.T) {
  4117  	// check construction and use of type not in binary
  4118  	type T int
  4119  	st := SliceOf(TypeOf(T(1)))
  4120  	if got, want := st.String(), "[]reflect_test.T"; got != want {
  4121  		t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
  4122  	}
  4123  	v := MakeSlice(st, 10, 10)
  4124  	runtime.GC()
  4125  	for i := 0; i < v.Len(); i++ {
  4126  		v.Index(i).Set(ValueOf(T(i)))
  4127  		runtime.GC()
  4128  	}
  4129  	s := fmt.Sprint(v.Interface())
  4130  	want := "[0 1 2 3 4 5 6 7 8 9]"
  4131  	if s != want {
  4132  		t.Errorf("constructed slice = %s, want %s", s, want)
  4133  	}
  4134  
  4135  	// check that type already in binary is found
  4136  	type T1 int
  4137  	checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
  4138  }
  4139  
  4140  func TestSliceOverflow(t *testing.T) {
  4141  	// check that MakeSlice panics when size of slice overflows uint
  4142  	const S = 1e6
  4143  	s := uint(S)
  4144  	l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
  4145  	if l*s >= s {
  4146  		t.Fatal("slice size does not overflow")
  4147  	}
  4148  	var x [S]byte
  4149  	st := SliceOf(TypeOf(x))
  4150  	defer func() {
  4151  		err := recover()
  4152  		if err == nil {
  4153  			t.Fatal("slice overflow does not panic")
  4154  		}
  4155  	}()
  4156  	MakeSlice(st, int(l), int(l))
  4157  }
  4158  
  4159  func TestSliceOfGC(t *testing.T) {
  4160  	type T *uintptr
  4161  	tt := TypeOf(T(nil))
  4162  	st := SliceOf(tt)
  4163  	const n = 100
  4164  	var x []any
  4165  	for i := 0; i < n; i++ {
  4166  		v := MakeSlice(st, n, n)
  4167  		for j := 0; j < v.Len(); j++ {
  4168  			p := new(uintptr)
  4169  			*p = uintptr(i*n + j)
  4170  			v.Index(j).Set(ValueOf(p).Convert(tt))
  4171  		}
  4172  		x = append(x, v.Interface())
  4173  	}
  4174  	runtime.GC()
  4175  
  4176  	for i, xi := range x {
  4177  		v := ValueOf(xi)
  4178  		for j := 0; j < v.Len(); j++ {
  4179  			k := v.Index(j).Elem().Interface()
  4180  			if k != uintptr(i*n+j) {
  4181  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  4182  			}
  4183  		}
  4184  	}
  4185  }
  4186  
  4187  func TestStructOfFieldName(t *testing.T) {
  4188  	// invalid field name "1nvalid"
  4189  	shouldPanic(func() {
  4190  		StructOf([]StructField{
  4191  			{Name: "valid", Type: TypeOf("")},
  4192  			{Name: "1nvalid", Type: TypeOf("")},
  4193  		})
  4194  	})
  4195  
  4196  	// invalid field name "+"
  4197  	shouldPanic(func() {
  4198  		StructOf([]StructField{
  4199  			{Name: "val1d", Type: TypeOf("")},
  4200  			{Name: "+", Type: TypeOf("")},
  4201  		})
  4202  	})
  4203  
  4204  	// no field name
  4205  	shouldPanic(func() {
  4206  		StructOf([]StructField{
  4207  			{Name: "", Type: TypeOf("")},
  4208  		})
  4209  	})
  4210  
  4211  	// verify creation of a struct with valid struct fields
  4212  	validFields := []StructField{
  4213  		{
  4214  			Name: "φ",
  4215  			Type: TypeOf(""),
  4216  		},
  4217  		{
  4218  			Name: "ValidName",
  4219  			Type: TypeOf(""),
  4220  		},
  4221  		{
  4222  			Name: "Val1dNam5",
  4223  			Type: TypeOf(""),
  4224  		},
  4225  	}
  4226  
  4227  	validStruct := StructOf(validFields)
  4228  
  4229  	const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
  4230  	if got, want := validStruct.String(), structStr; got != want {
  4231  		t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
  4232  	}
  4233  }
  4234  
  4235  func TestStructOf(t *testing.T) {
  4236  	// check construction and use of type not in binary
  4237  	fields := []StructField{
  4238  		{
  4239  			Name: "S",
  4240  			Tag:  "s",
  4241  			Type: TypeOf(""),
  4242  		},
  4243  		{
  4244  			Name: "X",
  4245  			Tag:  "x",
  4246  			Type: TypeOf(byte(0)),
  4247  		},
  4248  		{
  4249  			Name: "Y",
  4250  			Type: TypeOf(uint64(0)),
  4251  		},
  4252  		{
  4253  			Name: "Z",
  4254  			Type: TypeOf([3]uint16{}),
  4255  		},
  4256  	}
  4257  
  4258  	st := StructOf(fields)
  4259  	v := New(st).Elem()
  4260  	runtime.GC()
  4261  	v.FieldByName("X").Set(ValueOf(byte(2)))
  4262  	v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
  4263  	runtime.GC()
  4264  
  4265  	s := fmt.Sprint(v.Interface())
  4266  	want := `{ 1 0 [0 0 0]}`
  4267  	if s != want {
  4268  		t.Errorf("constructed struct = %s, want %s", s, want)
  4269  	}
  4270  	const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
  4271  	if got, want := st.String(), stStr; got != want {
  4272  		t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
  4273  	}
  4274  
  4275  	// check the size, alignment and field offsets
  4276  	stt := TypeOf(struct {
  4277  		String string
  4278  		X      byte
  4279  		Y      uint64
  4280  		Z      [3]uint16
  4281  	}{})
  4282  	if st.Size() != stt.Size() {
  4283  		t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
  4284  	}
  4285  	if st.Align() != stt.Align() {
  4286  		t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
  4287  	}
  4288  	if st.FieldAlign() != stt.FieldAlign() {
  4289  		t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
  4290  	}
  4291  	for i := 0; i < st.NumField(); i++ {
  4292  		o1 := st.Field(i).Offset
  4293  		o2 := stt.Field(i).Offset
  4294  		if o1 != o2 {
  4295  			t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
  4296  		}
  4297  	}
  4298  
  4299  	// Check size and alignment with a trailing zero-sized field.
  4300  	st = StructOf([]StructField{
  4301  		{
  4302  			Name: "F1",
  4303  			Type: TypeOf(byte(0)),
  4304  		},
  4305  		{
  4306  			Name: "F2",
  4307  			Type: TypeOf([0]*byte{}),
  4308  		},
  4309  	})
  4310  	stt = TypeOf(struct {
  4311  		G1 byte
  4312  		G2 [0]*byte
  4313  	}{})
  4314  	if st.Size() != stt.Size() {
  4315  		t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
  4316  	}
  4317  	if st.Align() != stt.Align() {
  4318  		t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
  4319  	}
  4320  	if st.FieldAlign() != stt.FieldAlign() {
  4321  		t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
  4322  	}
  4323  	for i := 0; i < st.NumField(); i++ {
  4324  		o1 := st.Field(i).Offset
  4325  		o2 := stt.Field(i).Offset
  4326  		if o1 != o2 {
  4327  			t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
  4328  		}
  4329  	}
  4330  
  4331  	// check duplicate names
  4332  	shouldPanic(func() {
  4333  		StructOf([]StructField{
  4334  			{Name: "string", Type: TypeOf("")},
  4335  			{Name: "string", Type: TypeOf("")},
  4336  		})
  4337  	})
  4338  	shouldPanic(func() {
  4339  		StructOf([]StructField{
  4340  			{Type: TypeOf("")},
  4341  			{Name: "string", Type: TypeOf("")},
  4342  		})
  4343  	})
  4344  	shouldPanic(func() {
  4345  		StructOf([]StructField{
  4346  			{Type: TypeOf("")},
  4347  			{Type: TypeOf("")},
  4348  		})
  4349  	})
  4350  	// check that type already in binary is found
  4351  	checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
  4352  
  4353  	// gccgo used to fail this test.
  4354  	type structFieldType any
  4355  	checkSameType(t,
  4356  		StructOf([]StructField{
  4357  			{
  4358  				Name: "F",
  4359  				Type: TypeOf((*structFieldType)(nil)).Elem(),
  4360  			},
  4361  		}),
  4362  		struct{ F structFieldType }{})
  4363  }
  4364  
  4365  // isExported reports whether name is an exported Go symbol
  4366  // (that is, whether it begins with an upper-case letter).
  4367  func isExported(name string) bool {
  4368  	ch, _ := utf8.DecodeRuneInString(name)
  4369  	return unicode.IsUpper(ch)
  4370  }
  4371  
  4372  func TestStructOfGC(t *testing.T) {
  4373  	type T *uintptr
  4374  	tt := TypeOf(T(nil))
  4375  	fields := []StructField{
  4376  		{Name: "X", Type: tt},
  4377  		{Name: "Y", Type: tt},
  4378  	}
  4379  	st := StructOf(fields)
  4380  
  4381  	const n = 10000
  4382  	var x []any
  4383  	for i := 0; i < n; i++ {
  4384  		v := New(st).Elem()
  4385  		for j := 0; j < v.NumField(); j++ {
  4386  			p := new(uintptr)
  4387  			*p = uintptr(i*n + j)
  4388  			v.Field(j).Set(ValueOf(p).Convert(tt))
  4389  		}
  4390  		x = append(x, v.Interface())
  4391  	}
  4392  	runtime.GC()
  4393  
  4394  	for i, xi := range x {
  4395  		v := ValueOf(xi)
  4396  		for j := 0; j < v.NumField(); j++ {
  4397  			k := v.Field(j).Elem().Interface()
  4398  			if k != uintptr(i*n+j) {
  4399  				t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
  4400  			}
  4401  		}
  4402  	}
  4403  }
  4404  
  4405  func TestStructOfAlg(t *testing.T) {
  4406  	st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
  4407  	v1 := New(st).Elem()
  4408  	v2 := New(st).Elem()
  4409  	if !DeepEqual(v1.Interface(), v1.Interface()) {
  4410  		t.Errorf("constructed struct %v not equal to itself", v1.Interface())
  4411  	}
  4412  	v1.FieldByName("X").Set(ValueOf(int(1)))
  4413  	if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
  4414  		t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
  4415  	}
  4416  
  4417  	st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
  4418  	v1 = New(st).Elem()
  4419  	shouldPanic(func() { _ = v1.Interface() == v1.Interface() })
  4420  }
  4421  
  4422  func TestStructOfGenericAlg(t *testing.T) {
  4423  	st1 := StructOf([]StructField{
  4424  		{Name: "X", Tag: "x", Type: TypeOf(int64(0))},
  4425  		{Name: "Y", Type: TypeOf(string(""))},
  4426  	})
  4427  	st := StructOf([]StructField{
  4428  		{Name: "S0", Type: st1},
  4429  		{Name: "S1", Type: st1},
  4430  	})
  4431  
  4432  	tests := []struct {
  4433  		rt  Type
  4434  		idx []int
  4435  	}{
  4436  		{
  4437  			rt:  st,
  4438  			idx: []int{0, 1},
  4439  		},
  4440  		{
  4441  			rt:  st1,
  4442  			idx: []int{1},
  4443  		},
  4444  		{
  4445  			rt: StructOf(
  4446  				[]StructField{
  4447  					{Name: "XX", Type: TypeOf([0]int{})},
  4448  					{Name: "YY", Type: TypeOf("")},
  4449  				},
  4450  			),
  4451  			idx: []int{1},
  4452  		},
  4453  		{
  4454  			rt: StructOf(
  4455  				[]StructField{
  4456  					{Name: "XX", Type: TypeOf([0]int{})},
  4457  					{Name: "YY", Type: TypeOf("")},
  4458  					{Name: "ZZ", Type: TypeOf([2]int{})},
  4459  				},
  4460  			),
  4461  			idx: []int{1},
  4462  		},
  4463  		{
  4464  			rt: StructOf(
  4465  				[]StructField{
  4466  					{Name: "XX", Type: TypeOf([1]int{})},
  4467  					{Name: "YY", Type: TypeOf("")},
  4468  				},
  4469  			),
  4470  			idx: []int{1},
  4471  		},
  4472  		{
  4473  			rt: StructOf(
  4474  				[]StructField{
  4475  					{Name: "XX", Type: TypeOf([1]int{})},
  4476  					{Name: "YY", Type: TypeOf("")},
  4477  					{Name: "ZZ", Type: TypeOf([1]int{})},
  4478  				},
  4479  			),
  4480  			idx: []int{1},
  4481  		},
  4482  		{
  4483  			rt: StructOf(
  4484  				[]StructField{
  4485  					{Name: "XX", Type: TypeOf([2]int{})},
  4486  					{Name: "YY", Type: TypeOf("")},
  4487  					{Name: "ZZ", Type: TypeOf([2]int{})},
  4488  				},
  4489  			),
  4490  			idx: []int{1},
  4491  		},
  4492  		{
  4493  			rt: StructOf(
  4494  				[]StructField{
  4495  					{Name: "XX", Type: TypeOf(int64(0))},
  4496  					{Name: "YY", Type: TypeOf(byte(0))},
  4497  					{Name: "ZZ", Type: TypeOf("")},
  4498  				},
  4499  			),
  4500  			idx: []int{2},
  4501  		},
  4502  		{
  4503  			rt: StructOf(
  4504  				[]StructField{
  4505  					{Name: "XX", Type: TypeOf(int64(0))},
  4506  					{Name: "YY", Type: TypeOf(int64(0))},
  4507  					{Name: "ZZ", Type: TypeOf("")},
  4508  					{Name: "AA", Type: TypeOf([1]int64{})},
  4509  				},
  4510  			),
  4511  			idx: []int{2},
  4512  		},
  4513  	}
  4514  
  4515  	for _, table := range tests {
  4516  		v1 := New(table.rt).Elem()
  4517  		v2 := New(table.rt).Elem()
  4518  
  4519  		if !DeepEqual(v1.Interface(), v1.Interface()) {
  4520  			t.Errorf("constructed struct %v not equal to itself", v1.Interface())
  4521  		}
  4522  
  4523  		v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
  4524  		v2.FieldByIndex(table.idx).Set(ValueOf("def"))
  4525  		if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
  4526  			t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
  4527  		}
  4528  
  4529  		abc := "abc"
  4530  		v1.FieldByIndex(table.idx).Set(ValueOf(abc))
  4531  		val := "+" + abc + "-"
  4532  		v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
  4533  		if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
  4534  			t.Errorf("constructed structs %v and %v should be equal", i1, i2)
  4535  		}
  4536  
  4537  		// Test hash
  4538  		m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
  4539  		m.SetMapIndex(v1, ValueOf(1))
  4540  		if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
  4541  			t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
  4542  		}
  4543  
  4544  		v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
  4545  		if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
  4546  			t.Errorf("constructed structs %v and %v should be equal", i1, i2)
  4547  		}
  4548  
  4549  		if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
  4550  			t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
  4551  		}
  4552  	}
  4553  }
  4554  
  4555  func TestStructOfDirectIface(t *testing.T) {
  4556  	{
  4557  		type T struct{ X [1]*byte }
  4558  		i1 := Zero(TypeOf(T{})).Interface()
  4559  		v1 := ValueOf(&i1).Elem()
  4560  		p1 := v1.InterfaceData()[1]
  4561  
  4562  		i2 := Zero(StructOf([]StructField{
  4563  			{
  4564  				Name: "X",
  4565  				Type: ArrayOf(1, TypeOf((*int8)(nil))),
  4566  			},
  4567  		})).Interface()
  4568  		v2 := ValueOf(&i2).Elem()
  4569  		p2 := v2.InterfaceData()[1]
  4570  
  4571  		if p1 != 0 {
  4572  			t.Errorf("got p1=%v. want=%v", p1, nil)
  4573  		}
  4574  
  4575  		if p2 != 0 {
  4576  			t.Errorf("got p2=%v. want=%v", p2, nil)
  4577  		}
  4578  	}
  4579  	{
  4580  		type T struct{ X [0]*byte }
  4581  		i1 := Zero(TypeOf(T{})).Interface()
  4582  		v1 := ValueOf(&i1).Elem()
  4583  		p1 := v1.InterfaceData()[1]
  4584  
  4585  		i2 := Zero(StructOf([]StructField{
  4586  			{
  4587  				Name: "X",
  4588  				Type: ArrayOf(0, TypeOf((*int8)(nil))),
  4589  			},
  4590  		})).Interface()
  4591  		v2 := ValueOf(&i2).Elem()
  4592  		p2 := v2.InterfaceData()[1]
  4593  
  4594  		if p1 == 0 {
  4595  			t.Errorf("got p1=%v. want=not-%v", p1, nil)
  4596  		}
  4597  
  4598  		if p2 == 0 {
  4599  			t.Errorf("got p2=%v. want=not-%v", p2, nil)
  4600  		}
  4601  	}
  4602  }
  4603  
  4604  type StructI int
  4605  
  4606  func (i StructI) Get() int { return int(i) }
  4607  
  4608  type StructIPtr int
  4609  
  4610  func (i *StructIPtr) Get() int { return int(*i) }
  4611  
  4612  func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
  4613  
  4614  type SettableStruct struct {
  4615  	SettableField int
  4616  }
  4617  
  4618  func (p *SettableStruct) Set(v int) { p.SettableField = v }
  4619  
  4620  type SettablePointer struct {
  4621  	SettableField *int
  4622  }
  4623  
  4624  func (p *SettablePointer) Set(v int) { *p.SettableField = v }
  4625  
  4626  func TestStructOfWithInterface(t *testing.T) {
  4627  	const want = 42
  4628  	type Iface interface {
  4629  		Get() int
  4630  	}
  4631  	type IfaceSet interface {
  4632  		Set(int)
  4633  	}
  4634  	tests := []struct {
  4635  		name string
  4636  		typ  Type
  4637  		val  Value
  4638  		impl bool
  4639  	}{
  4640  		{
  4641  			name: "StructI",
  4642  			typ:  TypeOf(StructI(want)),
  4643  			val:  ValueOf(StructI(want)),
  4644  			impl: true,
  4645  		},
  4646  		{
  4647  			name: "StructI",
  4648  			typ:  PtrTo(TypeOf(StructI(want))),
  4649  			val: ValueOf(func() any {
  4650  				v := StructI(want)
  4651  				return &v
  4652  			}()),
  4653  			impl: true,
  4654  		},
  4655  		{
  4656  			name: "StructIPtr",
  4657  			typ:  PtrTo(TypeOf(StructIPtr(want))),
  4658  			val: ValueOf(func() any {
  4659  				v := StructIPtr(want)
  4660  				return &v
  4661  			}()),
  4662  			impl: true,
  4663  		},
  4664  		{
  4665  			name: "StructIPtr",
  4666  			typ:  TypeOf(StructIPtr(want)),
  4667  			val:  ValueOf(StructIPtr(want)),
  4668  			impl: false,
  4669  		},
  4670  		// {
  4671  		//	typ:  TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
  4672  		//	val:  ValueOf(StructI(want)),
  4673  		//	impl: true,
  4674  		// },
  4675  	}
  4676  
  4677  	for i, table := range tests {
  4678  		for j := 0; j < 2; j++ {
  4679  			var fields []StructField
  4680  			if j == 1 {
  4681  				fields = append(fields, StructField{
  4682  					Name:    "Dummy",
  4683  					PkgPath: "",
  4684  					Type:    TypeOf(int(0)),
  4685  				})
  4686  			}
  4687  			fields = append(fields, StructField{
  4688  				Name:      table.name,
  4689  				Anonymous: true,
  4690  				PkgPath:   "",
  4691  				Type:      table.typ,
  4692  			})
  4693  
  4694  			// We currently do not correctly implement methods
  4695  			// for embedded fields other than the first.
  4696  			// Therefore, for now, we expect those methods
  4697  			// to not exist.  See issues 15924 and 20824.
  4698  			// When those issues are fixed, this test of panic
  4699  			// should be removed.
  4700  			if j == 1 && table.impl {
  4701  				func() {
  4702  					defer func() {
  4703  						if err := recover(); err == nil {
  4704  							t.Errorf("test-%d-%d did not panic", i, j)
  4705  						}
  4706  					}()
  4707  					_ = StructOf(fields)
  4708  				}()
  4709  				continue
  4710  			}
  4711  
  4712  			rt := StructOf(fields)
  4713  			rv := New(rt).Elem()
  4714  			rv.Field(j).Set(table.val)
  4715  
  4716  			if _, ok := rv.Interface().(Iface); ok != table.impl {
  4717  				if table.impl {
  4718  					t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
  4719  				} else {
  4720  					t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
  4721  				}
  4722  				continue
  4723  			}
  4724  
  4725  			if !table.impl {
  4726  				continue
  4727  			}
  4728  
  4729  			v := rv.Interface().(Iface).Get()
  4730  			if v != want {
  4731  				t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
  4732  			}
  4733  
  4734  			fct := rv.MethodByName("Get")
  4735  			out := fct.Call(nil)
  4736  			if !DeepEqual(out[0].Interface(), want) {
  4737  				t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
  4738  			}
  4739  		}
  4740  	}
  4741  
  4742  	// Test an embedded nil pointer with pointer methods.
  4743  	fields := []StructField{{
  4744  		Name:      "StructIPtr",
  4745  		Anonymous: true,
  4746  		Type:      PtrTo(TypeOf(StructIPtr(want))),
  4747  	}}
  4748  	rt := StructOf(fields)
  4749  	rv := New(rt).Elem()
  4750  	// This should panic since the pointer is nil.
  4751  	shouldPanic(func() {
  4752  		rv.Interface().(IfaceSet).Set(want)
  4753  	})
  4754  
  4755  	// Test an embedded nil pointer to a struct with pointer methods.
  4756  
  4757  	fields = []StructField{{
  4758  		Name:      "SettableStruct",
  4759  		Anonymous: true,
  4760  		Type:      PtrTo(TypeOf(SettableStruct{})),
  4761  	}}
  4762  	rt = StructOf(fields)
  4763  	rv = New(rt).Elem()
  4764  	// This should panic since the pointer is nil.
  4765  	shouldPanic(func() {
  4766  		rv.Interface().(IfaceSet).Set(want)
  4767  	})
  4768  
  4769  	// The behavior is different if there is a second field,
  4770  	// since now an interface value holds a pointer to the struct
  4771  	// rather than just holding a copy of the struct.
  4772  	fields = []StructField{
  4773  		{
  4774  			Name:      "SettableStruct",
  4775  			Anonymous: true,
  4776  			Type:      PtrTo(TypeOf(SettableStruct{})),
  4777  		},
  4778  		{
  4779  			Name:      "EmptyStruct",
  4780  			Anonymous: true,
  4781  			Type:      StructOf(nil),
  4782  		},
  4783  	}
  4784  	// With the current implementation this is expected to panic.
  4785  	// Ideally it should work and we should be able to see a panic
  4786  	// if we call the Set method.
  4787  	shouldPanic(func() {
  4788  		StructOf(fields)
  4789  	})
  4790  
  4791  	// Embed a field that can be stored directly in an interface,
  4792  	// with a second field.
  4793  	fields = []StructField{
  4794  		{
  4795  			Name:      "SettablePointer",
  4796  			Anonymous: true,
  4797  			Type:      TypeOf(SettablePointer{}),
  4798  		},
  4799  		{
  4800  			Name:      "EmptyStruct",
  4801  			Anonymous: true,
  4802  			Type:      StructOf(nil),
  4803  		},
  4804  	}
  4805  	// With the current implementation this is expected to panic.
  4806  	// Ideally it should work and we should be able to call the
  4807  	// Set and Get methods.
  4808  	shouldPanic(func() {
  4809  		StructOf(fields)
  4810  	})
  4811  }
  4812  
  4813  func TestStructOfTooManyFields(t *testing.T) {
  4814  	// Bug Fix: #25402 - this should not panic
  4815  	tt := StructOf([]StructField{
  4816  		{Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
  4817  	})
  4818  
  4819  	if _, present := tt.MethodByName("After"); !present {
  4820  		t.Errorf("Expected method `After` to be found")
  4821  	}
  4822  }
  4823  
  4824  func TestChanOf(t *testing.T) {
  4825  	// check construction and use of type not in binary
  4826  	type T string
  4827  	ct := ChanOf(BothDir, TypeOf(T("")))
  4828  	v := MakeChan(ct, 2)
  4829  	runtime.GC()
  4830  	v.Send(ValueOf(T("hello")))
  4831  	runtime.GC()
  4832  	v.Send(ValueOf(T("world")))
  4833  	runtime.GC()
  4834  
  4835  	sv1, _ := v.Recv()
  4836  	sv2, _ := v.Recv()
  4837  	s1 := sv1.String()
  4838  	s2 := sv2.String()
  4839  	if s1 != "hello" || s2 != "world" {
  4840  		t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
  4841  	}
  4842  
  4843  	// check that type already in binary is found
  4844  	type T1 int
  4845  	checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
  4846  }
  4847  
  4848  func TestChanOfDir(t *testing.T) {
  4849  	// check construction and use of type not in binary
  4850  	type T string
  4851  	crt := ChanOf(RecvDir, TypeOf(T("")))
  4852  	cst := ChanOf(SendDir, TypeOf(T("")))
  4853  
  4854  	// check that type already in binary is found
  4855  	type T1 int
  4856  	checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
  4857  	checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
  4858  
  4859  	// check String form of ChanDir
  4860  	if crt.ChanDir().String() != "<-chan" {
  4861  		t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
  4862  	}
  4863  	if cst.ChanDir().String() != "chan<-" {
  4864  		t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
  4865  	}
  4866  }
  4867  
  4868  func TestChanOfGC(t *testing.T) {
  4869  	done := make(chan bool, 1)
  4870  	go func() {
  4871  		select {
  4872  		case <-done:
  4873  		case <-time.After(5 * time.Second):
  4874  			panic("deadlock in TestChanOfGC")
  4875  		}
  4876  	}()
  4877  
  4878  	defer func() {
  4879  		done <- true
  4880  	}()
  4881  
  4882  	type T *uintptr
  4883  	tt := TypeOf(T(nil))
  4884  	ct := ChanOf(BothDir, tt)
  4885  
  4886  	// NOTE: The garbage collector handles allocated channels specially,
  4887  	// so we have to save pointers to channels in x; the pointer code will
  4888  	// use the gc info in the newly constructed chan type.
  4889  	const n = 100
  4890  	var x []any
  4891  	for i := 0; i < n; i++ {
  4892  		v := MakeChan(ct, n)
  4893  		for j := 0; j < n; j++ {
  4894  			p := new(uintptr)
  4895  			*p = uintptr(i*n + j)
  4896  			v.Send(ValueOf(p).Convert(tt))
  4897  		}
  4898  		pv := New(ct)
  4899  		pv.Elem().Set(v)
  4900  		x = append(x, pv.Interface())
  4901  	}
  4902  	runtime.GC()
  4903  
  4904  	for i, xi := range x {
  4905  		v := ValueOf(xi).Elem()
  4906  		for j := 0; j < n; j++ {
  4907  			pv, _ := v.Recv()
  4908  			k := pv.Elem().Interface()
  4909  			if k != uintptr(i*n+j) {
  4910  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  4911  			}
  4912  		}
  4913  	}
  4914  }
  4915  
  4916  func TestMapOf(t *testing.T) {
  4917  	// check construction and use of type not in binary
  4918  	type K string
  4919  	type V float64
  4920  
  4921  	v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
  4922  	runtime.GC()
  4923  	v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
  4924  	runtime.GC()
  4925  
  4926  	s := fmt.Sprint(v.Interface())
  4927  	want := "map[a:1]"
  4928  	if s != want {
  4929  		t.Errorf("constructed map = %s, want %s", s, want)
  4930  	}
  4931  
  4932  	// check that type already in binary is found
  4933  	checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
  4934  
  4935  	// check that invalid key type panics
  4936  	shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
  4937  }
  4938  
  4939  func TestMapOfGCKeys(t *testing.T) {
  4940  	type T *uintptr
  4941  	tt := TypeOf(T(nil))
  4942  	mt := MapOf(tt, TypeOf(false))
  4943  
  4944  	// NOTE: The garbage collector handles allocated maps specially,
  4945  	// so we have to save pointers to maps in x; the pointer code will
  4946  	// use the gc info in the newly constructed map type.
  4947  	const n = 100
  4948  	var x []any
  4949  	for i := 0; i < n; i++ {
  4950  		v := MakeMap(mt)
  4951  		for j := 0; j < n; j++ {
  4952  			p := new(uintptr)
  4953  			*p = uintptr(i*n + j)
  4954  			v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
  4955  		}
  4956  		pv := New(mt)
  4957  		pv.Elem().Set(v)
  4958  		x = append(x, pv.Interface())
  4959  	}
  4960  	runtime.GC()
  4961  
  4962  	for i, xi := range x {
  4963  		v := ValueOf(xi).Elem()
  4964  		var out []int
  4965  		for _, kv := range v.MapKeys() {
  4966  			out = append(out, int(kv.Elem().Interface().(uintptr)))
  4967  		}
  4968  		sort.Ints(out)
  4969  		for j, k := range out {
  4970  			if k != i*n+j {
  4971  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  4972  			}
  4973  		}
  4974  	}
  4975  }
  4976  
  4977  func TestMapOfGCValues(t *testing.T) {
  4978  	type T *uintptr
  4979  	tt := TypeOf(T(nil))
  4980  	mt := MapOf(TypeOf(1), tt)
  4981  
  4982  	// NOTE: The garbage collector handles allocated maps specially,
  4983  	// so we have to save pointers to maps in x; the pointer code will
  4984  	// use the gc info in the newly constructed map type.
  4985  	const n = 100
  4986  	var x []any
  4987  	for i := 0; i < n; i++ {
  4988  		v := MakeMap(mt)
  4989  		for j := 0; j < n; j++ {
  4990  			p := new(uintptr)
  4991  			*p = uintptr(i*n + j)
  4992  			v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
  4993  		}
  4994  		pv := New(mt)
  4995  		pv.Elem().Set(v)
  4996  		x = append(x, pv.Interface())
  4997  	}
  4998  	runtime.GC()
  4999  
  5000  	for i, xi := range x {
  5001  		v := ValueOf(xi).Elem()
  5002  		for j := 0; j < n; j++ {
  5003  			k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
  5004  			if k != uintptr(i*n+j) {
  5005  				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  5006  			}
  5007  		}
  5008  	}
  5009  }
  5010  
  5011  func TestFuncOf(t *testing.T) {
  5012  	// check construction and use of type not in binary
  5013  	type K string
  5014  	type V float64
  5015  
  5016  	fn := func(args []Value) []Value {
  5017  		if len(args) != 1 {
  5018  			t.Errorf("args == %v, want exactly one arg", args)
  5019  		} else if args[0].Type() != TypeOf(K("")) {
  5020  			t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
  5021  		} else if args[0].String() != "gopher" {
  5022  			t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
  5023  		}
  5024  		return []Value{ValueOf(V(3.14))}
  5025  	}
  5026  	v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
  5027  
  5028  	outs := v.Call([]Value{ValueOf(K("gopher"))})
  5029  	if len(outs) != 1 {
  5030  		t.Fatalf("v.Call returned %v, want exactly one result", outs)
  5031  	} else if outs[0].Type() != TypeOf(V(0)) {
  5032  		t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
  5033  	}
  5034  	f := outs[0].Float()
  5035  	if f != 3.14 {
  5036  		t.Errorf("constructed func returned %f, want %f", f, 3.14)
  5037  	}
  5038  
  5039  	// check that types already in binary are found
  5040  	type T1 int
  5041  	testCases := []struct {
  5042  		in, out  []Type
  5043  		variadic bool
  5044  		want     any
  5045  	}{
  5046  		{in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
  5047  		{in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
  5048  		{in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
  5049  		{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
  5050  		{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
  5051  	}
  5052  	for _, tt := range testCases {
  5053  		checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
  5054  	}
  5055  
  5056  	// check that variadic requires last element be a slice.
  5057  	FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
  5058  	shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
  5059  	shouldPanic(func() { FuncOf(nil, nil, true) })
  5060  }
  5061  
  5062  type B1 struct {
  5063  	X int
  5064  	Y int
  5065  	Z int
  5066  }
  5067  
  5068  func BenchmarkFieldByName1(b *testing.B) {
  5069  	t := TypeOf(B1{})
  5070  	b.RunParallel(func(pb *testing.PB) {
  5071  		for pb.Next() {
  5072  			t.FieldByName("Z")
  5073  		}
  5074  	})
  5075  }
  5076  
  5077  func BenchmarkFieldByName2(b *testing.B) {
  5078  	t := TypeOf(S3{})
  5079  	b.RunParallel(func(pb *testing.PB) {
  5080  		for pb.Next() {
  5081  			t.FieldByName("B")
  5082  		}
  5083  	})
  5084  }
  5085  
  5086  type R0 struct {
  5087  	*R1
  5088  	*R2
  5089  	*R3
  5090  	*R4
  5091  }
  5092  
  5093  type R1 struct {
  5094  	*R5
  5095  	*R6
  5096  	*R7
  5097  	*R8
  5098  }
  5099  
  5100  type R2 R1
  5101  
  5102  type R3 R1
  5103  
  5104  type R4 R1
  5105  
  5106  type R5 struct {
  5107  	*R9
  5108  	*R10
  5109  	*R11
  5110  	*R12
  5111  }
  5112  
  5113  type R6 R5
  5114  
  5115  type R7 R5
  5116  
  5117  type R8 R5
  5118  
  5119  type R9 struct {
  5120  	*R13
  5121  	*R14
  5122  	*R15
  5123  	*R16
  5124  }
  5125  
  5126  type R10 R9
  5127  
  5128  type R11 R9
  5129  
  5130  type R12 R9
  5131  
  5132  type R13 struct {
  5133  	*R17
  5134  	*R18
  5135  	*R19
  5136  	*R20
  5137  }
  5138  
  5139  type R14 R13
  5140  
  5141  type R15 R13
  5142  
  5143  type R16 R13
  5144  
  5145  type R17 struct {
  5146  	*R21
  5147  	*R22
  5148  	*R23
  5149  	*R24
  5150  }
  5151  
  5152  type R18 R17
  5153  
  5154  type R19 R17
  5155  
  5156  type R20 R17
  5157  
  5158  type R21 struct {
  5159  	X int
  5160  }
  5161  
  5162  type R22 R21
  5163  
  5164  type R23 R21
  5165  
  5166  type R24 R21
  5167  
  5168  func TestEmbed(t *testing.T) {
  5169  	typ := TypeOf(R0{})
  5170  	f, ok := typ.FieldByName("X")
  5171  	if ok {
  5172  		t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
  5173  	}
  5174  }
  5175  
  5176  func BenchmarkFieldByName3(b *testing.B) {
  5177  	t := TypeOf(R0{})
  5178  	b.RunParallel(func(pb *testing.PB) {
  5179  		for pb.Next() {
  5180  			t.FieldByName("X")
  5181  		}
  5182  	})
  5183  }
  5184  
  5185  type S struct {
  5186  	i1 int64
  5187  	i2 int64
  5188  }
  5189  
  5190  func BenchmarkInterfaceBig(b *testing.B) {
  5191  	v := ValueOf(S{})
  5192  	b.RunParallel(func(pb *testing.PB) {
  5193  		for pb.Next() {
  5194  			v.Interface()
  5195  		}
  5196  	})
  5197  	b.StopTimer()
  5198  }
  5199  
  5200  func TestAllocsInterfaceBig(t *testing.T) {
  5201  	if testing.Short() {
  5202  		t.Skip("skipping malloc count in short mode")
  5203  	}
  5204  	v := ValueOf(S{})
  5205  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  5206  		t.Error("allocs:", allocs)
  5207  	}
  5208  }
  5209  
  5210  func BenchmarkInterfaceSmall(b *testing.B) {
  5211  	v := ValueOf(int64(0))
  5212  	b.RunParallel(func(pb *testing.PB) {
  5213  		for pb.Next() {
  5214  			v.Interface()
  5215  		}
  5216  	})
  5217  }
  5218  
  5219  func TestAllocsInterfaceSmall(t *testing.T) {
  5220  	if testing.Short() {
  5221  		t.Skip("skipping malloc count in short mode")
  5222  	}
  5223  	v := ValueOf(int64(0))
  5224  	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  5225  		t.Error("allocs:", allocs)
  5226  	}
  5227  }
  5228  
  5229  // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
  5230  // The basic usage is:
  5231  //
  5232  //	for x.Next() {
  5233  //		... code using x.Maybe() or x.Choice(n) to create test cases ...
  5234  //	}
  5235  //
  5236  // Each iteration of the loop returns a different set of results, until all
  5237  // possible result sets have been explored. It is okay for different code paths
  5238  // to make different method call sequences on x, but there must be no
  5239  // other source of non-determinism in the call sequences.
  5240  //
  5241  // When faced with a new decision, x chooses randomly. Future explorations
  5242  // of that path will choose successive values for the result. Thus, stopping
  5243  // the loop after a fixed number of iterations gives somewhat stochastic
  5244  // testing.
  5245  //
  5246  // Example:
  5247  //
  5248  //	for x.Next() {
  5249  //		v := make([]bool, x.Choose(4))
  5250  //		for i := range v {
  5251  //			v[i] = x.Maybe()
  5252  //		}
  5253  //		fmt.Println(v)
  5254  //	}
  5255  //
  5256  // prints (in some order):
  5257  //
  5258  //	[]
  5259  //	[false]
  5260  //	[true]
  5261  //	[false false]
  5262  //	[false true]
  5263  //	...
  5264  //	[true true]
  5265  //	[false false false]
  5266  //	...
  5267  //	[true true true]
  5268  //	[false false false false]
  5269  //	...
  5270  //	[true true true true]
  5271  type exhaustive struct {
  5272  	r    *rand.Rand
  5273  	pos  int
  5274  	last []choice
  5275  }
  5276  
  5277  type choice struct {
  5278  	off int
  5279  	n   int
  5280  	max int
  5281  }
  5282  
  5283  func (x *exhaustive) Next() bool {
  5284  	if x.r == nil {
  5285  		x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
  5286  	}
  5287  	x.pos = 0
  5288  	if x.last == nil {
  5289  		x.last = []choice{}
  5290  		return true
  5291  	}
  5292  	for i := len(x.last) - 1; i >= 0; i-- {
  5293  		c := &x.last[i]
  5294  		if c.n+1 < c.max {
  5295  			c.n++
  5296  			x.last = x.last[:i+1]
  5297  			return true
  5298  		}
  5299  	}
  5300  	return false
  5301  }
  5302  
  5303  func (x *exhaustive) Choose(max int) int {
  5304  	if x.pos >= len(x.last) {
  5305  		x.last = append(x.last, choice{off: x.r.Intn(max), n: 0, max: max})
  5306  	}
  5307  	c := &x.last[x.pos]
  5308  	x.pos++
  5309  	if c.max != max {
  5310  		panic("inconsistent use of exhaustive tester")
  5311  	}
  5312  	return (c.n + c.off) % max
  5313  }
  5314  
  5315  func (x *exhaustive) Maybe() bool {
  5316  	return x.Choose(2) == 1
  5317  }
  5318  
  5319  func GCFunc(args []Value) []Value {
  5320  	runtime.GC()
  5321  	return []Value{}
  5322  }
  5323  
  5324  func TestReflectFuncTraceback(t *testing.T) {
  5325  	f := MakeFunc(TypeOf(func() {}), GCFunc)
  5326  	f.Call([]Value{})
  5327  }
  5328  
  5329  func TestReflectMethodTraceback(t *testing.T) {
  5330  	p := Point{x: 3, y: 4}
  5331  	m := ValueOf(p).MethodByName("GCMethod")
  5332  	i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
  5333  	if i != 8 {
  5334  		t.Errorf("Call returned %d; want 8", i)
  5335  	}
  5336  }
  5337  
  5338  func TestBigZero(t *testing.T) {
  5339  	const size = 1 << 10
  5340  	var v [size]byte
  5341  	z := Zero(ValueOf(v).Type()).Interface().([size]byte)
  5342  	for i := 0; i < size; i++ {
  5343  		if z[i] != 0 {
  5344  			t.Fatalf("Zero object not all zero, index %d", i)
  5345  		}
  5346  	}
  5347  }
  5348  
  5349  func TestFieldByIndexNil(t *testing.T) {
  5350  	type P struct {
  5351  		F int
  5352  	}
  5353  	type T struct {
  5354  		*P
  5355  	}
  5356  	v := ValueOf(T{})
  5357  
  5358  	v.FieldByName("P") // should be fine
  5359  
  5360  	defer func() {
  5361  		if err := recover(); err == nil {
  5362  			t.Fatalf("no error")
  5363  		} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
  5364  			t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
  5365  		}
  5366  	}()
  5367  	v.FieldByName("F") // should panic
  5368  
  5369  	t.Fatalf("did not panic")
  5370  }
  5371  
  5372  // Given
  5373  //	type Outer struct {
  5374  //		*Inner
  5375  //		...
  5376  //	}
  5377  // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
  5378  // The implementation is logically:
  5379  //	func (p *Outer) M() {
  5380  //		(p.Inner).M()
  5381  //	}
  5382  // but since the only change here is the replacement of one pointer receiver with another,
  5383  // the actual generated code overwrites the original receiver with the p.Inner pointer and
  5384  // then jumps to the M method expecting the *Inner receiver.
  5385  //
  5386  // During reflect.Value.Call, we create an argument frame and the associated data structures
  5387  // to describe it to the garbage collector, populate the frame, call reflect.call to
  5388  // run a function call using that frame, and then copy the results back out of the frame.
  5389  // The reflect.call function does a memmove of the frame structure onto the
  5390  // stack (to set up the inputs), runs the call, and the memmoves the stack back to
  5391  // the frame structure (to preserve the outputs).
  5392  //
  5393  // Originally reflect.call did not distinguish inputs from outputs: both memmoves
  5394  // were for the full stack frame. However, in the case where the called function was
  5395  // one of these wrappers, the rewritten receiver is almost certainly a different type
  5396  // than the original receiver. This is not a problem on the stack, where we use the
  5397  // program counter to determine the type information and understand that
  5398  // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
  5399  // memory word is now an *Inner. But in the statically typed argument frame created
  5400  // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
  5401  // off the stack into the frame will store an *Inner there, and then if a garbage collection
  5402  // happens to scan that argument frame before it is discarded, it will scan the *Inner
  5403  // memory as if it were an *Outer. If the two have different memory layouts, the
  5404  // collection will interpret the memory incorrectly.
  5405  //
  5406  // One such possible incorrect interpretation is to treat two arbitrary memory words
  5407  // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
  5408  // an interface requires dereferencing the itab word, the misinterpretation will try to
  5409  // deference Inner.P1, causing a crash during garbage collection.
  5410  //
  5411  // This came up in a real program in issue 7725.
  5412  
  5413  type Outer struct {
  5414  	*Inner
  5415  	R io.Reader
  5416  }
  5417  
  5418  type Inner struct {
  5419  	X  *Outer
  5420  	P1 uintptr
  5421  	P2 uintptr
  5422  }
  5423  
  5424  func (pi *Inner) M() {
  5425  	// Clear references to pi so that the only way the
  5426  	// garbage collection will find the pointer is in the
  5427  	// argument frame, typed as a *Outer.
  5428  	pi.X.Inner = nil
  5429  
  5430  	// Set up an interface value that will cause a crash.
  5431  	// P1 = 1 is a non-zero, so the interface looks non-nil.
  5432  	// P2 = pi ensures that the data word points into the
  5433  	// allocated heap; if not the collection skips the interface
  5434  	// value as irrelevant, without dereferencing P1.
  5435  	pi.P1 = 1
  5436  	pi.P2 = uintptr(unsafe.Pointer(pi))
  5437  }
  5438  
  5439  func TestMakeFuncStackCopy(t *testing.T) {
  5440  	target := func(in []Value) []Value {
  5441  		runtime.GC()
  5442  		useStack(16)
  5443  		return []Value{ValueOf(9)}
  5444  	}
  5445  
  5446  	var concrete func(*int, int) int
  5447  	fn := MakeFunc(ValueOf(concrete).Type(), target)
  5448  	ValueOf(&concrete).Elem().Set(fn)
  5449  	x := concrete(nil, 7)
  5450  	if x != 9 {
  5451  		t.Errorf("have %#q want 9", x)
  5452  	}
  5453  }
  5454  
  5455  // use about n KB of stack
  5456  func useStack(n int) {
  5457  	if n == 0 {
  5458  		return
  5459  	}
  5460  	var b [1024]byte // makes frame about 1KB
  5461  	useStack(n - 1 + int(b[99]))
  5462  }
  5463  
  5464  type Impl struct{}
  5465  
  5466  func (Impl) F() {}
  5467  
  5468  func TestValueString(t *testing.T) {
  5469  	rv := ValueOf(Impl{})
  5470  	if rv.String() != "<reflect_test.Impl Value>" {
  5471  		t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
  5472  	}
  5473  
  5474  	method := rv.Method(0)
  5475  	if method.String() != "<func() Value>" {
  5476  		t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
  5477  	}
  5478  }
  5479  
  5480  func TestInvalid(t *testing.T) {
  5481  	// Used to have inconsistency between IsValid() and Kind() != Invalid.
  5482  	type T struct{ v any }
  5483  
  5484  	v := ValueOf(T{}).Field(0)
  5485  	if !v.IsValid() || v.Kind() != Interface {
  5486  		t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
  5487  	}
  5488  	v = v.Elem()
  5489  	if v.IsValid() || v.Kind() != Invalid {
  5490  		t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
  5491  	}
  5492  }
  5493  
  5494  // Issue 8917.
  5495  func TestLargeGCProg(t *testing.T) {
  5496  	fv := ValueOf(func([256]*byte) {})
  5497  	fv.Call([]Value{ValueOf([256]*byte{})})
  5498  }
  5499  
  5500  func fieldIndexRecover(t Type, i int) (recovered any) {
  5501  	defer func() {
  5502  		recovered = recover()
  5503  	}()
  5504  
  5505  	t.Field(i)
  5506  	return
  5507  }
  5508  
  5509  // Issue 15046.
  5510  func TestTypeFieldOutOfRangePanic(t *testing.T) {
  5511  	typ := TypeOf(struct{ X int }{X: 10})
  5512  	testIndices := [...]struct {
  5513  		i         int
  5514  		mustPanic bool
  5515  	}{
  5516  		0: {i: -2, mustPanic: true},
  5517  		1: {i: 0, mustPanic: false},
  5518  		2: {i: 1, mustPanic: true},
  5519  		3: {i: 1 << 10, mustPanic: true},
  5520  	}
  5521  	for i, tt := range testIndices {
  5522  		recoveredErr := fieldIndexRecover(typ, tt.i)
  5523  		if tt.mustPanic {
  5524  			if recoveredErr == nil {
  5525  				t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
  5526  			}
  5527  		} else {
  5528  			if recoveredErr != nil {
  5529  				t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
  5530  			}
  5531  		}
  5532  	}
  5533  }
  5534  
  5535  // Issue 9179.
  5536  func TestCallGC(t *testing.T) {
  5537  	f := func(a, b, c, d, e string) {}
  5538  
  5539  	g := func(in []Value) []Value {
  5540  		runtime.GC()
  5541  		return nil
  5542  	}
  5543  	typ := ValueOf(f).Type()
  5544  	f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
  5545  	f2("four", "five5", "six666", "seven77", "eight888")
  5546  }
  5547  
  5548  // Issue 18635 (function version).
  5549  func TestKeepFuncLive(t *testing.T) {
  5550  	// Test that we keep makeFuncImpl live as long as it is
  5551  	// referenced on the stack.
  5552  	typ := TypeOf(func(i int) {})
  5553  	var f, g func(in []Value) []Value
  5554  	f = func(in []Value) []Value {
  5555  		clobber()
  5556  		i := int(in[0].Int())
  5557  		if i > 0 {
  5558  			// We can't use Value.Call here because
  5559  			// runtime.call* will keep the makeFuncImpl
  5560  			// alive. However, by converting it to an
  5561  			// interface value and calling that,
  5562  			// reflect.callReflect is the only thing that
  5563  			// can keep the makeFuncImpl live.
  5564  			//
  5565  			// Alternate between f and g so that if we do
  5566  			// reuse the memory prematurely it's more
  5567  			// likely to get obviously corrupted.
  5568  			MakeFunc(typ, g).Interface().(func(i int))(i - 1)
  5569  		}
  5570  		return nil
  5571  	}
  5572  	g = func(in []Value) []Value {
  5573  		clobber()
  5574  		i := int(in[0].Int())
  5575  		MakeFunc(typ, f).Interface().(func(i int))(i)
  5576  		return nil
  5577  	}
  5578  	MakeFunc(typ, f).Call([]Value{ValueOf(10)})
  5579  }
  5580  
  5581  type UnExportedFirst int
  5582  
  5583  func (i UnExportedFirst) ΦExported() {}
  5584  
  5585  func (i UnExportedFirst) unexported() {}
  5586  
  5587  // Issue 21177
  5588  func TestMethodByNameUnExportedFirst(t *testing.T) {
  5589  	defer func() {
  5590  		if recover() != nil {
  5591  			t.Errorf("should not panic")
  5592  		}
  5593  	}()
  5594  	typ := TypeOf(UnExportedFirst(0))
  5595  	m, _ := typ.MethodByName("ΦExported")
  5596  	if m.Name != "ΦExported" {
  5597  		t.Errorf("got %s, expected ΦExported", m.Name)
  5598  	}
  5599  }
  5600  
  5601  // Issue 18635 (method version).
  5602  type KeepMethodLive struct{}
  5603  
  5604  func (k KeepMethodLive) Method1(i int) {
  5605  	clobber()
  5606  	if i > 0 {
  5607  		ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
  5608  	}
  5609  }
  5610  
  5611  func (k KeepMethodLive) Method2(i int) {
  5612  	clobber()
  5613  	ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
  5614  }
  5615  
  5616  func TestKeepMethodLive(t *testing.T) {
  5617  	// Test that we keep methodValue live as long as it is
  5618  	// referenced on the stack.
  5619  	KeepMethodLive{}.Method1(10)
  5620  }
  5621  
  5622  // clobber tries to clobber unreachable memory.
  5623  func clobber() {
  5624  	runtime.GC()
  5625  	for i := 1; i < 32; i++ {
  5626  		for j := 0; j < 10; j++ {
  5627  			obj := make([]*byte, i)
  5628  			sink = obj
  5629  		}
  5630  	}
  5631  	runtime.GC()
  5632  }
  5633  
  5634  type funcLayoutTest struct {
  5635  	rcvr, t                  Type
  5636  	size, argsize, retOffset uintptr
  5637  	stack                    []byte // pointer bitmap: 1 is pointer, 0 is scalar
  5638  	gc                       []byte
  5639  }
  5640  
  5641  var funcLayoutTests []funcLayoutTest
  5642  
  5643  func init() {
  5644  	var argAlign uintptr = PtrSize
  5645  	if runtime.GOARCH == "amd64p32" {
  5646  		argAlign = 2 * PtrSize
  5647  	}
  5648  	roundup := func(x uintptr, a uintptr) uintptr {
  5649  		return (x + a - 1) / a * a
  5650  	}
  5651  
  5652  	funcLayoutTests = append(funcLayoutTests,
  5653  		funcLayoutTest{
  5654  			rcvr:      nil,
  5655  			t:         ValueOf(func(a, b string) string { return "" }).Type(),
  5656  			size:      6 * PtrSize,
  5657  			argsize:   4 * PtrSize,
  5658  			retOffset: 4 * PtrSize,
  5659  			stack:     []byte{1, 0, 1, 0, 1},
  5660  			gc:        []byte{1, 0, 1, 0, 1},
  5661  		})
  5662  
  5663  	var r []byte
  5664  	if PtrSize == 4 {
  5665  		r = []byte{0, 0, 0, 1}
  5666  	} else {
  5667  		r = []byte{0, 0, 1}
  5668  	}
  5669  	funcLayoutTests = append(funcLayoutTests,
  5670  		funcLayoutTest{
  5671  			rcvr:      nil,
  5672  			t:         ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
  5673  			size:      roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
  5674  			argsize:   roundup(3*4, PtrSize) + PtrSize + 2,
  5675  			retOffset: roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
  5676  			stack:     r,
  5677  			gc:        r,
  5678  		})
  5679  
  5680  	funcLayoutTests = append(funcLayoutTests,
  5681  		funcLayoutTest{
  5682  			rcvr:      nil,
  5683  			t:         ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
  5684  			size:      4 * PtrSize,
  5685  			argsize:   4 * PtrSize,
  5686  			retOffset: 4 * PtrSize,
  5687  			stack:     []byte{1, 0, 1, 1},
  5688  			gc:        []byte{1, 0, 1, 1},
  5689  		})
  5690  
  5691  	type S struct {
  5692  		a, b uintptr
  5693  		c, d *byte
  5694  	}
  5695  	funcLayoutTests = append(funcLayoutTests,
  5696  		funcLayoutTest{
  5697  			rcvr:      nil,
  5698  			t:         ValueOf(func(a S) {}).Type(),
  5699  			size:      4 * PtrSize,
  5700  			argsize:   4 * PtrSize,
  5701  			retOffset: 4 * PtrSize,
  5702  			stack:     []byte{0, 0, 1, 1},
  5703  			gc:        []byte{0, 0, 1, 1},
  5704  		})
  5705  
  5706  	funcLayoutTests = append(funcLayoutTests,
  5707  		funcLayoutTest{
  5708  			rcvr:      ValueOf((*byte)(nil)).Type(),
  5709  			t:         ValueOf(func(a uintptr, b *int) {}).Type(),
  5710  			size:      roundup(3*PtrSize, argAlign),
  5711  			argsize:   3 * PtrSize,
  5712  			retOffset: roundup(3*PtrSize, argAlign),
  5713  			stack:     []byte{1, 0, 1},
  5714  			gc:        []byte{1, 0, 1},
  5715  		})
  5716  
  5717  	funcLayoutTests = append(funcLayoutTests,
  5718  		funcLayoutTest{
  5719  			rcvr:      nil,
  5720  			t:         ValueOf(func(a uintptr) {}).Type(),
  5721  			size:      roundup(PtrSize, argAlign),
  5722  			argsize:   PtrSize,
  5723  			retOffset: roundup(PtrSize, argAlign),
  5724  			stack:     []byte{},
  5725  			gc:        []byte{},
  5726  		})
  5727  
  5728  	funcLayoutTests = append(funcLayoutTests,
  5729  		funcLayoutTest{
  5730  			rcvr:      nil,
  5731  			t:         ValueOf(func() uintptr { return 0 }).Type(),
  5732  			size:      PtrSize,
  5733  			argsize:   0,
  5734  			retOffset: 0,
  5735  			stack:     []byte{},
  5736  			gc:        []byte{},
  5737  		})
  5738  
  5739  	funcLayoutTests = append(funcLayoutTests,
  5740  		funcLayoutTest{
  5741  			rcvr:      ValueOf(uintptr(0)).Type(),
  5742  			t:         ValueOf(func(a uintptr) {}).Type(),
  5743  			size:      2 * PtrSize,
  5744  			argsize:   2 * PtrSize,
  5745  			retOffset: 2 * PtrSize,
  5746  			stack:     []byte{1},
  5747  			gc:        []byte{1},
  5748  			// Note: this one is tricky, as the receiver is not a pointer. But we
  5749  			// pass the receiver by reference to the autogenerated pointer-receiver
  5750  			// version of the function.
  5751  		})
  5752  }
  5753  
  5754  func naclpad() []byte {
  5755  	if runtime.GOARCH == "amd64p32" {
  5756  		return lit(0)
  5757  	}
  5758  	return nil
  5759  }
  5760  
  5761  func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
  5762  
  5763  func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
  5764  
  5765  func lit(x ...byte) []byte { return x }
  5766  
  5767  func TestTypeOfTypeOf(t *testing.T) {
  5768  	// Check that all the type constructors return concrete *rtype implementations.
  5769  	// It's difficult to test directly because the reflect package is only at arm's length.
  5770  	// The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
  5771  	check := func(name string, typ Type) {
  5772  		if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
  5773  			t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
  5774  		}
  5775  	}
  5776  
  5777  	type T struct{ int }
  5778  	check("TypeOf", TypeOf(T{}))
  5779  
  5780  	check("ArrayOf", ArrayOf(10, TypeOf(T{})))
  5781  	check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
  5782  	check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
  5783  	check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
  5784  	check("PtrTo", PtrTo(TypeOf(T{})))
  5785  	check("SliceOf", SliceOf(TypeOf(T{})))
  5786  }
  5787  
  5788  type XM struct{ _ bool }
  5789  
  5790  func (*XM) String() string { return "" }
  5791  
  5792  func TestPtrToMethods(t *testing.T) {
  5793  	var y struct{ XM }
  5794  	yp := New(TypeOf(y)).Interface()
  5795  	_, ok := yp.(fmt.Stringer)
  5796  	if !ok {
  5797  		t.Fatal("does not implement Stringer, but should")
  5798  	}
  5799  }
  5800  
  5801  func TestMapAlloc(t *testing.T) {
  5802  	m := ValueOf(make(map[int]int, 10))
  5803  	k := ValueOf(5)
  5804  	v := ValueOf(7)
  5805  	allocs := testing.AllocsPerRun(100, func() {
  5806  		m.SetMapIndex(k, v)
  5807  	})
  5808  	if allocs > 0.5 {
  5809  		t.Errorf("allocs per map assignment: want 0 got %f", allocs)
  5810  	}
  5811  
  5812  	const size = 1000
  5813  	tmp := 0
  5814  	val := ValueOf(&tmp).Elem()
  5815  	allocs = testing.AllocsPerRun(100, func() {
  5816  		mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
  5817  		// Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
  5818  		for i := 0; i < size/2; i++ {
  5819  			val.SetInt(int64(i))
  5820  			mv.SetMapIndex(val, val)
  5821  		}
  5822  	})
  5823  	if allocs > 10 {
  5824  		t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
  5825  	}
  5826  	// Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
  5827  	// the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
  5828  	// map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
  5829  }
  5830  
  5831  func TestChanAlloc(t *testing.T) {
  5832  	// Note: for a chan int, the return Value must be allocated, so we
  5833  	// use a chan *int instead.
  5834  	c := ValueOf(make(chan *int, 1))
  5835  	v := ValueOf(new(int))
  5836  	allocs := testing.AllocsPerRun(100, func() {
  5837  		c.Send(v)
  5838  		_, _ = c.Recv()
  5839  	})
  5840  	if allocs < 0.5 || allocs > 1.5 {
  5841  		t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
  5842  	}
  5843  	// Note: there is one allocation in reflect.recv which seems to be
  5844  	// a limitation of escape analysis. If that is ever fixed the
  5845  	// allocs < 0.5 condition will trigger and this test should be fixed.
  5846  }
  5847  
  5848  type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
  5849  
  5850  type nameTest struct {
  5851  	v    any
  5852  	want string
  5853  }
  5854  
  5855  var nameTests = []nameTest{
  5856  	{v: (*int32)(nil), want: "int32"},
  5857  	{v: (*D1)(nil), want: "D1"},
  5858  	{v: (*[]D1)(nil), want: ""},
  5859  	{v: (*chan D1)(nil), want: ""},
  5860  	{v: (*func() D1)(nil), want: ""},
  5861  	{v: (*<-chan D1)(nil), want: ""},
  5862  	{v: (*chan<- D1)(nil), want: ""},
  5863  	{v: (*any)(nil), want: ""},
  5864  	{v: (*interface {
  5865  		F()
  5866  	})(nil), want: ""},
  5867  	{v: (*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), want: "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
  5868  }
  5869  
  5870  func TestNames(t *testing.T) {
  5871  	for _, test := range nameTests {
  5872  		typ := TypeOf(test.v).Elem()
  5873  		if got := typ.Name(); got != test.want {
  5874  			t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
  5875  		}
  5876  	}
  5877  }
  5878  
  5879  func TestTypeStrings(t *testing.T) {
  5880  	type stringTest struct {
  5881  		typ  Type
  5882  		want string
  5883  	}
  5884  	stringTests := []stringTest{
  5885  		{typ: TypeOf(func(int) {}), want: "func(int)"},
  5886  		{typ: FuncOf([]Type{TypeOf(int(0))}, nil, false), want: "func(int)"},
  5887  		{typ: TypeOf(XM{}), want: "reflect_test.XM"},
  5888  		{typ: TypeOf(new(XM)), want: "*reflect_test.XM"},
  5889  		{typ: TypeOf(new(XM).String), want: "func() string"},
  5890  		{typ: TypeOf(new(XM)).Method(0).Type, want: "func(*reflect_test.XM) string"},
  5891  		{typ: ChanOf(3, TypeOf(XM{})), want: "chan reflect_test.XM"},
  5892  		{typ: MapOf(TypeOf(int(0)), TypeOf(XM{})), want: "map[int]reflect_test.XM"},
  5893  		{typ: ArrayOf(3, TypeOf(XM{})), want: "[3]reflect_test.XM"},
  5894  		{typ: ArrayOf(3, TypeOf(struct{}{})), want: "[3]struct {}"},
  5895  	}
  5896  
  5897  	for i, test := range stringTests {
  5898  		if got, want := test.typ.String(), test.want; got != want {
  5899  			t.Errorf("type %d String()=%q, want %q", i, got, want)
  5900  		}
  5901  	}
  5902  }
  5903  
  5904  func BenchmarkNew(b *testing.B) {
  5905  	v := TypeOf(XM{})
  5906  	b.RunParallel(func(pb *testing.PB) {
  5907  		for pb.Next() {
  5908  			New(v)
  5909  		}
  5910  	})
  5911  }
  5912  
  5913  func TestSwapper(t *testing.T) {
  5914  	type I int
  5915  	var a, b, c I
  5916  	type pair struct {
  5917  		x, y int
  5918  	}
  5919  	type pairPtr struct {
  5920  		x, y int
  5921  		p    *I
  5922  	}
  5923  	type S string
  5924  
  5925  	tests := []struct {
  5926  		in   any
  5927  		i, j int
  5928  		want any
  5929  	}{
  5930  		{
  5931  			in:   []int{1, 20, 300},
  5932  			i:    0,
  5933  			j:    2,
  5934  			want: []int{300, 20, 1},
  5935  		},
  5936  		{
  5937  			in:   []uintptr{1, 20, 300},
  5938  			i:    0,
  5939  			j:    2,
  5940  			want: []uintptr{300, 20, 1},
  5941  		},
  5942  		{
  5943  			in:   []int16{1, 20, 300},
  5944  			i:    0,
  5945  			j:    2,
  5946  			want: []int16{300, 20, 1},
  5947  		},
  5948  		{
  5949  			in:   []int8{1, 20, 100},
  5950  			i:    0,
  5951  			j:    2,
  5952  			want: []int8{100, 20, 1},
  5953  		},
  5954  		{
  5955  			in:   []*I{&a, &b, &c},
  5956  			i:    0,
  5957  			j:    2,
  5958  			want: []*I{&c, &b, &a},
  5959  		},
  5960  		{
  5961  			in:   []string{"eric", "sergey", "larry"},
  5962  			i:    0,
  5963  			j:    2,
  5964  			want: []string{"larry", "sergey", "eric"},
  5965  		},
  5966  		{
  5967  			in:   []S{"eric", "sergey", "larry"},
  5968  			i:    0,
  5969  			j:    2,
  5970  			want: []S{"larry", "sergey", "eric"},
  5971  		},
  5972  		{
  5973  			in:   []pair{{x: 1, y: 2}, {x: 3, y: 4}, {x: 5, y: 6}},
  5974  			i:    0,
  5975  			j:    2,
  5976  			want: []pair{{x: 5, y: 6}, {x: 3, y: 4}, {x: 1, y: 2}},
  5977  		},
  5978  		{
  5979  			in:   []pairPtr{{x: 1, y: 2, p: &a}, {x: 3, y: 4, p: &b}, {x: 5, y: 6, p: &c}},
  5980  			i:    0,
  5981  			j:    2,
  5982  			want: []pairPtr{{x: 5, y: 6, p: &c}, {x: 3, y: 4, p: &b}, {x: 1, y: 2, p: &a}},
  5983  		},
  5984  	}
  5985  
  5986  	for i, tt := range tests {
  5987  		inStr := fmt.Sprint(tt.in)
  5988  		Swapper(tt.in)(tt.i, tt.j)
  5989  		if !DeepEqual(tt.in, tt.want) {
  5990  			t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
  5991  		}
  5992  	}
  5993  }
  5994  
  5995  // TestUnaddressableField tests that the reflect package will not allow
  5996  // a type from another package to be used as a named type with an
  5997  // unexported field.
  5998  //
  5999  // This ensures that unexported fields cannot be modified by other packages.
  6000  func TestUnaddressableField(t *testing.T) {
  6001  	var b Buffer // type defined in reflect, a different package
  6002  	var localBuffer struct {
  6003  		buf []byte
  6004  	}
  6005  	lv := ValueOf(&localBuffer).Elem()
  6006  	rv := ValueOf(b)
  6007  	shouldPanic(func() {
  6008  		lv.Set(rv)
  6009  	})
  6010  }
  6011  
  6012  type Tint int
  6013  
  6014  type Tint2 = Tint
  6015  
  6016  type Talias1 struct {
  6017  	byte
  6018  	uint8
  6019  	int
  6020  	int32
  6021  	rune
  6022  }
  6023  
  6024  type Talias2 struct {
  6025  	Tint
  6026  	Tint2
  6027  }
  6028  
  6029  func TestAliasNames(t *testing.T) {
  6030  	t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
  6031  	out := fmt.Sprintf("%#v", t1)
  6032  	want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
  6033  	if out != want {
  6034  		t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
  6035  	}
  6036  
  6037  	t2 := Talias2{Tint: 1, Tint2: 2}
  6038  	out = fmt.Sprintf("%#v", t2)
  6039  	want = "reflect_test.Talias2{Tint:1, Tint2:2}"
  6040  	if out != want {
  6041  		t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
  6042  	}
  6043  }
  6044  
  6045  func TestIssue22031(t *testing.T) {
  6046  	type s []struct{ C int }
  6047  
  6048  	type t1 struct{ s }
  6049  	type t2 struct{ f s }
  6050  
  6051  	tests := []Value{
  6052  		ValueOf(t1{s: s{{}}}).Field(0).Index(0).Field(0),
  6053  		ValueOf(t2{f: s{{}}}).Field(0).Index(0).Field(0),
  6054  	}
  6055  
  6056  	for i, test := range tests {
  6057  		if test.CanSet() {
  6058  			t.Errorf("%d: CanSet: got true, want false", i)
  6059  		}
  6060  	}
  6061  }
  6062  
  6063  type NonExportedFirst int
  6064  
  6065  func (i NonExportedFirst) ΦExported() {}
  6066  
  6067  func (i NonExportedFirst) nonexported() int { panic("wrong") }
  6068  
  6069  func TestIssue22073(t *testing.T) {
  6070  	m := ValueOf(NonExportedFirst(0)).Method(0)
  6071  
  6072  	if got := m.Type().NumOut(); got != 0 {
  6073  		t.Errorf("NumOut: got %v, want 0", got)
  6074  	}
  6075  
  6076  	// Shouldn't panic.
  6077  	m.Call(nil)
  6078  }
  6079  
  6080  func TestMapIterNonEmptyMap(t *testing.T) {
  6081  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  6082  	iter := ValueOf(m).MapRange()
  6083  	if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
  6084  		t.Errorf("iterator returned %s (after sorting), want %s", got, want)
  6085  	}
  6086  }
  6087  
  6088  func TestMapIterNilMap(t *testing.T) {
  6089  	var m map[string]int
  6090  	iter := ValueOf(m).MapRange()
  6091  	if got, want := iterateToString(iter), `[]`; got != want {
  6092  		t.Errorf("non-empty result iteratoring nil map: %s", got)
  6093  	}
  6094  }
  6095  
  6096  func TestMapIterSafety(t *testing.T) {
  6097  	// Using a zero MapIter causes a panic, but not a crash.
  6098  	func() {
  6099  		defer func() { recover() }()
  6100  		new(MapIter).Key()
  6101  		t.Fatal("Key did not panic")
  6102  	}()
  6103  	func() {
  6104  		defer func() { recover() }()
  6105  		new(MapIter).Value()
  6106  		t.Fatal("Value did not panic")
  6107  	}()
  6108  	func() {
  6109  		defer func() { recover() }()
  6110  		new(MapIter).Next()
  6111  		t.Fatal("Next did not panic")
  6112  	}()
  6113  
  6114  	// Calling Key/Value on a MapIter before Next
  6115  	// causes a panic, but not a crash.
  6116  	var m map[string]int
  6117  	iter := ValueOf(m).MapRange()
  6118  
  6119  	func() {
  6120  		defer func() { recover() }()
  6121  		iter.Key()
  6122  		t.Fatal("Key did not panic")
  6123  	}()
  6124  	func() {
  6125  		defer func() { recover() }()
  6126  		iter.Value()
  6127  		t.Fatal("Value did not panic")
  6128  	}()
  6129  
  6130  	// Calling Next, Key, or Value on an exhausted iterator
  6131  	// causes a panic, but not a crash.
  6132  	iter.Next() // -> false
  6133  	func() {
  6134  		defer func() { recover() }()
  6135  		iter.Key()
  6136  		t.Fatal("Key did not panic")
  6137  	}()
  6138  	func() {
  6139  		defer func() { recover() }()
  6140  		iter.Value()
  6141  		t.Fatal("Value did not panic")
  6142  	}()
  6143  	func() {
  6144  		defer func() { recover() }()
  6145  		iter.Next()
  6146  		t.Fatal("Next did not panic")
  6147  	}()
  6148  }
  6149  
  6150  func TestMapIterNext(t *testing.T) {
  6151  	// The first call to Next should reflect any
  6152  	// insertions to the map since the iterator was created.
  6153  	m := map[string]int{}
  6154  	iter := ValueOf(m).MapRange()
  6155  	m["one"] = 1
  6156  	if got, want := iterateToString(iter), `[one: 1]`; got != want {
  6157  		t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
  6158  	}
  6159  }
  6160  
  6161  func TestMapIterDelete0(t *testing.T) {
  6162  	// Delete all elements before first iteration.
  6163  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  6164  	iter := ValueOf(m).MapRange()
  6165  	delete(m, "one")
  6166  	delete(m, "two")
  6167  	delete(m, "three")
  6168  	if got, want := iterateToString(iter), `[]`; got != want {
  6169  		t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
  6170  	}
  6171  }
  6172  
  6173  func TestMapIterDelete1(t *testing.T) {
  6174  	// Delete all elements after first iteration.
  6175  	m := map[string]int{"one": 1, "two": 2, "three": 3}
  6176  	iter := ValueOf(m).MapRange()
  6177  	var got []string
  6178  	for iter.Next() {
  6179  		got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
  6180  		delete(m, "one")
  6181  		delete(m, "two")
  6182  		delete(m, "three")
  6183  	}
  6184  	if len(got) != 1 {
  6185  		t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
  6186  	}
  6187  }
  6188  
  6189  // iterateToString returns the set of elements
  6190  // returned by an iterator in readable form.
  6191  func iterateToString(it *MapIter) string {
  6192  	var got []string
  6193  	for it.Next() {
  6194  		line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
  6195  		got = append(got, line)
  6196  	}
  6197  	sort.Strings(got)
  6198  	return "[" + strings.Join(got, ", ") + "]"
  6199  }