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
5package reflect_test
6
7import (
8	"bytes"
9	"encoding/base64"
10	"flag"
11	"fmt"
12	"io"
13	"math/rand"
14	"os"
15	. "reflect"
16	"runtime"
17	"sort"
18	"strconv"
19	"strings"
20	"sync"
21	"testing"
22	"time"
23	"unsafe"
24)
25
26func TestBool(t *testing.T) {
27	v := ValueOf(true)
28	if v.Bool() != true {
29		t.Fatal("ValueOf(true).Bool() = false")
30	}
31}
32
33type integer int
34type T struct {
35	a int
36	b float64
37	c string
38	d *int
39}
40
41type pair struct {
42	i interface{}
43	s string
44}
45
46func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
47
48func assert(t *testing.T, s, want string) {
49	if s != want {
50		t.Errorf("have %#q want %#q", s, want)
51	}
52}
53
54func typestring(i interface{}) string { return TypeOf(i).String() }
55
56var typeTests = []pair{
57	{struct{ x int }{}, "int"},
58	{struct{ x int8 }{}, "int8"},
59	{struct{ x int16 }{}, "int16"},
60	{struct{ x int32 }{}, "int32"},
61	{struct{ x int64 }{}, "int64"},
62	{struct{ x uint }{}, "uint"},
63	{struct{ x uint8 }{}, "uint8"},
64	{struct{ x uint16 }{}, "uint16"},
65	{struct{ x uint32 }{}, "uint32"},
66	{struct{ x uint64 }{}, "uint64"},
67	{struct{ x float32 }{}, "float32"},
68	{struct{ x float64 }{}, "float64"},
69	{struct{ x int8 }{}, "int8"},
70	{struct{ x (**int8) }{}, "**int8"},
71	{struct{ x (**integer) }{}, "**reflect_test.integer"},
72	{struct{ x ([32]int32) }{}, "[32]int32"},
73	{struct{ x ([]int8) }{}, "[]int8"},
74	{struct{ x (map[string]int32) }{}, "map[string]int32"},
75	{struct{ x (chan<- string) }{}, "chan<- string"},
76	{struct {
77		x struct {
78			c chan *int32
79			d float32
80		}
81	}{},
82		"struct { c chan *int32; d float32 }",
83	},
84	{struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
85	{struct {
86		x struct {
87			c func(chan *integer, *int8)
88		}
89	}{},
90		"struct { c func(chan *reflect_test.integer, *int8) }",
91	},
92	{struct {
93		x struct {
94			a int8
95			b int32
96		}
97	}{},
98		"struct { a int8; b int32 }",
99	},
100	{struct {
101		x struct {
102			a int8
103			b int8
104			c int32
105		}
106	}{},
107		"struct { a int8; b int8; c int32 }",
108	},
109	{struct {
110		x struct {
111			a int8
112			b int8
113			c int8
114			d int32
115		}
116	}{},
117		"struct { a int8; b int8; c int8; d int32 }",
118	},
119	{struct {
120		x struct {
121			a int8
122			b int8
123			c int8
124			d int8
125			e int32
126		}
127	}{},
128		"struct { a int8; b int8; c int8; d int8; e int32 }",
129	},
130	{struct {
131		x struct {
132			a int8
133			b int8
134			c int8
135			d int8
136			e int8
137			f int32
138		}
139	}{},
140		"struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
141	},
142	{struct {
143		x struct {
144			a int8 `reflect:"hi there"`
145		}
146	}{},
147		`struct { a int8 "reflect:\"hi there\"" }`,
148	},
149	{struct {
150		x struct {
151			a int8 `reflect:"hi \x00there\t\n\"\\"`
152		}
153	}{},
154		`struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
155	},
156	{struct {
157		x struct {
158			f func(args ...int)
159		}
160	}{},
161		"struct { f func(...int) }",
162	},
163	{struct {
164		x (interface {
165			a(func(func(int) int) func(func(int)) int)
166			b()
167		})
168	}{},
169		"interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
170	},
171}
172
173var valueTests = []pair{
174	{new(int), "132"},
175	{new(int8), "8"},
176	{new(int16), "16"},
177	{new(int32), "32"},
178	{new(int64), "64"},
179	{new(uint), "132"},
180	{new(uint8), "8"},
181	{new(uint16), "16"},
182	{new(uint32), "32"},
183	{new(uint64), "64"},
184	{new(float32), "256.25"},
185	{new(float64), "512.125"},
186	{new(complex64), "532.125+10i"},
187	{new(complex128), "564.25+1i"},
188	{new(string), "stringy cheese"},
189	{new(bool), "true"},
190	{new(*int8), "*int8(0)"},
191	{new(**int8), "**int8(0)"},
192	{new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
193	{new(**integer), "**reflect_test.integer(0)"},
194	{new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
195	{new(chan<- string), "chan<- string"},
196	{new(func(a int8, b int32)), "func(int8, int32)(0)"},
197	{new(struct {
198		c chan *int32
199		d float32
200	}),
201		"struct { c chan *int32; d float32 }{chan *int32, 0}",
202	},
203	{new(struct{ c func(chan *integer, *int8) }),
204		"struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
205	},
206	{new(struct {
207		a int8
208		b int32
209	}),
210		"struct { a int8; b int32 }{0, 0}",
211	},
212	{new(struct {
213		a int8
214		b int8
215		c int32
216	}),
217		"struct { a int8; b int8; c int32 }{0, 0, 0}",
218	},
219}
220
221func testType(t *testing.T, i int, typ Type, want string) {
222	s := typ.String()
223	if s != want {
224		t.Errorf("#%d: have %#q, want %#q", i, s, want)
225	}
226}
227
228func TestTypes(t *testing.T) {
229	for i, tt := range typeTests {
230		testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
231	}
232}
233
234func TestSet(t *testing.T) {
235	for i, tt := range valueTests {
236		v := ValueOf(tt.i)
237		v = v.Elem()
238		switch v.Kind() {
239		case Int:
240			v.SetInt(132)
241		case Int8:
242			v.SetInt(8)
243		case Int16:
244			v.SetInt(16)
245		case Int32:
246			v.SetInt(32)
247		case Int64:
248			v.SetInt(64)
249		case Uint:
250			v.SetUint(132)
251		case Uint8:
252			v.SetUint(8)
253		case Uint16:
254			v.SetUint(16)
255		case Uint32:
256			v.SetUint(32)
257		case Uint64:
258			v.SetUint(64)
259		case Float32:
260			v.SetFloat(256.25)
261		case Float64:
262			v.SetFloat(512.125)
263		case Complex64:
264			v.SetComplex(532.125 + 10i)
265		case Complex128:
266			v.SetComplex(564.25 + 1i)
267		case String:
268			v.SetString("stringy cheese")
269		case Bool:
270			v.SetBool(true)
271		}
272		s := valueToString(v)
273		if s != tt.s {
274			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
275		}
276	}
277}
278
279func TestSetValue(t *testing.T) {
280	for i, tt := range valueTests {
281		v := ValueOf(tt.i).Elem()
282		switch v.Kind() {
283		case Int:
284			v.Set(ValueOf(int(132)))
285		case Int8:
286			v.Set(ValueOf(int8(8)))
287		case Int16:
288			v.Set(ValueOf(int16(16)))
289		case Int32:
290			v.Set(ValueOf(int32(32)))
291		case Int64:
292			v.Set(ValueOf(int64(64)))
293		case Uint:
294			v.Set(ValueOf(uint(132)))
295		case Uint8:
296			v.Set(ValueOf(uint8(8)))
297		case Uint16:
298			v.Set(ValueOf(uint16(16)))
299		case Uint32:
300			v.Set(ValueOf(uint32(32)))
301		case Uint64:
302			v.Set(ValueOf(uint64(64)))
303		case Float32:
304			v.Set(ValueOf(float32(256.25)))
305		case Float64:
306			v.Set(ValueOf(512.125))
307		case Complex64:
308			v.Set(ValueOf(complex64(532.125 + 10i)))
309		case Complex128:
310			v.Set(ValueOf(complex128(564.25 + 1i)))
311		case String:
312			v.Set(ValueOf("stringy cheese"))
313		case Bool:
314			v.Set(ValueOf(true))
315		}
316		s := valueToString(v)
317		if s != tt.s {
318			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
319		}
320	}
321}
322
323var _i = 7
324
325var valueToStringTests = []pair{
326	{123, "123"},
327	{123.5, "123.5"},
328	{byte(123), "123"},
329	{"abc", "abc"},
330	{T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
331	{new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
332	{[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
333	{&[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})"},
334	{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
335	{&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
336}
337
338func TestValueToString(t *testing.T) {
339	for i, test := range valueToStringTests {
340		s := valueToString(ValueOf(test.i))
341		if s != test.s {
342			t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
343		}
344	}
345}
346
347func TestArrayElemSet(t *testing.T) {
348	v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
349	v.Index(4).SetInt(123)
350	s := valueToString(v)
351	const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
352	if s != want {
353		t.Errorf("[10]int: have %#q want %#q", s, want)
354	}
355
356	v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
357	v.Index(4).SetInt(123)
358	s = valueToString(v)
359	const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
360	if s != want1 {
361		t.Errorf("[]int: have %#q want %#q", s, want1)
362	}
363}
364
365func TestPtrPointTo(t *testing.T) {
366	var ip *int32
367	var i int32 = 1234
368	vip := ValueOf(&ip)
369	vi := ValueOf(&i).Elem()
370	vip.Elem().Set(vi.Addr())
371	if *ip != 1234 {
372		t.Errorf("got %d, want 1234", *ip)
373	}
374
375	ip = nil
376	vp := ValueOf(&ip).Elem()
377	vp.Set(Zero(vp.Type()))
378	if ip != nil {
379		t.Errorf("got non-nil (%p), want nil", ip)
380	}
381}
382
383func TestPtrSetNil(t *testing.T) {
384	var i int32 = 1234
385	ip := &i
386	vip := ValueOf(&ip)
387	vip.Elem().Set(Zero(vip.Elem().Type()))
388	if ip != nil {
389		t.Errorf("got non-nil (%d), want nil", *ip)
390	}
391}
392
393func TestMapSetNil(t *testing.T) {
394	m := make(map[string]int)
395	vm := ValueOf(&m)
396	vm.Elem().Set(Zero(vm.Elem().Type()))
397	if m != nil {
398		t.Errorf("got non-nil (%p), want nil", m)
399	}
400}
401
402func TestAll(t *testing.T) {
403	testType(t, 1, TypeOf((int8)(0)), "int8")
404	testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
405
406	typ := TypeOf((*struct {
407		c chan *int32
408		d float32
409	})(nil))
410	testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
411	etyp := typ.Elem()
412	testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
413	styp := etyp
414	f := styp.Field(0)
415	testType(t, 5, f.Type, "chan *int32")
416
417	f, present := styp.FieldByName("d")
418	if !present {
419		t.Errorf("FieldByName says present field is absent")
420	}
421	testType(t, 6, f.Type, "float32")
422
423	f, present = styp.FieldByName("absent")
424	if present {
425		t.Errorf("FieldByName says absent field is present")
426	}
427
428	typ = TypeOf([32]int32{})
429	testType(t, 7, typ, "[32]int32")
430	testType(t, 8, typ.Elem(), "int32")
431
432	typ = TypeOf((map[string]*int32)(nil))
433	testType(t, 9, typ, "map[string]*int32")
434	mtyp := typ
435	testType(t, 10, mtyp.Key(), "string")
436	testType(t, 11, mtyp.Elem(), "*int32")
437
438	typ = TypeOf((chan<- string)(nil))
439	testType(t, 12, typ, "chan<- string")
440	testType(t, 13, typ.Elem(), "string")
441
442	// make sure tag strings are not part of element type
443	typ = TypeOf(struct {
444		d []uint32 `reflect:"TAG"`
445	}{}).Field(0).Type
446	testType(t, 14, typ, "[]uint32")
447}
448
449func TestInterfaceGet(t *testing.T) {
450	var inter struct {
451		E interface{}
452	}
453	inter.E = 123.456
454	v1 := ValueOf(&inter)
455	v2 := v1.Elem().Field(0)
456	assert(t, v2.Type().String(), "interface {}")
457	i2 := v2.Interface()
458	v3 := ValueOf(i2)
459	assert(t, v3.Type().String(), "float64")
460}
461
462func TestInterfaceValue(t *testing.T) {
463	var inter struct {
464		E interface{}
465	}
466	inter.E = 123.456
467	v1 := ValueOf(&inter)
468	v2 := v1.Elem().Field(0)
469	assert(t, v2.Type().String(), "interface {}")
470	v3 := v2.Elem()
471	assert(t, v3.Type().String(), "float64")
472
473	i3 := v2.Interface()
474	if _, ok := i3.(float64); !ok {
475		t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
476	}
477}
478
479func TestFunctionValue(t *testing.T) {
480	var x interface{} = func() {}
481	v := ValueOf(x)
482	if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
483		t.Fatalf("TestFunction returned wrong pointer")
484	}
485	assert(t, v.Type().String(), "func()")
486}
487
488var appendTests = []struct {
489	orig, extra []int
490}{
491	{make([]int, 2, 4), []int{22}},
492	{make([]int, 2, 4), []int{22, 33, 44}},
493}
494
495func sameInts(x, y []int) bool {
496	if len(x) != len(y) {
497		return false
498	}
499	for i, xx := range x {
500		if xx != y[i] {
501			return false
502		}
503	}
504	return true
505}
506
507func TestAppend(t *testing.T) {
508	for i, test := range appendTests {
509		origLen, extraLen := len(test.orig), len(test.extra)
510		want := append(test.orig, test.extra...)
511		// Convert extra from []int to []Value.
512		e0 := make([]Value, len(test.extra))
513		for j, e := range test.extra {
514			e0[j] = ValueOf(e)
515		}
516		// Convert extra from []int to *SliceValue.
517		e1 := ValueOf(test.extra)
518		// Test Append.
519		a0 := ValueOf(test.orig)
520		have0 := Append(a0, e0...).Interface().([]int)
521		if !sameInts(have0, want) {
522			t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
523		}
524		// Check that the orig and extra slices were not modified.
525		if len(test.orig) != origLen {
526			t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
527		}
528		if len(test.extra) != extraLen {
529			t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
530		}
531		// Test AppendSlice.
532		a1 := ValueOf(test.orig)
533		have1 := AppendSlice(a1, e1).Interface().([]int)
534		if !sameInts(have1, want) {
535			t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
536		}
537		// Check that the orig and extra slices were not modified.
538		if len(test.orig) != origLen {
539			t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
540		}
541		if len(test.extra) != extraLen {
542			t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
543		}
544	}
545}
546
547func TestCopy(t *testing.T) {
548	a := []int{1, 2, 3, 4, 10, 9, 8, 7}
549	b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
550	c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
551	for i := 0; i < len(b); i++ {
552		if b[i] != c[i] {
553			t.Fatalf("b != c before test")
554		}
555	}
556	a1 := a
557	b1 := b
558	aa := ValueOf(&a1).Elem()
559	ab := ValueOf(&b1).Elem()
560	for tocopy := 1; tocopy <= 7; tocopy++ {
561		aa.SetLen(tocopy)
562		Copy(ab, aa)
563		aa.SetLen(8)
564		for i := 0; i < tocopy; i++ {
565			if a[i] != b[i] {
566				t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
567					tocopy, i, a[i], i, b[i])
568			}
569		}
570		for i := tocopy; i < len(b); i++ {
571			if b[i] != c[i] {
572				if i < len(a) {
573					t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
574						tocopy, i, a[i], i, b[i], i, c[i])
575				} else {
576					t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
577						tocopy, i, b[i], i, c[i])
578				}
579			} else {
580				t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
581			}
582		}
583	}
584}
585
586func TestCopyArray(t *testing.T) {
587	a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
588	b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
589	c := b
590	aa := ValueOf(&a).Elem()
591	ab := ValueOf(&b).Elem()
592	Copy(ab, aa)
593	for i := 0; i < len(a); i++ {
594		if a[i] != b[i] {
595			t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
596		}
597	}
598	for i := len(a); i < len(b); i++ {
599		if b[i] != c[i] {
600			t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
601		} else {
602			t.Logf("elem %d is okay\n", i)
603		}
604	}
605}
606
607func TestBigUnnamedStruct(t *testing.T) {
608	b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
609	v := ValueOf(b)
610	b1 := v.Interface().(struct {
611		a, b, c, d int64
612	})
613	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
614		t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
615	}
616}
617
618type big struct {
619	a, b, c, d, e int64
620}
621
622func TestBigStruct(t *testing.T) {
623	b := big{1, 2, 3, 4, 5}
624	v := ValueOf(b)
625	b1 := v.Interface().(big)
626	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
627		t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
628	}
629}
630
631type Basic struct {
632	x int
633	y float32
634}
635
636type NotBasic Basic
637
638type DeepEqualTest struct {
639	a, b interface{}
640	eq   bool
641}
642
643// Simple functions for DeepEqual tests.
644var (
645	fn1 func()             // nil.
646	fn2 func()             // nil.
647	fn3 = func() { fn1() } // Not nil.
648)
649
650var deepEqualTests = []DeepEqualTest{
651	// Equalities
652	{nil, nil, true},
653	{1, 1, true},
654	{int32(1), int32(1), true},
655	{0.5, 0.5, true},
656	{float32(0.5), float32(0.5), true},
657	{"hello", "hello", true},
658	{make([]int, 10), make([]int, 10), true},
659	{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
660	{Basic{1, 0.5}, Basic{1, 0.5}, true},
661	{error(nil), error(nil), true},
662	{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
663	{fn1, fn2, true},
664
665	// Inequalities
666	{1, 2, false},
667	{int32(1), int32(2), false},
668	{0.5, 0.6, false},
669	{float32(0.5), float32(0.6), false},
670	{"hello", "hey", false},
671	{make([]int, 10), make([]int, 11), false},
672	{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
673	{Basic{1, 0.5}, Basic{1, 0.6}, false},
674	{Basic{1, 0}, Basic{2, 0}, false},
675	{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
676	{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
677	{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
678	{map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
679	{nil, 1, false},
680	{1, nil, false},
681	{fn1, fn3, false},
682	{fn3, fn3, false},
683	{[][]int{{1}}, [][]int{{2}}, false},
684
685	// Nil vs empty: not the same.
686	{[]int{}, []int(nil), false},
687	{[]int{}, []int{}, true},
688	{[]int(nil), []int(nil), true},
689	{map[int]int{}, map[int]int(nil), false},
690	{map[int]int{}, map[int]int{}, true},
691	{map[int]int(nil), map[int]int(nil), true},
692
693	// Mismatched types
694	{1, 1.0, false},
695	{int32(1), int64(1), false},
696	{0.5, "hello", false},
697	{[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
698	{&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
699	{Basic{1, 0.5}, NotBasic{1, 0.5}, false},
700	{map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
701}
702
703func TestDeepEqual(t *testing.T) {
704	for _, test := range deepEqualTests {
705		if r := DeepEqual(test.a, test.b); r != test.eq {
706			t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
707		}
708	}
709}
710
711func TestTypeOf(t *testing.T) {
712	// Special case for nil
713	if typ := TypeOf(nil); typ != nil {
714		t.Errorf("expected nil type for nil value; got %v", typ)
715	}
716	for _, test := range deepEqualTests {
717		v := ValueOf(test.a)
718		if !v.IsValid() {
719			continue
720		}
721		typ := TypeOf(test.a)
722		if typ != v.Type() {
723			t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
724		}
725	}
726}
727
728type Recursive struct {
729	x int
730	r *Recursive
731}
732
733func TestDeepEqualRecursiveStruct(t *testing.T) {
734	a, b := new(Recursive), new(Recursive)
735	*a = Recursive{12, a}
736	*b = Recursive{12, b}
737	if !DeepEqual(a, b) {
738		t.Error("DeepEqual(recursive same) = false, want true")
739	}
740}
741
742type _Complex struct {
743	a int
744	b [3]*_Complex
745	c *string
746	d map[float64]float64
747}
748
749func TestDeepEqualComplexStruct(t *testing.T) {
750	m := make(map[float64]float64)
751	stra, strb := "hello", "hello"
752	a, b := new(_Complex), new(_Complex)
753	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
754	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
755	if !DeepEqual(a, b) {
756		t.Error("DeepEqual(complex same) = false, want true")
757	}
758}
759
760func TestDeepEqualComplexStructInequality(t *testing.T) {
761	m := make(map[float64]float64)
762	stra, strb := "hello", "helloo" // Difference is here
763	a, b := new(_Complex), new(_Complex)
764	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
765	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
766	if DeepEqual(a, b) {
767		t.Error("DeepEqual(complex different) = true, want false")
768	}
769}
770
771type UnexpT struct {
772	m map[int]int
773}
774
775func TestDeepEqualUnexportedMap(t *testing.T) {
776	// Check that DeepEqual can look at unexported fields.
777	x1 := UnexpT{map[int]int{1: 2}}
778	x2 := UnexpT{map[int]int{1: 2}}
779	if !DeepEqual(&x1, &x2) {
780		t.Error("DeepEqual(x1, x2) = false, want true")
781	}
782
783	y1 := UnexpT{map[int]int{2: 3}}
784	if DeepEqual(&x1, &y1) {
785		t.Error("DeepEqual(x1, y1) = true, want false")
786	}
787}
788
789func check2ndField(x interface{}, offs uintptr, t *testing.T) {
790	s := ValueOf(x)
791	f := s.Type().Field(1)
792	if f.Offset != offs {
793		t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
794	}
795}
796
797// Check that structure alignment & offsets viewed through reflect agree with those
798// from the compiler itself.
799func TestAlignment(t *testing.T) {
800	type T1inner struct {
801		a int
802	}
803	type T1 struct {
804		T1inner
805		f int
806	}
807	type T2inner struct {
808		a, b int
809	}
810	type T2 struct {
811		T2inner
812		f int
813	}
814
815	x := T1{T1inner{2}, 17}
816	check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
817
818	x1 := T2{T2inner{2, 3}, 17}
819	check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
820}
821
822func Nil(a interface{}, t *testing.T) {
823	n := ValueOf(a).Field(0)
824	if !n.IsNil() {
825		t.Errorf("%v should be nil", a)
826	}
827}
828
829func NotNil(a interface{}, t *testing.T) {
830	n := ValueOf(a).Field(0)
831	if n.IsNil() {
832		t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
833	}
834}
835
836func TestIsNil(t *testing.T) {
837	// These implement IsNil.
838	// Wrap in extra struct to hide interface type.
839	doNil := []interface{}{
840		struct{ x *int }{},
841		struct{ x interface{} }{},
842		struct{ x map[string]int }{},
843		struct{ x func() bool }{},
844		struct{ x chan int }{},
845		struct{ x []string }{},
846	}
847	for _, ts := range doNil {
848		ty := TypeOf(ts).Field(0).Type
849		v := Zero(ty)
850		v.IsNil() // panics if not okay to call
851	}
852
853	// Check the implementations
854	var pi struct {
855		x *int
856	}
857	Nil(pi, t)
858	pi.x = new(int)
859	NotNil(pi, t)
860
861	var si struct {
862		x []int
863	}
864	Nil(si, t)
865	si.x = make([]int, 10)
866	NotNil(si, t)
867
868	var ci struct {
869		x chan int
870	}
871	Nil(ci, t)
872	ci.x = make(chan int)
873	NotNil(ci, t)
874
875	var mi struct {
876		x map[int]int
877	}
878	Nil(mi, t)
879	mi.x = make(map[int]int)
880	NotNil(mi, t)
881
882	var ii struct {
883		x interface{}
884	}
885	Nil(ii, t)
886	ii.x = 2
887	NotNil(ii, t)
888
889	var fi struct {
890		x func(t *testing.T)
891	}
892	Nil(fi, t)
893	fi.x = TestIsNil
894	NotNil(fi, t)
895}
896
897func TestInterfaceExtraction(t *testing.T) {
898	var s struct {
899		W io.Writer
900	}
901
902	s.W = os.Stdout
903	v := Indirect(ValueOf(&s)).Field(0).Interface()
904	if v != s.W.(interface{}) {
905		t.Error("Interface() on interface: ", v, s.W)
906	}
907}
908
909func TestNilPtrValueSub(t *testing.T) {
910	var pi *int
911	if pv := ValueOf(pi); pv.Elem().IsValid() {
912		t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
913	}
914}
915
916func TestMap(t *testing.T) {
917	m := map[string]int{"a": 1, "b": 2}
918	mv := ValueOf(m)
919	if n := mv.Len(); n != len(m) {
920		t.Errorf("Len = %d, want %d", n, len(m))
921	}
922	keys := mv.MapKeys()
923	newmap := MakeMap(mv.Type())
924	for k, v := range m {
925		// Check that returned Keys match keys in range.
926		// These aren't required to be in the same order.
927		seen := false
928		for _, kv := range keys {
929			if kv.String() == k {
930				seen = true
931				break
932			}
933		}
934		if !seen {
935			t.Errorf("Missing key %q", k)
936		}
937
938		// Check that value lookup is correct.
939		vv := mv.MapIndex(ValueOf(k))
940		if vi := vv.Int(); vi != int64(v) {
941			t.Errorf("Key %q: have value %d, want %d", k, vi, v)
942		}
943
944		// Copy into new map.
945		newmap.SetMapIndex(ValueOf(k), ValueOf(v))
946	}
947	vv := mv.MapIndex(ValueOf("not-present"))
948	if vv.IsValid() {
949		t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
950	}
951
952	newm := newmap.Interface().(map[string]int)
953	if len(newm) != len(m) {
954		t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
955	}
956
957	for k, v := range newm {
958		mv, ok := m[k]
959		if mv != v {
960			t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
961		}
962	}
963
964	newmap.SetMapIndex(ValueOf("a"), Value{})
965	v, ok := newm["a"]
966	if ok {
967		t.Errorf("newm[\"a\"] = %d after delete", v)
968	}
969
970	mv = ValueOf(&m).Elem()
971	mv.Set(Zero(mv.Type()))
972	if m != nil {
973		t.Errorf("mv.Set(nil) failed")
974	}
975}
976
977func TestNilMap(t *testing.T) {
978	var m map[string]int
979	mv := ValueOf(m)
980	keys := mv.MapKeys()
981	if len(keys) != 0 {
982		t.Errorf(">0 keys for nil map: %v", keys)
983	}
984
985	// Check that value for missing key is zero.
986	x := mv.MapIndex(ValueOf("hello"))
987	if x.Kind() != Invalid {
988		t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
989	}
990
991	// Check big value too.
992	var mbig map[string][10 << 20]byte
993	x = ValueOf(mbig).MapIndex(ValueOf("hello"))
994	if x.Kind() != Invalid {
995		t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
996	}
997
998	// Test that deletes from a nil map succeed.
999	mv.SetMapIndex(ValueOf("hi"), Value{})
1000}
1001
1002func TestChan(t *testing.T) {
1003	for loop := 0; loop < 2; loop++ {
1004		var c chan int
1005		var cv Value
1006
1007		// check both ways to allocate channels
1008		switch loop {
1009		case 1:
1010			c = make(chan int, 1)
1011			cv = ValueOf(c)
1012		case 0:
1013			cv = MakeChan(TypeOf(c), 1)
1014			c = cv.Interface().(chan int)
1015		}
1016
1017		// Send
1018		cv.Send(ValueOf(2))
1019		if i := <-c; i != 2 {
1020			t.Errorf("reflect Send 2, native recv %d", i)
1021		}
1022
1023		// Recv
1024		c <- 3
1025		if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1026			t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1027		}
1028
1029		// TryRecv fail
1030		val, ok := cv.TryRecv()
1031		if val.IsValid() || ok {
1032			t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1033		}
1034
1035		// TryRecv success
1036		c <- 4
1037		val, ok = cv.TryRecv()
1038		if !val.IsValid() {
1039			t.Errorf("TryRecv on ready chan got nil")
1040		} else if i := val.Int(); i != 4 || !ok {
1041			t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1042		}
1043
1044		// TrySend fail
1045		c <- 100
1046		ok = cv.TrySend(ValueOf(5))
1047		i := <-c
1048		if ok {
1049			t.Errorf("TrySend on full chan succeeded: value %d", i)
1050		}
1051
1052		// TrySend success
1053		ok = cv.TrySend(ValueOf(6))
1054		if !ok {
1055			t.Errorf("TrySend on empty chan failed")
1056			select {
1057			case x := <-c:
1058				t.Errorf("TrySend failed but it did send %d", x)
1059			default:
1060			}
1061		} else {
1062			if i = <-c; i != 6 {
1063				t.Errorf("TrySend 6, recv %d", i)
1064			}
1065		}
1066
1067		// Close
1068		c <- 123
1069		cv.Close()
1070		if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1071			t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1072		}
1073		if i, ok := cv.Recv(); i.Int() != 0 || ok {
1074			t.Errorf("after close Recv %d, %t", i.Int(), ok)
1075		}
1076	}
1077
1078	// check creation of unbuffered channel
1079	var c chan int
1080	cv := MakeChan(TypeOf(c), 0)
1081	c = cv.Interface().(chan int)
1082	if cv.TrySend(ValueOf(7)) {
1083		t.Errorf("TrySend on sync chan succeeded")
1084	}
1085	if v, ok := cv.TryRecv(); v.IsValid() || ok {
1086		t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1087	}
1088
1089	// len/cap
1090	cv = MakeChan(TypeOf(c), 10)
1091	c = cv.Interface().(chan int)
1092	for i := 0; i < 3; i++ {
1093		c <- i
1094	}
1095	if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1096		t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1097	}
1098}
1099
1100// caseInfo describes a single case in a select test.
1101type caseInfo struct {
1102	desc      string
1103	canSelect bool
1104	recv      Value
1105	closed    bool
1106	helper    func()
1107	panic     bool
1108}
1109
1110var allselect = flag.Bool("allselect", false, "exhaustive select test")
1111
1112func TestSelect(t *testing.T) {
1113	selectWatch.once.Do(func() { go selectWatcher() })
1114
1115	var x exhaustive
1116	nch := 0
1117	newop := func(n int, cap int) (ch, val Value) {
1118		nch++
1119		if nch%101%2 == 1 {
1120			c := make(chan int, cap)
1121			ch = ValueOf(c)
1122			val = ValueOf(n)
1123		} else {
1124			c := make(chan string, cap)
1125			ch = ValueOf(c)
1126			val = ValueOf(fmt.Sprint(n))
1127		}
1128		return
1129	}
1130
1131	for n := 0; x.Next(); n++ {
1132		if testing.Short() && n >= 1000 {
1133			break
1134		}
1135		if n >= 100000 && !*allselect {
1136			break
1137		}
1138		if n%100000 == 0 && testing.Verbose() {
1139			println("TestSelect", n)
1140		}
1141		var cases []SelectCase
1142		var info []caseInfo
1143
1144		// Ready send.
1145		if x.Maybe() {
1146			ch, val := newop(len(cases), 1)
1147			cases = append(cases, SelectCase{
1148				Dir:  SelectSend,
1149				Chan: ch,
1150				Send: val,
1151			})
1152			info = append(info, caseInfo{desc: "ready send", canSelect: true})
1153		}
1154
1155		// Ready recv.
1156		if x.Maybe() {
1157			ch, val := newop(len(cases), 1)
1158			ch.Send(val)
1159			cases = append(cases, SelectCase{
1160				Dir:  SelectRecv,
1161				Chan: ch,
1162			})
1163			info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1164		}
1165
1166		// Blocking send.
1167		if x.Maybe() {
1168			ch, val := newop(len(cases), 0)
1169			cases = append(cases, SelectCase{
1170				Dir:  SelectSend,
1171				Chan: ch,
1172				Send: val,
1173			})
1174			// Let it execute?
1175			if x.Maybe() {
1176				f := func() { ch.Recv() }
1177				info = append(info, caseInfo{desc: "blocking send", helper: f})
1178			} else {
1179				info = append(info, caseInfo{desc: "blocking send"})
1180			}
1181		}
1182
1183		// Blocking recv.
1184		if x.Maybe() {
1185			ch, val := newop(len(cases), 0)
1186			cases = append(cases, SelectCase{
1187				Dir:  SelectRecv,
1188				Chan: ch,
1189			})
1190			// Let it execute?
1191			if x.Maybe() {
1192				f := func() { ch.Send(val) }
1193				info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1194			} else {
1195				info = append(info, caseInfo{desc: "blocking recv"})
1196			}
1197		}
1198
1199		// Zero Chan send.
1200		if x.Maybe() {
1201			// Maybe include value to send.
1202			var val Value
1203			if x.Maybe() {
1204				val = ValueOf(100)
1205			}
1206			cases = append(cases, SelectCase{
1207				Dir:  SelectSend,
1208				Send: val,
1209			})
1210			info = append(info, caseInfo{desc: "zero Chan send"})
1211		}
1212
1213		// Zero Chan receive.
1214		if x.Maybe() {
1215			cases = append(cases, SelectCase{
1216				Dir: SelectRecv,
1217			})
1218			info = append(info, caseInfo{desc: "zero Chan recv"})
1219		}
1220
1221		// nil Chan send.
1222		if x.Maybe() {
1223			cases = append(cases, SelectCase{
1224				Dir:  SelectSend,
1225				Chan: ValueOf((chan int)(nil)),
1226				Send: ValueOf(101),
1227			})
1228			info = append(info, caseInfo{desc: "nil Chan send"})
1229		}
1230
1231		// nil Chan recv.
1232		if x.Maybe() {
1233			cases = append(cases, SelectCase{
1234				Dir:  SelectRecv,
1235				Chan: ValueOf((chan int)(nil)),
1236			})
1237			info = append(info, caseInfo{desc: "nil Chan recv"})
1238		}
1239
1240		// closed Chan send.
1241		if x.Maybe() {
1242			ch := make(chan int)
1243			close(ch)
1244			cases = append(cases, SelectCase{
1245				Dir:  SelectSend,
1246				Chan: ValueOf(ch),
1247				Send: ValueOf(101),
1248			})
1249			info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1250		}
1251
1252		// closed Chan recv.
1253		if x.Maybe() {
1254			ch, val := newop(len(cases), 0)
1255			ch.Close()
1256			val = Zero(val.Type())
1257			cases = append(cases, SelectCase{
1258				Dir:  SelectRecv,
1259				Chan: ch,
1260			})
1261			info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1262		}
1263
1264		var helper func() // goroutine to help the select complete
1265
1266		// Add default? Must be last case here, but will permute.
1267		// Add the default if the select would otherwise
1268		// block forever, and maybe add it anyway.
1269		numCanSelect := 0
1270		canProceed := false
1271		canBlock := true
1272		canPanic := false
1273		helpers := []int{}
1274		for i, c := range info {
1275			if c.canSelect {
1276				canProceed = true
1277				canBlock = false
1278				numCanSelect++
1279				if c.panic {
1280					canPanic = true
1281				}
1282			} else if c.helper != nil {
1283				canProceed = true
1284				helpers = append(helpers, i)
1285			}
1286		}
1287		if !canProceed || x.Maybe() {
1288			cases = append(cases, SelectCase{
1289				Dir: SelectDefault,
1290			})
1291			info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1292			numCanSelect++
1293		} else if canBlock {
1294			// Select needs to communicate with another goroutine.
1295			cas := &info[helpers[x.Choose(len(helpers))]]
1296			helper = cas.helper
1297			cas.canSelect = true
1298			numCanSelect++
1299		}
1300
1301		// Permute cases and case info.
1302		// Doing too much here makes the exhaustive loop
1303		// too exhausting, so just do two swaps.
1304		for loop := 0; loop < 2; loop++ {
1305			i := x.Choose(len(cases))
1306			j := x.Choose(len(cases))
1307			cases[i], cases[j] = cases[j], cases[i]
1308			info[i], info[j] = info[j], info[i]
1309		}
1310
1311		if helper != nil {
1312			// We wait before kicking off a goroutine to satisfy a blocked select.
1313			// The pause needs to be big enough to let the select block before
1314			// we run the helper, but if we lose that race once in a while it's okay: the
1315			// select will just proceed immediately. Not a big deal.
1316			// For short tests we can grow [sic] the timeout a bit without fear of taking too long
1317			pause := 10 * time.Microsecond
1318			if testing.Short() {
1319				pause = 100 * time.Microsecond
1320			}
1321			time.AfterFunc(pause, helper)
1322		}
1323
1324		// Run select.
1325		i, recv, recvOK, panicErr := runSelect(cases, info)
1326		if panicErr != nil && !canPanic {
1327			t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1328		}
1329		if panicErr == nil && canPanic && numCanSelect == 1 {
1330			t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1331		}
1332		if panicErr != nil {
1333			continue
1334		}
1335
1336		cas := info[i]
1337		if !cas.canSelect {
1338			recvStr := ""
1339			if recv.IsValid() {
1340				recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1341			}
1342			t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1343			continue
1344		}
1345		if cas.panic {
1346			t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1347			continue
1348		}
1349
1350		if cases[i].Dir == SelectRecv {
1351			if !recv.IsValid() {
1352				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1353			}
1354			if !cas.recv.IsValid() {
1355				t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1356			}
1357			if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1358				if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1359					t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1360				}
1361				t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1362			}
1363		} else {
1364			if recv.IsValid() || recvOK {
1365				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1366			}
1367		}
1368	}
1369}
1370
1371// selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1372// If the selectWatcher notices that the select has been blocked for >1 second, it prints
1373// an error describing the select and panics the entire test binary.
1374var selectWatch struct {
1375	sync.Mutex
1376	once sync.Once
1377	now  time.Time
1378	info []caseInfo
1379}
1380
1381func selectWatcher() {
1382	for {
1383		time.Sleep(1 * time.Second)
1384		selectWatch.Lock()
1385		if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1386			fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1387			panic("select stuck")
1388		}
1389		selectWatch.Unlock()
1390	}
1391}
1392
1393// runSelect runs a single select test.
1394// It returns the values returned by Select but also returns
1395// a panic value if the Select panics.
1396func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1397	defer func() {
1398		panicErr = recover()
1399
1400		selectWatch.Lock()
1401		selectWatch.info = nil
1402		selectWatch.Unlock()
1403	}()
1404
1405	selectWatch.Lock()
1406	selectWatch.now = time.Now()
1407	selectWatch.info = info
1408	selectWatch.Unlock()
1409
1410	chosen, recv, recvOK = Select(cases)
1411	return
1412}
1413
1414// fmtSelect formats the information about a single select test.
1415func fmtSelect(info []caseInfo) string {
1416	var buf bytes.Buffer
1417	fmt.Fprintf(&buf, "\nselect {\n")
1418	for i, cas := range info {
1419		fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1420		if cas.recv.IsValid() {
1421			fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1422		}
1423		if cas.canSelect {
1424			fmt.Fprintf(&buf, " canselect")
1425		}
1426		if cas.panic {
1427			fmt.Fprintf(&buf, " panic")
1428		}
1429		fmt.Fprintf(&buf, "\n")
1430	}
1431	fmt.Fprintf(&buf, "}")
1432	return buf.String()
1433}
1434
1435type two [2]uintptr
1436
1437// Difficult test for function call because of
1438// implicit padding between arguments.
1439func 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) {
1440	return b, c, d, e, f, g, h
1441}
1442
1443func TestFunc(t *testing.T) {
1444	ret := ValueOf(dummy).Call([]Value{
1445		ValueOf(byte(10)),
1446		ValueOf(20),
1447		ValueOf(byte(30)),
1448		ValueOf(two{40, 50}),
1449		ValueOf(byte(60)),
1450		ValueOf(float32(70)),
1451		ValueOf(byte(80)),
1452	})
1453	if len(ret) != 7 {
1454		t.Fatalf("Call returned %d values, want 7", len(ret))
1455	}
1456
1457	i := byte(ret[0].Uint())
1458	j := int(ret[1].Int())
1459	k := byte(ret[2].Uint())
1460	l := ret[3].Interface().(two)
1461	m := byte(ret[4].Uint())
1462	n := float32(ret[5].Float())
1463	o := byte(ret[6].Uint())
1464
1465	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1466		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)
1467	}
1468}
1469
1470type emptyStruct struct{}
1471
1472type nonEmptyStruct struct {
1473	member int
1474}
1475
1476func returnEmpty() emptyStruct {
1477	return emptyStruct{}
1478}
1479
1480func takesEmpty(e emptyStruct) {
1481}
1482
1483func returnNonEmpty(i int) nonEmptyStruct {
1484	return nonEmptyStruct{member: i}
1485}
1486
1487func takesNonEmpty(n nonEmptyStruct) int {
1488	return n.member
1489}
1490
1491func TestCallWithStruct(t *testing.T) {
1492	r := ValueOf(returnEmpty).Call(nil)
1493	if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1494		t.Errorf("returning empty struct returned %#v instead", r)
1495	}
1496	r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1497	if len(r) != 0 {
1498		t.Errorf("takesEmpty returned values: %#v", r)
1499	}
1500	r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1501	if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1502		t.Errorf("returnNonEmpty returned %#v", r)
1503	}
1504	r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1505	if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1506		t.Errorf("takesNonEmpty returned %#v", r)
1507	}
1508}
1509
1510func BenchmarkCall(b *testing.B) {
1511	fv := ValueOf(func(a, b string) {})
1512	b.ReportAllocs()
1513	b.RunParallel(func(pb *testing.PB) {
1514		args := []Value{ValueOf("a"), ValueOf("b")}
1515		for pb.Next() {
1516			fv.Call(args)
1517		}
1518	})
1519}
1520
1521func TestMakeFunc(t *testing.T) {
1522	f := dummy
1523	fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1524	ValueOf(&f).Elem().Set(fv)
1525
1526	// Call g with small arguments so that there is
1527	// something predictable (and different from the
1528	// correct results) in those positions on the stack.
1529	g := dummy
1530	g(1, 2, 3, two{4, 5}, 6, 7, 8)
1531
1532	// Call constructed function f.
1533	i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1534	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1535		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)
1536	}
1537}
1538
1539func TestMakeFuncInterface(t *testing.T) {
1540	fn := func(i int) int { return i }
1541	incr := func(in []Value) []Value {
1542		return []Value{ValueOf(int(in[0].Int() + 1))}
1543	}
1544	fv := MakeFunc(TypeOf(fn), incr)
1545	ValueOf(&fn).Elem().Set(fv)
1546	if r := fn(2); r != 3 {
1547		t.Errorf("Call returned %d, want 3", r)
1548	}
1549	if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1550		t.Errorf("Call returned %d, want 15", r)
1551	}
1552	if r := fv.Interface().(func(int) int)(26); r != 27 {
1553		t.Errorf("Call returned %d, want 27", r)
1554	}
1555}
1556
1557func TestMakeFuncVariadic(t *testing.T) {
1558	// Test that variadic arguments are packed into a slice and passed as last arg
1559	fn := func(_ int, is ...int) []int { return nil }
1560	fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
1561	ValueOf(&fn).Elem().Set(fv)
1562
1563	r := fn(1, 2, 3)
1564	if r[0] != 2 || r[1] != 3 {
1565		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1566	}
1567
1568	r = fn(1, []int{2, 3}...)
1569	if r[0] != 2 || r[1] != 3 {
1570		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1571	}
1572
1573	r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1574	if r[0] != 2 || r[1] != 3 {
1575		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1576	}
1577
1578	r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1579	if r[0] != 2 || r[1] != 3 {
1580		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1581	}
1582
1583	f := fv.Interface().(func(int, ...int) []int)
1584
1585	r = f(1, 2, 3)
1586	if r[0] != 2 || r[1] != 3 {
1587		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1588	}
1589	r = f(1, []int{2, 3}...)
1590	if r[0] != 2 || r[1] != 3 {
1591		t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1592	}
1593}
1594
1595type Point struct {
1596	x, y int
1597}
1598
1599// This will be index 0.
1600func (p Point) AnotherMethod(scale int) int {
1601	return -1
1602}
1603
1604// This will be index 1.
1605func (p Point) Dist(scale int) int {
1606	//println("Point.Dist", p.x, p.y, scale)
1607	return p.x*p.x*scale + p.y*p.y*scale
1608}
1609
1610// This will be index 2.
1611func (p Point) GCMethod(k int) int {
1612	runtime.GC()
1613	return k + p.x
1614}
1615
1616// This will be index 3.
1617func (p Point) TotalDist(points ...Point) int {
1618	tot := 0
1619	for _, q := range points {
1620		dx := q.x - p.x
1621		dy := q.y - p.y
1622		tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
1623
1624	}
1625	return tot
1626}
1627
1628func TestMethod(t *testing.T) {
1629	// Non-curried method of type.
1630	p := Point{3, 4}
1631	i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1632	if i != 250 {
1633		t.Errorf("Type Method returned %d; want 250", i)
1634	}
1635
1636	m, ok := TypeOf(p).MethodByName("Dist")
1637	if !ok {
1638		t.Fatalf("method by name failed")
1639	}
1640	i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1641	if i != 275 {
1642		t.Errorf("Type MethodByName returned %d; want 275", i)
1643	}
1644
1645	i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1646	if i != 300 {
1647		t.Errorf("Pointer Type Method returned %d; want 300", i)
1648	}
1649
1650	m, ok = TypeOf(&p).MethodByName("Dist")
1651	if !ok {
1652		t.Fatalf("ptr method by name failed")
1653	}
1654	i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1655	if i != 325 {
1656		t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
1657	}
1658
1659	// Curried method of value.
1660	tfunc := TypeOf((func(int) int)(nil))
1661	v := ValueOf(p).Method(1)
1662	if tt := v.Type(); tt != tfunc {
1663		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1664	}
1665	i = v.Call([]Value{ValueOf(14)})[0].Int()
1666	if i != 350 {
1667		t.Errorf("Value Method returned %d; want 350", i)
1668	}
1669	v = ValueOf(p).MethodByName("Dist")
1670	if tt := v.Type(); tt != tfunc {
1671		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1672	}
1673	i = v.Call([]Value{ValueOf(15)})[0].Int()
1674	if i != 375 {
1675		t.Errorf("Value MethodByName returned %d; want 375", i)
1676	}
1677
1678	// Curried method of pointer.
1679	v = ValueOf(&p).Method(1)
1680	if tt := v.Type(); tt != tfunc {
1681		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1682	}
1683	i = v.Call([]Value{ValueOf(16)})[0].Int()
1684	if i != 400 {
1685		t.Errorf("Pointer Value Method returned %d; want 400", i)
1686	}
1687	v = ValueOf(&p).MethodByName("Dist")
1688	if tt := v.Type(); tt != tfunc {
1689		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1690	}
1691	i = v.Call([]Value{ValueOf(17)})[0].Int()
1692	if i != 425 {
1693		t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1694	}
1695
1696	// Curried method of interface value.
1697	// Have to wrap interface value in a struct to get at it.
1698	// Passing it to ValueOf directly would
1699	// access the underlying Point, not the interface.
1700	var x interface {
1701		Dist(int) int
1702	} = p
1703	pv := ValueOf(&x).Elem()
1704	v = pv.Method(0)
1705	if tt := v.Type(); tt != tfunc {
1706		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1707	}
1708	i = v.Call([]Value{ValueOf(18)})[0].Int()
1709	if i != 450 {
1710		t.Errorf("Interface Method returned %d; want 450", i)
1711	}
1712	v = pv.MethodByName("Dist")
1713	if tt := v.Type(); tt != tfunc {
1714		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1715	}
1716	i = v.Call([]Value{ValueOf(19)})[0].Int()
1717	if i != 475 {
1718		t.Errorf("Interface MethodByName returned %d; want 475", i)
1719	}
1720}
1721
1722func TestMethodValue(t *testing.T) {
1723	p := Point{3, 4}
1724	var i int64
1725
1726	// Curried method of value.
1727	tfunc := TypeOf((func(int) int)(nil))
1728	v := ValueOf(p).Method(1)
1729	if tt := v.Type(); tt != tfunc {
1730		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1731	}
1732	i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1733	if i != 250 {
1734		t.Errorf("Value Method returned %d; want 250", i)
1735	}
1736	v = ValueOf(p).MethodByName("Dist")
1737	if tt := v.Type(); tt != tfunc {
1738		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1739	}
1740	i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1741	if i != 275 {
1742		t.Errorf("Value MethodByName returned %d; want 275", i)
1743	}
1744
1745	// Curried method of pointer.
1746	v = ValueOf(&p).Method(1)
1747	if tt := v.Type(); tt != tfunc {
1748		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1749	}
1750	i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1751	if i != 300 {
1752		t.Errorf("Pointer Value Method returned %d; want 300", i)
1753	}
1754	v = ValueOf(&p).MethodByName("Dist")
1755	if tt := v.Type(); tt != tfunc {
1756		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1757	}
1758	i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1759	if i != 325 {
1760		t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
1761	}
1762
1763	// Curried method of pointer to pointer.
1764	pp := &p
1765	v = ValueOf(&pp).Elem().Method(1)
1766	if tt := v.Type(); tt != tfunc {
1767		t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
1768	}
1769	i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1770	if i != 350 {
1771		t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
1772	}
1773	v = ValueOf(&pp).Elem().MethodByName("Dist")
1774	if tt := v.Type(); tt != tfunc {
1775		t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1776	}
1777	i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1778	if i != 375 {
1779		t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
1780	}
1781
1782	// Curried method of interface value.
1783	// Have to wrap interface value in a struct to get at it.
1784	// Passing it to ValueOf directly would
1785	// access the underlying Point, not the interface.
1786	var s = struct {
1787		X interface {
1788			Dist(int) int
1789		}
1790	}{p}
1791	pv := ValueOf(s).Field(0)
1792	v = pv.Method(0)
1793	if tt := v.Type(); tt != tfunc {
1794		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1795	}
1796	i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
1797	if i != 400 {
1798		t.Errorf("Interface Method returned %d; want 400", i)
1799	}
1800	v = pv.MethodByName("Dist")
1801	if tt := v.Type(); tt != tfunc {
1802		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1803	}
1804	i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
1805	if i != 425 {
1806		t.Errorf("Interface MethodByName returned %d; want 425", i)
1807	}
1808}
1809
1810func TestVariadicMethodValue(t *testing.T) {
1811	p := Point{3, 4}
1812	points := []Point{{20, 21}, {22, 23}, {24, 25}}
1813	want := int64(p.TotalDist(points[0], points[1], points[2]))
1814
1815	// Curried method of value.
1816	tfunc := TypeOf((func(...Point) int)(nil))
1817	v := ValueOf(p).Method(3)
1818	if tt := v.Type(); tt != tfunc {
1819		t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
1820	}
1821	i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
1822	if i != want {
1823		t.Errorf("Variadic Method returned %d; want %d", i, want)
1824	}
1825	i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
1826	if i != want {
1827		t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
1828	}
1829
1830	f := v.Interface().(func(...Point) int)
1831	i = int64(f(points[0], points[1], points[2]))
1832	if i != want {
1833		t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
1834	}
1835	i = int64(f(points...))
1836	if i != want {
1837		t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
1838	}
1839}
1840
1841// Reflect version of $GOROOT/test/method5.go
1842
1843// Concrete types implementing M method.
1844// Smaller than a word, word-sized, larger than a word.
1845// Value and pointer receivers.
1846
1847type Tinter interface {
1848	M(int, byte) (byte, int)
1849}
1850
1851type Tsmallv byte
1852
1853func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1854
1855type Tsmallp byte
1856
1857func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1858
1859type Twordv uintptr
1860
1861func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1862
1863type Twordp uintptr
1864
1865func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1866
1867type Tbigv [2]uintptr
1868
1869func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1870
1871type Tbigp [2]uintptr
1872
1873func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1874
1875// Again, with an unexported method.
1876
1877type tsmallv byte
1878
1879func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1880
1881type tsmallp byte
1882
1883func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1884
1885type twordv uintptr
1886
1887func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1888
1889type twordp uintptr
1890
1891func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1892
1893type tbigv [2]uintptr
1894
1895func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1896
1897type tbigp [2]uintptr
1898
1899func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1900
1901type tinter interface {
1902	m(int, byte) (byte, int)
1903}
1904
1905// Embedding via pointer.
1906
1907type Tm1 struct {
1908	Tm2
1909}
1910
1911type Tm2 struct {
1912	*Tm3
1913}
1914
1915type Tm3 struct {
1916	*Tm4
1917}
1918
1919type Tm4 struct {
1920}
1921
1922func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
1923
1924func TestMethod5(t *testing.T) {
1925	CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1926		b, x := f(1000, 99)
1927		if b != 99 || x != 1000+inc {
1928			t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1929		}
1930	}
1931
1932	CheckV := func(name string, i Value, inc int) {
1933		bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
1934		b := bx[0].Interface()
1935		x := bx[1].Interface()
1936		if b != byte(99) || x != 1000+inc {
1937			t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1938		}
1939
1940		CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1941	}
1942
1943	var TinterType = TypeOf(new(Tinter)).Elem()
1944	var tinterType = TypeOf(new(tinter)).Elem()
1945
1946	CheckI := func(name string, i interface{}, inc int) {
1947		v := ValueOf(i)
1948		CheckV(name, v, inc)
1949		CheckV("(i="+name+")", v.Convert(TinterType), inc)
1950	}
1951
1952	sv := Tsmallv(1)
1953	CheckI("sv", sv, 1)
1954	CheckI("&sv", &sv, 1)
1955
1956	sp := Tsmallp(2)
1957	CheckI("&sp", &sp, 2)
1958
1959	wv := Twordv(3)
1960	CheckI("wv", wv, 3)
1961	CheckI("&wv", &wv, 3)
1962
1963	wp := Twordp(4)
1964	CheckI("&wp", &wp, 4)
1965
1966	bv := Tbigv([2]uintptr{5, 6})
1967	CheckI("bv", bv, 11)
1968	CheckI("&bv", &bv, 11)
1969
1970	bp := Tbigp([2]uintptr{7, 8})
1971	CheckI("&bp", &bp, 15)
1972
1973	t4 := Tm4{}
1974	t3 := Tm3{&t4}
1975	t2 := Tm2{&t3}
1976	t1 := Tm1{t2}
1977	CheckI("t4", t4, 40)
1978	CheckI("&t4", &t4, 40)
1979	CheckI("t3", t3, 40)
1980	CheckI("&t3", &t3, 40)
1981	CheckI("t2", t2, 40)
1982	CheckI("&t2", &t2, 40)
1983	CheckI("t1", t1, 40)
1984	CheckI("&t1", &t1, 40)
1985
1986	methodShouldPanic := func(name string, i interface{}) {
1987		v := ValueOf(i)
1988		m := v.Method(0)
1989		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1990		shouldPanic(func() { m.Interface() })
1991
1992		v = v.Convert(tinterType)
1993		m = v.Method(0)
1994		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1995		shouldPanic(func() { m.Interface() })
1996	}
1997
1998	_sv := tsmallv(1)
1999	methodShouldPanic("_sv", _sv)
2000	methodShouldPanic("&_sv", &_sv)
2001
2002	_sp := tsmallp(2)
2003	methodShouldPanic("&_sp", &_sp)
2004
2005	_wv := twordv(3)
2006	methodShouldPanic("_wv", _wv)
2007	methodShouldPanic("&_wv", &_wv)
2008
2009	_wp := twordp(4)
2010	methodShouldPanic("&_wp", &_wp)
2011
2012	_bv := tbigv([2]uintptr{5, 6})
2013	methodShouldPanic("_bv", _bv)
2014	methodShouldPanic("&_bv", &_bv)
2015
2016	_bp := tbigp([2]uintptr{7, 8})
2017	methodShouldPanic("&_bp", &_bp)
2018
2019	var tnil Tinter
2020	vnil := ValueOf(&tnil).Elem()
2021	shouldPanic(func() { vnil.Method(0) })
2022}
2023
2024func TestInterfaceSet(t *testing.T) {
2025	p := &Point{3, 4}
2026
2027	var s struct {
2028		I interface{}
2029		P interface {
2030			Dist(int) int
2031		}
2032	}
2033	sv := ValueOf(&s).Elem()
2034	sv.Field(0).Set(ValueOf(p))
2035	if q := s.I.(*Point); q != p {
2036		t.Errorf("i: have %p want %p", q, p)
2037	}
2038
2039	pv := sv.Field(1)
2040	pv.Set(ValueOf(p))
2041	if q := s.P.(*Point); q != p {
2042		t.Errorf("i: have %p want %p", q, p)
2043	}
2044
2045	i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2046	if i != 250 {
2047		t.Errorf("Interface Method returned %d; want 250", i)
2048	}
2049}
2050
2051type T1 struct {
2052	a string
2053	int
2054}
2055
2056func TestAnonymousFields(t *testing.T) {
2057	var field StructField
2058	var ok bool
2059	var t1 T1
2060	type1 := TypeOf(t1)
2061	if field, ok = type1.FieldByName("int"); !ok {
2062		t.Fatal("no field 'int'")
2063	}
2064	if field.Index[0] != 1 {
2065		t.Error("field index should be 1; is", field.Index)
2066	}
2067}
2068
2069type FTest struct {
2070	s     interface{}
2071	name  string
2072	index []int
2073	value int
2074}
2075
2076type D1 struct {
2077	d int
2078}
2079type D2 struct {
2080	d int
2081}
2082
2083type S0 struct {
2084	A, B, C int
2085	D1
2086	D2
2087}
2088
2089type S1 struct {
2090	B int
2091	S0
2092}
2093
2094type S2 struct {
2095	A int
2096	*S1
2097}
2098
2099type S1x struct {
2100	S1
2101}
2102
2103type S1y struct {
2104	S1
2105}
2106
2107type S3 struct {
2108	S1x
2109	S2
2110	D, E int
2111	*S1y
2112}
2113
2114type S4 struct {
2115	*S4
2116	A int
2117}
2118
2119// The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2120type S5 struct {
2121	S6
2122	S7
2123	S8
2124}
2125
2126type S6 struct {
2127	X int
2128}
2129
2130type S7 S6
2131
2132type S8 struct {
2133	S9
2134}
2135
2136type S9 struct {
2137	X int
2138	Y int
2139}
2140
2141// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2142type S10 struct {
2143	S11
2144	S12
2145	S13
2146}
2147
2148type S11 struct {
2149	S6
2150}
2151
2152type S12 struct {
2153	S6
2154}
2155
2156type S13 struct {
2157	S8
2158}
2159
2160// The X in S15.S11.S1 and S16.S11.S1 annihilate.
2161type S14 struct {
2162	S15
2163	S16
2164}
2165
2166type S15 struct {
2167	S11
2168}
2169
2170type S16 struct {
2171	S11
2172}
2173
2174var fieldTests = []FTest{
2175	{struct{}{}, "", nil, 0},
2176	{struct{}{}, "Foo", nil, 0},
2177	{S0{A: 'a'}, "A", []int{0}, 'a'},
2178	{S0{}, "D", nil, 0},
2179	{S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2180	{S1{B: 'b'}, "B", []int{0}, 'b'},
2181	{S1{}, "S0", []int{1}, 0},
2182	{S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2183	{S2{A: 'a'}, "A", []int{0}, 'a'},
2184	{S2{}, "S1", []int{1}, 0},
2185	{S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2186	{S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2187	{S2{}, "D", nil, 0},
2188	{S3{}, "S1", nil, 0},
2189	{S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2190	{S3{}, "B", nil, 0},
2191	{S3{D: 'd'}, "D", []int{2}, 0},
2192	{S3{E: 'e'}, "E", []int{3}, 'e'},
2193	{S4{A: 'a'}, "A", []int{1}, 'a'},
2194	{S4{}, "B", nil, 0},
2195	{S5{}, "X", nil, 0},
2196	{S5{}, "Y", []int{2, 0, 1}, 0},
2197	{S10{}, "X", nil, 0},
2198	{S10{}, "Y", []int{2, 0, 0, 1}, 0},
2199	{S14{}, "X", nil, 0},
2200}
2201
2202func TestFieldByIndex(t *testing.T) {
2203	for _, test := range fieldTests {
2204		s := TypeOf(test.s)
2205		f := s.FieldByIndex(test.index)
2206		if f.Name != "" {
2207			if test.index != nil {
2208				if f.Name != test.name {
2209					t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2210				}
2211			} else {
2212				t.Errorf("%s.%s found", s.Name(), f.Name)
2213			}
2214		} else if len(test.index) > 0 {
2215			t.Errorf("%s.%s not found", s.Name(), test.name)
2216		}
2217
2218		if test.value != 0 {
2219			v := ValueOf(test.s).FieldByIndex(test.index)
2220			if v.IsValid() {
2221				if x, ok := v.Interface().(int); ok {
2222					if x != test.value {
2223						t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2224					}
2225				} else {
2226					t.Errorf("%s%v value not an int", s.Name(), test.index)
2227				}
2228			} else {
2229				t.Errorf("%s%v value not found", s.Name(), test.index)
2230			}
2231		}
2232	}
2233}
2234
2235func TestFieldByName(t *testing.T) {
2236	for _, test := range fieldTests {
2237		s := TypeOf(test.s)
2238		f, found := s.FieldByName(test.name)
2239		if found {
2240			if test.index != nil {
2241				// Verify field depth and index.
2242				if len(f.Index) != len(test.index) {
2243					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)
2244				} else {
2245					for i, x := range f.Index {
2246						if x != test.index[i] {
2247							t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2248						}
2249					}
2250				}
2251			} else {
2252				t.Errorf("%s.%s found", s.Name(), f.Name)
2253			}
2254		} else if len(test.index) > 0 {
2255			t.Errorf("%s.%s not found", s.Name(), test.name)
2256		}
2257
2258		if test.value != 0 {
2259			v := ValueOf(test.s).FieldByName(test.name)
2260			if v.IsValid() {
2261				if x, ok := v.Interface().(int); ok {
2262					if x != test.value {
2263						t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2264					}
2265				} else {
2266					t.Errorf("%s.%s value not an int", s.Name(), test.name)
2267				}
2268			} else {
2269				t.Errorf("%s.%s value not found", s.Name(), test.name)
2270			}
2271		}
2272	}
2273}
2274
2275func TestImportPath(t *testing.T) {
2276	tests := []struct {
2277		t    Type
2278		path string
2279	}{
2280		{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2281		{TypeOf(int(0)), ""},
2282		{TypeOf(int8(0)), ""},
2283		{TypeOf(int16(0)), ""},
2284		{TypeOf(int32(0)), ""},
2285		{TypeOf(int64(0)), ""},
2286		{TypeOf(uint(0)), ""},
2287		{TypeOf(uint8(0)), ""},
2288		{TypeOf(uint16(0)), ""},
2289		{TypeOf(uint32(0)), ""},
2290		{TypeOf(uint64(0)), ""},
2291		{TypeOf(uintptr(0)), ""},
2292		{TypeOf(float32(0)), ""},
2293		{TypeOf(float64(0)), ""},
2294		{TypeOf(complex64(0)), ""},
2295		{TypeOf(complex128(0)), ""},
2296		{TypeOf(byte(0)), ""},
2297		{TypeOf(rune(0)), ""},
2298		{TypeOf([]byte(nil)), ""},
2299		{TypeOf([]rune(nil)), ""},
2300		{TypeOf(string("")), ""},
2301		{TypeOf((*interface{})(nil)).Elem(), ""},
2302		{TypeOf((*byte)(nil)), ""},
2303		{TypeOf((*rune)(nil)), ""},
2304		{TypeOf((*int64)(nil)), ""},
2305		{TypeOf(map[string]int{}), ""},
2306		{TypeOf((*error)(nil)).Elem(), ""},
2307	}
2308	for _, test := range tests {
2309		if path := test.t.PkgPath(); path != test.path {
2310			t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2311		}
2312	}
2313}
2314
2315func TestVariadicType(t *testing.T) {
2316	// Test example from Type documentation.
2317	var f func(x int, y ...float64)
2318	typ := TypeOf(f)
2319	if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2320		sl := typ.In(1)
2321		if sl.Kind() == Slice {
2322			if sl.Elem() == TypeOf(0.0) {
2323				// ok
2324				return
2325			}
2326		}
2327	}
2328
2329	// Failed
2330	t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2331	s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2332	for i := 0; i < typ.NumIn(); i++ {
2333		s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2334	}
2335	t.Error(s)
2336}
2337
2338type inner struct {
2339	x int
2340}
2341
2342type outer struct {
2343	y int
2344	inner
2345}
2346
2347func (*inner) m() {}
2348func (*outer) m() {}
2349
2350func TestNestedMethods(t *testing.T) {
2351	t.Skip("fails on gccgo due to function wrappers")
2352	typ := TypeOf((*outer)(nil))
2353	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
2354		t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
2355		for i := 0; i < typ.NumMethod(); i++ {
2356			m := typ.Method(i)
2357			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2358		}
2359	}
2360}
2361
2362type InnerInt struct {
2363	X int
2364}
2365
2366type OuterInt struct {
2367	Y int
2368	InnerInt
2369}
2370
2371func (i *InnerInt) M() int {
2372	return i.X
2373}
2374
2375func TestEmbeddedMethods(t *testing.T) {
2376	/* This part of the test fails on gccgo due to function wrappers.
2377	typ := TypeOf((*OuterInt)(nil))
2378	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2379		t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2380		for i := 0; i < typ.NumMethod(); i++ {
2381			m := typ.Method(i)
2382			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2383		}
2384	}
2385	*/
2386
2387	i := &InnerInt{3}
2388	if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
2389		t.Errorf("i.M() = %d, want 3", v)
2390	}
2391
2392	o := &OuterInt{1, InnerInt{2}}
2393	if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
2394		t.Errorf("i.M() = %d, want 2", v)
2395	}
2396
2397	f := (*OuterInt).M
2398	if v := f(o); v != 2 {
2399		t.Errorf("f(o) = %d, want 2", v)
2400	}
2401}
2402
2403func TestPtrTo(t *testing.T) {
2404	var i int
2405
2406	typ := TypeOf(i)
2407	for i = 0; i < 100; i++ {
2408		typ = PtrTo(typ)
2409	}
2410	for i = 0; i < 100; i++ {
2411		typ = typ.Elem()
2412	}
2413	if typ != TypeOf(i) {
2414		t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
2415	}
2416}
2417
2418func TestPtrToGC(t *testing.T) {
2419	type T *uintptr
2420	tt := TypeOf(T(nil))
2421	pt := PtrTo(tt)
2422	const n = 100
2423	var x []interface{}
2424	for i := 0; i < n; i++ {
2425		v := New(pt)
2426		p := new(*uintptr)
2427		*p = new(uintptr)
2428		**p = uintptr(i)
2429		v.Elem().Set(ValueOf(p).Convert(pt))
2430		x = append(x, v.Interface())
2431	}
2432	runtime.GC()
2433
2434	for i, xi := range x {
2435		k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2436		if k != uintptr(i) {
2437			t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2438		}
2439	}
2440}
2441
2442func TestAddr(t *testing.T) {
2443	var p struct {
2444		X, Y int
2445	}
2446
2447	v := ValueOf(&p)
2448	v = v.Elem()
2449	v = v.Addr()
2450	v = v.Elem()
2451	v = v.Field(0)
2452	v.SetInt(2)
2453	if p.X != 2 {
2454		t.Errorf("Addr.Elem.Set failed to set value")
2455	}
2456
2457	// Again but take address of the ValueOf value.
2458	// Exercises generation of PtrTypes not present in the binary.
2459	q := &p
2460	v = ValueOf(&q).Elem()
2461	v = v.Addr()
2462	v = v.Elem()
2463	v = v.Elem()
2464	v = v.Addr()
2465	v = v.Elem()
2466	v = v.Field(0)
2467	v.SetInt(3)
2468	if p.X != 3 {
2469		t.Errorf("Addr.Elem.Set failed to set value")
2470	}
2471
2472	// Starting without pointer we should get changed value
2473	// in interface.
2474	qq := p
2475	v = ValueOf(&qq).Elem()
2476	v0 := v
2477	v = v.Addr()
2478	v = v.Elem()
2479	v = v.Field(0)
2480	v.SetInt(4)
2481	if p.X != 3 { // should be unchanged from last time
2482		t.Errorf("somehow value Set changed original p")
2483	}
2484	p = v0.Interface().(struct {
2485		X, Y int
2486	})
2487	if p.X != 4 {
2488		t.Errorf("Addr.Elem.Set valued to set value in top value")
2489	}
2490
2491	// Verify that taking the address of a type gives us a pointer
2492	// which we can convert back using the usual interface
2493	// notation.
2494	var s struct {
2495		B *bool
2496	}
2497	ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2498	*(ps.(**bool)) = new(bool)
2499	if s.B == nil {
2500		t.Errorf("Addr.Interface direct assignment failed")
2501	}
2502}
2503
2504/* gccgo does do allocations here.
2505
2506func noAlloc(t *testing.T, n int, f func(int)) {
2507	if testing.Short() {
2508		t.Skip("skipping malloc count in short mode")
2509	}
2510	if runtime.GOMAXPROCS(0) > 1 {
2511		t.Skip("skipping; GOMAXPROCS>1")
2512	}
2513	i := -1
2514	allocs := testing.AllocsPerRun(n, func() {
2515		f(i)
2516		i++
2517	})
2518	if allocs > 0 {
2519		t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2520	}
2521}
2522
2523func TestAllocations(t *testing.T) {
2524	noAlloc(t, 100, func(j int) {
2525		var i interface{}
2526		var v Value
2527
2528		// We can uncomment this when compiler escape analysis
2529		// is good enough to see that the integer assigned to i
2530		// does not escape and therefore need not be allocated.
2531		//
2532		// i = 42 + j
2533		// v = ValueOf(i)
2534		// if int(v.Int()) != 42+j {
2535		// 	panic("wrong int")
2536		// }
2537
2538		i = func(j int) int { return j }
2539		v = ValueOf(i)
2540		if v.Interface().(func(int) int)(j) != j {
2541			panic("wrong result")
2542		}
2543	})
2544}
2545
2546*/
2547
2548func TestSmallNegativeInt(t *testing.T) {
2549	i := int16(-1)
2550	v := ValueOf(i)
2551	if v.Int() != -1 {
2552		t.Errorf("int16(-1).Int() returned %v", v.Int())
2553	}
2554}
2555
2556func TestIndex(t *testing.T) {
2557	xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2558	v := ValueOf(xs).Index(3).Interface().(byte)
2559	if v != xs[3] {
2560		t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2561	}
2562	xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2563	v = ValueOf(xa).Index(2).Interface().(byte)
2564	if v != xa[2] {
2565		t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2566	}
2567	s := "0123456789"
2568	v = ValueOf(s).Index(3).Interface().(byte)
2569	if v != s[3] {
2570		t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2571	}
2572}
2573
2574func TestSlice(t *testing.T) {
2575	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2576	v := ValueOf(xs).Slice(3, 5).Interface().([]int)
2577	if len(v) != 2 {
2578		t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2579	}
2580	if cap(v) != 5 {
2581		t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2582	}
2583	if !DeepEqual(v[0:5], xs[3:]) {
2584		t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
2585	}
2586	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2587	v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
2588	if len(v) != 3 {
2589		t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2590	}
2591	if cap(v) != 6 {
2592		t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2593	}
2594	if !DeepEqual(v[0:6], xa[2:]) {
2595		t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
2596	}
2597	s := "0123456789"
2598	vs := ValueOf(s).Slice(3, 5).Interface().(string)
2599	if vs != s[3:5] {
2600		t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2601	}
2602
2603	rv := ValueOf(&xs).Elem()
2604	rv = rv.Slice(3, 4)
2605	ptr2 := rv.Pointer()
2606	rv = rv.Slice(5, 5)
2607	ptr3 := rv.Pointer()
2608	if ptr3 != ptr2 {
2609		t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
2610	}
2611}
2612
2613func TestSlice3(t *testing.T) {
2614	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2615	v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
2616	if len(v) != 2 {
2617		t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
2618	}
2619	if cap(v) != 4 {
2620		t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
2621	}
2622	if !DeepEqual(v[0:4], xs[3:7:7]) {
2623		t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
2624	}
2625	rv := ValueOf(&xs).Elem()
2626	shouldPanic(func() { rv.Slice3(1, 2, 1) })
2627	shouldPanic(func() { rv.Slice3(1, 1, 11) })
2628	shouldPanic(func() { rv.Slice3(2, 2, 1) })
2629
2630	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2631	v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
2632	if len(v) != 3 {
2633		t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
2634	}
2635	if cap(v) != 4 {
2636		t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
2637	}
2638	if !DeepEqual(v[0:4], xa[2:6:6]) {
2639		t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
2640	}
2641	rv = ValueOf(&xa).Elem()
2642	shouldPanic(func() { rv.Slice3(1, 2, 1) })
2643	shouldPanic(func() { rv.Slice3(1, 1, 11) })
2644	shouldPanic(func() { rv.Slice3(2, 2, 1) })
2645
2646	s := "hello world"
2647	rv = ValueOf(&s).Elem()
2648	shouldPanic(func() { rv.Slice3(1, 2, 3) })
2649
2650	rv = ValueOf(&xs).Elem()
2651	rv = rv.Slice3(3, 5, 7)
2652	ptr2 := rv.Pointer()
2653	rv = rv.Slice3(4, 4, 4)
2654	ptr3 := rv.Pointer()
2655	if ptr3 != ptr2 {
2656		t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
2657	}
2658}
2659
2660func TestSetLenCap(t *testing.T) {
2661	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2662	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2663
2664	vs := ValueOf(&xs).Elem()
2665	shouldPanic(func() { vs.SetLen(10) })
2666	shouldPanic(func() { vs.SetCap(10) })
2667	shouldPanic(func() { vs.SetLen(-1) })
2668	shouldPanic(func() { vs.SetCap(-1) })
2669	shouldPanic(func() { vs.SetCap(6) }) // smaller than len
2670	vs.SetLen(5)
2671	if len(xs) != 5 || cap(xs) != 8 {
2672		t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
2673	}
2674	vs.SetCap(6)
2675	if len(xs) != 5 || cap(xs) != 6 {
2676		t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
2677	}
2678	vs.SetCap(5)
2679	if len(xs) != 5 || cap(xs) != 5 {
2680		t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
2681	}
2682	shouldPanic(func() { vs.SetCap(4) }) // smaller than len
2683	shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
2684
2685	va := ValueOf(&xa).Elem()
2686	shouldPanic(func() { va.SetLen(8) })
2687	shouldPanic(func() { va.SetCap(8) })
2688}
2689
2690func TestVariadic(t *testing.T) {
2691	var b bytes.Buffer
2692	V := ValueOf
2693
2694	b.Reset()
2695	V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
2696	if b.String() != "hello, 42 world" {
2697		t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
2698	}
2699
2700	b.Reset()
2701	V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
2702	if b.String() != "hello, 42 world" {
2703		t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
2704	}
2705}
2706
2707func TestFuncArg(t *testing.T) {
2708	f1 := func(i int, f func(int) int) int { return f(i) }
2709	f2 := func(i int) int { return i + 1 }
2710	r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
2711	if r[0].Int() != 101 {
2712		t.Errorf("function returned %d, want 101", r[0].Int())
2713	}
2714}
2715
2716func TestStructArg(t *testing.T) {
2717	type padded struct {
2718		B string
2719		C int32
2720	}
2721	var (
2722		gotA  padded
2723		gotB  uint32
2724		wantA = padded{"3", 4}
2725		wantB = uint32(5)
2726	)
2727	f := func(a padded, b uint32) {
2728		gotA, gotB = a, b
2729	}
2730	ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
2731	if gotA != wantA || gotB != wantB {
2732		t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
2733	}
2734}
2735
2736var tagGetTests = []struct {
2737	Tag   StructTag
2738	Key   string
2739	Value string
2740}{
2741	{`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2742	{`protobuf:"PB(1,2)"`, `foo`, ``},
2743	{`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2744	{`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2745	{`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2746	{`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
2747	{`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
2748}
2749
2750func TestTagGet(t *testing.T) {
2751	for _, tt := range tagGetTests {
2752		if v := tt.Tag.Get(tt.Key); v != tt.Value {
2753			t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
2754		}
2755	}
2756}
2757
2758func TestBytes(t *testing.T) {
2759	type B []byte
2760	x := B{1, 2, 3, 4}
2761	y := ValueOf(x).Bytes()
2762	if !bytes.Equal(x, y) {
2763		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2764	}
2765	if &x[0] != &y[0] {
2766		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2767	}
2768}
2769
2770func TestSetBytes(t *testing.T) {
2771	type B []byte
2772	var x B
2773	y := []byte{1, 2, 3, 4}
2774	ValueOf(&x).Elem().SetBytes(y)
2775	if !bytes.Equal(x, y) {
2776		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2777	}
2778	if &x[0] != &y[0] {
2779		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2780	}
2781}
2782
2783type Private struct {
2784	x int
2785	y **int
2786}
2787
2788func (p *Private) m() {
2789}
2790
2791type Public struct {
2792	X int
2793	Y **int
2794}
2795
2796func (p *Public) M() {
2797}
2798
2799func TestUnexported(t *testing.T) {
2800	var pub Public
2801	v := ValueOf(&pub)
2802	isValid(v.Elem().Field(0))
2803	isValid(v.Elem().Field(1))
2804	isValid(v.Elem().FieldByName("X"))
2805	isValid(v.Elem().FieldByName("Y"))
2806	isValid(v.Type().Method(0).Func)
2807	isNonNil(v.Elem().Field(0).Interface())
2808	isNonNil(v.Elem().Field(1).Interface())
2809	isNonNil(v.Elem().FieldByName("X").Interface())
2810	isNonNil(v.Elem().FieldByName("Y").Interface())
2811	isNonNil(v.Type().Method(0).Func.Interface())
2812
2813	var priv Private
2814	v = ValueOf(&priv)
2815	isValid(v.Elem().Field(0))
2816	isValid(v.Elem().Field(1))
2817	isValid(v.Elem().FieldByName("x"))
2818	isValid(v.Elem().FieldByName("y"))
2819	isValid(v.Type().Method(0).Func)
2820	shouldPanic(func() { v.Elem().Field(0).Interface() })
2821	shouldPanic(func() { v.Elem().Field(1).Interface() })
2822	shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
2823	shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
2824	shouldPanic(func() { v.Type().Method(0).Func.Interface() })
2825}
2826
2827func shouldPanic(f func()) {
2828	defer func() {
2829		if recover() == nil {
2830			panic("did not panic")
2831		}
2832	}()
2833	f()
2834}
2835
2836func isNonNil(x interface{}) {
2837	if x == nil {
2838		panic("nil interface")
2839	}
2840}
2841
2842func isValid(v Value) {
2843	if !v.IsValid() {
2844		panic("zero Value")
2845	}
2846}
2847
2848func TestAlias(t *testing.T) {
2849	x := string("hello")
2850	v := ValueOf(&x).Elem()
2851	oldvalue := v.Interface()
2852	v.SetString("world")
2853	newvalue := v.Interface()
2854
2855	if oldvalue != "hello" || newvalue != "world" {
2856		t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
2857	}
2858}
2859
2860var V = ValueOf
2861
2862func EmptyInterfaceV(x interface{}) Value {
2863	return ValueOf(&x).Elem()
2864}
2865
2866func ReaderV(x io.Reader) Value {
2867	return ValueOf(&x).Elem()
2868}
2869
2870func ReadWriterV(x io.ReadWriter) Value {
2871	return ValueOf(&x).Elem()
2872}
2873
2874type Empty struct{}
2875type MyString string
2876type MyBytes []byte
2877type MyRunes []int32
2878type MyFunc func()
2879type MyByte byte
2880
2881var convertTests = []struct {
2882	in  Value
2883	out Value
2884}{
2885	// numbers
2886	/*
2887		Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2888
2889		package main
2890
2891		import "fmt"
2892
2893		var numbers = []string{
2894			"int8", "uint8", "int16", "uint16",
2895			"int32", "uint32", "int64", "uint64",
2896			"int", "uint", "uintptr",
2897			"float32", "float64",
2898		}
2899
2900		func main() {
2901			// all pairs but in an unusual order,
2902			// to emit all the int8, uint8 cases
2903			// before n grows too big.
2904			n := 1
2905			for i, f := range numbers {
2906				for _, g := range numbers[i:] {
2907					fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2908					n++
2909					if f != g {
2910						fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2911						n++
2912					}
2913				}
2914			}
2915		}
2916	*/
2917	{V(int8(1)), V(int8(1))},
2918	{V(int8(2)), V(uint8(2))},
2919	{V(uint8(3)), V(int8(3))},
2920	{V(int8(4)), V(int16(4))},
2921	{V(int16(5)), V(int8(5))},
2922	{V(int8(6)), V(uint16(6))},
2923	{V(uint16(7)), V(int8(7))},
2924	{V(int8(8)), V(int32(8))},
2925	{V(int32(9)), V(int8(9))},
2926	{V(int8(10)), V(uint32(10))},
2927	{V(uint32(11)), V(int8(11))},
2928	{V(int8(12)), V(int64(12))},
2929	{V(int64(13)), V(int8(13))},
2930	{V(int8(14)), V(uint64(14))},
2931	{V(uint64(15)), V(int8(15))},
2932	{V(int8(16)), V(int(16))},
2933	{V(int(17)), V(int8(17))},
2934	{V(int8(18)), V(uint(18))},
2935	{V(uint(19)), V(int8(19))},
2936	{V(int8(20)), V(uintptr(20))},
2937	{V(uintptr(21)), V(int8(21))},
2938	{V(int8(22)), V(float32(22))},
2939	{V(float32(23)), V(int8(23))},
2940	{V(int8(24)), V(float64(24))},
2941	{V(float64(25)), V(int8(25))},
2942	{V(uint8(26)), V(uint8(26))},
2943	{V(uint8(27)), V(int16(27))},
2944	{V(int16(28)), V(uint8(28))},
2945	{V(uint8(29)), V(uint16(29))},
2946	{V(uint16(30)), V(uint8(30))},
2947	{V(uint8(31)), V(int32(31))},
2948	{V(int32(32)), V(uint8(32))},
2949	{V(uint8(33)), V(uint32(33))},
2950	{V(uint32(34)), V(uint8(34))},
2951	{V(uint8(35)), V(int64(35))},
2952	{V(int64(36)), V(uint8(36))},
2953	{V(uint8(37)), V(uint64(37))},
2954	{V(uint64(38)), V(uint8(38))},
2955	{V(uint8(39)), V(int(39))},
2956	{V(int(40)), V(uint8(40))},
2957	{V(uint8(41)), V(uint(41))},
2958	{V(uint(42)), V(uint8(42))},
2959	{V(uint8(43)), V(uintptr(43))},
2960	{V(uintptr(44)), V(uint8(44))},
2961	{V(uint8(45)), V(float32(45))},
2962	{V(float32(46)), V(uint8(46))},
2963	{V(uint8(47)), V(float64(47))},
2964	{V(float64(48)), V(uint8(48))},
2965	{V(int16(49)), V(int16(49))},
2966	{V(int16(50)), V(uint16(50))},
2967	{V(uint16(51)), V(int16(51))},
2968	{V(int16(52)), V(int32(52))},
2969	{V(int32(53)), V(int16(53))},
2970	{V(int16(54)), V(uint32(54))},
2971	{V(uint32(55)), V(int16(55))},
2972	{V(int16(56)), V(int64(56))},
2973	{V(int64(57)), V(int16(57))},
2974	{V(int16(58)), V(uint64(58))},
2975	{V(uint64(59)), V(int16(59))},
2976	{V(int16(60)), V(int(60))},
2977	{V(int(61)), V(int16(61))},
2978	{V(int16(62)), V(uint(62))},
2979	{V(uint(63)), V(int16(63))},
2980	{V(int16(64)), V(uintptr(64))},
2981	{V(uintptr(65)), V(int16(65))},
2982	{V(int16(66)), V(float32(66))},
2983	{V(float32(67)), V(int16(67))},
2984	{V(int16(68)), V(float64(68))},
2985	{V(float64(69)), V(int16(69))},
2986	{V(uint16(70)), V(uint16(70))},
2987	{V(uint16(71)), V(int32(71))},
2988	{V(int32(72)), V(uint16(72))},
2989	{V(uint16(73)), V(uint32(73))},
2990	{V(uint32(74)), V(uint16(74))},
2991	{V(uint16(75)), V(int64(75))},
2992	{V(int64(76)), V(uint16(76))},
2993	{V(uint16(77)), V(uint64(77))},
2994	{V(uint64(78)), V(uint16(78))},
2995	{V(uint16(79)), V(int(79))},
2996	{V(int(80)), V(uint16(80))},
2997	{V(uint16(81)), V(uint(81))},
2998	{V(uint(82)), V(uint16(82))},
2999	{V(uint16(83)), V(uintptr(83))},
3000	{V(uintptr(84)), V(uint16(84))},
3001	{V(uint16(85)), V(float32(85))},
3002	{V(float32(86)), V(uint16(86))},
3003	{V(uint16(87)), V(float64(87))},
3004	{V(float64(88)), V(uint16(88))},
3005	{V(int32(89)), V(int32(89))},
3006	{V(int32(90)), V(uint32(90))},
3007	{V(uint32(91)), V(int32(91))},
3008	{V(int32(92)), V(int64(92))},
3009	{V(int64(93)), V(int32(93))},
3010	{V(int32(94)), V(uint64(94))},
3011	{V(uint64(95)), V(int32(95))},
3012	{V(int32(96)), V(int(96))},
3013	{V(int(97)), V(int32(97))},
3014	{V(int32(98)), V(uint(98))},
3015	{V(uint(99)), V(int32(99))},
3016	{V(int32(100)), V(uintptr(100))},
3017	{V(uintptr(101)), V(int32(101))},
3018	{V(int32(102)), V(float32(102))},
3019	{V(float32(103)), V(int32(103))},
3020	{V(int32(104)), V(float64(104))},
3021	{V(float64(105)), V(int32(105))},
3022	{V(uint32(106)), V(uint32(106))},
3023	{V(uint32(107)), V(int64(107))},
3024	{V(int64(108)), V(uint32(108))},
3025	{V(uint32(109)), V(uint64(109))},
3026	{V(uint64(110)), V(uint32(110))},
3027	{V(uint32(111)), V(int(111))},
3028	{V(int(112)), V(uint32(112))},
3029	{V(uint32(113)), V(uint(113))},
3030	{V(uint(114)), V(uint32(114))},
3031	{V(uint32(115)), V(uintptr(115))},
3032	{V(uintptr(116)), V(uint32(116))},
3033	{V(uint32(117)), V(float32(117))},
3034	{V(float32(118)), V(uint32(118))},
3035	{V(uint32(119)), V(float64(119))},
3036	{V(float64(120)), V(uint32(120))},
3037	{V(int64(121)), V(int64(121))},
3038	{V(int64(122)), V(uint64(122))},
3039	{V(uint64(123)), V(int64(123))},
3040	{V(int64(124)), V(int(124))},
3041	{V(int(125)), V(int64(125))},
3042	{V(int64(126)), V(uint(126))},
3043	{V(uint(127)), V(int64(127))},
3044	{V(int64(128)), V(uintptr(128))},
3045	{V(uintptr(129)), V(int64(129))},
3046	{V(int64(130)), V(float32(130))},
3047	{V(float32(131)), V(int64(131))},
3048	{V(int64(132)), V(float64(132))},
3049	{V(float64(133)), V(int64(133))},
3050	{V(uint64(134)), V(uint64(134))},
3051	{V(uint64(135)), V(int(135))},
3052	{V(int(136)), V(uint64(136))},
3053	{V(uint64(137)), V(uint(137))},
3054	{V(uint(138)), V(uint64(138))},
3055	{V(uint64(139)), V(uintptr(139))},
3056	{V(uintptr(140)), V(uint64(140))},
3057	{V(uint64(141)), V(float32(141))},
3058	{V(float32(142)), V(uint64(142))},
3059	{V(uint64(143)), V(float64(143))},
3060	{V(float64(144)), V(uint64(144))},
3061	{V(int(145)), V(int(145))},
3062	{V(int(146)), V(uint(146))},
3063	{V(uint(147)), V(int(147))},
3064	{V(int(148)), V(uintptr(148))},
3065	{V(uintptr(149)), V(int(149))},
3066	{V(int(150)), V(float32(150))},
3067	{V(float32(151)), V(int(151))},
3068	{V(int(152)), V(float64(152))},
3069	{V(float64(153)), V(int(153))},
3070	{V(uint(154)), V(uint(154))},
3071	{V(uint(155)), V(uintptr(155))},
3072	{V(uintptr(156)), V(uint(156))},
3073	{V(uint(157)), V(float32(157))},
3074	{V(float32(158)), V(uint(158))},
3075	{V(uint(159)), V(float64(159))},
3076	{V(float64(160)), V(uint(160))},
3077	{V(uintptr(161)), V(uintptr(161))},
3078	{V(uintptr(162)), V(float32(162))},
3079	{V(float32(163)), V(uintptr(163))},
3080	{V(uintptr(164)), V(float64(164))},
3081	{V(float64(165)), V(uintptr(165))},
3082	{V(float32(166)), V(float32(166))},
3083	{V(float32(167)), V(float64(167))},
3084	{V(float64(168)), V(float32(168))},
3085	{V(float64(169)), V(float64(169))},
3086
3087	// truncation
3088	{V(float64(1.5)), V(int(1))},
3089
3090	// complex
3091	{V(complex64(1i)), V(complex64(1i))},
3092	{V(complex64(2i)), V(complex128(2i))},
3093	{V(complex128(3i)), V(complex64(3i))},
3094	{V(complex128(4i)), V(complex128(4i))},
3095
3096	// string
3097	{V(string("hello")), V(string("hello"))},
3098	{V(string("bytes1")), V([]byte("bytes1"))},
3099	{V([]byte("bytes2")), V(string("bytes2"))},
3100	{V([]byte("bytes3")), V([]byte("bytes3"))},
3101	{V(string("runes♝")), V([]rune("runes♝"))},
3102	{V([]rune("runes♕")), V(string("runes♕"))},
3103	{V([]rune("runes������")), V([]rune("runes������"))},
3104	{V(int('a')), V(string("a"))},
3105	{V(int8('a')), V(string("a"))},
3106	{V(int16('a')), V(string("a"))},
3107	{V(int32('a')), V(string("a"))},
3108	{V(int64('a')), V(string("a"))},
3109	{V(uint('a')), V(string("a"))},
3110	{V(uint8('a')), V(string("a"))},
3111	{V(uint16('a')), V(string("a"))},
3112	{V(uint32('a')), V(string("a"))},
3113	{V(uint64('a')), V(string("a"))},
3114	{V(uintptr('a')), V(string("a"))},
3115	{V(int(-1)), V(string("\uFFFD"))},
3116	{V(int8(-2)), V(string("\uFFFD"))},
3117	{V(int16(-3)), V(string("\uFFFD"))},
3118	{V(int32(-4)), V(string("\uFFFD"))},
3119	{V(int64(-5)), V(string("\uFFFD"))},
3120	{V(uint(0x110001)), V(string("\uFFFD"))},
3121	{V(uint32(0x110002)), V(string("\uFFFD"))},
3122	{V(uint64(0x110003)), V(string("\uFFFD"))},
3123	{V(uintptr(0x110004)), V(string("\uFFFD"))},
3124
3125	// named string
3126	{V(MyString("hello")), V(string("hello"))},
3127	{V(string("hello")), V(MyString("hello"))},
3128	{V(string("hello")), V(string("hello"))},
3129	{V(MyString("hello")), V(MyString("hello"))},
3130	{V(MyString("bytes1")), V([]byte("bytes1"))},
3131	{V([]byte("bytes2")), V(MyString("bytes2"))},
3132	{V([]byte("bytes3")), V([]byte("bytes3"))},
3133	{V(MyString("runes♝")), V([]rune("runes♝"))},
3134	{V([]rune("runes♕")), V(MyString("runes♕"))},
3135	{V([]rune("runes������")), V([]rune("runes������"))},
3136	{V([]rune("runes������")), V(MyRunes("runes������"))},
3137	{V(MyRunes("runes������")), V([]rune("runes������"))},
3138	{V(int('a')), V(MyString("a"))},
3139	{V(int8('a')), V(MyString("a"))},
3140	{V(int16('a')), V(MyString("a"))},
3141	{V(int32('a')), V(MyString("a"))},
3142	{V(int64('a')), V(MyString("a"))},
3143	{V(uint('a')), V(MyString("a"))},
3144	{V(uint8('a')), V(MyString("a"))},
3145	{V(uint16('a')), V(MyString("a"))},
3146	{V(uint32('a')), V(MyString("a"))},
3147	{V(uint64('a')), V(MyString("a"))},
3148	{V(uintptr('a')), V(MyString("a"))},
3149	{V(int(-1)), V(MyString("\uFFFD"))},
3150	{V(int8(-2)), V(MyString("\uFFFD"))},
3151	{V(int16(-3)), V(MyString("\uFFFD"))},
3152	{V(int32(-4)), V(MyString("\uFFFD"))},
3153	{V(int64(-5)), V(MyString("\uFFFD"))},
3154	{V(uint(0x110001)), V(MyString("\uFFFD"))},
3155	{V(uint32(0x110002)), V(MyString("\uFFFD"))},
3156	{V(uint64(0x110003)), V(MyString("\uFFFD"))},
3157	{V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3158
3159	// named []byte
3160	{V(string("bytes1")), V(MyBytes("bytes1"))},
3161	{V(MyBytes("bytes2")), V(string("bytes2"))},
3162	{V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3163	{V(MyString("bytes1")), V(MyBytes("bytes1"))},
3164	{V(MyBytes("bytes2")), V(MyString("bytes2"))},
3165
3166	// named []rune
3167	{V(string("runes♝")), V(MyRunes("runes♝"))},
3168	{V(MyRunes("runes♕")), V(string("runes♕"))},
3169	{V(MyRunes("runes������")), V(MyRunes("runes������"))},
3170	{V(MyString("runes♝")), V(MyRunes("runes♝"))},
3171	{V(MyRunes("runes♕")), V(MyString("runes♕"))},
3172
3173	// named types and equal underlying types
3174	{V(new(int)), V(new(integer))},
3175	{V(new(integer)), V(new(int))},
3176	{V(Empty{}), V(struct{}{})},
3177	{V(new(Empty)), V(new(struct{}))},
3178	{V(struct{}{}), V(Empty{})},
3179	{V(new(struct{})), V(new(Empty))},
3180	{V(Empty{}), V(Empty{})},
3181	{V(MyBytes{}), V([]byte{})},
3182	{V([]byte{}), V(MyBytes{})},
3183	{V((func())(nil)), V(MyFunc(nil))},
3184	{V((MyFunc)(nil)), V((func())(nil))},
3185
3186	// can convert *byte and *MyByte
3187	{V((*byte)(nil)), V((*MyByte)(nil))},
3188	{V((*MyByte)(nil)), V((*byte)(nil))},
3189
3190	// cannot convert mismatched array sizes
3191	{V([2]byte{}), V([2]byte{})},
3192	{V([3]byte{}), V([3]byte{})},
3193
3194	// cannot convert other instances
3195	{V((**byte)(nil)), V((**byte)(nil))},
3196	{V((**MyByte)(nil)), V((**MyByte)(nil))},
3197	{V((chan byte)(nil)), V((chan byte)(nil))},
3198	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3199	{V(([]byte)(nil)), V(([]byte)(nil))},
3200	{V(([]MyByte)(nil)), V(([]MyByte)(nil))},
3201	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3202	{V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
3203	{V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3204	{V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
3205	{V([2]byte{}), V([2]byte{})},
3206	{V([2]MyByte{}), V([2]MyByte{})},
3207
3208	// other
3209	{V((***int)(nil)), V((***int)(nil))},
3210	{V((***byte)(nil)), V((***byte)(nil))},
3211	{V((***int32)(nil)), V((***int32)(nil))},
3212	{V((***int64)(nil)), V((***int64)(nil))},
3213	{V((chan int)(nil)), V((<-chan int)(nil))},
3214	{V((chan int)(nil)), V((chan<- int)(nil))},
3215	{V((chan string)(nil)), V((<-chan string)(nil))},
3216	{V((chan string)(nil)), V((chan<- string)(nil))},
3217	{V((chan byte)(nil)), V((chan byte)(nil))},
3218	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3219	{V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3220	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3221	{V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3222	{V([]uint(nil)), V([]uint(nil))},
3223	{V([]int(nil)), V([]int(nil))},
3224	{V(new(interface{})), V(new(interface{}))},
3225	{V(new(io.Reader)), V(new(io.Reader))},
3226	{V(new(io.Writer)), V(new(io.Writer))},
3227
3228	// interfaces
3229	{V(int(1)), EmptyInterfaceV(int(1))},
3230	{V(string("hello")), EmptyInterfaceV(string("hello"))},
3231	{V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3232	{ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3233	{V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
3234}
3235
3236func TestConvert(t *testing.T) {
3237	canConvert := map[[2]Type]bool{}
3238	all := map[Type]bool{}
3239
3240	for _, tt := range convertTests {
3241		t1 := tt.in.Type()
3242		if !t1.ConvertibleTo(t1) {
3243			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
3244			continue
3245		}
3246
3247		t2 := tt.out.Type()
3248		if !t1.ConvertibleTo(t2) {
3249			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
3250			continue
3251		}
3252
3253		all[t1] = true
3254		all[t2] = true
3255		canConvert[[2]Type{t1, t2}] = true
3256
3257		// vout1 represents the in value converted to the in type.
3258		v1 := tt.in
3259		vout1 := v1.Convert(t1)
3260		out1 := vout1.Interface()
3261		if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
3262			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
3263		}
3264
3265		// vout2 represents the in value converted to the out type.
3266		vout2 := v1.Convert(t2)
3267		out2 := vout2.Interface()
3268		if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
3269			t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
3270		}
3271
3272		// vout3 represents a new value of the out type, set to vout2.  This makes
3273		// sure the converted value vout2 is really usable as a regular value.
3274		vout3 := New(t2).Elem()
3275		vout3.Set(vout2)
3276		out3 := vout3.Interface()
3277		if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
3278			t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
3279		}
3280
3281		if IsRO(v1) {
3282			t.Errorf("table entry %v is RO, should not be", v1)
3283		}
3284		if IsRO(vout1) {
3285			t.Errorf("self-conversion output %v is RO, should not be", vout1)
3286		}
3287		if IsRO(vout2) {
3288			t.Errorf("conversion output %v is RO, should not be", vout2)
3289		}
3290		if IsRO(vout3) {
3291			t.Errorf("set(conversion output) %v is RO, should not be", vout3)
3292		}
3293		if !IsRO(MakeRO(v1).Convert(t1)) {
3294			t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3295		}
3296		if !IsRO(MakeRO(v1).Convert(t2)) {
3297			t.Errorf("RO conversion output %v is not RO, should be", v1)
3298		}
3299	}
3300
3301	// Assume that of all the types we saw during the tests,
3302	// if there wasn't an explicit entry for a conversion between
3303	// a pair of types, then it's not to be allowed. This checks for
3304	// things like 'int64' converting to '*int'.
3305	for t1 := range all {
3306		for t2 := range all {
3307			expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3308			if ok := t1.ConvertibleTo(t2); ok != expectOK {
3309				t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3310			}
3311		}
3312	}
3313}
3314
3315type ComparableStruct struct {
3316	X int
3317}
3318
3319type NonComparableStruct struct {
3320	X int
3321	Y map[string]int
3322}
3323
3324var comparableTests = []struct {
3325	typ Type
3326	ok  bool
3327}{
3328	{TypeOf(1), true},
3329	{TypeOf("hello"), true},
3330	{TypeOf(new(byte)), true},
3331	{TypeOf((func())(nil)), false},
3332	{TypeOf([]byte{}), false},
3333	{TypeOf(map[string]int{}), false},
3334	{TypeOf(make(chan int)), true},
3335	{TypeOf(1.5), true},
3336	{TypeOf(false), true},
3337	{TypeOf(1i), true},
3338	{TypeOf(ComparableStruct{}), true},
3339	{TypeOf(NonComparableStruct{}), false},
3340	{TypeOf([10]map[string]int{}), false},
3341	{TypeOf([10]string{}), true},
3342	{TypeOf(new(interface{})).Elem(), true},
3343}
3344
3345func TestComparable(t *testing.T) {
3346	for _, tt := range comparableTests {
3347		if ok := tt.typ.Comparable(); ok != tt.ok {
3348			t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
3349		}
3350	}
3351}
3352
3353func TestOverflow(t *testing.T) {
3354	if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3355		t.Errorf("%v wrongly overflows float64", 1e300)
3356	}
3357
3358	maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3359	if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3360		t.Errorf("%v wrongly overflows float32", maxFloat32)
3361	}
3362	ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3363	if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3364		t.Errorf("%v should overflow float32", ovfFloat32)
3365	}
3366	if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3367		t.Errorf("%v should overflow float32", -ovfFloat32)
3368	}
3369
3370	maxInt32 := int64(0x7fffffff)
3371	if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3372		t.Errorf("%v wrongly overflows int32", maxInt32)
3373	}
3374	if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3375		t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3376	}
3377	ovfInt32 := int64(1 << 31)
3378	if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3379		t.Errorf("%v should overflow int32", ovfInt32)
3380	}
3381
3382	maxUint32 := uint64(0xffffffff)
3383	if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3384		t.Errorf("%v wrongly overflows uint32", maxUint32)
3385	}
3386	ovfUint32 := uint64(1 << 32)
3387	if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3388		t.Errorf("%v should overflow uint32", ovfUint32)
3389	}
3390}
3391
3392func checkSameType(t *testing.T, x, y interface{}) {
3393	if TypeOf(x) != TypeOf(y) {
3394		t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3395	}
3396}
3397
3398func TestArrayOf(t *testing.T) {
3399	// check construction and use of type not in binary
3400	for _, table := range []struct {
3401		n          int
3402		value      func(i int) interface{}
3403		comparable bool
3404		want       string
3405	}{
3406		{
3407			n:          0,
3408			value:      func(i int) interface{} { type Tint int; return Tint(i) },
3409			comparable: true,
3410			want:       "[]",
3411		},
3412		{
3413			n:          10,
3414			value:      func(i int) interface{} { type Tint int; return Tint(i) },
3415			comparable: true,
3416			want:       "[0 1 2 3 4 5 6 7 8 9]",
3417		},
3418		{
3419			n:          10,
3420			value:      func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
3421			comparable: true,
3422			want:       "[0 1 2 3 4 5 6 7 8 9]",
3423		},
3424		{
3425			n:          10,
3426			value:      func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
3427			comparable: true,
3428			want:       "[0 1 2 3 4 5 6 7 8 9]",
3429		},
3430		{
3431			n:          10,
3432			value:      func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
3433			comparable: true,
3434			want:       "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
3435		},
3436		{
3437			n:          10,
3438			value:      func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
3439			comparable: false,
3440			want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3441		},
3442		{
3443			n:          10,
3444			value:      func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
3445			comparable: true,
3446			want:       "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3447		},
3448		{
3449			n:          10,
3450			value:      func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
3451			comparable: true,
3452			want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3453		},
3454		{
3455			n:          10,
3456			value:      func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
3457			comparable: false,
3458			want:       "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3459		},
3460		{
3461			n:          10,
3462			value:      func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
3463			comparable: true,
3464			want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
3465		},
3466		{
3467			n: 10,
3468			value: func(i int) interface{} {
3469				type TstructUV struct {
3470					U int
3471					V float64
3472				}
3473				return TstructUV{i, float64(i)}
3474			},
3475			comparable: true,
3476			want:       "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
3477		},
3478	} {
3479		at := ArrayOf(table.n, TypeOf(table.value(0)))
3480		v := New(at).Elem()
3481		vok := New(at).Elem()
3482		vnot := New(at).Elem()
3483		for i := 0; i < v.Len(); i++ {
3484			v.Index(i).Set(ValueOf(table.value(i)))
3485			vok.Index(i).Set(ValueOf(table.value(i)))
3486			j := i
3487			if i+1 == v.Len() {
3488				j = i + 1
3489			}
3490			vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
3491		}
3492		s := fmt.Sprint(v.Interface())
3493		if s != table.want {
3494			t.Errorf("constructed array = %s, want %s", s, table.want)
3495		}
3496
3497		if table.comparable != at.Comparable() {
3498			t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
3499		}
3500		if table.comparable {
3501			if table.n > 0 {
3502				if DeepEqual(vnot.Interface(), v.Interface()) {
3503					t.Errorf(
3504						"arrays (%#v) compare ok (but should not)",
3505						v.Interface(),
3506					)
3507				}
3508			}
3509			if !DeepEqual(vok.Interface(), v.Interface()) {
3510				t.Errorf(
3511					"arrays (%#v) compare NOT-ok (but should)",
3512					v.Interface(),
3513				)
3514			}
3515		}
3516	}
3517
3518	// check that type already in binary is found
3519	type T int
3520	checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
3521}
3522
3523func TestArrayOfGC(t *testing.T) {
3524	type T *uintptr
3525	tt := TypeOf(T(nil))
3526	const n = 100
3527	var x []interface{}
3528	for i := 0; i < n; i++ {
3529		v := New(ArrayOf(n, tt)).Elem()
3530		for j := 0; j < v.Len(); j++ {
3531			p := new(uintptr)
3532			*p = uintptr(i*n + j)
3533			v.Index(j).Set(ValueOf(p).Convert(tt))
3534		}
3535		x = append(x, v.Interface())
3536	}
3537	runtime.GC()
3538
3539	for i, xi := range x {
3540		v := ValueOf(xi)
3541		for j := 0; j < v.Len(); j++ {
3542			k := v.Index(j).Elem().Interface()
3543			if k != uintptr(i*n+j) {
3544				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3545			}
3546		}
3547	}
3548}
3549
3550func TestArrayOfAlg(t *testing.T) {
3551	at := ArrayOf(6, TypeOf(byte(0)))
3552	v1 := New(at).Elem()
3553	v2 := New(at).Elem()
3554	if v1.Interface() != v1.Interface() {
3555		t.Errorf("constructed array %v not equal to itself", v1.Interface())
3556	}
3557	v1.Index(5).Set(ValueOf(byte(1)))
3558	if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
3559		t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
3560	}
3561
3562	at = ArrayOf(6, TypeOf([]int(nil)))
3563	v1 = New(at).Elem()
3564	shouldPanic(func() { _ = v1.Interface() == v1.Interface() })
3565}
3566
3567func TestArrayOfGenericAlg(t *testing.T) {
3568	at1 := ArrayOf(5, TypeOf(string("")))
3569	at := ArrayOf(6, at1)
3570	v1 := New(at).Elem()
3571	v2 := New(at).Elem()
3572	if v1.Interface() != v1.Interface() {
3573		t.Errorf("constructed array %v not equal to itself", v1.Interface())
3574	}
3575
3576	v1.Index(0).Index(0).Set(ValueOf("abc"))
3577	v2.Index(0).Index(0).Set(ValueOf("efg"))
3578	if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
3579		t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
3580	}
3581
3582	v1.Index(0).Index(0).Set(ValueOf("abc"))
3583	v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
3584	if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
3585		t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
3586	}
3587
3588	// Test hash
3589	m := MakeMap(MapOf(at, TypeOf(int(0))))
3590	m.SetMapIndex(v1, ValueOf(1))
3591	if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
3592		t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
3593	}
3594}
3595
3596func TestArrayOfDirectIface(t *testing.T) {
3597	t.Skip("skipping test because gccgo uses a different directiface value")
3598	{
3599		type T [1]*byte
3600		i1 := Zero(TypeOf(T{})).Interface()
3601		v1 := ValueOf(&i1).Elem()
3602		p1 := v1.InterfaceData()[1]
3603
3604		i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
3605		v2 := ValueOf(&i2).Elem()
3606		p2 := v2.InterfaceData()[1]
3607
3608		if p1 != 0 {
3609			t.Errorf("got p1=%v. want=%v", p1, nil)
3610		}
3611
3612		if p2 != 0 {
3613			t.Errorf("got p2=%v. want=%v", p2, nil)
3614		}
3615	}
3616	{
3617		type T [0]*byte
3618		i1 := Zero(TypeOf(T{})).Interface()
3619		v1 := ValueOf(&i1).Elem()
3620		p1 := v1.InterfaceData()[1]
3621
3622		i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
3623		v2 := ValueOf(&i2).Elem()
3624		p2 := v2.InterfaceData()[1]
3625
3626		if p1 == 0 {
3627			t.Errorf("got p1=%v. want=not-%v", p1, nil)
3628		}
3629
3630		if p2 == 0 {
3631			t.Errorf("got p2=%v. want=not-%v", p2, nil)
3632		}
3633	}
3634}
3635
3636func TestSliceOf(t *testing.T) {
3637	// check construction and use of type not in binary
3638	type T int
3639	st := SliceOf(TypeOf(T(1)))
3640	v := MakeSlice(st, 10, 10)
3641	runtime.GC()
3642	for i := 0; i < v.Len(); i++ {
3643		v.Index(i).Set(ValueOf(T(i)))
3644		runtime.GC()
3645	}
3646	s := fmt.Sprint(v.Interface())
3647	want := "[0 1 2 3 4 5 6 7 8 9]"
3648	if s != want {
3649		t.Errorf("constructed slice = %s, want %s", s, want)
3650	}
3651
3652	// check that type already in binary is found
3653	type T1 int
3654	checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
3655}
3656
3657func TestSliceOverflow(t *testing.T) {
3658	// check that MakeSlice panics when size of slice overflows uint
3659	const S = 1e6
3660	s := uint(S)
3661	l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
3662	if l*s >= s {
3663		t.Fatal("slice size does not overflow")
3664	}
3665	var x [S]byte
3666	st := SliceOf(TypeOf(x))
3667	defer func() {
3668		err := recover()
3669		if err == nil {
3670			t.Fatal("slice overflow does not panic")
3671		}
3672	}()
3673	MakeSlice(st, int(l), int(l))
3674}
3675
3676func TestSliceOfGC(t *testing.T) {
3677	type T *uintptr
3678	tt := TypeOf(T(nil))
3679	st := SliceOf(tt)
3680	const n = 100
3681	var x []interface{}
3682	for i := 0; i < n; i++ {
3683		v := MakeSlice(st, n, n)
3684		for j := 0; j < v.Len(); j++ {
3685			p := new(uintptr)
3686			*p = uintptr(i*n + j)
3687			v.Index(j).Set(ValueOf(p).Convert(tt))
3688		}
3689		x = append(x, v.Interface())
3690	}
3691	runtime.GC()
3692
3693	for i, xi := range x {
3694		v := ValueOf(xi)
3695		for j := 0; j < v.Len(); j++ {
3696			k := v.Index(j).Elem().Interface()
3697			if k != uintptr(i*n+j) {
3698				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3699			}
3700		}
3701	}
3702}
3703
3704func TestChanOf(t *testing.T) {
3705	// check construction and use of type not in binary
3706	type T string
3707	ct := ChanOf(BothDir, TypeOf(T("")))
3708	v := MakeChan(ct, 2)
3709	runtime.GC()
3710	v.Send(ValueOf(T("hello")))
3711	runtime.GC()
3712	v.Send(ValueOf(T("world")))
3713	runtime.GC()
3714
3715	sv1, _ := v.Recv()
3716	sv2, _ := v.Recv()
3717	s1 := sv1.String()
3718	s2 := sv2.String()
3719	if s1 != "hello" || s2 != "world" {
3720		t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
3721	}
3722
3723	// check that type already in binary is found
3724	type T1 int
3725	checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
3726}
3727
3728func TestChanOfDir(t *testing.T) {
3729	// check construction and use of type not in binary
3730	type T string
3731	crt := ChanOf(RecvDir, TypeOf(T("")))
3732	cst := ChanOf(SendDir, TypeOf(T("")))
3733
3734	// check that type already in binary is found
3735	type T1 int
3736	checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil))
3737	checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil))
3738
3739	// check String form of ChanDir
3740	if crt.ChanDir().String() != "<-chan" {
3741		t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
3742	}
3743	if cst.ChanDir().String() != "chan<-" {
3744		t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
3745	}
3746}
3747
3748func TestChanOfGC(t *testing.T) {
3749	done := make(chan bool, 1)
3750	go func() {
3751		select {
3752		case <-done:
3753		case <-time.After(5 * time.Second):
3754			panic("deadlock in TestChanOfGC")
3755		}
3756	}()
3757
3758	defer func() {
3759		done <- true
3760	}()
3761
3762	type T *uintptr
3763	tt := TypeOf(T(nil))
3764	ct := ChanOf(BothDir, tt)
3765
3766	// NOTE: The garbage collector handles allocated channels specially,
3767	// so we have to save pointers to channels in x; the pointer code will
3768	// use the gc info in the newly constructed chan type.
3769	const n = 100
3770	var x []interface{}
3771	for i := 0; i < n; i++ {
3772		v := MakeChan(ct, n)
3773		for j := 0; j < n; j++ {
3774			p := new(uintptr)
3775			*p = uintptr(i*n + j)
3776			v.Send(ValueOf(p).Convert(tt))
3777		}
3778		pv := New(ct)
3779		pv.Elem().Set(v)
3780		x = append(x, pv.Interface())
3781	}
3782	runtime.GC()
3783
3784	for i, xi := range x {
3785		v := ValueOf(xi).Elem()
3786		for j := 0; j < n; j++ {
3787			pv, _ := v.Recv()
3788			k := pv.Elem().Interface()
3789			if k != uintptr(i*n+j) {
3790				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3791			}
3792		}
3793	}
3794}
3795
3796func TestMapOf(t *testing.T) {
3797	// check construction and use of type not in binary
3798	type K string
3799	type V float64
3800
3801	v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
3802	runtime.GC()
3803	v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
3804	runtime.GC()
3805
3806	s := fmt.Sprint(v.Interface())
3807	want := "map[a:1]"
3808	if s != want {
3809		t.Errorf("constructed map = %s, want %s", s, want)
3810	}
3811
3812	// check that type already in binary is found
3813	checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
3814
3815	// check that invalid key type panics
3816	shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3817}
3818
3819func TestMapOfGCKeys(t *testing.T) {
3820	type T *uintptr
3821	tt := TypeOf(T(nil))
3822	mt := MapOf(tt, TypeOf(false))
3823
3824	// NOTE: The garbage collector handles allocated maps specially,
3825	// so we have to save pointers to maps in x; the pointer code will
3826	// use the gc info in the newly constructed map type.
3827	const n = 100
3828	var x []interface{}
3829	for i := 0; i < n; i++ {
3830		v := MakeMap(mt)
3831		for j := 0; j < n; j++ {
3832			p := new(uintptr)
3833			*p = uintptr(i*n + j)
3834			v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
3835		}
3836		pv := New(mt)
3837		pv.Elem().Set(v)
3838		x = append(x, pv.Interface())
3839	}
3840	runtime.GC()
3841
3842	for i, xi := range x {
3843		v := ValueOf(xi).Elem()
3844		var out []int
3845		for _, kv := range v.MapKeys() {
3846			out = append(out, int(kv.Elem().Interface().(uintptr)))
3847		}
3848		sort.Ints(out)
3849		for j, k := range out {
3850			if k != i*n+j {
3851				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3852			}
3853		}
3854	}
3855}
3856
3857func TestMapOfGCValues(t *testing.T) {
3858	type T *uintptr
3859	tt := TypeOf(T(nil))
3860	mt := MapOf(TypeOf(1), tt)
3861
3862	// NOTE: The garbage collector handles allocated maps specially,
3863	// so we have to save pointers to maps in x; the pointer code will
3864	// use the gc info in the newly constructed map type.
3865	const n = 100
3866	var x []interface{}
3867	for i := 0; i < n; i++ {
3868		v := MakeMap(mt)
3869		for j := 0; j < n; j++ {
3870			p := new(uintptr)
3871			*p = uintptr(i*n + j)
3872			v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
3873		}
3874		pv := New(mt)
3875		pv.Elem().Set(v)
3876		x = append(x, pv.Interface())
3877	}
3878	runtime.GC()
3879
3880	for i, xi := range x {
3881		v := ValueOf(xi).Elem()
3882		for j := 0; j < n; j++ {
3883			k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
3884			if k != uintptr(i*n+j) {
3885				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3886			}
3887		}
3888	}
3889}
3890
3891func TestTypelinksSorted(t *testing.T) {
3892	var last string
3893	for i, n := range TypeLinks() {
3894		if n < last {
3895			t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
3896		}
3897		last = n
3898	}
3899}
3900
3901func TestFuncOf(t *testing.T) {
3902	// check construction and use of type not in binary
3903	type K string
3904	type V float64
3905
3906	fn := func(args []Value) []Value {
3907		if len(args) != 1 {
3908			t.Errorf("args == %v, want exactly one arg", args)
3909		} else if args[0].Type() != TypeOf(K("")) {
3910			t.Errorf("args[0] is type %v, want %v", args[0].Type, TypeOf(K("")))
3911		} else if args[0].String() != "gopher" {
3912			t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
3913		}
3914		return []Value{ValueOf(V(3.14))}
3915	}
3916	v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
3917
3918	outs := v.Call([]Value{ValueOf(K("gopher"))})
3919	if len(outs) != 1 {
3920		t.Fatalf("v.Call returned %v, want exactly one result", outs)
3921	} else if outs[0].Type() != TypeOf(V(0)) {
3922		t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type, TypeOf(V(0)))
3923	}
3924	f := outs[0].Float()
3925	if f != 3.14 {
3926		t.Errorf("constructed func returned %f, want %f", f, 3.14)
3927	}
3928
3929	// check that types already in binary are found
3930	type T1 int
3931	testCases := []struct {
3932		in, out  []Type
3933		variadic bool
3934		want     interface{}
3935	}{
3936		{in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
3937		{in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
3938		{in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
3939		{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
3940		{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
3941	}
3942	for _, tt := range testCases {
3943		checkSameType(t, Zero(FuncOf(tt.in, tt.out, tt.variadic)).Interface(), tt.want)
3944	}
3945
3946	// check that variadic requires last element be a slice.
3947	FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
3948	shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
3949	shouldPanic(func() { FuncOf(nil, nil, true) })
3950}
3951
3952type B1 struct {
3953	X int
3954	Y int
3955	Z int
3956}
3957
3958func BenchmarkFieldByName1(b *testing.B) {
3959	t := TypeOf(B1{})
3960	for i := 0; i < b.N; i++ {
3961		t.FieldByName("Z")
3962	}
3963}
3964
3965func BenchmarkFieldByName2(b *testing.B) {
3966	t := TypeOf(S3{})
3967	for i := 0; i < b.N; i++ {
3968		t.FieldByName("B")
3969	}
3970}
3971
3972type R0 struct {
3973	*R1
3974	*R2
3975	*R3
3976	*R4
3977}
3978
3979type R1 struct {
3980	*R5
3981	*R6
3982	*R7
3983	*R8
3984}
3985
3986type R2 R1
3987type R3 R1
3988type R4 R1
3989
3990type R5 struct {
3991	*R9
3992	*R10
3993	*R11
3994	*R12
3995}
3996
3997type R6 R5
3998type R7 R5
3999type R8 R5
4000
4001type R9 struct {
4002	*R13
4003	*R14
4004	*R15
4005	*R16
4006}
4007
4008type R10 R9
4009type R11 R9
4010type R12 R9
4011
4012type R13 struct {
4013	*R17
4014	*R18
4015	*R19
4016	*R20
4017}
4018
4019type R14 R13
4020type R15 R13
4021type R16 R13
4022
4023type R17 struct {
4024	*R21
4025	*R22
4026	*R23
4027	*R24
4028}
4029
4030type R18 R17
4031type R19 R17
4032type R20 R17
4033
4034type R21 struct {
4035	X int
4036}
4037
4038type R22 R21
4039type R23 R21
4040type R24 R21
4041
4042func TestEmbed(t *testing.T) {
4043	typ := TypeOf(R0{})
4044	f, ok := typ.FieldByName("X")
4045	if ok {
4046		t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
4047	}
4048}
4049
4050func BenchmarkFieldByName3(b *testing.B) {
4051	t := TypeOf(R0{})
4052	for i := 0; i < b.N; i++ {
4053		t.FieldByName("X")
4054	}
4055}
4056
4057type S struct {
4058	i1 int64
4059	i2 int64
4060}
4061
4062func BenchmarkInterfaceBig(b *testing.B) {
4063	v := ValueOf(S{})
4064	for i := 0; i < b.N; i++ {
4065		v.Interface()
4066	}
4067	b.StopTimer()
4068}
4069
4070func TestAllocsInterfaceBig(t *testing.T) {
4071	if testing.Short() {
4072		t.Skip("skipping malloc count in short mode")
4073	}
4074	v := ValueOf(S{})
4075	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
4076		t.Error("allocs:", allocs)
4077	}
4078}
4079
4080func BenchmarkInterfaceSmall(b *testing.B) {
4081	v := ValueOf(int64(0))
4082	for i := 0; i < b.N; i++ {
4083		v.Interface()
4084	}
4085}
4086
4087func TestAllocsInterfaceSmall(t *testing.T) {
4088	if testing.Short() {
4089		t.Skip("skipping malloc count in short mode")
4090	}
4091	v := ValueOf(int64(0))
4092	if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
4093		t.Error("allocs:", allocs)
4094	}
4095}
4096
4097// An exhaustive is a mechanism for writing exhaustive or stochastic tests.
4098// The basic usage is:
4099//
4100//	for x.Next() {
4101//		... code using x.Maybe() or x.Choice(n) to create test cases ...
4102//	}
4103//
4104// Each iteration of the loop returns a different set of results, until all
4105// possible result sets have been explored. It is okay for different code paths
4106// to make different method call sequences on x, but there must be no
4107// other source of non-determinism in the call sequences.
4108//
4109// When faced with a new decision, x chooses randomly. Future explorations
4110// of that path will choose successive values for the result. Thus, stopping
4111// the loop after a fixed number of iterations gives somewhat stochastic
4112// testing.
4113//
4114// Example:
4115//
4116//	for x.Next() {
4117//		v := make([]bool, x.Choose(4))
4118//		for i := range v {
4119//			v[i] = x.Maybe()
4120//		}
4121//		fmt.Println(v)
4122//	}
4123//
4124// prints (in some order):
4125//
4126//	[]
4127//	[false]
4128//	[true]
4129//	[false false]
4130//	[false true]
4131//	...
4132//	[true true]
4133//	[false false false]
4134//	...
4135//	[true true true]
4136//	[false false false false]
4137//	...
4138//	[true true true true]
4139//
4140type exhaustive struct {
4141	r    *rand.Rand
4142	pos  int
4143	last []choice
4144}
4145
4146type choice struct {
4147	off int
4148	n   int
4149	max int
4150}
4151
4152func (x *exhaustive) Next() bool {
4153	if x.r == nil {
4154		x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
4155	}
4156	x.pos = 0
4157	if x.last == nil {
4158		x.last = []choice{}
4159		return true
4160	}
4161	for i := len(x.last) - 1; i >= 0; i-- {
4162		c := &x.last[i]
4163		if c.n+1 < c.max {
4164			c.n++
4165			x.last = x.last[:i+1]
4166			return true
4167		}
4168	}
4169	return false
4170}
4171
4172func (x *exhaustive) Choose(max int) int {
4173	if x.pos >= len(x.last) {
4174		x.last = append(x.last, choice{x.r.Intn(max), 0, max})
4175	}
4176	c := &x.last[x.pos]
4177	x.pos++
4178	if c.max != max {
4179		panic("inconsistent use of exhaustive tester")
4180	}
4181	return (c.n + c.off) % max
4182}
4183
4184func (x *exhaustive) Maybe() bool {
4185	return x.Choose(2) == 1
4186}
4187
4188func GCFunc(args []Value) []Value {
4189	runtime.GC()
4190	return []Value{}
4191}
4192
4193func TestReflectFuncTraceback(t *testing.T) {
4194	f := MakeFunc(TypeOf(func() {}), GCFunc)
4195	f.Call([]Value{})
4196}
4197
4198func TestReflectMethodTraceback(t *testing.T) {
4199	p := Point{3, 4}
4200	m := ValueOf(p).MethodByName("GCMethod")
4201	i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
4202	if i != 8 {
4203		t.Errorf("Call returned %d; want 8", i)
4204	}
4205}
4206
4207func TestBigZero(t *testing.T) {
4208	const size = 1 << 10
4209	var v [size]byte
4210	z := Zero(ValueOf(v).Type()).Interface().([size]byte)
4211	for i := 0; i < size; i++ {
4212		if z[i] != 0 {
4213			t.Fatalf("Zero object not all zero, index %d", i)
4214		}
4215	}
4216}
4217
4218func TestFieldByIndexNil(t *testing.T) {
4219	type P struct {
4220		F int
4221	}
4222	type T struct {
4223		*P
4224	}
4225	v := ValueOf(T{})
4226
4227	v.FieldByName("P") // should be fine
4228
4229	defer func() {
4230		if err := recover(); err == nil {
4231			t.Fatalf("no error")
4232		} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
4233			t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
4234		}
4235	}()
4236	v.FieldByName("F") // should panic
4237
4238	t.Fatalf("did not panic")
4239}
4240
4241// Given
4242//	type Outer struct {
4243//		*Inner
4244//		...
4245//	}
4246// the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
4247// The implementation is logically:
4248//	func (p *Outer) M() {
4249//		(p.Inner).M()
4250//	}
4251// but since the only change here is the replacement of one pointer receiver with another,
4252// the actual generated code overwrites the original receiver with the p.Inner pointer and
4253// then jumps to the M method expecting the *Inner receiver.
4254//
4255// During reflect.Value.Call, we create an argument frame and the associated data structures
4256// to describe it to the garbage collector, populate the frame, call reflect.call to
4257// run a function call using that frame, and then copy the results back out of the frame.
4258// The reflect.call function does a memmove of the frame structure onto the
4259// stack (to set up the inputs), runs the call, and the memmoves the stack back to
4260// the frame structure (to preserve the outputs).
4261//
4262// Originally reflect.call did not distinguish inputs from outputs: both memmoves
4263// were for the full stack frame. However, in the case where the called function was
4264// one of these wrappers, the rewritten receiver is almost certainly a different type
4265// than the original receiver. This is not a problem on the stack, where we use the
4266// program counter to determine the type information and understand that
4267// during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
4268// memory word is now an *Inner. But in the statically typed argument frame created
4269// by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
4270// off the stack into the frame will store an *Inner there, and then if a garbage collection
4271// happens to scan that argument frame before it is discarded, it will scan the *Inner
4272// memory as if it were an *Outer. If the two have different memory layouts, the
4273// collection will intepret the memory incorrectly.
4274//
4275// One such possible incorrect interpretation is to treat two arbitrary memory words
4276// (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
4277// an interface requires dereferencing the itab word, the misinterpretation will try to
4278// deference Inner.P1, causing a crash during garbage collection.
4279//
4280// This came up in a real program in issue 7725.
4281
4282type Outer struct {
4283	*Inner
4284	R io.Reader
4285}
4286
4287type Inner struct {
4288	X  *Outer
4289	P1 uintptr
4290	P2 uintptr
4291}
4292
4293func (pi *Inner) M() {
4294	// Clear references to pi so that the only way the
4295	// garbage collection will find the pointer is in the
4296	// argument frame, typed as a *Outer.
4297	pi.X.Inner = nil
4298
4299	// Set up an interface value that will cause a crash.
4300	// P1 = 1 is a non-zero, so the interface looks non-nil.
4301	// P2 = pi ensures that the data word points into the
4302	// allocated heap; if not the collection skips the interface
4303	// value as irrelevant, without dereferencing P1.
4304	pi.P1 = 1
4305	pi.P2 = uintptr(unsafe.Pointer(pi))
4306}
4307
4308func TestCallMethodJump(t *testing.T) {
4309	// In reflect.Value.Call, trigger a garbage collection after reflect.call
4310	// returns but before the args frame has been discarded.
4311	// This is a little clumsy but makes the failure repeatable.
4312	*CallGC = true
4313
4314	p := &Outer{Inner: new(Inner)}
4315	p.Inner.X = p
4316	ValueOf(p).Method(0).Call(nil)
4317
4318	// Stop garbage collecting during reflect.call.
4319	*CallGC = false
4320}
4321
4322func TestMakeFuncStackCopy(t *testing.T) {
4323	target := func(in []Value) []Value {
4324		runtime.GC()
4325		useStack(16)
4326		return []Value{ValueOf(9)}
4327	}
4328
4329	var concrete func(*int, int) int
4330	fn := MakeFunc(ValueOf(concrete).Type(), target)
4331	ValueOf(&concrete).Elem().Set(fn)
4332	x := concrete(nil, 7)
4333	if x != 9 {
4334		t.Errorf("have %#q want 9", x)
4335	}
4336}
4337
4338// use about n KB of stack
4339func useStack(n int) {
4340	if n == 0 {
4341		return
4342	}
4343	var b [1024]byte // makes frame about 1KB
4344	useStack(n - 1 + int(b[99]))
4345}
4346
4347type Impl struct{}
4348
4349func (Impl) f() {}
4350
4351func TestValueString(t *testing.T) {
4352	rv := ValueOf(Impl{})
4353	if rv.String() != "<reflect_test.Impl Value>" {
4354		t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
4355	}
4356
4357	method := rv.Method(0)
4358	if method.String() != "<func() Value>" {
4359		t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
4360	}
4361}
4362
4363func TestInvalid(t *testing.T) {
4364	// Used to have inconsistency between IsValid() and Kind() != Invalid.
4365	type T struct{ v interface{} }
4366
4367	v := ValueOf(T{}).Field(0)
4368	if v.IsValid() != true || v.Kind() != Interface {
4369		t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
4370	}
4371	v = v.Elem()
4372	if v.IsValid() != false || v.Kind() != Invalid {
4373		t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
4374	}
4375}
4376
4377// Issue 8917.
4378func TestLargeGCProg(t *testing.T) {
4379	fv := ValueOf(func([256]*byte) {})
4380	fv.Call([]Value{ValueOf([256]*byte{})})
4381}
4382
4383// Issue 9179.
4384func TestCallGC(t *testing.T) {
4385	f := func(a, b, c, d, e string) {
4386	}
4387	g := func(in []Value) []Value {
4388		runtime.GC()
4389		return nil
4390	}
4391	typ := ValueOf(f).Type()
4392	f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
4393	f2("four", "five5", "six666", "seven77", "eight888")
4394}
4395
4396type funcLayoutTest struct {
4397	rcvr, t                  Type
4398	size, argsize, retOffset uintptr
4399	stack                    []byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized)
4400	gc                       []byte
4401}
4402
4403var funcLayoutTests []funcLayoutTest
4404
4405func init() {
4406	var argAlign uintptr = PtrSize
4407	if runtime.GOARCH == "amd64p32" {
4408		argAlign = 2 * PtrSize
4409	}
4410	roundup := func(x uintptr, a uintptr) uintptr {
4411		return (x + a - 1) / a * a
4412	}
4413
4414	funcLayoutTests = append(funcLayoutTests,
4415		funcLayoutTest{
4416			nil,
4417			ValueOf(func(a, b string) string { return "" }).Type(),
4418			6 * PtrSize,
4419			4 * PtrSize,
4420			4 * PtrSize,
4421			[]byte{1, 0, 1},
4422			[]byte{1, 0, 1, 0, 1},
4423		})
4424
4425	var r []byte
4426	if PtrSize == 4 {
4427		r = []byte{0, 0, 0, 1}
4428	} else {
4429		r = []byte{0, 0, 1}
4430	}
4431	funcLayoutTests = append(funcLayoutTests,
4432		funcLayoutTest{
4433			nil,
4434			ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
4435			roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
4436			roundup(3*4, PtrSize) + PtrSize + 2,
4437			roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
4438			r,
4439			r,
4440		})
4441
4442	funcLayoutTests = append(funcLayoutTests,
4443		funcLayoutTest{
4444			nil,
4445			ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
4446			4 * PtrSize,
4447			4 * PtrSize,
4448			4 * PtrSize,
4449			[]byte{1, 0, 1, 1},
4450			[]byte{1, 0, 1, 1},
4451		})
4452
4453	type S struct {
4454		a, b uintptr
4455		c, d *byte
4456	}
4457	funcLayoutTests = append(funcLayoutTests,
4458		funcLayoutTest{
4459			nil,
4460			ValueOf(func(a S) {}).Type(),
4461			4 * PtrSize,
4462			4 * PtrSize,
4463			4 * PtrSize,
4464			[]byte{0, 0, 1, 1},
4465			[]byte{0, 0, 1, 1},
4466		})
4467
4468	funcLayoutTests = append(funcLayoutTests,
4469		funcLayoutTest{
4470			ValueOf((*byte)(nil)).Type(),
4471			ValueOf(func(a uintptr, b *int) {}).Type(),
4472			roundup(3*PtrSize, argAlign),
4473			3 * PtrSize,
4474			roundup(3*PtrSize, argAlign),
4475			[]byte{1, 0, 1},
4476			[]byte{1, 0, 1},
4477		})
4478
4479	funcLayoutTests = append(funcLayoutTests,
4480		funcLayoutTest{
4481			nil,
4482			ValueOf(func(a uintptr) {}).Type(),
4483			roundup(PtrSize, argAlign),
4484			PtrSize,
4485			roundup(PtrSize, argAlign),
4486			[]byte{},
4487			[]byte{},
4488		})
4489
4490	funcLayoutTests = append(funcLayoutTests,
4491		funcLayoutTest{
4492			nil,
4493			ValueOf(func() uintptr { return 0 }).Type(),
4494			PtrSize,
4495			0,
4496			0,
4497			[]byte{},
4498			[]byte{},
4499		})
4500
4501	funcLayoutTests = append(funcLayoutTests,
4502		funcLayoutTest{
4503			ValueOf(uintptr(0)).Type(),
4504			ValueOf(func(a uintptr) {}).Type(),
4505			2 * PtrSize,
4506			2 * PtrSize,
4507			2 * PtrSize,
4508			[]byte{1},
4509			[]byte{1},
4510			// Note: this one is tricky, as the receiver is not a pointer.  But we
4511			// pass the receiver by reference to the autogenerated pointer-receiver
4512			// version of the function.
4513		})
4514}
4515
4516func TestFuncLayout(t *testing.T) {
4517	t.Skip("gccgo does not use funcLayout")
4518	for _, lt := range funcLayoutTests {
4519		typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr)
4520		if typ.Size() != lt.size {
4521			t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size)
4522		}
4523		if argsize != lt.argsize {
4524			t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize)
4525		}
4526		if retOffset != lt.retOffset {
4527			t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset)
4528		}
4529		if !bytes.Equal(stack, lt.stack) {
4530			t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack)
4531		}
4532		if !bytes.Equal(gc, lt.gc) {
4533			t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc)
4534		}
4535		if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
4536			t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs)
4537		}
4538	}
4539}
4540
4541func verifyGCBits(t *testing.T, typ Type, bits []byte) {
4542	heapBits := GCBits(New(typ).Interface())
4543	if !bytes.Equal(heapBits, bits) {
4544		t.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ, heapBits, bits)
4545	}
4546}
4547
4548func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
4549	// Creating a slice causes the runtime to repeat a bitmap,
4550	// which exercises a different path from making the compiler
4551	// repeat a bitmap for a small array or executing a repeat in
4552	// a GC program.
4553	val := MakeSlice(typ, 0, cap)
4554	data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
4555	heapBits := GCBits(data.Interface())
4556	// Repeat the bitmap for the slice size, trimming scalars in
4557	// the last element.
4558	bits = rep(cap, bits)
4559	for len(bits) > 2 && bits[len(bits)-1] == 0 {
4560		bits = bits[:len(bits)-1]
4561	}
4562	if !bytes.Equal(heapBits, bits) {
4563		t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
4564	}
4565}
4566
4567func TestGCBits(t *testing.T) {
4568	t.Skip("gccgo does not use gcbits yet")
4569
4570	verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
4571
4572	// Building blocks for types seen by the compiler (like [2]Xscalar).
4573	// The compiler will create the type structures for the derived types,
4574	// including their GC metadata.
4575	type Xscalar struct{ x uintptr }
4576	type Xptr struct{ x *byte }
4577	type Xptrscalar struct {
4578		*byte
4579		uintptr
4580	}
4581	type Xscalarptr struct {
4582		uintptr
4583		*byte
4584	}
4585	type Xbigptrscalar struct {
4586		_ [100]*byte
4587		_ [100]uintptr
4588	}
4589
4590	var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
4591	{
4592		// Building blocks for types constructed by reflect.
4593		// This code is in a separate block so that code below
4594		// cannot accidentally refer to these.
4595		// The compiler must NOT see types derived from these
4596		// (for example, [2]Scalar must NOT appear in the program),
4597		// or else reflect will use it instead of having to construct one.
4598		// The goal is to test the construction.
4599		type Scalar struct{ x uintptr }
4600		type Ptr struct{ x *byte }
4601		type Ptrscalar struct {
4602			*byte
4603			uintptr
4604		}
4605		type Scalarptr struct {
4606			uintptr
4607			*byte
4608		}
4609		type Bigptrscalar struct {
4610			_ [100]*byte
4611			_ [100]uintptr
4612		}
4613		type Int64 int64
4614		Tscalar = TypeOf(Scalar{})
4615		Tint64 = TypeOf(Int64(0))
4616		Tptr = TypeOf(Ptr{})
4617		Tscalarptr = TypeOf(Scalarptr{})
4618		Tptrscalar = TypeOf(Ptrscalar{})
4619		Tbigptrscalar = TypeOf(Bigptrscalar{})
4620	}
4621
4622	empty := []byte{}
4623
4624	verifyGCBits(t, TypeOf(Xscalar{}), empty)
4625	verifyGCBits(t, Tscalar, empty)
4626	verifyGCBits(t, TypeOf(Xptr{}), lit(1))
4627	verifyGCBits(t, Tptr, lit(1))
4628	verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
4629	verifyGCBits(t, Tscalarptr, lit(0, 1))
4630	verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
4631	verifyGCBits(t, Tptrscalar, lit(1))
4632
4633	verifyGCBits(t, TypeOf([0]Xptr{}), empty)
4634	verifyGCBits(t, ArrayOf(0, Tptr), empty)
4635	verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
4636	verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
4637	verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
4638	verifyGCBits(t, ArrayOf(2, Tscalar), empty)
4639	verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
4640	verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
4641	verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
4642	verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
4643	verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
4644	verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
4645	verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
4646	verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
4647	verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
4648	verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
4649	verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
4650	verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
4651	verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
4652	verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
4653	verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
4654	verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
4655	verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
4656	verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
4657	verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
4658	verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
4659
4660	verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
4661	verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
4662	verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
4663	verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
4664	verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
4665	verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
4666	verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
4667	verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
4668	verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
4669	verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
4670	verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
4671	verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
4672	verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
4673	verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
4674	verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
4675	verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
4676	verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
4677	verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
4678	verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
4679	verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
4680	verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
4681	verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
4682	verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
4683	verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
4684	verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
4685	verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
4686
4687	verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
4688	verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
4689
4690	verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
4691	verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
4692
4693	verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
4694	verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
4695
4696	verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
4697	verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
4698
4699	verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
4700	verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
4701
4702	hdr := make([]byte, 8/PtrSize)
4703
4704	verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
4705		verifyGCBits(t, MapBucketOf(k, e), want)
4706		verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
4707	}
4708	verifyMapBucket(t,
4709		Tscalar, Tptr,
4710		map[Xscalar]Xptr(nil),
4711		join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
4712	verifyMapBucket(t,
4713		Tscalarptr, Tptr,
4714		map[Xscalarptr]Xptr(nil),
4715		join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
4716	verifyMapBucket(t, Tint64, Tptr,
4717		map[int64]Xptr(nil),
4718		join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), naclpad(), lit(1)))
4719	verifyMapBucket(t,
4720		Tscalar, Tscalar,
4721		map[Xscalar]Xscalar(nil),
4722		empty)
4723	verifyMapBucket(t,
4724		ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
4725		map[[2]Xscalarptr][3]Xptrscalar(nil),
4726		join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
4727	verifyMapBucket(t,
4728		ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
4729		map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
4730		join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
4731	verifyMapBucket(t,
4732		ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
4733		map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
4734		join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
4735	verifyMapBucket(t,
4736		ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
4737		map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
4738		join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
4739	verifyMapBucket(t,
4740		ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
4741		map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
4742		join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
4743}
4744
4745func naclpad() []byte {
4746	if runtime.GOARCH == "amd64p32" {
4747		return lit(0)
4748	}
4749	return nil
4750}
4751
4752func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
4753func join(b ...[]byte) []byte    { return bytes.Join(b, nil) }
4754func lit(x ...byte) []byte       { return x }
4755
4756func TestTypeOfTypeOf(t *testing.T) {
4757	// Check that all the type constructors return concrete *rtype implementations.
4758	// It's difficult to test directly because the reflect package is only at arm's length.
4759	// The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
4760	check := func(name string, typ Type) {
4761		if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
4762			t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
4763		}
4764	}
4765
4766	type T struct{ int }
4767	check("TypeOf", TypeOf(T{}))
4768
4769	check("ArrayOf", ArrayOf(10, TypeOf(T{})))
4770	check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
4771	check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
4772	check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
4773	check("PtrTo", PtrTo(TypeOf(T{})))
4774	check("SliceOf", SliceOf(TypeOf(T{})))
4775}
4776
4777type XM struct{}
4778
4779func (*XM) String() string { return "" }
4780
4781func TestPtrToMethods(t *testing.T) {
4782	var y struct{ XM }
4783	yp := New(TypeOf(y)).Interface()
4784	_, ok := yp.(fmt.Stringer)
4785	if !ok {
4786		t.Fatal("does not implement Stringer, but should")
4787	}
4788}
4789