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	"sync"
19	"testing"
20	"time"
21	"unsafe"
22)
23
24func TestBool(t *testing.T) {
25	v := ValueOf(true)
26	if v.Bool() != true {
27		t.Fatal("ValueOf(true).Bool() = false")
28	}
29}
30
31type integer int
32type T struct {
33	a int
34	b float64
35	c string
36	d *int
37}
38
39type pair struct {
40	i interface{}
41	s string
42}
43
44func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
45
46func assert(t *testing.T, s, want string) {
47	if s != want {
48		t.Errorf("have %#q want %#q", s, want)
49	}
50}
51
52func typestring(i interface{}) string { return TypeOf(i).String() }
53
54var typeTests = []pair{
55	{struct{ x int }{}, "int"},
56	{struct{ x int8 }{}, "int8"},
57	{struct{ x int16 }{}, "int16"},
58	{struct{ x int32 }{}, "int32"},
59	{struct{ x int64 }{}, "int64"},
60	{struct{ x uint }{}, "uint"},
61	{struct{ x uint8 }{}, "uint8"},
62	{struct{ x uint16 }{}, "uint16"},
63	{struct{ x uint32 }{}, "uint32"},
64	{struct{ x uint64 }{}, "uint64"},
65	{struct{ x float32 }{}, "float32"},
66	{struct{ x float64 }{}, "float64"},
67	{struct{ x int8 }{}, "int8"},
68	{struct{ x (**int8) }{}, "**int8"},
69	{struct{ x (**integer) }{}, "**reflect_test.integer"},
70	{struct{ x ([32]int32) }{}, "[32]int32"},
71	{struct{ x ([]int8) }{}, "[]int8"},
72	{struct{ x (map[string]int32) }{}, "map[string]int32"},
73	{struct{ x (chan<- string) }{}, "chan<- string"},
74	{struct {
75		x struct {
76			c chan *int32
77			d float32
78		}
79	}{},
80		"struct { c chan *int32; d float32 }",
81	},
82	{struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
83	{struct {
84		x struct {
85			c func(chan *integer, *int8)
86		}
87	}{},
88		"struct { c func(chan *reflect_test.integer, *int8) }",
89	},
90	{struct {
91		x struct {
92			a int8
93			b int32
94		}
95	}{},
96		"struct { a int8; b int32 }",
97	},
98	{struct {
99		x struct {
100			a int8
101			b int8
102			c int32
103		}
104	}{},
105		"struct { a int8; b int8; c int32 }",
106	},
107	{struct {
108		x struct {
109			a int8
110			b int8
111			c int8
112			d int32
113		}
114	}{},
115		"struct { a int8; b int8; c int8; d int32 }",
116	},
117	{struct {
118		x struct {
119			a int8
120			b int8
121			c int8
122			d int8
123			e int32
124		}
125	}{},
126		"struct { a int8; b int8; c int8; d int8; e int32 }",
127	},
128	{struct {
129		x struct {
130			a int8
131			b int8
132			c int8
133			d int8
134			e int8
135			f int32
136		}
137	}{},
138		"struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
139	},
140	{struct {
141		x struct {
142			a int8 `reflect:"hi there"`
143		}
144	}{},
145		`struct { a int8 "reflect:\"hi there\"" }`,
146	},
147	{struct {
148		x struct {
149			a int8 `reflect:"hi \x00there\t\n\"\\"`
150		}
151	}{},
152		`struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
153	},
154	{struct {
155		x struct {
156			f func(args ...int)
157		}
158	}{},
159		"struct { f func(...int) }",
160	},
161	{struct {
162		x (interface {
163			a(func(func(int) int) func(func(int)) int)
164			b()
165		})
166	}{},
167		"interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
168	},
169}
170
171var valueTests = []pair{
172	{new(int8), "8"},
173	{new(int16), "16"},
174	{new(int32), "32"},
175	{new(int64), "64"},
176	{new(uint8), "8"},
177	{new(uint16), "16"},
178	{new(uint32), "32"},
179	{new(uint64), "64"},
180	{new(float32), "256.25"},
181	{new(float64), "512.125"},
182	{new(string), "stringy cheese"},
183	{new(bool), "true"},
184	{new(*int8), "*int8(0)"},
185	{new(**int8), "**int8(0)"},
186	{new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
187	{new(**integer), "**reflect_test.integer(0)"},
188	{new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
189	{new(chan<- string), "chan<- string"},
190	{new(func(a int8, b int32)), "func(int8, int32)(0)"},
191	{new(struct {
192		c chan *int32
193		d float32
194	}),
195		"struct { c chan *int32; d float32 }{chan *int32, 0}",
196	},
197	{new(struct{ c func(chan *integer, *int8) }),
198		"struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
199	},
200	{new(struct {
201		a int8
202		b int32
203	}),
204		"struct { a int8; b int32 }{0, 0}",
205	},
206	{new(struct {
207		a int8
208		b int8
209		c int32
210	}),
211		"struct { a int8; b int8; c int32 }{0, 0, 0}",
212	},
213}
214
215func testType(t *testing.T, i int, typ Type, want string) {
216	s := typ.String()
217	if s != want {
218		t.Errorf("#%d: have %#q, want %#q", i, s, want)
219	}
220}
221
222func TestTypes(t *testing.T) {
223	for i, tt := range typeTests {
224		testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
225	}
226}
227
228func TestSet(t *testing.T) {
229	for i, tt := range valueTests {
230		v := ValueOf(tt.i)
231		v = v.Elem()
232		switch v.Kind() {
233		case Int:
234			v.SetInt(132)
235		case Int8:
236			v.SetInt(8)
237		case Int16:
238			v.SetInt(16)
239		case Int32:
240			v.SetInt(32)
241		case Int64:
242			v.SetInt(64)
243		case Uint:
244			v.SetUint(132)
245		case Uint8:
246			v.SetUint(8)
247		case Uint16:
248			v.SetUint(16)
249		case Uint32:
250			v.SetUint(32)
251		case Uint64:
252			v.SetUint(64)
253		case Float32:
254			v.SetFloat(256.25)
255		case Float64:
256			v.SetFloat(512.125)
257		case Complex64:
258			v.SetComplex(532.125 + 10i)
259		case Complex128:
260			v.SetComplex(564.25 + 1i)
261		case String:
262			v.SetString("stringy cheese")
263		case Bool:
264			v.SetBool(true)
265		}
266		s := valueToString(v)
267		if s != tt.s {
268			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
269		}
270	}
271}
272
273func TestSetValue(t *testing.T) {
274	for i, tt := range valueTests {
275		v := ValueOf(tt.i).Elem()
276		switch v.Kind() {
277		case Int:
278			v.Set(ValueOf(int(132)))
279		case Int8:
280			v.Set(ValueOf(int8(8)))
281		case Int16:
282			v.Set(ValueOf(int16(16)))
283		case Int32:
284			v.Set(ValueOf(int32(32)))
285		case Int64:
286			v.Set(ValueOf(int64(64)))
287		case Uint:
288			v.Set(ValueOf(uint(132)))
289		case Uint8:
290			v.Set(ValueOf(uint8(8)))
291		case Uint16:
292			v.Set(ValueOf(uint16(16)))
293		case Uint32:
294			v.Set(ValueOf(uint32(32)))
295		case Uint64:
296			v.Set(ValueOf(uint64(64)))
297		case Float32:
298			v.Set(ValueOf(float32(256.25)))
299		case Float64:
300			v.Set(ValueOf(512.125))
301		case Complex64:
302			v.Set(ValueOf(complex64(532.125 + 10i)))
303		case Complex128:
304			v.Set(ValueOf(complex128(564.25 + 1i)))
305		case String:
306			v.Set(ValueOf("stringy cheese"))
307		case Bool:
308			v.Set(ValueOf(true))
309		}
310		s := valueToString(v)
311		if s != tt.s {
312			t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
313		}
314	}
315}
316
317var _i = 7
318
319var valueToStringTests = []pair{
320	{123, "123"},
321	{123.5, "123.5"},
322	{byte(123), "123"},
323	{"abc", "abc"},
324	{T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
325	{new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
326	{[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
327	{&[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})"},
328	{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
329	{&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
330}
331
332func TestValueToString(t *testing.T) {
333	for i, test := range valueToStringTests {
334		s := valueToString(ValueOf(test.i))
335		if s != test.s {
336			t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
337		}
338	}
339}
340
341func TestArrayElemSet(t *testing.T) {
342	v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
343	v.Index(4).SetInt(123)
344	s := valueToString(v)
345	const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
346	if s != want {
347		t.Errorf("[10]int: have %#q want %#q", s, want)
348	}
349
350	v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
351	v.Index(4).SetInt(123)
352	s = valueToString(v)
353	const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
354	if s != want1 {
355		t.Errorf("[]int: have %#q want %#q", s, want1)
356	}
357}
358
359func TestPtrPointTo(t *testing.T) {
360	var ip *int32
361	var i int32 = 1234
362	vip := ValueOf(&ip)
363	vi := ValueOf(&i).Elem()
364	vip.Elem().Set(vi.Addr())
365	if *ip != 1234 {
366		t.Errorf("got %d, want 1234", *ip)
367	}
368
369	ip = nil
370	vp := ValueOf(&ip).Elem()
371	vp.Set(Zero(vp.Type()))
372	if ip != nil {
373		t.Errorf("got non-nil (%p), want nil", ip)
374	}
375}
376
377func TestPtrSetNil(t *testing.T) {
378	var i int32 = 1234
379	ip := &i
380	vip := ValueOf(&ip)
381	vip.Elem().Set(Zero(vip.Elem().Type()))
382	if ip != nil {
383		t.Errorf("got non-nil (%d), want nil", *ip)
384	}
385}
386
387func TestMapSetNil(t *testing.T) {
388	m := make(map[string]int)
389	vm := ValueOf(&m)
390	vm.Elem().Set(Zero(vm.Elem().Type()))
391	if m != nil {
392		t.Errorf("got non-nil (%p), want nil", m)
393	}
394}
395
396func TestAll(t *testing.T) {
397	testType(t, 1, TypeOf((int8)(0)), "int8")
398	testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
399
400	typ := TypeOf((*struct {
401		c chan *int32
402		d float32
403	})(nil))
404	testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
405	etyp := typ.Elem()
406	testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
407	styp := etyp
408	f := styp.Field(0)
409	testType(t, 5, f.Type, "chan *int32")
410
411	f, present := styp.FieldByName("d")
412	if !present {
413		t.Errorf("FieldByName says present field is absent")
414	}
415	testType(t, 6, f.Type, "float32")
416
417	f, present = styp.FieldByName("absent")
418	if present {
419		t.Errorf("FieldByName says absent field is present")
420	}
421
422	typ = TypeOf([32]int32{})
423	testType(t, 7, typ, "[32]int32")
424	testType(t, 8, typ.Elem(), "int32")
425
426	typ = TypeOf((map[string]*int32)(nil))
427	testType(t, 9, typ, "map[string]*int32")
428	mtyp := typ
429	testType(t, 10, mtyp.Key(), "string")
430	testType(t, 11, mtyp.Elem(), "*int32")
431
432	typ = TypeOf((chan<- string)(nil))
433	testType(t, 12, typ, "chan<- string")
434	testType(t, 13, typ.Elem(), "string")
435
436	// make sure tag strings are not part of element type
437	typ = TypeOf(struct {
438		d []uint32 `reflect:"TAG"`
439	}{}).Field(0).Type
440	testType(t, 14, typ, "[]uint32")
441}
442
443func TestInterfaceGet(t *testing.T) {
444	var inter struct {
445		E interface{}
446	}
447	inter.E = 123.456
448	v1 := ValueOf(&inter)
449	v2 := v1.Elem().Field(0)
450	assert(t, v2.Type().String(), "interface {}")
451	i2 := v2.Interface()
452	v3 := ValueOf(i2)
453	assert(t, v3.Type().String(), "float64")
454}
455
456func TestInterfaceValue(t *testing.T) {
457	var inter struct {
458		E interface{}
459	}
460	inter.E = 123.456
461	v1 := ValueOf(&inter)
462	v2 := v1.Elem().Field(0)
463	assert(t, v2.Type().String(), "interface {}")
464	v3 := v2.Elem()
465	assert(t, v3.Type().String(), "float64")
466
467	i3 := v2.Interface()
468	if _, ok := i3.(float64); !ok {
469		t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
470	}
471}
472
473func TestFunctionValue(t *testing.T) {
474	var x interface{} = func() {}
475	v := ValueOf(x)
476	if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
477		t.Fatalf("TestFunction returned wrong pointer")
478	}
479	assert(t, v.Type().String(), "func()")
480}
481
482var appendTests = []struct {
483	orig, extra []int
484}{
485	{make([]int, 2, 4), []int{22}},
486	{make([]int, 2, 4), []int{22, 33, 44}},
487}
488
489func sameInts(x, y []int) bool {
490	if len(x) != len(y) {
491		return false
492	}
493	for i, xx := range x {
494		if xx != y[i] {
495			return false
496		}
497	}
498	return true
499}
500
501func TestAppend(t *testing.T) {
502	for i, test := range appendTests {
503		origLen, extraLen := len(test.orig), len(test.extra)
504		want := append(test.orig, test.extra...)
505		// Convert extra from []int to []Value.
506		e0 := make([]Value, len(test.extra))
507		for j, e := range test.extra {
508			e0[j] = ValueOf(e)
509		}
510		// Convert extra from []int to *SliceValue.
511		e1 := ValueOf(test.extra)
512		// Test Append.
513		a0 := ValueOf(test.orig)
514		have0 := Append(a0, e0...).Interface().([]int)
515		if !sameInts(have0, want) {
516			t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
517		}
518		// Check that the orig and extra slices were not modified.
519		if len(test.orig) != origLen {
520			t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
521		}
522		if len(test.extra) != extraLen {
523			t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
524		}
525		// Test AppendSlice.
526		a1 := ValueOf(test.orig)
527		have1 := AppendSlice(a1, e1).Interface().([]int)
528		if !sameInts(have1, want) {
529			t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
530		}
531		// Check that the orig and extra slices were not modified.
532		if len(test.orig) != origLen {
533			t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
534		}
535		if len(test.extra) != extraLen {
536			t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
537		}
538	}
539}
540
541func TestCopy(t *testing.T) {
542	a := []int{1, 2, 3, 4, 10, 9, 8, 7}
543	b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
544	c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
545	for i := 0; i < len(b); i++ {
546		if b[i] != c[i] {
547			t.Fatalf("b != c before test")
548		}
549	}
550	a1 := a
551	b1 := b
552	aa := ValueOf(&a1).Elem()
553	ab := ValueOf(&b1).Elem()
554	for tocopy := 1; tocopy <= 7; tocopy++ {
555		aa.SetLen(tocopy)
556		Copy(ab, aa)
557		aa.SetLen(8)
558		for i := 0; i < tocopy; i++ {
559			if a[i] != b[i] {
560				t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
561					tocopy, i, a[i], i, b[i])
562			}
563		}
564		for i := tocopy; i < len(b); i++ {
565			if b[i] != c[i] {
566				if i < len(a) {
567					t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
568						tocopy, i, a[i], i, b[i], i, c[i])
569				} else {
570					t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
571						tocopy, i, b[i], i, c[i])
572				}
573			} else {
574				t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
575			}
576		}
577	}
578}
579
580func TestCopyArray(t *testing.T) {
581	a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
582	b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
583	c := b
584	aa := ValueOf(&a).Elem()
585	ab := ValueOf(&b).Elem()
586	Copy(ab, aa)
587	for i := 0; i < len(a); i++ {
588		if a[i] != b[i] {
589			t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
590		}
591	}
592	for i := len(a); i < len(b); i++ {
593		if b[i] != c[i] {
594			t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
595		} else {
596			t.Logf("elem %d is okay\n", i)
597		}
598	}
599}
600
601func TestBigUnnamedStruct(t *testing.T) {
602	b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
603	v := ValueOf(b)
604	b1 := v.Interface().(struct {
605		a, b, c, d int64
606	})
607	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
608		t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
609	}
610}
611
612type big struct {
613	a, b, c, d, e int64
614}
615
616func TestBigStruct(t *testing.T) {
617	b := big{1, 2, 3, 4, 5}
618	v := ValueOf(b)
619	b1 := v.Interface().(big)
620	if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
621		t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
622	}
623}
624
625type Basic struct {
626	x int
627	y float32
628}
629
630type NotBasic Basic
631
632type DeepEqualTest struct {
633	a, b interface{}
634	eq   bool
635}
636
637// Simple functions for DeepEqual tests.
638var (
639	fn1 func()             // nil.
640	fn2 func()             // nil.
641	fn3 = func() { fn1() } // Not nil.
642)
643
644var deepEqualTests = []DeepEqualTest{
645	// Equalities
646	{nil, nil, true},
647	{1, 1, true},
648	{int32(1), int32(1), true},
649	{0.5, 0.5, true},
650	{float32(0.5), float32(0.5), true},
651	{"hello", "hello", true},
652	{make([]int, 10), make([]int, 10), true},
653	{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
654	{Basic{1, 0.5}, Basic{1, 0.5}, true},
655	{error(nil), error(nil), true},
656	{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
657	{fn1, fn2, true},
658
659	// Inequalities
660	{1, 2, false},
661	{int32(1), int32(2), false},
662	{0.5, 0.6, false},
663	{float32(0.5), float32(0.6), false},
664	{"hello", "hey", false},
665	{make([]int, 10), make([]int, 11), false},
666	{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
667	{Basic{1, 0.5}, Basic{1, 0.6}, false},
668	{Basic{1, 0}, Basic{2, 0}, false},
669	{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
670	{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
671	{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
672	{map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
673	{nil, 1, false},
674	{1, nil, false},
675	{fn1, fn3, false},
676	{fn3, fn3, false},
677
678	// Nil vs empty: not the same.
679	{[]int{}, []int(nil), false},
680	{[]int{}, []int{}, true},
681	{[]int(nil), []int(nil), true},
682	{map[int]int{}, map[int]int(nil), false},
683	{map[int]int{}, map[int]int{}, true},
684	{map[int]int(nil), map[int]int(nil), true},
685
686	// Mismatched types
687	{1, 1.0, false},
688	{int32(1), int64(1), false},
689	{0.5, "hello", false},
690	{[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
691	{&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
692	{Basic{1, 0.5}, NotBasic{1, 0.5}, false},
693	{map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
694}
695
696func TestDeepEqual(t *testing.T) {
697	for _, test := range deepEqualTests {
698		if r := DeepEqual(test.a, test.b); r != test.eq {
699			t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
700		}
701	}
702}
703
704func TestTypeOf(t *testing.T) {
705	// Special case for nil
706	if typ := TypeOf(nil); typ != nil {
707		t.Errorf("expected nil type for nil value; got %v", typ)
708	}
709	for _, test := range deepEqualTests {
710		v := ValueOf(test.a)
711		if !v.IsValid() {
712			continue
713		}
714		typ := TypeOf(test.a)
715		if typ != v.Type() {
716			t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
717		}
718	}
719}
720
721type Recursive struct {
722	x int
723	r *Recursive
724}
725
726func TestDeepEqualRecursiveStruct(t *testing.T) {
727	a, b := new(Recursive), new(Recursive)
728	*a = Recursive{12, a}
729	*b = Recursive{12, b}
730	if !DeepEqual(a, b) {
731		t.Error("DeepEqual(recursive same) = false, want true")
732	}
733}
734
735type _Complex struct {
736	a int
737	b [3]*_Complex
738	c *string
739	d map[float64]float64
740}
741
742func TestDeepEqualComplexStruct(t *testing.T) {
743	m := make(map[float64]float64)
744	stra, strb := "hello", "hello"
745	a, b := new(_Complex), new(_Complex)
746	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
747	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
748	if !DeepEqual(a, b) {
749		t.Error("DeepEqual(complex same) = false, want true")
750	}
751}
752
753func TestDeepEqualComplexStructInequality(t *testing.T) {
754	m := make(map[float64]float64)
755	stra, strb := "hello", "helloo" // Difference is here
756	a, b := new(_Complex), new(_Complex)
757	*a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
758	*b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
759	if DeepEqual(a, b) {
760		t.Error("DeepEqual(complex different) = true, want false")
761	}
762}
763
764type UnexpT struct {
765	m map[int]int
766}
767
768func TestDeepEqualUnexportedMap(t *testing.T) {
769	// Check that DeepEqual can look at unexported fields.
770	x1 := UnexpT{map[int]int{1: 2}}
771	x2 := UnexpT{map[int]int{1: 2}}
772	if !DeepEqual(&x1, &x2) {
773		t.Error("DeepEqual(x1, x2) = false, want true")
774	}
775
776	y1 := UnexpT{map[int]int{2: 3}}
777	if DeepEqual(&x1, &y1) {
778		t.Error("DeepEqual(x1, y1) = true, want false")
779	}
780}
781
782func check2ndField(x interface{}, offs uintptr, t *testing.T) {
783	s := ValueOf(x)
784	f := s.Type().Field(1)
785	if f.Offset != offs {
786		t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
787	}
788}
789
790// Check that structure alignment & offsets viewed through reflect agree with those
791// from the compiler itself.
792func TestAlignment(t *testing.T) {
793	type T1inner struct {
794		a int
795	}
796	type T1 struct {
797		T1inner
798		f int
799	}
800	type T2inner struct {
801		a, b int
802	}
803	type T2 struct {
804		T2inner
805		f int
806	}
807
808	x := T1{T1inner{2}, 17}
809	check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
810
811	x1 := T2{T2inner{2, 3}, 17}
812	check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
813}
814
815func Nil(a interface{}, t *testing.T) {
816	n := ValueOf(a).Field(0)
817	if !n.IsNil() {
818		t.Errorf("%v should be nil", a)
819	}
820}
821
822func NotNil(a interface{}, t *testing.T) {
823	n := ValueOf(a).Field(0)
824	if n.IsNil() {
825		t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
826	}
827}
828
829func TestIsNil(t *testing.T) {
830	// These implement IsNil.
831	// Wrap in extra struct to hide interface type.
832	doNil := []interface{}{
833		struct{ x *int }{},
834		struct{ x interface{} }{},
835		struct{ x map[string]int }{},
836		struct{ x func() bool }{},
837		struct{ x chan int }{},
838		struct{ x []string }{},
839	}
840	for _, ts := range doNil {
841		ty := TypeOf(ts).Field(0).Type
842		v := Zero(ty)
843		v.IsNil() // panics if not okay to call
844	}
845
846	// Check the implementations
847	var pi struct {
848		x *int
849	}
850	Nil(pi, t)
851	pi.x = new(int)
852	NotNil(pi, t)
853
854	var si struct {
855		x []int
856	}
857	Nil(si, t)
858	si.x = make([]int, 10)
859	NotNil(si, t)
860
861	var ci struct {
862		x chan int
863	}
864	Nil(ci, t)
865	ci.x = make(chan int)
866	NotNil(ci, t)
867
868	var mi struct {
869		x map[int]int
870	}
871	Nil(mi, t)
872	mi.x = make(map[int]int)
873	NotNil(mi, t)
874
875	var ii struct {
876		x interface{}
877	}
878	Nil(ii, t)
879	ii.x = 2
880	NotNil(ii, t)
881
882	var fi struct {
883		x func(t *testing.T)
884	}
885	Nil(fi, t)
886	fi.x = TestIsNil
887	NotNil(fi, t)
888}
889
890func TestInterfaceExtraction(t *testing.T) {
891	var s struct {
892		W io.Writer
893	}
894
895	s.W = os.Stdout
896	v := Indirect(ValueOf(&s)).Field(0).Interface()
897	if v != s.W.(interface{}) {
898		t.Error("Interface() on interface: ", v, s.W)
899	}
900}
901
902func TestNilPtrValueSub(t *testing.T) {
903	var pi *int
904	if pv := ValueOf(pi); pv.Elem().IsValid() {
905		t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
906	}
907}
908
909func TestMap(t *testing.T) {
910	m := map[string]int{"a": 1, "b": 2}
911	mv := ValueOf(m)
912	if n := mv.Len(); n != len(m) {
913		t.Errorf("Len = %d, want %d", n, len(m))
914	}
915	keys := mv.MapKeys()
916	newmap := MakeMap(mv.Type())
917	for k, v := range m {
918		// Check that returned Keys match keys in range.
919		// These aren't required to be in the same order.
920		seen := false
921		for _, kv := range keys {
922			if kv.String() == k {
923				seen = true
924				break
925			}
926		}
927		if !seen {
928			t.Errorf("Missing key %q", k)
929		}
930
931		// Check that value lookup is correct.
932		vv := mv.MapIndex(ValueOf(k))
933		if vi := vv.Int(); vi != int64(v) {
934			t.Errorf("Key %q: have value %d, want %d", k, vi, v)
935		}
936
937		// Copy into new map.
938		newmap.SetMapIndex(ValueOf(k), ValueOf(v))
939	}
940	vv := mv.MapIndex(ValueOf("not-present"))
941	if vv.IsValid() {
942		t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
943	}
944
945	newm := newmap.Interface().(map[string]int)
946	if len(newm) != len(m) {
947		t.Errorf("length after copy: newm=%d, m=%d", newm, m)
948	}
949
950	for k, v := range newm {
951		mv, ok := m[k]
952		if mv != v {
953			t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
954		}
955	}
956
957	newmap.SetMapIndex(ValueOf("a"), Value{})
958	v, ok := newm["a"]
959	if ok {
960		t.Errorf("newm[\"a\"] = %d after delete", v)
961	}
962
963	mv = ValueOf(&m).Elem()
964	mv.Set(Zero(mv.Type()))
965	if m != nil {
966		t.Errorf("mv.Set(nil) failed")
967	}
968}
969
970func TestChan(t *testing.T) {
971	for loop := 0; loop < 2; loop++ {
972		var c chan int
973		var cv Value
974
975		// check both ways to allocate channels
976		switch loop {
977		case 1:
978			c = make(chan int, 1)
979			cv = ValueOf(c)
980		case 0:
981			cv = MakeChan(TypeOf(c), 1)
982			c = cv.Interface().(chan int)
983		}
984
985		// Send
986		cv.Send(ValueOf(2))
987		if i := <-c; i != 2 {
988			t.Errorf("reflect Send 2, native recv %d", i)
989		}
990
991		// Recv
992		c <- 3
993		if i, ok := cv.Recv(); i.Int() != 3 || !ok {
994			t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
995		}
996
997		// TryRecv fail
998		val, ok := cv.TryRecv()
999		if val.IsValid() || ok {
1000			t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1001		}
1002
1003		// TryRecv success
1004		c <- 4
1005		val, ok = cv.TryRecv()
1006		if !val.IsValid() {
1007			t.Errorf("TryRecv on ready chan got nil")
1008		} else if i := val.Int(); i != 4 || !ok {
1009			t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1010		}
1011
1012		// TrySend fail
1013		c <- 100
1014		ok = cv.TrySend(ValueOf(5))
1015		i := <-c
1016		if ok {
1017			t.Errorf("TrySend on full chan succeeded: value %d", i)
1018		}
1019
1020		// TrySend success
1021		ok = cv.TrySend(ValueOf(6))
1022		if !ok {
1023			t.Errorf("TrySend on empty chan failed")
1024		} else {
1025			if i = <-c; i != 6 {
1026				t.Errorf("TrySend 6, recv %d", i)
1027			}
1028		}
1029
1030		// Close
1031		c <- 123
1032		cv.Close()
1033		if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1034			t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1035		}
1036		if i, ok := cv.Recv(); i.Int() != 0 || ok {
1037			t.Errorf("after close Recv %d, %t", i.Int(), ok)
1038		}
1039	}
1040
1041	// check creation of unbuffered channel
1042	var c chan int
1043	cv := MakeChan(TypeOf(c), 0)
1044	c = cv.Interface().(chan int)
1045	if cv.TrySend(ValueOf(7)) {
1046		t.Errorf("TrySend on sync chan succeeded")
1047	}
1048	if v, ok := cv.TryRecv(); v.IsValid() || ok {
1049		t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1050	}
1051
1052	// len/cap
1053	cv = MakeChan(TypeOf(c), 10)
1054	c = cv.Interface().(chan int)
1055	for i := 0; i < 3; i++ {
1056		c <- i
1057	}
1058	if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1059		t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1060	}
1061}
1062
1063// caseInfo describes a single case in a select test.
1064type caseInfo struct {
1065	desc      string
1066	canSelect bool
1067	recv      Value
1068	closed    bool
1069	helper    func()
1070	panic     bool
1071}
1072
1073var allselect = flag.Bool("allselect", false, "exhaustive select test")
1074
1075func TestSelect(t *testing.T) {
1076	selectWatch.once.Do(func() { go selectWatcher() })
1077
1078	var x exhaustive
1079	nch := 0
1080	newop := func(n int, cap int) (ch, val Value) {
1081		nch++
1082		if nch%101%2 == 1 {
1083			c := make(chan int, cap)
1084			ch = ValueOf(c)
1085			val = ValueOf(n)
1086		} else {
1087			c := make(chan string, cap)
1088			ch = ValueOf(c)
1089			val = ValueOf(fmt.Sprint(n))
1090		}
1091		return
1092	}
1093
1094	for n := 0; x.Next(); n++ {
1095		if testing.Short() && n >= 1000 {
1096			break
1097		}
1098		if n >= 100000 && !*allselect {
1099			break
1100		}
1101		if n%100000 == 0 && testing.Verbose() {
1102			println("TestSelect", n)
1103		}
1104		var cases []SelectCase
1105		var info []caseInfo
1106
1107		// Ready send.
1108		if x.Maybe() {
1109			ch, val := newop(len(cases), 1)
1110			cases = append(cases, SelectCase{
1111				Dir:  SelectSend,
1112				Chan: ch,
1113				Send: val,
1114			})
1115			info = append(info, caseInfo{desc: "ready send", canSelect: true})
1116		}
1117
1118		// Ready recv.
1119		if x.Maybe() {
1120			ch, val := newop(len(cases), 1)
1121			ch.Send(val)
1122			cases = append(cases, SelectCase{
1123				Dir:  SelectRecv,
1124				Chan: ch,
1125			})
1126			info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1127		}
1128
1129		// Blocking send.
1130		if x.Maybe() {
1131			ch, val := newop(len(cases), 0)
1132			cases = append(cases, SelectCase{
1133				Dir:  SelectSend,
1134				Chan: ch,
1135				Send: val,
1136			})
1137			// Let it execute?
1138			if x.Maybe() {
1139				f := func() { ch.Recv() }
1140				info = append(info, caseInfo{desc: "blocking send", helper: f})
1141			} else {
1142				info = append(info, caseInfo{desc: "blocking send"})
1143			}
1144		}
1145
1146		// Blocking recv.
1147		if x.Maybe() {
1148			ch, val := newop(len(cases), 0)
1149			cases = append(cases, SelectCase{
1150				Dir:  SelectRecv,
1151				Chan: ch,
1152			})
1153			// Let it execute?
1154			if x.Maybe() {
1155				f := func() { ch.Send(val) }
1156				info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1157			} else {
1158				info = append(info, caseInfo{desc: "blocking recv"})
1159			}
1160		}
1161
1162		// Zero Chan send.
1163		if x.Maybe() {
1164			// Maybe include value to send.
1165			var val Value
1166			if x.Maybe() {
1167				val = ValueOf(100)
1168			}
1169			cases = append(cases, SelectCase{
1170				Dir:  SelectSend,
1171				Send: val,
1172			})
1173			info = append(info, caseInfo{desc: "zero Chan send"})
1174		}
1175
1176		// Zero Chan receive.
1177		if x.Maybe() {
1178			cases = append(cases, SelectCase{
1179				Dir: SelectRecv,
1180			})
1181			info = append(info, caseInfo{desc: "zero Chan recv"})
1182		}
1183
1184		// nil Chan send.
1185		if x.Maybe() {
1186			cases = append(cases, SelectCase{
1187				Dir:  SelectSend,
1188				Chan: ValueOf((chan int)(nil)),
1189				Send: ValueOf(101),
1190			})
1191			info = append(info, caseInfo{desc: "nil Chan send"})
1192		}
1193
1194		// nil Chan recv.
1195		if x.Maybe() {
1196			cases = append(cases, SelectCase{
1197				Dir:  SelectRecv,
1198				Chan: ValueOf((chan int)(nil)),
1199			})
1200			info = append(info, caseInfo{desc: "nil Chan recv"})
1201		}
1202
1203		// closed Chan send.
1204		if x.Maybe() {
1205			ch := make(chan int)
1206			close(ch)
1207			cases = append(cases, SelectCase{
1208				Dir:  SelectSend,
1209				Chan: ValueOf(ch),
1210				Send: ValueOf(101),
1211			})
1212			info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1213		}
1214
1215		// closed Chan recv.
1216		if x.Maybe() {
1217			ch, val := newop(len(cases), 0)
1218			ch.Close()
1219			val = Zero(val.Type())
1220			cases = append(cases, SelectCase{
1221				Dir:  SelectRecv,
1222				Chan: ch,
1223			})
1224			info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1225		}
1226
1227		var helper func() // goroutine to help the select complete
1228
1229		// Add default? Must be last case here, but will permute.
1230		// Add the default if the select would otherwise
1231		// block forever, and maybe add it anyway.
1232		numCanSelect := 0
1233		canProceed := false
1234		canBlock := true
1235		canPanic := false
1236		helpers := []int{}
1237		for i, c := range info {
1238			if c.canSelect {
1239				canProceed = true
1240				canBlock = false
1241				numCanSelect++
1242				if c.panic {
1243					canPanic = true
1244				}
1245			} else if c.helper != nil {
1246				canProceed = true
1247				helpers = append(helpers, i)
1248			}
1249		}
1250		if !canProceed || x.Maybe() {
1251			cases = append(cases, SelectCase{
1252				Dir: SelectDefault,
1253			})
1254			info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1255			numCanSelect++
1256		} else if canBlock {
1257			// Select needs to communicate with another goroutine.
1258			cas := &info[helpers[x.Choose(len(helpers))]]
1259			helper = cas.helper
1260			cas.canSelect = true
1261			numCanSelect++
1262		}
1263
1264		// Permute cases and case info.
1265		// Doing too much here makes the exhaustive loop
1266		// too exhausting, so just do two swaps.
1267		for loop := 0; loop < 2; loop++ {
1268			i := x.Choose(len(cases))
1269			j := x.Choose(len(cases))
1270			cases[i], cases[j] = cases[j], cases[i]
1271			info[i], info[j] = info[j], info[i]
1272		}
1273
1274		if helper != nil {
1275			// We wait before kicking off a goroutine to satisfy a blocked select.
1276			// The pause needs to be big enough to let the select block before
1277			// we run the helper, but if we lose that race once in a while it's okay: the
1278			// select will just proceed immediately. Not a big deal.
1279			// For short tests we can grow [sic] the timeout a bit without fear of taking too long
1280			pause := 10 * time.Microsecond
1281			if testing.Short() {
1282				pause = 100 * time.Microsecond
1283			}
1284			time.AfterFunc(pause, helper)
1285		}
1286
1287		// Run select.
1288		i, recv, recvOK, panicErr := runSelect(cases, info)
1289		if panicErr != nil && !canPanic {
1290			t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1291		}
1292		if panicErr == nil && canPanic && numCanSelect == 1 {
1293			t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1294		}
1295		if panicErr != nil {
1296			continue
1297		}
1298
1299		cas := info[i]
1300		if !cas.canSelect {
1301			recvStr := ""
1302			if recv.IsValid() {
1303				recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1304			}
1305			t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1306			continue
1307		}
1308		if cas.panic {
1309			t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1310			continue
1311		}
1312
1313		if cases[i].Dir == SelectRecv {
1314			if !recv.IsValid() {
1315				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1316			}
1317			if !cas.recv.IsValid() {
1318				t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1319			}
1320			if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1321				if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1322					t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1323				}
1324				t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1325			}
1326		} else {
1327			if recv.IsValid() || recvOK {
1328				t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1329			}
1330		}
1331	}
1332}
1333
1334// selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1335// If the selectWatcher notices that the select has been blocked for >1 second, it prints
1336// an error describing the select and panics the entire test binary.
1337var selectWatch struct {
1338	sync.Mutex
1339	once sync.Once
1340	now  time.Time
1341	info []caseInfo
1342}
1343
1344func selectWatcher() {
1345	for {
1346		time.Sleep(1 * time.Second)
1347		selectWatch.Lock()
1348		if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
1349			fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1350			panic("select stuck")
1351		}
1352		selectWatch.Unlock()
1353	}
1354}
1355
1356// runSelect runs a single select test.
1357// It returns the values returned by Select but also returns
1358// a panic value if the Select panics.
1359func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1360	defer func() {
1361		panicErr = recover()
1362
1363		selectWatch.Lock()
1364		selectWatch.info = nil
1365		selectWatch.Unlock()
1366	}()
1367
1368	selectWatch.Lock()
1369	selectWatch.now = time.Now()
1370	selectWatch.info = info
1371	selectWatch.Unlock()
1372
1373	chosen, recv, recvOK = Select(cases)
1374	return
1375}
1376
1377// fmtSelect formats the information about a single select test.
1378func fmtSelect(info []caseInfo) string {
1379	var buf bytes.Buffer
1380	fmt.Fprintf(&buf, "\nselect {\n")
1381	for i, cas := range info {
1382		fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1383		if cas.recv.IsValid() {
1384			fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1385		}
1386		if cas.canSelect {
1387			fmt.Fprintf(&buf, " canselect")
1388		}
1389		if cas.panic {
1390			fmt.Fprintf(&buf, " panic")
1391		}
1392		fmt.Fprintf(&buf, "\n")
1393	}
1394	fmt.Fprintf(&buf, "}")
1395	return buf.String()
1396}
1397
1398type two [2]uintptr
1399
1400// Difficult test for function call because of
1401// implicit padding between arguments.
1402func 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) {
1403	return b, c, d, e, f, g, h
1404}
1405
1406func TestFunc(t *testing.T) {
1407	ret := ValueOf(dummy).Call([]Value{
1408		ValueOf(byte(10)),
1409		ValueOf(20),
1410		ValueOf(byte(30)),
1411		ValueOf(two{40, 50}),
1412		ValueOf(byte(60)),
1413		ValueOf(float32(70)),
1414		ValueOf(byte(80)),
1415	})
1416	if len(ret) != 7 {
1417		t.Fatalf("Call returned %d values, want 7", len(ret))
1418	}
1419
1420	i := byte(ret[0].Uint())
1421	j := int(ret[1].Int())
1422	k := byte(ret[2].Uint())
1423	l := ret[3].Interface().(two)
1424	m := byte(ret[4].Uint())
1425	n := float32(ret[5].Float())
1426	o := byte(ret[6].Uint())
1427
1428	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1429		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)
1430	}
1431}
1432
1433type emptyStruct struct{}
1434
1435type nonEmptyStruct struct {
1436	member int
1437}
1438
1439func returnEmpty() emptyStruct {
1440	return emptyStruct{}
1441}
1442
1443func takesEmpty(e emptyStruct) {
1444}
1445
1446func returnNonEmpty(i int) nonEmptyStruct {
1447	return nonEmptyStruct{member: i}
1448}
1449
1450func takesNonEmpty(n nonEmptyStruct) int {
1451	return n.member
1452}
1453
1454func TestCallWithStruct(t *testing.T) {
1455	r := ValueOf(returnEmpty).Call([]Value{})
1456	if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1457		t.Errorf("returning empty struct returned %s instead", r)
1458	}
1459	r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1460	if len(r) != 0 {
1461		t.Errorf("takesEmpty returned values: %s", r)
1462	}
1463	r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1464	if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1465		t.Errorf("returnNonEmpty returned %s", r)
1466	}
1467	r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1468	if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1469		t.Errorf("takesNonEmpty returned %s", r)
1470	}
1471}
1472
1473func TestMakeFunc(t *testing.T) {
1474	switch runtime.GOARCH {
1475	case "amd64", "386":
1476	default:
1477		t.Skip("MakeFunc not implemented for " + runtime.GOARCH)
1478	}
1479
1480	f := dummy
1481	fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1482	ValueOf(&f).Elem().Set(fv)
1483
1484	// Call g with small arguments so that there is
1485	// something predictable (and different from the
1486	// correct results) in those positions on the stack.
1487	g := dummy
1488	g(1, 2, 3, two{4, 5}, 6, 7, 8)
1489
1490	// Call constructed function f.
1491	i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1492	if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1493		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)
1494	}
1495}
1496
1497func TestMakeFuncInterface(t *testing.T) {
1498	switch runtime.GOARCH {
1499	case "amd64", "386":
1500	default:
1501		t.Skip("MakeFunc not implemented for " + runtime.GOARCH)
1502	}
1503
1504	fn := func(i int) int { return i }
1505	incr := func(in []Value) []Value {
1506		return []Value{ValueOf(int(in[0].Int() + 1))}
1507	}
1508	fv := MakeFunc(TypeOf(fn), incr)
1509	ValueOf(&fn).Elem().Set(fv)
1510	if r := fn(2); r != 3 {
1511		t.Errorf("Call returned %d, want 3", r)
1512	}
1513	if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1514		t.Errorf("Call returned %d, want 15", r)
1515	}
1516	if r := fv.Interface().(func(int) int)(26); r != 27 {
1517		t.Errorf("Call returned %d, want 27", r)
1518	}
1519}
1520
1521type Point struct {
1522	x, y int
1523}
1524
1525// This will be index 0.
1526func (p Point) AnotherMethod(scale int) int {
1527	return -1
1528}
1529
1530// This will be index 1.
1531func (p Point) Dist(scale int) int {
1532	//println("Point.Dist", p.x, p.y, scale)
1533	return p.x*p.x*scale + p.y*p.y*scale
1534}
1535
1536func TestMethod(t *testing.T) {
1537	// Non-curried method of type.
1538	p := Point{3, 4}
1539	i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1540	if i != 250 {
1541		t.Errorf("Type Method returned %d; want 250", i)
1542	}
1543
1544	m, ok := TypeOf(p).MethodByName("Dist")
1545	if !ok {
1546		t.Fatalf("method by name failed")
1547	}
1548	i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1549	if i != 275 {
1550		t.Errorf("Type MethodByName returned %d; want 275", i)
1551	}
1552
1553	i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1554	if i != 300 {
1555		t.Errorf("Pointer Type Method returned %d; want 300", i)
1556	}
1557
1558	m, ok = TypeOf(&p).MethodByName("Dist")
1559	if !ok {
1560		t.Fatalf("ptr method by name failed")
1561	}
1562	i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1563	if i != 325 {
1564		t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
1565	}
1566
1567	// Curried method of value.
1568	tfunc := TypeOf((func(int) int)(nil))
1569	v := ValueOf(p).Method(1)
1570	if tt := v.Type(); tt != tfunc {
1571		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1572	}
1573	i = v.Call([]Value{ValueOf(14)})[0].Int()
1574	if i != 350 {
1575		t.Errorf("Value Method returned %d; want 350", i)
1576	}
1577	v = ValueOf(p).MethodByName("Dist")
1578	if tt := v.Type(); tt != tfunc {
1579		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1580	}
1581	i = v.Call([]Value{ValueOf(15)})[0].Int()
1582	if i != 375 {
1583		t.Errorf("Value MethodByName returned %d; want 375", i)
1584	}
1585
1586	// Curried method of pointer.
1587	v = ValueOf(&p).Method(1)
1588	if tt := v.Type(); tt != tfunc {
1589		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1590	}
1591	i = v.Call([]Value{ValueOf(16)})[0].Int()
1592	if i != 400 {
1593		t.Errorf("Pointer Value Method returned %d; want 400", i)
1594	}
1595	v = ValueOf(&p).MethodByName("Dist")
1596	if tt := v.Type(); tt != tfunc {
1597		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1598	}
1599	i = v.Call([]Value{ValueOf(17)})[0].Int()
1600	if i != 425 {
1601		t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1602	}
1603
1604	// Curried method of interface value.
1605	// Have to wrap interface value in a struct to get at it.
1606	// Passing it to ValueOf directly would
1607	// access the underlying Point, not the interface.
1608	var x interface {
1609		Dist(int) int
1610	} = p
1611	pv := ValueOf(&x).Elem()
1612	v = pv.Method(0)
1613	if tt := v.Type(); tt != tfunc {
1614		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1615	}
1616	i = v.Call([]Value{ValueOf(18)})[0].Int()
1617	if i != 450 {
1618		t.Errorf("Interface Method returned %d; want 450", i)
1619	}
1620	v = pv.MethodByName("Dist")
1621	if tt := v.Type(); tt != tfunc {
1622		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1623	}
1624	i = v.Call([]Value{ValueOf(19)})[0].Int()
1625	if i != 475 {
1626		t.Errorf("Interface MethodByName returned %d; want 475", i)
1627	}
1628}
1629
1630func TestMethodValue(t *testing.T) {
1631	switch runtime.GOARCH {
1632	case "amd64", "386":
1633	default:
1634		t.Skip("reflect method values not implemented for " + runtime.GOARCH)
1635	}
1636
1637	p := Point{3, 4}
1638	var i int64
1639
1640	// Curried method of value.
1641	tfunc := TypeOf((func(int) int)(nil))
1642	v := ValueOf(p).Method(1)
1643	if tt := v.Type(); tt != tfunc {
1644		t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1645	}
1646	i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1647	if i != 250 {
1648		t.Errorf("Value Method returned %d; want 250", i)
1649	}
1650	v = ValueOf(p).MethodByName("Dist")
1651	if tt := v.Type(); tt != tfunc {
1652		t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1653	}
1654	i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1655	if i != 275 {
1656		t.Errorf("Value MethodByName returned %d; want 275", i)
1657	}
1658
1659	// Curried method of pointer.
1660	v = ValueOf(&p).Method(1)
1661	if tt := v.Type(); tt != tfunc {
1662		t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1663	}
1664	i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1665	if i != 300 {
1666		t.Errorf("Pointer Value Method returned %d; want 300", i)
1667	}
1668	v = ValueOf(&p).MethodByName("Dist")
1669	if tt := v.Type(); tt != tfunc {
1670		t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1671	}
1672	i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1673	if i != 325 {
1674		t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
1675	}
1676
1677	// Curried method of interface value.
1678	// Have to wrap interface value in a struct to get at it.
1679	// Passing it to ValueOf directly would
1680	// access the underlying Point, not the interface.
1681	var s = struct {
1682		X interface {
1683			Dist(int) int
1684		}
1685	}{p}
1686	pv := ValueOf(s).Field(0)
1687	v = pv.Method(0)
1688	if tt := v.Type(); tt != tfunc {
1689		t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1690	}
1691	i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1692	if i != 350 {
1693		t.Errorf("Interface Method returned %d; want 350", i)
1694	}
1695	v = pv.MethodByName("Dist")
1696	if tt := v.Type(); tt != tfunc {
1697		t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1698	}
1699	i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1700	if i != 375 {
1701		t.Errorf("Interface MethodByName returned %d; want 375", i)
1702	}
1703}
1704
1705// Reflect version of $GOROOT/test/method5.go
1706
1707// Concrete types implementing M method.
1708// Smaller than a word, word-sized, larger than a word.
1709// Value and pointer receivers.
1710
1711type Tinter interface {
1712	M(int, byte) (byte, int)
1713}
1714
1715type Tsmallv byte
1716
1717func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1718
1719type Tsmallp byte
1720
1721func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1722
1723type Twordv uintptr
1724
1725func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1726
1727type Twordp uintptr
1728
1729func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1730
1731type Tbigv [2]uintptr
1732
1733func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1734
1735type Tbigp [2]uintptr
1736
1737func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1738
1739// Again, with an unexported method.
1740
1741type tsmallv byte
1742
1743func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1744
1745type tsmallp byte
1746
1747func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1748
1749type twordv uintptr
1750
1751func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1752
1753type twordp uintptr
1754
1755func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1756
1757type tbigv [2]uintptr
1758
1759func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1760
1761type tbigp [2]uintptr
1762
1763func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1764
1765type tinter interface {
1766	m(int, byte) (byte, int)
1767}
1768
1769// Embedding via pointer.
1770
1771type Tm1 struct {
1772	Tm2
1773}
1774
1775type Tm2 struct {
1776	*Tm3
1777}
1778
1779type Tm3 struct {
1780	*Tm4
1781}
1782
1783type Tm4 struct {
1784}
1785
1786func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
1787
1788func TestMethod5(t *testing.T) {
1789	switch runtime.GOARCH {
1790	case "amd64", "386":
1791	default:
1792		t.Skip("reflect method values not implemented for " + runtime.GOARCH)
1793	}
1794
1795	CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1796		b, x := f(1000, 99)
1797		if b != 99 || x != 1000+inc {
1798			t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1799		}
1800	}
1801
1802	CheckV := func(name string, i Value, inc int) {
1803		bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
1804		b := bx[0].Interface()
1805		x := bx[1].Interface()
1806		if b != byte(99) || x != 1000+inc {
1807			t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1808		}
1809
1810		CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1811	}
1812
1813	var TinterType = TypeOf(new(Tinter)).Elem()
1814	var tinterType = TypeOf(new(tinter)).Elem()
1815
1816	CheckI := func(name string, i interface{}, inc int) {
1817		v := ValueOf(i)
1818		CheckV(name, v, inc)
1819		CheckV("(i="+name+")", v.Convert(TinterType), inc)
1820	}
1821
1822	sv := Tsmallv(1)
1823	CheckI("sv", sv, 1)
1824	CheckI("&sv", &sv, 1)
1825
1826	sp := Tsmallp(2)
1827	CheckI("&sp", &sp, 2)
1828
1829	wv := Twordv(3)
1830	CheckI("wv", wv, 3)
1831	CheckI("&wv", &wv, 3)
1832
1833	wp := Twordp(4)
1834	CheckI("&wp", &wp, 4)
1835
1836	bv := Tbigv([2]uintptr{5, 6})
1837	CheckI("bv", bv, 11)
1838	CheckI("&bv", &bv, 11)
1839
1840	bp := Tbigp([2]uintptr{7, 8})
1841	CheckI("&bp", &bp, 15)
1842
1843	t4 := Tm4{}
1844	t3 := Tm3{&t4}
1845	t2 := Tm2{&t3}
1846	t1 := Tm1{t2}
1847	CheckI("t4", t4, 40)
1848	CheckI("&t4", &t4, 40)
1849	CheckI("t3", t3, 40)
1850	CheckI("&t3", &t3, 40)
1851	CheckI("t2", t2, 40)
1852	CheckI("&t2", &t2, 40)
1853	CheckI("t1", t1, 40)
1854	CheckI("&t1", &t1, 40)
1855
1856	methodShouldPanic := func(name string, i interface{}) {
1857		v := ValueOf(i)
1858		m := v.Method(0)
1859		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1860		shouldPanic(func() { m.Interface() })
1861
1862		v = v.Convert(tinterType)
1863		m = v.Method(0)
1864		shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1865		shouldPanic(func() { m.Interface() })
1866	}
1867
1868	_sv := tsmallv(1)
1869	methodShouldPanic("_sv", _sv)
1870	methodShouldPanic("&_sv", &_sv)
1871
1872	_sp := tsmallp(2)
1873	methodShouldPanic("&_sp", &_sp)
1874
1875	_wv := twordv(3)
1876	methodShouldPanic("_wv", _wv)
1877	methodShouldPanic("&_wv", &_wv)
1878
1879	_wp := twordp(4)
1880	methodShouldPanic("&_wp", &_wp)
1881
1882	_bv := tbigv([2]uintptr{5, 6})
1883	methodShouldPanic("_bv", _bv)
1884	methodShouldPanic("&_bv", &_bv)
1885
1886	_bp := tbigp([2]uintptr{7, 8})
1887	methodShouldPanic("&_bp", &_bp)
1888
1889	var tnil Tinter
1890	vnil := ValueOf(&tnil).Elem()
1891	shouldPanic(func() { vnil.Method(0) })
1892}
1893
1894func TestInterfaceSet(t *testing.T) {
1895	p := &Point{3, 4}
1896
1897	var s struct {
1898		I interface{}
1899		P interface {
1900			Dist(int) int
1901		}
1902	}
1903	sv := ValueOf(&s).Elem()
1904	sv.Field(0).Set(ValueOf(p))
1905	if q := s.I.(*Point); q != p {
1906		t.Errorf("i: have %p want %p", q, p)
1907	}
1908
1909	pv := sv.Field(1)
1910	pv.Set(ValueOf(p))
1911	if q := s.P.(*Point); q != p {
1912		t.Errorf("i: have %p want %p", q, p)
1913	}
1914
1915	i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1916	if i != 250 {
1917		t.Errorf("Interface Method returned %d; want 250", i)
1918	}
1919}
1920
1921type T1 struct {
1922	a string
1923	int
1924}
1925
1926func TestAnonymousFields(t *testing.T) {
1927	var field StructField
1928	var ok bool
1929	var t1 T1
1930	type1 := TypeOf(t1)
1931	if field, ok = type1.FieldByName("int"); !ok {
1932		t.Fatal("no field 'int'")
1933	}
1934	if field.Index[0] != 1 {
1935		t.Error("field index should be 1; is", field.Index)
1936	}
1937}
1938
1939type FTest struct {
1940	s     interface{}
1941	name  string
1942	index []int
1943	value int
1944}
1945
1946type D1 struct {
1947	d int
1948}
1949type D2 struct {
1950	d int
1951}
1952
1953type S0 struct {
1954	A, B, C int
1955	D1
1956	D2
1957}
1958
1959type S1 struct {
1960	B int
1961	S0
1962}
1963
1964type S2 struct {
1965	A int
1966	*S1
1967}
1968
1969type S1x struct {
1970	S1
1971}
1972
1973type S1y struct {
1974	S1
1975}
1976
1977type S3 struct {
1978	S1x
1979	S2
1980	D, E int
1981	*S1y
1982}
1983
1984type S4 struct {
1985	*S4
1986	A int
1987}
1988
1989// The X in S6 and S7 annihilate, but they also block the X in S8.S9.
1990type S5 struct {
1991	S6
1992	S7
1993	S8
1994}
1995
1996type S6 struct {
1997	X int
1998}
1999
2000type S7 S6
2001
2002type S8 struct {
2003	S9
2004}
2005
2006type S9 struct {
2007	X int
2008	Y int
2009}
2010
2011// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2012type S10 struct {
2013	S11
2014	S12
2015	S13
2016}
2017
2018type S11 struct {
2019	S6
2020}
2021
2022type S12 struct {
2023	S6
2024}
2025
2026type S13 struct {
2027	S8
2028}
2029
2030// The X in S15.S11.S1 and S16.S11.S1 annihilate.
2031type S14 struct {
2032	S15
2033	S16
2034}
2035
2036type S15 struct {
2037	S11
2038}
2039
2040type S16 struct {
2041	S11
2042}
2043
2044var fieldTests = []FTest{
2045	{struct{}{}, "", nil, 0},
2046	{struct{}{}, "Foo", nil, 0},
2047	{S0{A: 'a'}, "A", []int{0}, 'a'},
2048	{S0{}, "D", nil, 0},
2049	{S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2050	{S1{B: 'b'}, "B", []int{0}, 'b'},
2051	{S1{}, "S0", []int{1}, 0},
2052	{S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2053	{S2{A: 'a'}, "A", []int{0}, 'a'},
2054	{S2{}, "S1", []int{1}, 0},
2055	{S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2056	{S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2057	{S2{}, "D", nil, 0},
2058	{S3{}, "S1", nil, 0},
2059	{S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2060	{S3{}, "B", nil, 0},
2061	{S3{D: 'd'}, "D", []int{2}, 0},
2062	{S3{E: 'e'}, "E", []int{3}, 'e'},
2063	{S4{A: 'a'}, "A", []int{1}, 'a'},
2064	{S4{}, "B", nil, 0},
2065	{S5{}, "X", nil, 0},
2066	{S5{}, "Y", []int{2, 0, 1}, 0},
2067	{S10{}, "X", nil, 0},
2068	{S10{}, "Y", []int{2, 0, 0, 1}, 0},
2069	{S14{}, "X", nil, 0},
2070}
2071
2072func TestFieldByIndex(t *testing.T) {
2073	for _, test := range fieldTests {
2074		s := TypeOf(test.s)
2075		f := s.FieldByIndex(test.index)
2076		if f.Name != "" {
2077			if test.index != nil {
2078				if f.Name != test.name {
2079					t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2080				}
2081			} else {
2082				t.Errorf("%s.%s found", s.Name(), f.Name)
2083			}
2084		} else if len(test.index) > 0 {
2085			t.Errorf("%s.%s not found", s.Name(), test.name)
2086		}
2087
2088		if test.value != 0 {
2089			v := ValueOf(test.s).FieldByIndex(test.index)
2090			if v.IsValid() {
2091				if x, ok := v.Interface().(int); ok {
2092					if x != test.value {
2093						t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2094					}
2095				} else {
2096					t.Errorf("%s%v value not an int", s.Name(), test.index)
2097				}
2098			} else {
2099				t.Errorf("%s%v value not found", s.Name(), test.index)
2100			}
2101		}
2102	}
2103}
2104
2105func TestFieldByName(t *testing.T) {
2106	for _, test := range fieldTests {
2107		s := TypeOf(test.s)
2108		f, found := s.FieldByName(test.name)
2109		if found {
2110			if test.index != nil {
2111				// Verify field depth and index.
2112				if len(f.Index) != len(test.index) {
2113					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)
2114				} else {
2115					for i, x := range f.Index {
2116						if x != test.index[i] {
2117							t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2118						}
2119					}
2120				}
2121			} else {
2122				t.Errorf("%s.%s found", s.Name(), f.Name)
2123			}
2124		} else if len(test.index) > 0 {
2125			t.Errorf("%s.%s not found", s.Name(), test.name)
2126		}
2127
2128		if test.value != 0 {
2129			v := ValueOf(test.s).FieldByName(test.name)
2130			if v.IsValid() {
2131				if x, ok := v.Interface().(int); ok {
2132					if x != test.value {
2133						t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2134					}
2135				} else {
2136					t.Errorf("%s.%s value not an int", s.Name(), test.name)
2137				}
2138			} else {
2139				t.Errorf("%s.%s value not found", s.Name(), test.name)
2140			}
2141		}
2142	}
2143}
2144
2145func TestImportPath(t *testing.T) {
2146	tests := []struct {
2147		t    Type
2148		path string
2149	}{
2150		{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2151		{TypeOf(int(0)), ""},
2152		{TypeOf(int8(0)), ""},
2153		{TypeOf(int16(0)), ""},
2154		{TypeOf(int32(0)), ""},
2155		{TypeOf(int64(0)), ""},
2156		{TypeOf(uint(0)), ""},
2157		{TypeOf(uint8(0)), ""},
2158		{TypeOf(uint16(0)), ""},
2159		{TypeOf(uint32(0)), ""},
2160		{TypeOf(uint64(0)), ""},
2161		{TypeOf(uintptr(0)), ""},
2162		{TypeOf(float32(0)), ""},
2163		{TypeOf(float64(0)), ""},
2164		{TypeOf(complex64(0)), ""},
2165		{TypeOf(complex128(0)), ""},
2166		{TypeOf(byte(0)), ""},
2167		{TypeOf(rune(0)), ""},
2168		{TypeOf([]byte(nil)), ""},
2169		{TypeOf([]rune(nil)), ""},
2170		{TypeOf(string("")), ""},
2171		{TypeOf((*interface{})(nil)).Elem(), ""},
2172		{TypeOf((*byte)(nil)), ""},
2173		{TypeOf((*rune)(nil)), ""},
2174		{TypeOf((*int64)(nil)), ""},
2175		{TypeOf(map[string]int{}), ""},
2176		{TypeOf((*error)(nil)).Elem(), ""},
2177	}
2178	for _, test := range tests {
2179		if path := test.t.PkgPath(); path != test.path {
2180			t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2181		}
2182	}
2183}
2184
2185func TestVariadicType(t *testing.T) {
2186	// Test example from Type documentation.
2187	var f func(x int, y ...float64)
2188	typ := TypeOf(f)
2189	if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2190		sl := typ.In(1)
2191		if sl.Kind() == Slice {
2192			if sl.Elem() == TypeOf(0.0) {
2193				// ok
2194				return
2195			}
2196		}
2197	}
2198
2199	// Failed
2200	t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2201	s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2202	for i := 0; i < typ.NumIn(); i++ {
2203		s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2204	}
2205	t.Error(s)
2206}
2207
2208type inner struct {
2209	x int
2210}
2211
2212type outer struct {
2213	y int
2214	inner
2215}
2216
2217func (*inner) m() {}
2218func (*outer) m() {}
2219
2220func TestNestedMethods(t *testing.T) {
2221	t.Skip("fails on gccgo due to function wrappers")
2222	typ := TypeOf((*outer)(nil))
2223	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
2224		t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
2225		for i := 0; i < typ.NumMethod(); i++ {
2226			m := typ.Method(i)
2227			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2228		}
2229	}
2230}
2231
2232type InnerInt struct {
2233	X int
2234}
2235
2236type OuterInt struct {
2237	Y int
2238	InnerInt
2239}
2240
2241func (i *InnerInt) M() int {
2242	return i.X
2243}
2244
2245func TestEmbeddedMethods(t *testing.T) {
2246	/* This part of the test fails on gccgo due to function wrappers.
2247	typ := TypeOf((*OuterInt)(nil))
2248	if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2249		t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2250		for i := 0; i < typ.NumMethod(); i++ {
2251			m := typ.Method(i)
2252			t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2253		}
2254	}
2255	*/
2256
2257	i := &InnerInt{3}
2258	if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
2259		t.Errorf("i.M() = %d, want 3", v)
2260	}
2261
2262	o := &OuterInt{1, InnerInt{2}}
2263	if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
2264		t.Errorf("i.M() = %d, want 2", v)
2265	}
2266
2267	f := (*OuterInt).M
2268	if v := f(o); v != 2 {
2269		t.Errorf("f(o) = %d, want 2", v)
2270	}
2271}
2272
2273func TestPtrTo(t *testing.T) {
2274	var i int
2275
2276	typ := TypeOf(i)
2277	for i = 0; i < 100; i++ {
2278		typ = PtrTo(typ)
2279	}
2280	for i = 0; i < 100; i++ {
2281		typ = typ.Elem()
2282	}
2283	if typ != TypeOf(i) {
2284		t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
2285	}
2286}
2287
2288func TestPtrToGC(t *testing.T) {
2289	type T *uintptr
2290	tt := TypeOf(T(nil))
2291	pt := PtrTo(tt)
2292	const n = 100
2293	var x []interface{}
2294	for i := 0; i < n; i++ {
2295		v := New(pt)
2296		p := new(*uintptr)
2297		*p = new(uintptr)
2298		**p = uintptr(i)
2299		v.Elem().Set(ValueOf(p).Convert(pt))
2300		x = append(x, v.Interface())
2301	}
2302	runtime.GC()
2303
2304	for i, xi := range x {
2305		k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2306		if k != uintptr(i) {
2307			t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2308		}
2309	}
2310}
2311
2312func TestAddr(t *testing.T) {
2313	var p struct {
2314		X, Y int
2315	}
2316
2317	v := ValueOf(&p)
2318	v = v.Elem()
2319	v = v.Addr()
2320	v = v.Elem()
2321	v = v.Field(0)
2322	v.SetInt(2)
2323	if p.X != 2 {
2324		t.Errorf("Addr.Elem.Set failed to set value")
2325	}
2326
2327	// Again but take address of the ValueOf value.
2328	// Exercises generation of PtrTypes not present in the binary.
2329	q := &p
2330	v = ValueOf(&q).Elem()
2331	v = v.Addr()
2332	v = v.Elem()
2333	v = v.Elem()
2334	v = v.Addr()
2335	v = v.Elem()
2336	v = v.Field(0)
2337	v.SetInt(3)
2338	if p.X != 3 {
2339		t.Errorf("Addr.Elem.Set failed to set value")
2340	}
2341
2342	// Starting without pointer we should get changed value
2343	// in interface.
2344	qq := p
2345	v = ValueOf(&qq).Elem()
2346	v0 := v
2347	v = v.Addr()
2348	v = v.Elem()
2349	v = v.Field(0)
2350	v.SetInt(4)
2351	if p.X != 3 { // should be unchanged from last time
2352		t.Errorf("somehow value Set changed original p")
2353	}
2354	p = v0.Interface().(struct {
2355		X, Y int
2356	})
2357	if p.X != 4 {
2358		t.Errorf("Addr.Elem.Set valued to set value in top value")
2359	}
2360
2361	// Verify that taking the address of a type gives us a pointer
2362	// which we can convert back using the usual interface
2363	// notation.
2364	var s struct {
2365		B *bool
2366	}
2367	ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2368	*(ps.(**bool)) = new(bool)
2369	if s.B == nil {
2370		t.Errorf("Addr.Interface direct assignment failed")
2371	}
2372}
2373
2374/* gccgo does do allocations here.
2375
2376func noAlloc(t *testing.T, n int, f func(int)) {
2377	if runtime.GOMAXPROCS(0) > 1 {
2378		t.Skip("skipping; GOMAXPROCS>1")
2379	}
2380	i := -1
2381	allocs := testing.AllocsPerRun(n, func() {
2382		f(i)
2383		i++
2384	})
2385	if allocs > 0 {
2386		t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2387	}
2388}
2389
2390func TestAllocations(t *testing.T) {
2391	noAlloc(t, 100, func(j int) {
2392		var i interface{}
2393		var v Value
2394		i = 42 + j
2395		v = ValueOf(i)
2396		if int(v.Int()) != 42+j {
2397			panic("wrong int")
2398		}
2399	})
2400}
2401
2402*/
2403
2404func TestSmallNegativeInt(t *testing.T) {
2405	i := int16(-1)
2406	v := ValueOf(i)
2407	if v.Int() != -1 {
2408		t.Errorf("int16(-1).Int() returned %v", v.Int())
2409	}
2410}
2411
2412func TestIndex(t *testing.T) {
2413	xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2414	v := ValueOf(xs).Index(3).Interface().(byte)
2415	if v != xs[3] {
2416		t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2417	}
2418	xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2419	v = ValueOf(xa).Index(2).Interface().(byte)
2420	if v != xa[2] {
2421		t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2422	}
2423	s := "0123456789"
2424	v = ValueOf(s).Index(3).Interface().(byte)
2425	if v != s[3] {
2426		t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2427	}
2428}
2429
2430func TestSlice(t *testing.T) {
2431	xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2432	v := ValueOf(xs).Slice(3, 5).Interface().([]int)
2433	if len(v) != 2 {
2434		t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2435	}
2436	if cap(v) != 5 {
2437		t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2438	}
2439	if !DeepEqual(v[0:5], xs[3:]) {
2440		t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
2441	}
2442	xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2443	v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
2444	if len(v) != 3 {
2445		t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2446	}
2447	if cap(v) != 6 {
2448		t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2449	}
2450	if !DeepEqual(v[0:6], xa[2:]) {
2451		t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
2452	}
2453	s := "0123456789"
2454	vs := ValueOf(s).Slice(3, 5).Interface().(string)
2455	if vs != s[3:5] {
2456		t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2457	}
2458}
2459
2460func TestVariadic(t *testing.T) {
2461	var b bytes.Buffer
2462	V := ValueOf
2463
2464	b.Reset()
2465	V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
2466	if b.String() != "hello, 42 world" {
2467		t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
2468	}
2469
2470	b.Reset()
2471	V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
2472	if b.String() != "hello, 42 world" {
2473		t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
2474	}
2475}
2476
2477func TestFuncArg(t *testing.T) {
2478	f1 := func(i int, f func(int) int) int { return f(i) }
2479	f2 := func(i int) int { return i + 1 }
2480	r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
2481	if r[0].Int() != 101 {
2482		t.Errorf("function returned %d, want 101", r[0].Int())
2483	}
2484}
2485
2486var tagGetTests = []struct {
2487	Tag   StructTag
2488	Key   string
2489	Value string
2490}{
2491	{`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2492	{`protobuf:"PB(1,2)"`, `foo`, ``},
2493	{`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2494	{`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2495	{`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2496}
2497
2498func TestTagGet(t *testing.T) {
2499	for _, tt := range tagGetTests {
2500		if v := tt.Tag.Get(tt.Key); v != tt.Value {
2501			t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
2502		}
2503	}
2504}
2505
2506func TestBytes(t *testing.T) {
2507	type B []byte
2508	x := B{1, 2, 3, 4}
2509	y := ValueOf(x).Bytes()
2510	if !bytes.Equal(x, y) {
2511		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2512	}
2513	if &x[0] != &y[0] {
2514		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2515	}
2516}
2517
2518func TestSetBytes(t *testing.T) {
2519	type B []byte
2520	var x B
2521	y := []byte{1, 2, 3, 4}
2522	ValueOf(&x).Elem().SetBytes(y)
2523	if !bytes.Equal(x, y) {
2524		t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2525	}
2526	if &x[0] != &y[0] {
2527		t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2528	}
2529}
2530
2531type Private struct {
2532	x int
2533	y **int
2534}
2535
2536func (p *Private) m() {
2537}
2538
2539type Public struct {
2540	X int
2541	Y **int
2542}
2543
2544func (p *Public) M() {
2545}
2546
2547func TestUnexported(t *testing.T) {
2548	var pub Public
2549	v := ValueOf(&pub)
2550	isValid(v.Elem().Field(0))
2551	isValid(v.Elem().Field(1))
2552	isValid(v.Elem().FieldByName("X"))
2553	isValid(v.Elem().FieldByName("Y"))
2554	isValid(v.Type().Method(0).Func)
2555	isNonNil(v.Elem().Field(0).Interface())
2556	isNonNil(v.Elem().Field(1).Interface())
2557	isNonNil(v.Elem().FieldByName("X").Interface())
2558	isNonNil(v.Elem().FieldByName("Y").Interface())
2559	isNonNil(v.Type().Method(0).Func.Interface())
2560
2561	var priv Private
2562	v = ValueOf(&priv)
2563	isValid(v.Elem().Field(0))
2564	isValid(v.Elem().Field(1))
2565	isValid(v.Elem().FieldByName("x"))
2566	isValid(v.Elem().FieldByName("y"))
2567	isValid(v.Type().Method(0).Func)
2568	shouldPanic(func() { v.Elem().Field(0).Interface() })
2569	shouldPanic(func() { v.Elem().Field(1).Interface() })
2570	shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
2571	shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
2572	shouldPanic(func() { v.Type().Method(0).Func.Interface() })
2573}
2574
2575func shouldPanic(f func()) {
2576	defer func() {
2577		if recover() == nil {
2578			panic("did not panic")
2579		}
2580	}()
2581	f()
2582}
2583
2584func isNonNil(x interface{}) {
2585	if x == nil {
2586		panic("nil interface")
2587	}
2588}
2589
2590func isValid(v Value) {
2591	if !v.IsValid() {
2592		panic("zero Value")
2593	}
2594}
2595
2596func TestAlias(t *testing.T) {
2597	x := string("hello")
2598	v := ValueOf(&x).Elem()
2599	oldvalue := v.Interface()
2600	v.SetString("world")
2601	newvalue := v.Interface()
2602
2603	if oldvalue != "hello" || newvalue != "world" {
2604		t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
2605	}
2606}
2607
2608var V = ValueOf
2609
2610func EmptyInterfaceV(x interface{}) Value {
2611	return ValueOf(&x).Elem()
2612}
2613
2614func ReaderV(x io.Reader) Value {
2615	return ValueOf(&x).Elem()
2616}
2617
2618func ReadWriterV(x io.ReadWriter) Value {
2619	return ValueOf(&x).Elem()
2620}
2621
2622type Empty struct{}
2623type MyString string
2624type MyBytes []byte
2625type MyRunes []int32
2626type MyFunc func()
2627type MyByte byte
2628
2629var convertTests = []struct {
2630	in  Value
2631	out Value
2632}{
2633	// numbers
2634	/*
2635		Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2636
2637		package main
2638
2639		import "fmt"
2640
2641		var numbers = []string{
2642			"int8", "uint8", "int16", "uint16",
2643			"int32", "uint32", "int64", "uint64",
2644			"int", "uint", "uintptr",
2645			"float32", "float64",
2646		}
2647
2648		func main() {
2649			// all pairs but in an unusual order,
2650			// to emit all the int8, uint8 cases
2651			// before n grows too big.
2652			n := 1
2653			for i, f := range numbers {
2654				for _, g := range numbers[i:] {
2655					fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2656					n++
2657					if f != g {
2658						fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2659						n++
2660					}
2661				}
2662			}
2663		}
2664	*/
2665	{V(int8(1)), V(int8(1))},
2666	{V(int8(2)), V(uint8(2))},
2667	{V(uint8(3)), V(int8(3))},
2668	{V(int8(4)), V(int16(4))},
2669	{V(int16(5)), V(int8(5))},
2670	{V(int8(6)), V(uint16(6))},
2671	{V(uint16(7)), V(int8(7))},
2672	{V(int8(8)), V(int32(8))},
2673	{V(int32(9)), V(int8(9))},
2674	{V(int8(10)), V(uint32(10))},
2675	{V(uint32(11)), V(int8(11))},
2676	{V(int8(12)), V(int64(12))},
2677	{V(int64(13)), V(int8(13))},
2678	{V(int8(14)), V(uint64(14))},
2679	{V(uint64(15)), V(int8(15))},
2680	{V(int8(16)), V(int(16))},
2681	{V(int(17)), V(int8(17))},
2682	{V(int8(18)), V(uint(18))},
2683	{V(uint(19)), V(int8(19))},
2684	{V(int8(20)), V(uintptr(20))},
2685	{V(uintptr(21)), V(int8(21))},
2686	{V(int8(22)), V(float32(22))},
2687	{V(float32(23)), V(int8(23))},
2688	{V(int8(24)), V(float64(24))},
2689	{V(float64(25)), V(int8(25))},
2690	{V(uint8(26)), V(uint8(26))},
2691	{V(uint8(27)), V(int16(27))},
2692	{V(int16(28)), V(uint8(28))},
2693	{V(uint8(29)), V(uint16(29))},
2694	{V(uint16(30)), V(uint8(30))},
2695	{V(uint8(31)), V(int32(31))},
2696	{V(int32(32)), V(uint8(32))},
2697	{V(uint8(33)), V(uint32(33))},
2698	{V(uint32(34)), V(uint8(34))},
2699	{V(uint8(35)), V(int64(35))},
2700	{V(int64(36)), V(uint8(36))},
2701	{V(uint8(37)), V(uint64(37))},
2702	{V(uint64(38)), V(uint8(38))},
2703	{V(uint8(39)), V(int(39))},
2704	{V(int(40)), V(uint8(40))},
2705	{V(uint8(41)), V(uint(41))},
2706	{V(uint(42)), V(uint8(42))},
2707	{V(uint8(43)), V(uintptr(43))},
2708	{V(uintptr(44)), V(uint8(44))},
2709	{V(uint8(45)), V(float32(45))},
2710	{V(float32(46)), V(uint8(46))},
2711	{V(uint8(47)), V(float64(47))},
2712	{V(float64(48)), V(uint8(48))},
2713	{V(int16(49)), V(int16(49))},
2714	{V(int16(50)), V(uint16(50))},
2715	{V(uint16(51)), V(int16(51))},
2716	{V(int16(52)), V(int32(52))},
2717	{V(int32(53)), V(int16(53))},
2718	{V(int16(54)), V(uint32(54))},
2719	{V(uint32(55)), V(int16(55))},
2720	{V(int16(56)), V(int64(56))},
2721	{V(int64(57)), V(int16(57))},
2722	{V(int16(58)), V(uint64(58))},
2723	{V(uint64(59)), V(int16(59))},
2724	{V(int16(60)), V(int(60))},
2725	{V(int(61)), V(int16(61))},
2726	{V(int16(62)), V(uint(62))},
2727	{V(uint(63)), V(int16(63))},
2728	{V(int16(64)), V(uintptr(64))},
2729	{V(uintptr(65)), V(int16(65))},
2730	{V(int16(66)), V(float32(66))},
2731	{V(float32(67)), V(int16(67))},
2732	{V(int16(68)), V(float64(68))},
2733	{V(float64(69)), V(int16(69))},
2734	{V(uint16(70)), V(uint16(70))},
2735	{V(uint16(71)), V(int32(71))},
2736	{V(int32(72)), V(uint16(72))},
2737	{V(uint16(73)), V(uint32(73))},
2738	{V(uint32(74)), V(uint16(74))},
2739	{V(uint16(75)), V(int64(75))},
2740	{V(int64(76)), V(uint16(76))},
2741	{V(uint16(77)), V(uint64(77))},
2742	{V(uint64(78)), V(uint16(78))},
2743	{V(uint16(79)), V(int(79))},
2744	{V(int(80)), V(uint16(80))},
2745	{V(uint16(81)), V(uint(81))},
2746	{V(uint(82)), V(uint16(82))},
2747	{V(uint16(83)), V(uintptr(83))},
2748	{V(uintptr(84)), V(uint16(84))},
2749	{V(uint16(85)), V(float32(85))},
2750	{V(float32(86)), V(uint16(86))},
2751	{V(uint16(87)), V(float64(87))},
2752	{V(float64(88)), V(uint16(88))},
2753	{V(int32(89)), V(int32(89))},
2754	{V(int32(90)), V(uint32(90))},
2755	{V(uint32(91)), V(int32(91))},
2756	{V(int32(92)), V(int64(92))},
2757	{V(int64(93)), V(int32(93))},
2758	{V(int32(94)), V(uint64(94))},
2759	{V(uint64(95)), V(int32(95))},
2760	{V(int32(96)), V(int(96))},
2761	{V(int(97)), V(int32(97))},
2762	{V(int32(98)), V(uint(98))},
2763	{V(uint(99)), V(int32(99))},
2764	{V(int32(100)), V(uintptr(100))},
2765	{V(uintptr(101)), V(int32(101))},
2766	{V(int32(102)), V(float32(102))},
2767	{V(float32(103)), V(int32(103))},
2768	{V(int32(104)), V(float64(104))},
2769	{V(float64(105)), V(int32(105))},
2770	{V(uint32(106)), V(uint32(106))},
2771	{V(uint32(107)), V(int64(107))},
2772	{V(int64(108)), V(uint32(108))},
2773	{V(uint32(109)), V(uint64(109))},
2774	{V(uint64(110)), V(uint32(110))},
2775	{V(uint32(111)), V(int(111))},
2776	{V(int(112)), V(uint32(112))},
2777	{V(uint32(113)), V(uint(113))},
2778	{V(uint(114)), V(uint32(114))},
2779	{V(uint32(115)), V(uintptr(115))},
2780	{V(uintptr(116)), V(uint32(116))},
2781	{V(uint32(117)), V(float32(117))},
2782	{V(float32(118)), V(uint32(118))},
2783	{V(uint32(119)), V(float64(119))},
2784	{V(float64(120)), V(uint32(120))},
2785	{V(int64(121)), V(int64(121))},
2786	{V(int64(122)), V(uint64(122))},
2787	{V(uint64(123)), V(int64(123))},
2788	{V(int64(124)), V(int(124))},
2789	{V(int(125)), V(int64(125))},
2790	{V(int64(126)), V(uint(126))},
2791	{V(uint(127)), V(int64(127))},
2792	{V(int64(128)), V(uintptr(128))},
2793	{V(uintptr(129)), V(int64(129))},
2794	{V(int64(130)), V(float32(130))},
2795	{V(float32(131)), V(int64(131))},
2796	{V(int64(132)), V(float64(132))},
2797	{V(float64(133)), V(int64(133))},
2798	{V(uint64(134)), V(uint64(134))},
2799	{V(uint64(135)), V(int(135))},
2800	{V(int(136)), V(uint64(136))},
2801	{V(uint64(137)), V(uint(137))},
2802	{V(uint(138)), V(uint64(138))},
2803	{V(uint64(139)), V(uintptr(139))},
2804	{V(uintptr(140)), V(uint64(140))},
2805	{V(uint64(141)), V(float32(141))},
2806	{V(float32(142)), V(uint64(142))},
2807	{V(uint64(143)), V(float64(143))},
2808	{V(float64(144)), V(uint64(144))},
2809	{V(int(145)), V(int(145))},
2810	{V(int(146)), V(uint(146))},
2811	{V(uint(147)), V(int(147))},
2812	{V(int(148)), V(uintptr(148))},
2813	{V(uintptr(149)), V(int(149))},
2814	{V(int(150)), V(float32(150))},
2815	{V(float32(151)), V(int(151))},
2816	{V(int(152)), V(float64(152))},
2817	{V(float64(153)), V(int(153))},
2818	{V(uint(154)), V(uint(154))},
2819	{V(uint(155)), V(uintptr(155))},
2820	{V(uintptr(156)), V(uint(156))},
2821	{V(uint(157)), V(float32(157))},
2822	{V(float32(158)), V(uint(158))},
2823	{V(uint(159)), V(float64(159))},
2824	{V(float64(160)), V(uint(160))},
2825	{V(uintptr(161)), V(uintptr(161))},
2826	{V(uintptr(162)), V(float32(162))},
2827	{V(float32(163)), V(uintptr(163))},
2828	{V(uintptr(164)), V(float64(164))},
2829	{V(float64(165)), V(uintptr(165))},
2830	{V(float32(166)), V(float32(166))},
2831	{V(float32(167)), V(float64(167))},
2832	{V(float64(168)), V(float32(168))},
2833	{V(float64(169)), V(float64(169))},
2834
2835	// truncation
2836	{V(float64(1.5)), V(int(1))},
2837
2838	// complex
2839	{V(complex64(1i)), V(complex64(1i))},
2840	{V(complex64(2i)), V(complex128(2i))},
2841	{V(complex128(3i)), V(complex64(3i))},
2842	{V(complex128(4i)), V(complex128(4i))},
2843
2844	// string
2845	{V(string("hello")), V(string("hello"))},
2846	{V(string("bytes1")), V([]byte("bytes1"))},
2847	{V([]byte("bytes2")), V(string("bytes2"))},
2848	{V([]byte("bytes3")), V([]byte("bytes3"))},
2849	{V(string("runes♝")), V([]rune("runes♝"))},
2850	{V([]rune("runes♕")), V(string("runes♕"))},
2851	{V([]rune("runes������")), V([]rune("runes������"))},
2852	{V(int('a')), V(string("a"))},
2853	{V(int8('a')), V(string("a"))},
2854	{V(int16('a')), V(string("a"))},
2855	{V(int32('a')), V(string("a"))},
2856	{V(int64('a')), V(string("a"))},
2857	{V(uint('a')), V(string("a"))},
2858	{V(uint8('a')), V(string("a"))},
2859	{V(uint16('a')), V(string("a"))},
2860	{V(uint32('a')), V(string("a"))},
2861	{V(uint64('a')), V(string("a"))},
2862	{V(uintptr('a')), V(string("a"))},
2863	{V(int(-1)), V(string("\uFFFD"))},
2864	{V(int8(-2)), V(string("\uFFFD"))},
2865	{V(int16(-3)), V(string("\uFFFD"))},
2866	{V(int32(-4)), V(string("\uFFFD"))},
2867	{V(int64(-5)), V(string("\uFFFD"))},
2868	{V(uint(0x110001)), V(string("\uFFFD"))},
2869	{V(uint32(0x110002)), V(string("\uFFFD"))},
2870	{V(uint64(0x110003)), V(string("\uFFFD"))},
2871	{V(uintptr(0x110004)), V(string("\uFFFD"))},
2872
2873	// named string
2874	{V(MyString("hello")), V(string("hello"))},
2875	{V(string("hello")), V(MyString("hello"))},
2876	{V(string("hello")), V(string("hello"))},
2877	{V(MyString("hello")), V(MyString("hello"))},
2878	{V(MyString("bytes1")), V([]byte("bytes1"))},
2879	{V([]byte("bytes2")), V(MyString("bytes2"))},
2880	{V([]byte("bytes3")), V([]byte("bytes3"))},
2881	{V(MyString("runes♝")), V([]rune("runes♝"))},
2882	{V([]rune("runes♕")), V(MyString("runes♕"))},
2883	{V([]rune("runes������")), V([]rune("runes������"))},
2884	{V([]rune("runes������")), V(MyRunes("runes������"))},
2885	{V(MyRunes("runes������")), V([]rune("runes������"))},
2886	{V(int('a')), V(MyString("a"))},
2887	{V(int8('a')), V(MyString("a"))},
2888	{V(int16('a')), V(MyString("a"))},
2889	{V(int32('a')), V(MyString("a"))},
2890	{V(int64('a')), V(MyString("a"))},
2891	{V(uint('a')), V(MyString("a"))},
2892	{V(uint8('a')), V(MyString("a"))},
2893	{V(uint16('a')), V(MyString("a"))},
2894	{V(uint32('a')), V(MyString("a"))},
2895	{V(uint64('a')), V(MyString("a"))},
2896	{V(uintptr('a')), V(MyString("a"))},
2897	{V(int(-1)), V(MyString("\uFFFD"))},
2898	{V(int8(-2)), V(MyString("\uFFFD"))},
2899	{V(int16(-3)), V(MyString("\uFFFD"))},
2900	{V(int32(-4)), V(MyString("\uFFFD"))},
2901	{V(int64(-5)), V(MyString("\uFFFD"))},
2902	{V(uint(0x110001)), V(MyString("\uFFFD"))},
2903	{V(uint32(0x110002)), V(MyString("\uFFFD"))},
2904	{V(uint64(0x110003)), V(MyString("\uFFFD"))},
2905	{V(uintptr(0x110004)), V(MyString("\uFFFD"))},
2906
2907	// named []byte
2908	{V(string("bytes1")), V(MyBytes("bytes1"))},
2909	{V(MyBytes("bytes2")), V(string("bytes2"))},
2910	{V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
2911	{V(MyString("bytes1")), V(MyBytes("bytes1"))},
2912	{V(MyBytes("bytes2")), V(MyString("bytes2"))},
2913
2914	// named []rune
2915	{V(string("runes♝")), V(MyRunes("runes♝"))},
2916	{V(MyRunes("runes♕")), V(string("runes♕"))},
2917	{V(MyRunes("runes������")), V(MyRunes("runes������"))},
2918	{V(MyString("runes♝")), V(MyRunes("runes♝"))},
2919	{V(MyRunes("runes♕")), V(MyString("runes♕"))},
2920
2921	// named types and equal underlying types
2922	{V(new(int)), V(new(integer))},
2923	{V(new(integer)), V(new(int))},
2924	{V(Empty{}), V(struct{}{})},
2925	{V(new(Empty)), V(new(struct{}))},
2926	{V(struct{}{}), V(Empty{})},
2927	{V(new(struct{})), V(new(Empty))},
2928	{V(Empty{}), V(Empty{})},
2929	{V(MyBytes{}), V([]byte{})},
2930	{V([]byte{}), V(MyBytes{})},
2931	{V((func())(nil)), V(MyFunc(nil))},
2932	{V((MyFunc)(nil)), V((func())(nil))},
2933
2934	// can convert *byte and *MyByte
2935	{V((*byte)(nil)), V((*MyByte)(nil))},
2936	{V((*MyByte)(nil)), V((*byte)(nil))},
2937
2938	// cannot convert mismatched array sizes
2939	{V([2]byte{}), V([2]byte{})},
2940	{V([3]byte{}), V([3]byte{})},
2941
2942	// cannot convert other instances
2943	{V((**byte)(nil)), V((**byte)(nil))},
2944	{V((**MyByte)(nil)), V((**MyByte)(nil))},
2945	{V((chan byte)(nil)), V((chan byte)(nil))},
2946	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
2947	{V(([]byte)(nil)), V(([]byte)(nil))},
2948	{V(([]MyByte)(nil)), V(([]MyByte)(nil))},
2949	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
2950	{V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
2951	{V((map[byte]int)(nil)), V((map[byte]int)(nil))},
2952	{V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
2953	{V([2]byte{}), V([2]byte{})},
2954	{V([2]MyByte{}), V([2]MyByte{})},
2955
2956	// other
2957	{V((***int)(nil)), V((***int)(nil))},
2958	{V((***byte)(nil)), V((***byte)(nil))},
2959	{V((***int32)(nil)), V((***int32)(nil))},
2960	{V((***int64)(nil)), V((***int64)(nil))},
2961	{V((chan int)(nil)), V((<-chan int)(nil))},
2962	{V((chan int)(nil)), V((chan<- int)(nil))},
2963	{V((chan string)(nil)), V((<-chan string)(nil))},
2964	{V((chan string)(nil)), V((chan<- string)(nil))},
2965	{V((chan byte)(nil)), V((chan byte)(nil))},
2966	{V((chan MyByte)(nil)), V((chan MyByte)(nil))},
2967	{V((map[int]bool)(nil)), V((map[int]bool)(nil))},
2968	{V((map[int]byte)(nil)), V((map[int]byte)(nil))},
2969	{V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
2970	{V([]uint(nil)), V([]uint(nil))},
2971	{V([]int(nil)), V([]int(nil))},
2972	{V(new(interface{})), V(new(interface{}))},
2973	{V(new(io.Reader)), V(new(io.Reader))},
2974	{V(new(io.Writer)), V(new(io.Writer))},
2975
2976	// interfaces
2977	{V(int(1)), EmptyInterfaceV(int(1))},
2978	{V(string("hello")), EmptyInterfaceV(string("hello"))},
2979	{V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
2980	{ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
2981	{V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
2982}
2983
2984func TestConvert(t *testing.T) {
2985	canConvert := map[[2]Type]bool{}
2986	all := map[Type]bool{}
2987
2988	for _, tt := range convertTests {
2989		t1 := tt.in.Type()
2990		if !t1.ConvertibleTo(t1) {
2991			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
2992			continue
2993		}
2994
2995		t2 := tt.out.Type()
2996		if !t1.ConvertibleTo(t2) {
2997			t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
2998			continue
2999		}
3000
3001		all[t1] = true
3002		all[t2] = true
3003		canConvert[[2]Type{t1, t2}] = true
3004
3005		v1 := tt.in
3006		vout1 := v1.Convert(t1)
3007		out1 := vout1.Interface()
3008		if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
3009			t.Errorf("ValueOf(%T(%v)).Convert(%s) = %T(%v), want %T(%v)", tt.in.Interface(), tt.in.Interface(), t1, out1, out1, tt.in.Interface(), tt.in.Interface())
3010		}
3011
3012		vout := v1.Convert(t2)
3013		out := vout.Interface()
3014		if vout.Type() != tt.out.Type() || !DeepEqual(out, tt.out.Interface()) {
3015			t.Errorf("ValueOf(%T(%v)).Convert(%s) = %T(%v), want %T(%v)", tt.in.Interface(), tt.in.Interface(), t2, out, out, tt.out.Interface(), tt.out.Interface())
3016		}
3017
3018		if IsRO(v1) {
3019			t.Errorf("table entry %v is RO, should not be", v1)
3020		}
3021		if IsRO(vout1) {
3022			t.Errorf("self-conversion output %v is RO, should not be", vout1)
3023		}
3024		if IsRO(vout) {
3025			t.Errorf("conversion output %v is RO, should not be", vout)
3026		}
3027		if !IsRO(MakeRO(v1).Convert(t1)) {
3028			t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3029		}
3030		if !IsRO(MakeRO(v1).Convert(t2)) {
3031			t.Errorf("RO conversion output %v is not RO, should be", v1)
3032		}
3033	}
3034
3035	// Assume that of all the types we saw during the tests,
3036	// if there wasn't an explicit entry for a conversion between
3037	// a pair of types, then it's not to be allowed. This checks for
3038	// things like 'int64' converting to '*int'.
3039	for t1 := range all {
3040		for t2 := range all {
3041			expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3042			if ok := t1.ConvertibleTo(t2); ok != expectOK {
3043				t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3044			}
3045		}
3046	}
3047}
3048
3049func TestOverflow(t *testing.T) {
3050	if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3051		t.Errorf("%v wrongly overflows float64", 1e300)
3052	}
3053
3054	maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3055	if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3056		t.Errorf("%v wrongly overflows float32", maxFloat32)
3057	}
3058	ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3059	if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3060		t.Errorf("%v should overflow float32", ovfFloat32)
3061	}
3062	if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3063		t.Errorf("%v should overflow float32", -ovfFloat32)
3064	}
3065
3066	maxInt32 := int64(0x7fffffff)
3067	if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3068		t.Errorf("%v wrongly overflows int32", maxInt32)
3069	}
3070	if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3071		t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3072	}
3073	ovfInt32 := int64(1 << 31)
3074	if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3075		t.Errorf("%v should overflow int32", ovfInt32)
3076	}
3077
3078	maxUint32 := uint64(0xffffffff)
3079	if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3080		t.Errorf("%v wrongly overflows uint32", maxUint32)
3081	}
3082	ovfUint32 := uint64(1 << 32)
3083	if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3084		t.Errorf("%v should overflow uint32", ovfUint32)
3085	}
3086}
3087
3088func checkSameType(t *testing.T, x, y interface{}) {
3089	if TypeOf(x) != TypeOf(y) {
3090		t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3091	}
3092}
3093
3094func TestArrayOf(t *testing.T) {
3095	// check construction and use of type not in binary
3096	type T int
3097	at := ArrayOf(10, TypeOf(T(1)))
3098	v := New(at).Elem()
3099	for i := 0; i < v.Len(); i++ {
3100		v.Index(i).Set(ValueOf(T(i)))
3101	}
3102	s := fmt.Sprint(v.Interface())
3103	want := "[0 1 2 3 4 5 6 7 8 9]"
3104	if s != want {
3105		t.Errorf("constructed array = %s, want %s", s, want)
3106	}
3107
3108	// check that type already in binary is found
3109	checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
3110}
3111
3112func TestSliceOf(t *testing.T) {
3113	// check construction and use of type not in binary
3114	type T int
3115	st := SliceOf(TypeOf(T(1)))
3116	v := MakeSlice(st, 10, 10)
3117	runtime.GC()
3118	for i := 0; i < v.Len(); i++ {
3119		v.Index(i).Set(ValueOf(T(i)))
3120		runtime.GC()
3121	}
3122	s := fmt.Sprint(v.Interface())
3123	want := "[0 1 2 3 4 5 6 7 8 9]"
3124	if s != want {
3125		t.Errorf("constructed slice = %s, want %s", s, want)
3126	}
3127
3128	// check that type already in binary is found
3129	type T1 int
3130	checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
3131}
3132
3133func TestSliceOverflow(t *testing.T) {
3134	// check that MakeSlice panics when size of slice overflows uint
3135	const S = 1e6
3136	s := uint(S)
3137	l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
3138	if l*s >= s {
3139		t.Fatal("slice size does not overflow")
3140	}
3141	var x [S]byte
3142	st := SliceOf(TypeOf(x))
3143	defer func() {
3144		err := recover()
3145		if err == nil {
3146			t.Fatal("slice overflow does not panic")
3147		}
3148	}()
3149	MakeSlice(st, int(l), int(l))
3150}
3151
3152func TestSliceOfGC(t *testing.T) {
3153	type T *uintptr
3154	tt := TypeOf(T(nil))
3155	st := SliceOf(tt)
3156	const n = 100
3157	var x []interface{}
3158	for i := 0; i < n; i++ {
3159		v := MakeSlice(st, n, n)
3160		for j := 0; j < v.Len(); j++ {
3161			p := new(uintptr)
3162			*p = uintptr(i*n + j)
3163			v.Index(j).Set(ValueOf(p).Convert(tt))
3164		}
3165		x = append(x, v.Interface())
3166	}
3167	runtime.GC()
3168
3169	for i, xi := range x {
3170		v := ValueOf(xi)
3171		for j := 0; j < v.Len(); j++ {
3172			k := v.Index(j).Elem().Interface()
3173			if k != uintptr(i*n+j) {
3174				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3175			}
3176		}
3177	}
3178}
3179
3180func TestChanOf(t *testing.T) {
3181	// check construction and use of type not in binary
3182	type T string
3183	ct := ChanOf(BothDir, TypeOf(T("")))
3184	v := MakeChan(ct, 2)
3185	runtime.GC()
3186	v.Send(ValueOf(T("hello")))
3187	runtime.GC()
3188	v.Send(ValueOf(T("world")))
3189	runtime.GC()
3190
3191	sv1, _ := v.Recv()
3192	sv2, _ := v.Recv()
3193	s1 := sv1.String()
3194	s2 := sv2.String()
3195	if s1 != "hello" || s2 != "world" {
3196		t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
3197	}
3198
3199	// check that type already in binary is found
3200	type T1 int
3201	checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
3202}
3203
3204func TestChanOfGC(t *testing.T) {
3205	done := make(chan bool, 1)
3206	go func() {
3207		select {
3208		case <-done:
3209		case <-time.After(5 * time.Second):
3210			panic("deadlock in TestChanOfGC")
3211		}
3212	}()
3213
3214	defer func() {
3215		done <- true
3216	}()
3217
3218	type T *uintptr
3219	tt := TypeOf(T(nil))
3220	ct := ChanOf(BothDir, tt)
3221
3222	// NOTE: The garbage collector handles allocated channels specially,
3223	// so we have to save pointers to channels in x; the pointer code will
3224	// use the gc info in the newly constructed chan type.
3225	const n = 100
3226	var x []interface{}
3227	for i := 0; i < n; i++ {
3228		v := MakeChan(ct, n)
3229		for j := 0; j < n; j++ {
3230			p := new(uintptr)
3231			*p = uintptr(i*n + j)
3232			v.Send(ValueOf(p).Convert(tt))
3233		}
3234		pv := New(ct)
3235		pv.Elem().Set(v)
3236		x = append(x, pv.Interface())
3237	}
3238	runtime.GC()
3239
3240	for i, xi := range x {
3241		v := ValueOf(xi).Elem()
3242		for j := 0; j < n; j++ {
3243			pv, _ := v.Recv()
3244			k := pv.Elem().Interface()
3245			if k != uintptr(i*n+j) {
3246				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3247			}
3248		}
3249	}
3250}
3251
3252func TestMapOf(t *testing.T) {
3253	// check construction and use of type not in binary
3254	type K string
3255	type V float64
3256
3257	v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
3258	runtime.GC()
3259	v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
3260	runtime.GC()
3261
3262	s := fmt.Sprint(v.Interface())
3263	want := "map[a:1]"
3264	if s != want {
3265		t.Errorf("constructed map = %s, want %s", s, want)
3266	}
3267
3268	// check that type already in binary is found
3269	checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
3270
3271	// check that invalid key type panics
3272	shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3273}
3274
3275func TestMapOfGCKeys(t *testing.T) {
3276	type T *uintptr
3277	tt := TypeOf(T(nil))
3278	mt := MapOf(tt, TypeOf(false))
3279
3280	// NOTE: The garbage collector handles allocated maps specially,
3281	// so we have to save pointers to maps in x; the pointer code will
3282	// use the gc info in the newly constructed map type.
3283	const n = 100
3284	var x []interface{}
3285	for i := 0; i < n; i++ {
3286		v := MakeMap(mt)
3287		for j := 0; j < n; j++ {
3288			p := new(uintptr)
3289			*p = uintptr(i*n + j)
3290			v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
3291		}
3292		pv := New(mt)
3293		pv.Elem().Set(v)
3294		x = append(x, pv.Interface())
3295	}
3296	runtime.GC()
3297
3298	for i, xi := range x {
3299		v := ValueOf(xi).Elem()
3300		var out []int
3301		for _, kv := range v.MapKeys() {
3302			out = append(out, int(kv.Elem().Interface().(uintptr)))
3303		}
3304		sort.Ints(out)
3305		for j, k := range out {
3306			if k != i*n+j {
3307				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3308			}
3309		}
3310	}
3311}
3312
3313func TestMapOfGCValues(t *testing.T) {
3314	type T *uintptr
3315	tt := TypeOf(T(nil))
3316	mt := MapOf(TypeOf(1), tt)
3317
3318	// NOTE: The garbage collector handles allocated maps specially,
3319	// so we have to save pointers to maps in x; the pointer code will
3320	// use the gc info in the newly constructed map type.
3321	const n = 100
3322	var x []interface{}
3323	for i := 0; i < n; i++ {
3324		v := MakeMap(mt)
3325		for j := 0; j < n; j++ {
3326			p := new(uintptr)
3327			*p = uintptr(i*n + j)
3328			v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
3329		}
3330		pv := New(mt)
3331		pv.Elem().Set(v)
3332		x = append(x, pv.Interface())
3333	}
3334	runtime.GC()
3335
3336	for i, xi := range x {
3337		v := ValueOf(xi).Elem()
3338		for j := 0; j < n; j++ {
3339			k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
3340			if k != uintptr(i*n+j) {
3341				t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3342			}
3343		}
3344	}
3345}
3346
3347type B1 struct {
3348	X int
3349	Y int
3350	Z int
3351}
3352
3353func BenchmarkFieldByName1(b *testing.B) {
3354	t := TypeOf(B1{})
3355	for i := 0; i < b.N; i++ {
3356		t.FieldByName("Z")
3357	}
3358}
3359
3360func BenchmarkFieldByName2(b *testing.B) {
3361	t := TypeOf(S3{})
3362	for i := 0; i < b.N; i++ {
3363		t.FieldByName("B")
3364	}
3365}
3366
3367type R0 struct {
3368	*R1
3369	*R2
3370	*R3
3371	*R4
3372}
3373
3374type R1 struct {
3375	*R5
3376	*R6
3377	*R7
3378	*R8
3379}
3380
3381type R2 R1
3382type R3 R1
3383type R4 R1
3384
3385type R5 struct {
3386	*R9
3387	*R10
3388	*R11
3389	*R12
3390}
3391
3392type R6 R5
3393type R7 R5
3394type R8 R5
3395
3396type R9 struct {
3397	*R13
3398	*R14
3399	*R15
3400	*R16
3401}
3402
3403type R10 R9
3404type R11 R9
3405type R12 R9
3406
3407type R13 struct {
3408	*R17
3409	*R18
3410	*R19
3411	*R20
3412}
3413
3414type R14 R13
3415type R15 R13
3416type R16 R13
3417
3418type R17 struct {
3419	*R21
3420	*R22
3421	*R23
3422	*R24
3423}
3424
3425type R18 R17
3426type R19 R17
3427type R20 R17
3428
3429type R21 struct {
3430	X int
3431}
3432
3433type R22 R21
3434type R23 R21
3435type R24 R21
3436
3437func TestEmbed(t *testing.T) {
3438	typ := TypeOf(R0{})
3439	f, ok := typ.FieldByName("X")
3440	if ok {
3441		t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
3442	}
3443}
3444
3445func BenchmarkFieldByName3(b *testing.B) {
3446	t := TypeOf(R0{})
3447	for i := 0; i < b.N; i++ {
3448		t.FieldByName("X")
3449	}
3450}
3451
3452// An exhaustive is a mechanism for writing exhaustive or stochastic tests.
3453// The basic usage is:
3454//
3455//	for x.Next() {
3456//		... code using x.Maybe() or x.Choice(n) to create test cases ...
3457//	}
3458//
3459// Each iteration of the loop returns a different set of results, until all
3460// possible result sets have been explored. It is okay for different code paths
3461// to make different method call sequences on x, but there must be no
3462// other source of non-determinism in the call sequences.
3463//
3464// When faced with a new decision, x chooses randomly. Future explorations
3465// of that path will choose successive values for the result. Thus, stopping
3466// the loop after a fixed number of iterations gives somewhat stochastic
3467// testing.
3468//
3469// Example:
3470//
3471//	for x.Next() {
3472//		v := make([]bool, x.Choose(4))
3473//		for i := range v {
3474//			v[i] = x.Maybe()
3475//		}
3476//		fmt.Println(v)
3477//	}
3478//
3479// prints (in some order):
3480//
3481//	[]
3482//	[false]
3483//	[true]
3484//	[false false]
3485//	[false true]
3486//	...
3487//	[true true]
3488//	[false false false]
3489//	...
3490//	[true true true]
3491//	[false false false false]
3492//	...
3493//	[true true true true]
3494//
3495type exhaustive struct {
3496	r    *rand.Rand
3497	pos  int
3498	last []choice
3499}
3500
3501type choice struct {
3502	off int
3503	n   int
3504	max int
3505}
3506
3507func (x *exhaustive) Next() bool {
3508	if x.r == nil {
3509		x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
3510	}
3511	x.pos = 0
3512	if x.last == nil {
3513		x.last = []choice{}
3514		return true
3515	}
3516	for i := len(x.last) - 1; i >= 0; i-- {
3517		c := &x.last[i]
3518		if c.n+1 < c.max {
3519			c.n++
3520			x.last = x.last[:i+1]
3521			return true
3522		}
3523	}
3524	return false
3525}
3526
3527func (x *exhaustive) Choose(max int) int {
3528	if x.pos >= len(x.last) {
3529		x.last = append(x.last, choice{x.r.Intn(max), 0, max})
3530	}
3531	c := &x.last[x.pos]
3532	x.pos++
3533	if c.max != max {
3534		panic("inconsistent use of exhaustive tester")
3535	}
3536	return (c.n + c.off) % max
3537}
3538
3539func (x *exhaustive) Maybe() bool {
3540	return x.Choose(2) == 1
3541}
3542