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