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