OSDN Git Service

c35dc26e90dc3ac44ac7e9da3a7e2555aa349779
[pf3gnuchains/gcc-fork.git] / libgo / go / reflect / all_test.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package reflect_test
6
7 import (
8         "bytes"
9         "encoding/base64"
10         "fmt"
11         "io"
12         "os"
13         . "reflect"
14         /*      "runtime" */
15         "testing"
16         "unsafe"
17 )
18
19 func TestBool(t *testing.T) {
20         v := ValueOf(true)
21         if v.Bool() != true {
22                 t.Fatal("ValueOf(true).Bool() = false")
23         }
24 }
25
26 type integer int
27 type T struct {
28         a int
29         b float64
30         c string
31         d *int
32 }
33
34 type pair struct {
35         i interface{}
36         s string
37 }
38
39 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
40
41 func assert(t *testing.T, s, want string) {
42         if s != want {
43                 t.Errorf("have %#q want %#q", s, want)
44         }
45 }
46
47 func typestring(i interface{}) string { return TypeOf(i).String() }
48
49 var typeTests = []pair{
50         {struct{ x int }{}, "int"},
51         {struct{ x int8 }{}, "int8"},
52         {struct{ x int16 }{}, "int16"},
53         {struct{ x int32 }{}, "int32"},
54         {struct{ x int64 }{}, "int64"},
55         {struct{ x uint }{}, "uint"},
56         {struct{ x uint8 }{}, "uint8"},
57         {struct{ x uint16 }{}, "uint16"},
58         {struct{ x uint32 }{}, "uint32"},
59         {struct{ x uint64 }{}, "uint64"},
60         {struct{ x float32 }{}, "float32"},
61         {struct{ x float64 }{}, "float64"},
62         {struct{ x int8 }{}, "int8"},
63         {struct{ x (**int8) }{}, "**int8"},
64         {struct{ x (**integer) }{}, "**reflect_test.integer"},
65         {struct{ x ([32]int32) }{}, "[32]int32"},
66         {struct{ x ([]int8) }{}, "[]int8"},
67         {struct{ x (map[string]int32) }{}, "map[string]int32"},
68         {struct{ x (chan<- string) }{}, "chan<- string"},
69         {struct {
70                 x struct {
71                         c chan *int32
72                         d float32
73                 }
74         }{},
75                 "struct { c chan *int32; d float32 }",
76         },
77         {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
78         {struct {
79                 x struct {
80                         c func(chan *integer, *int8)
81                 }
82         }{},
83                 "struct { c func(chan *reflect_test.integer, *int8) }",
84         },
85         {struct {
86                 x struct {
87                         a int8
88                         b int32
89                 }
90         }{},
91                 "struct { a int8; b int32 }",
92         },
93         {struct {
94                 x struct {
95                         a int8
96                         b int8
97                         c int32
98                 }
99         }{},
100                 "struct { a int8; b int8; c int32 }",
101         },
102         {struct {
103                 x struct {
104                         a int8
105                         b int8
106                         c int8
107                         d int32
108                 }
109         }{},
110                 "struct { a int8; b int8; c int8; d int32 }",
111         },
112         {struct {
113                 x struct {
114                         a int8
115                         b int8
116                         c int8
117                         d int8
118                         e int32
119                 }
120         }{},
121                 "struct { a int8; b int8; c int8; d int8; e int32 }",
122         },
123         {struct {
124                 x struct {
125                         a int8
126                         b int8
127                         c int8
128                         d int8
129                         e int8
130                         f int32
131                 }
132         }{},
133                 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
134         },
135         {struct {
136                 x struct {
137                         a int8 `reflect:"hi there"`
138                 }
139         }{},
140                 `struct { a int8 "reflect:\"hi there\"" }`,
141         },
142         {struct {
143                 x struct {
144                         a int8 `reflect:"hi \x00there\t\n\"\\"`
145                 }
146         }{},
147                 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
148         },
149         {struct {
150                 x struct {
151                         f func(args ...int)
152                 }
153         }{},
154                 "struct { f func(...int) }",
155         },
156         {struct {
157                 x (interface {
158                         a(func(func(int) int) func(func(int)) int)
159                         b()
160                 })
161         }{},
162                 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
163         },
164 }
165
166 var valueTests = []pair{
167         {new(int8), "8"},
168         {new(int16), "16"},
169         {new(int32), "32"},
170         {new(int64), "64"},
171         {new(uint8), "8"},
172         {new(uint16), "16"},
173         {new(uint32), "32"},
174         {new(uint64), "64"},
175         {new(float32), "256.25"},
176         {new(float64), "512.125"},
177         {new(string), "stringy cheese"},
178         {new(bool), "true"},
179         {new(*int8), "*int8(0)"},
180         {new(**int8), "**int8(0)"},
181         {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
182         {new(**integer), "**reflect_test.integer(0)"},
183         {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
184         {new(chan<- string), "chan<- string"},
185         {new(func(a int8, b int32)), "func(int8, int32)(0)"},
186         {new(struct {
187                 c chan *int32
188                 d float32
189         }),
190                 "struct { c chan *int32; d float32 }{chan *int32, 0}",
191         },
192         {new(struct{ c func(chan *integer, *int8) }),
193                 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
194         },
195         {new(struct {
196                 a int8
197                 b int32
198         }),
199                 "struct { a int8; b int32 }{0, 0}",
200         },
201         {new(struct {
202                 a int8
203                 b int8
204                 c int32
205         }),
206                 "struct { a int8; b int8; c int32 }{0, 0, 0}",
207         },
208 }
209
210 func testType(t *testing.T, i int, typ Type, want string) {
211         s := typ.String()
212         if s != want {
213                 t.Errorf("#%d: have %#q, want %#q", i, s, want)
214         }
215 }
216
217 func TestTypes(t *testing.T) {
218         for i, tt := range typeTests {
219                 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
220         }
221 }
222
223 func TestSet(t *testing.T) {
224         for i, tt := range valueTests {
225                 v := ValueOf(tt.i)
226                 v = v.Elem()
227                 switch v.Kind() {
228                 case Int:
229                         v.SetInt(132)
230                 case Int8:
231                         v.SetInt(8)
232                 case Int16:
233                         v.SetInt(16)
234                 case Int32:
235                         v.SetInt(32)
236                 case Int64:
237                         v.SetInt(64)
238                 case Uint:
239                         v.SetUint(132)
240                 case Uint8:
241                         v.SetUint(8)
242                 case Uint16:
243                         v.SetUint(16)
244                 case Uint32:
245                         v.SetUint(32)
246                 case Uint64:
247                         v.SetUint(64)
248                 case Float32:
249                         v.SetFloat(256.25)
250                 case Float64:
251                         v.SetFloat(512.125)
252                 case Complex64:
253                         v.SetComplex(532.125 + 10i)
254                 case Complex128:
255                         v.SetComplex(564.25 + 1i)
256                 case String:
257                         v.SetString("stringy cheese")
258                 case Bool:
259                         v.SetBool(true)
260                 }
261                 s := valueToString(v)
262                 if s != tt.s {
263                         t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
264                 }
265         }
266 }
267
268 func TestSetValue(t *testing.T) {
269         for i, tt := range valueTests {
270                 v := ValueOf(tt.i).Elem()
271                 switch v.Kind() {
272                 case Int:
273                         v.Set(ValueOf(int(132)))
274                 case Int8:
275                         v.Set(ValueOf(int8(8)))
276                 case Int16:
277                         v.Set(ValueOf(int16(16)))
278                 case Int32:
279                         v.Set(ValueOf(int32(32)))
280                 case Int64:
281                         v.Set(ValueOf(int64(64)))
282                 case Uint:
283                         v.Set(ValueOf(uint(132)))
284                 case Uint8:
285                         v.Set(ValueOf(uint8(8)))
286                 case Uint16:
287                         v.Set(ValueOf(uint16(16)))
288                 case Uint32:
289                         v.Set(ValueOf(uint32(32)))
290                 case Uint64:
291                         v.Set(ValueOf(uint64(64)))
292                 case Float32:
293                         v.Set(ValueOf(float32(256.25)))
294                 case Float64:
295                         v.Set(ValueOf(512.125))
296                 case Complex64:
297                         v.Set(ValueOf(complex64(532.125 + 10i)))
298                 case Complex128:
299                         v.Set(ValueOf(complex128(564.25 + 1i)))
300                 case String:
301                         v.Set(ValueOf("stringy cheese"))
302                 case Bool:
303                         v.Set(ValueOf(true))
304                 }
305                 s := valueToString(v)
306                 if s != tt.s {
307                         t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
308                 }
309         }
310 }
311
312 var _i = 7
313
314 var valueToStringTests = []pair{
315         {123, "123"},
316         {123.5, "123.5"},
317         {byte(123), "123"},
318         {"abc", "abc"},
319         {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
320         {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
321         {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
322         {&[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})"},
323         {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
324         {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
325 }
326
327 func TestValueToString(t *testing.T) {
328         for i, test := range valueToStringTests {
329                 s := valueToString(ValueOf(test.i))
330                 if s != test.s {
331                         t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
332                 }
333         }
334 }
335
336 func TestArrayElemSet(t *testing.T) {
337         v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
338         v.Index(4).SetInt(123)
339         s := valueToString(v)
340         const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
341         if s != want {
342                 t.Errorf("[10]int: have %#q want %#q", s, want)
343         }
344
345         v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
346         v.Index(4).SetInt(123)
347         s = valueToString(v)
348         const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
349         if s != want1 {
350                 t.Errorf("[]int: have %#q want %#q", s, want1)
351         }
352 }
353
354 func TestPtrPointTo(t *testing.T) {
355         var ip *int32
356         var i int32 = 1234
357         vip := ValueOf(&ip)
358         vi := ValueOf(&i).Elem()
359         vip.Elem().Set(vi.Addr())
360         if *ip != 1234 {
361                 t.Errorf("got %d, want 1234", *ip)
362         }
363
364         ip = nil
365         vp := ValueOf(&ip).Elem()
366         vp.Set(Zero(vp.Type()))
367         if ip != nil {
368                 t.Errorf("got non-nil (%p), want nil", ip)
369         }
370 }
371
372 func TestPtrSetNil(t *testing.T) {
373         var i int32 = 1234
374         ip := &i
375         vip := ValueOf(&ip)
376         vip.Elem().Set(Zero(vip.Elem().Type()))
377         if ip != nil {
378                 t.Errorf("got non-nil (%d), want nil", *ip)
379         }
380 }
381
382 func TestMapSetNil(t *testing.T) {
383         m := make(map[string]int)
384         vm := ValueOf(&m)
385         vm.Elem().Set(Zero(vm.Elem().Type()))
386         if m != nil {
387                 t.Errorf("got non-nil (%p), want nil", m)
388         }
389 }
390
391 func TestAll(t *testing.T) {
392         testType(t, 1, TypeOf((int8)(0)), "int8")
393         testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
394
395         typ := TypeOf((*struct {
396                 c chan *int32
397                 d float32
398         })(nil))
399         testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
400         etyp := typ.Elem()
401         testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
402         styp := etyp
403         f := styp.Field(0)
404         testType(t, 5, f.Type, "chan *int32")
405
406         f, present := styp.FieldByName("d")
407         if !present {
408                 t.Errorf("FieldByName says present field is absent")
409         }
410         testType(t, 6, f.Type, "float32")
411
412         f, present = styp.FieldByName("absent")
413         if present {
414                 t.Errorf("FieldByName says absent field is present")
415         }
416
417         typ = TypeOf([32]int32{})
418         testType(t, 7, typ, "[32]int32")
419         testType(t, 8, typ.Elem(), "int32")
420
421         typ = TypeOf((map[string]*int32)(nil))
422         testType(t, 9, typ, "map[string]*int32")
423         mtyp := typ
424         testType(t, 10, mtyp.Key(), "string")
425         testType(t, 11, mtyp.Elem(), "*int32")
426
427         typ = TypeOf((chan<- string)(nil))
428         testType(t, 12, typ, "chan<- string")
429         testType(t, 13, typ.Elem(), "string")
430
431         // make sure tag strings are not part of element type
432         typ = TypeOf(struct {
433                 d []uint32 `reflect:"TAG"`
434         }{}).Field(0).Type
435         testType(t, 14, typ, "[]uint32")
436 }
437
438 func TestInterfaceGet(t *testing.T) {
439         var inter struct {
440                 E interface{}
441         }
442         inter.E = 123.456
443         v1 := ValueOf(&inter)
444         v2 := v1.Elem().Field(0)
445         assert(t, v2.Type().String(), "interface {}")
446         i2 := v2.Interface()
447         v3 := ValueOf(i2)
448         assert(t, v3.Type().String(), "float64")
449 }
450
451 func TestInterfaceValue(t *testing.T) {
452         var inter struct {
453                 E interface{}
454         }
455         inter.E = 123.456
456         v1 := ValueOf(&inter)
457         v2 := v1.Elem().Field(0)
458         assert(t, v2.Type().String(), "interface {}")
459         v3 := v2.Elem()
460         assert(t, v3.Type().String(), "float64")
461
462         i3 := v2.Interface()
463         if _, ok := i3.(float64); !ok {
464                 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
465         }
466 }
467
468 func TestFunctionValue(t *testing.T) {
469         var x interface{} = func() {}
470         v := ValueOf(x)
471         if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
472                 t.Fatalf("TestFunction returned wrong pointer")
473         }
474         assert(t, v.Type().String(), "func()")
475 }
476
477 var appendTests = []struct {
478         orig, extra []int
479 }{
480         {make([]int, 2, 4), []int{22}},
481         {make([]int, 2, 4), []int{22, 33, 44}},
482 }
483
484 func sameInts(x, y []int) bool {
485         if len(x) != len(y) {
486                 return false
487         }
488         for i, xx := range x {
489                 if xx != y[i] {
490                         return false
491                 }
492         }
493         return true
494 }
495
496 func TestAppend(t *testing.T) {
497         for i, test := range appendTests {
498                 origLen, extraLen := len(test.orig), len(test.extra)
499                 want := append(test.orig, test.extra...)
500                 // Convert extra from []int to []Value.
501                 e0 := make([]Value, len(test.extra))
502                 for j, e := range test.extra {
503                         e0[j] = ValueOf(e)
504                 }
505                 // Convert extra from []int to *SliceValue.
506                 e1 := ValueOf(test.extra)
507                 // Test Append.
508                 a0 := ValueOf(test.orig)
509                 have0 := Append(a0, e0...).Interface().([]int)
510                 if !sameInts(have0, want) {
511                         t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
512                 }
513                 // Check that the orig and extra slices were not modified.
514                 if len(test.orig) != origLen {
515                         t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
516                 }
517                 if len(test.extra) != extraLen {
518                         t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
519                 }
520                 // Test AppendSlice.
521                 a1 := ValueOf(test.orig)
522                 have1 := AppendSlice(a1, e1).Interface().([]int)
523                 if !sameInts(have1, want) {
524                         t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
525                 }
526                 // Check that the orig and extra slices were not modified.
527                 if len(test.orig) != origLen {
528                         t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
529                 }
530                 if len(test.extra) != extraLen {
531                         t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
532                 }
533         }
534 }
535
536 func TestCopy(t *testing.T) {
537         a := []int{1, 2, 3, 4, 10, 9, 8, 7}
538         b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
539         c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
540         for i := 0; i < len(b); i++ {
541                 if b[i] != c[i] {
542                         t.Fatalf("b != c before test")
543                 }
544         }
545         a1 := a
546         b1 := b
547         aa := ValueOf(&a1).Elem()
548         ab := ValueOf(&b1).Elem()
549         for tocopy := 1; tocopy <= 7; tocopy++ {
550                 aa.SetLen(tocopy)
551                 Copy(ab, aa)
552                 aa.SetLen(8)
553                 for i := 0; i < tocopy; i++ {
554                         if a[i] != b[i] {
555                                 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
556                                         tocopy, i, a[i], i, b[i])
557                         }
558                 }
559                 for i := tocopy; i < len(b); i++ {
560                         if b[i] != c[i] {
561                                 if i < len(a) {
562                                         t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
563                                                 tocopy, i, a[i], i, b[i], i, c[i])
564                                 } else {
565                                         t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
566                                                 tocopy, i, b[i], i, c[i])
567                                 }
568                         } else {
569                                 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
570                         }
571                 }
572         }
573 }
574
575 func TestCopyArray(t *testing.T) {
576         a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
577         b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
578         c := b
579         aa := ValueOf(&a).Elem()
580         ab := ValueOf(&b).Elem()
581         Copy(ab, aa)
582         for i := 0; i < len(a); i++ {
583                 if a[i] != b[i] {
584                         t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
585                 }
586         }
587         for i := len(a); i < len(b); i++ {
588                 if b[i] != c[i] {
589                         t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
590                 } else {
591                         t.Logf("elem %d is okay\n", i)
592                 }
593         }
594 }
595
596 func TestBigUnnamedStruct(t *testing.T) {
597         b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
598         v := ValueOf(b)
599         b1 := v.Interface().(struct {
600                 a, b, c, d int64
601         })
602         if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
603                 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
604         }
605 }
606
607 type big struct {
608         a, b, c, d, e int64
609 }
610
611 func TestBigStruct(t *testing.T) {
612         b := big{1, 2, 3, 4, 5}
613         v := ValueOf(b)
614         b1 := v.Interface().(big)
615         if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
616                 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
617         }
618 }
619
620 type Basic struct {
621         x int
622         y float32
623 }
624
625 type NotBasic Basic
626
627 type DeepEqualTest struct {
628         a, b interface{}
629         eq   bool
630 }
631
632 // Simple functions for DeepEqual tests.
633 var (
634         fn1 func()             // nil.
635         fn2 func()             // nil.
636         fn3 = func() { fn1() } // Not nil.
637 )
638
639 var deepEqualTests = []DeepEqualTest{
640         // Equalities
641         {nil, nil, true},
642         {1, 1, true},
643         {int32(1), int32(1), true},
644         {0.5, 0.5, true},
645         {float32(0.5), float32(0.5), true},
646         {"hello", "hello", true},
647         {make([]int, 10), make([]int, 10), true},
648         {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
649         {Basic{1, 0.5}, Basic{1, 0.5}, true},
650         {error(nil), error(nil), true},
651         {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
652         {fn1, fn2, true},
653
654         // Inequalities
655         {1, 2, false},
656         {int32(1), int32(2), false},
657         {0.5, 0.6, false},
658         {float32(0.5), float32(0.6), false},
659         {"hello", "hey", false},
660         {make([]int, 10), make([]int, 11), false},
661         {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
662         {Basic{1, 0.5}, Basic{1, 0.6}, false},
663         {Basic{1, 0}, Basic{2, 0}, false},
664         {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
665         {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
666         {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
667         {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
668         {nil, 1, false},
669         {1, nil, false},
670         {fn1, fn3, false},
671         {fn3, fn3, false},
672
673         // Nil vs empty: not the same.
674         {[]int{}, []int(nil), false},
675         {[]int{}, []int{}, true},
676         {[]int(nil), []int(nil), true},
677         {map[int]int{}, map[int]int(nil), false},
678         {map[int]int{}, map[int]int{}, true},
679         {map[int]int(nil), map[int]int(nil), true},
680
681         // Mismatched types
682         {1, 1.0, false},
683         {int32(1), int64(1), false},
684         {0.5, "hello", false},
685         {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
686         {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
687         {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
688         {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
689 }
690
691 func TestDeepEqual(t *testing.T) {
692         for _, test := range deepEqualTests {
693                 if r := DeepEqual(test.a, test.b); r != test.eq {
694                         t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
695                 }
696         }
697 }
698
699 func TestTypeOf(t *testing.T) {
700         // Special case for nil
701         if typ := TypeOf(nil); typ != nil {
702                 t.Errorf("expected nil type for nil value; got %v", typ)
703         }
704         for _, test := range deepEqualTests {
705                 v := ValueOf(test.a)
706                 if !v.IsValid() {
707                         continue
708                 }
709                 typ := TypeOf(test.a)
710                 if typ != v.Type() {
711                         t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
712                 }
713         }
714 }
715
716 type Recursive struct {
717         x int
718         r *Recursive
719 }
720
721 func TestDeepEqualRecursiveStruct(t *testing.T) {
722         a, b := new(Recursive), new(Recursive)
723         *a = Recursive{12, a}
724         *b = Recursive{12, b}
725         if !DeepEqual(a, b) {
726                 t.Error("DeepEqual(recursive same) = false, want true")
727         }
728 }
729
730 type _Complex struct {
731         a int
732         b [3]*_Complex
733         c *string
734         d map[float64]float64
735 }
736
737 func TestDeepEqualComplexStruct(t *testing.T) {
738         m := make(map[float64]float64)
739         stra, strb := "hello", "hello"
740         a, b := new(_Complex), new(_Complex)
741         *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
742         *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
743         if !DeepEqual(a, b) {
744                 t.Error("DeepEqual(complex same) = false, want true")
745         }
746 }
747
748 func TestDeepEqualComplexStructInequality(t *testing.T) {
749         m := make(map[float64]float64)
750         stra, strb := "hello", "helloo" // Difference is here
751         a, b := new(_Complex), new(_Complex)
752         *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
753         *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
754         if DeepEqual(a, b) {
755                 t.Error("DeepEqual(complex different) = true, want false")
756         }
757 }
758
759 type UnexpT struct {
760         m map[int]int
761 }
762
763 func TestDeepEqualUnexportedMap(t *testing.T) {
764         // Check that DeepEqual can look at unexported fields.
765         x1 := UnexpT{map[int]int{1: 2}}
766         x2 := UnexpT{map[int]int{1: 2}}
767         if !DeepEqual(&x1, &x2) {
768                 t.Error("DeepEqual(x1, x2) = false, want true")
769         }
770
771         y1 := UnexpT{map[int]int{2: 3}}
772         if DeepEqual(&x1, &y1) {
773                 t.Error("DeepEqual(x1, y1) = true, want false")
774         }
775 }
776
777 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
778         s := ValueOf(x)
779         f := s.Type().Field(1)
780         if f.Offset != offs {
781                 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
782         }
783 }
784
785 // Check that structure alignment & offsets viewed through reflect agree with those
786 // from the compiler itself.
787 func TestAlignment(t *testing.T) {
788         type T1inner struct {
789                 a int
790         }
791         type T1 struct {
792                 T1inner
793                 f int
794         }
795         type T2inner struct {
796                 a, b int
797         }
798         type T2 struct {
799                 T2inner
800                 f int
801         }
802
803         x := T1{T1inner{2}, 17}
804         check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
805
806         x1 := T2{T2inner{2, 3}, 17}
807         check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
808 }
809
810 func Nil(a interface{}, t *testing.T) {
811         n := ValueOf(a).Field(0)
812         if !n.IsNil() {
813                 t.Errorf("%v should be nil", a)
814         }
815 }
816
817 func NotNil(a interface{}, t *testing.T) {
818         n := ValueOf(a).Field(0)
819         if n.IsNil() {
820                 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
821         }
822 }
823
824 func TestIsNil(t *testing.T) {
825         // These implement IsNil.
826         // Wrap in extra struct to hide interface type.
827         doNil := []interface{}{
828                 struct{ x *int }{},
829                 struct{ x interface{} }{},
830                 struct{ x map[string]int }{},
831                 struct{ x func() bool }{},
832                 struct{ x chan int }{},
833                 struct{ x []string }{},
834         }
835         for _, ts := range doNil {
836                 ty := TypeOf(ts).Field(0).Type
837                 v := Zero(ty)
838                 v.IsNil() // panics if not okay to call
839         }
840
841         // Check the implementations
842         var pi struct {
843                 x *int
844         }
845         Nil(pi, t)
846         pi.x = new(int)
847         NotNil(pi, t)
848
849         var si struct {
850                 x []int
851         }
852         Nil(si, t)
853         si.x = make([]int, 10)
854         NotNil(si, t)
855
856         var ci struct {
857                 x chan int
858         }
859         Nil(ci, t)
860         ci.x = make(chan int)
861         NotNil(ci, t)
862
863         var mi struct {
864                 x map[int]int
865         }
866         Nil(mi, t)
867         mi.x = make(map[int]int)
868         NotNil(mi, t)
869
870         var ii struct {
871                 x interface{}
872         }
873         Nil(ii, t)
874         ii.x = 2
875         NotNil(ii, t)
876
877         var fi struct {
878                 x func(t *testing.T)
879         }
880         Nil(fi, t)
881         fi.x = TestIsNil
882         NotNil(fi, t)
883 }
884
885 func TestInterfaceExtraction(t *testing.T) {
886         var s struct {
887                 W io.Writer
888         }
889
890         s.W = os.Stdout
891         v := Indirect(ValueOf(&s)).Field(0).Interface()
892         if v != s.W.(interface{}) {
893                 t.Error("Interface() on interface: ", v, s.W)
894         }
895 }
896
897 func TestNilPtrValueSub(t *testing.T) {
898         var pi *int
899         if pv := ValueOf(pi); pv.Elem().IsValid() {
900                 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
901         }
902 }
903
904 func TestMap(t *testing.T) {
905         m := map[string]int{"a": 1, "b": 2}
906         mv := ValueOf(m)
907         if n := mv.Len(); n != len(m) {
908                 t.Errorf("Len = %d, want %d", n, len(m))
909         }
910         keys := mv.MapKeys()
911         newmap := MakeMap(mv.Type())
912         for k, v := range m {
913                 // Check that returned Keys match keys in range.
914                 // These aren't required to be in the same order.
915                 seen := false
916                 for _, kv := range keys {
917                         if kv.String() == k {
918                                 seen = true
919                                 break
920                         }
921                 }
922                 if !seen {
923                         t.Errorf("Missing key %q", k)
924                 }
925
926                 // Check that value lookup is correct.
927                 vv := mv.MapIndex(ValueOf(k))
928                 if vi := vv.Int(); vi != int64(v) {
929                         t.Errorf("Key %q: have value %d, want %d", k, vi, v)
930                 }
931
932                 // Copy into new map.
933                 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
934         }
935         vv := mv.MapIndex(ValueOf("not-present"))
936         if vv.IsValid() {
937                 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
938         }
939
940         newm := newmap.Interface().(map[string]int)
941         if len(newm) != len(m) {
942                 t.Errorf("length after copy: newm=%d, m=%d", newm, m)
943         }
944
945         for k, v := range newm {
946                 mv, ok := m[k]
947                 if mv != v {
948                         t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
949                 }
950         }
951
952         newmap.SetMapIndex(ValueOf("a"), Value{})
953         v, ok := newm["a"]
954         if ok {
955                 t.Errorf("newm[\"a\"] = %d after delete", v)
956         }
957
958         mv = ValueOf(&m).Elem()
959         mv.Set(Zero(mv.Type()))
960         if m != nil {
961                 t.Errorf("mv.Set(nil) failed")
962         }
963 }
964
965 func TestChan(t *testing.T) {
966         for loop := 0; loop < 2; loop++ {
967                 var c chan int
968                 var cv Value
969
970                 // check both ways to allocate channels
971                 switch loop {
972                 case 1:
973                         c = make(chan int, 1)
974                         cv = ValueOf(c)
975                 case 0:
976                         cv = MakeChan(TypeOf(c), 1)
977                         c = cv.Interface().(chan int)
978                 }
979
980                 // Send
981                 cv.Send(ValueOf(2))
982                 if i := <-c; i != 2 {
983                         t.Errorf("reflect Send 2, native recv %d", i)
984                 }
985
986                 // Recv
987                 c <- 3
988                 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
989                         t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
990                 }
991
992                 // TryRecv fail
993                 val, ok := cv.TryRecv()
994                 if val.IsValid() || ok {
995                         t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
996                 }
997
998                 // TryRecv success
999                 c <- 4
1000                 val, ok = cv.TryRecv()
1001                 if !val.IsValid() {
1002                         t.Errorf("TryRecv on ready chan got nil")
1003                 } else if i := val.Int(); i != 4 || !ok {
1004                         t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1005                 }
1006
1007                 // TrySend fail
1008                 c <- 100
1009                 ok = cv.TrySend(ValueOf(5))
1010                 i := <-c
1011                 if ok {
1012                         t.Errorf("TrySend on full chan succeeded: value %d", i)
1013                 }
1014
1015                 // TrySend success
1016                 ok = cv.TrySend(ValueOf(6))
1017                 if !ok {
1018                         t.Errorf("TrySend on empty chan failed")
1019                 } else {
1020                         if i = <-c; i != 6 {
1021                                 t.Errorf("TrySend 6, recv %d", i)
1022                         }
1023                 }
1024
1025                 // Close
1026                 c <- 123
1027                 cv.Close()
1028                 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1029                         t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1030                 }
1031                 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1032                         t.Errorf("after close Recv %d, %t", i.Int(), ok)
1033                 }
1034         }
1035
1036         // check creation of unbuffered channel
1037         var c chan int
1038         cv := MakeChan(TypeOf(c), 0)
1039         c = cv.Interface().(chan int)
1040         if cv.TrySend(ValueOf(7)) {
1041                 t.Errorf("TrySend on sync chan succeeded")
1042         }
1043         if v, ok := cv.TryRecv(); v.IsValid() || ok {
1044                 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1045         }
1046
1047         // len/cap
1048         cv = MakeChan(TypeOf(c), 10)
1049         c = cv.Interface().(chan int)
1050         for i := 0; i < 3; i++ {
1051                 c <- i
1052         }
1053         if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1054                 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1055         }
1056
1057 }
1058
1059 // Difficult test for function call because of
1060 // implicit padding between arguments.
1061 func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1062         return b, c, d
1063 }
1064
1065 func TestFunc(t *testing.T) {
1066         ret := ValueOf(dummy).Call([]Value{ValueOf(byte(10)), ValueOf(20), ValueOf(byte(30))})
1067         if len(ret) != 3 {
1068                 t.Fatalf("Call returned %d values, want 3", len(ret))
1069         }
1070
1071         i := byte(ret[0].Uint())
1072         j := int(ret[1].Int())
1073         k := byte(ret[2].Uint())
1074         if i != 10 || j != 20 || k != 30 {
1075                 t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1076         }
1077 }
1078
1079 type Point struct {
1080         x, y int
1081 }
1082
1083 // This will be index 0.
1084 func (p Point) AnotherMethod(scale int) int {
1085         return -1
1086 }
1087
1088 // This will be index 1.
1089 func (p Point) Dist(scale int) int {
1090         //      println("Point.Dist", p.x, p.y, scale)
1091         return p.x*p.x*scale + p.y*p.y*scale
1092 }
1093
1094 func TestMethod(t *testing.T) {
1095         // Non-curried method of type.
1096         p := Point{3, 4}
1097         i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1098         if i != 250 {
1099                 t.Errorf("Type Method returned %d; want 250", i)
1100         }
1101
1102         m, ok := TypeOf(p).MethodByName("Dist")
1103         if !ok {
1104                 t.Fatalf("method by name failed")
1105         }
1106         m.Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1107         if i != 250 {
1108                 t.Errorf("Type MethodByName returned %d; want 250", i)
1109         }
1110
1111         i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1112         if i != 250 {
1113                 t.Errorf("Pointer Type Method returned %d; want 250", i)
1114         }
1115
1116         m, ok = TypeOf(&p).MethodByName("Dist")
1117         if !ok {
1118                 t.Fatalf("ptr method by name failed")
1119         }
1120         i = m.Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1121         if i != 250 {
1122                 t.Errorf("Pointer Type MethodByName returned %d; want 250", i)
1123         }
1124
1125         // Curried method of value.
1126         tfunc := TypeOf(func(int) int(nil))
1127         v := ValueOf(p).Method(1)
1128         if tt := v.Type(); tt != tfunc {
1129                 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1130         }
1131         i = v.Call([]Value{ValueOf(10)})[0].Int()
1132         if i != 250 {
1133                 t.Errorf("Value Method returned %d; want 250", i)
1134         }
1135         v = ValueOf(p).MethodByName("Dist")
1136         if tt := v.Type(); tt != tfunc {
1137                 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1138         }
1139         i = v.Call([]Value{ValueOf(10)})[0].Int()
1140         if i != 250 {
1141                 t.Errorf("Value MethodByName returned %d; want 250", i)
1142         }
1143
1144         // Curried method of pointer.
1145         v = ValueOf(&p).Method(1)
1146         if tt := v.Type(); tt != tfunc {
1147                 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1148         }
1149         i = v.Call([]Value{ValueOf(10)})[0].Int()
1150         if i != 250 {
1151                 t.Errorf("Pointer Value Method returned %d; want 250", i)
1152         }
1153         v = ValueOf(&p).MethodByName("Dist")
1154         if tt := v.Type(); tt != tfunc {
1155                 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1156         }
1157         i = v.Call([]Value{ValueOf(10)})[0].Int()
1158         if i != 250 {
1159                 t.Errorf("Pointer Value MethodByName returned %d; want 250", i)
1160         }
1161
1162         // Curried method of interface value.
1163         // Have to wrap interface value in a struct to get at it.
1164         // Passing it to ValueOf directly would
1165         // access the underlying Point, not the interface.
1166         var s = struct {
1167                 X interface {
1168                         Dist(int) int
1169                 }
1170         }{p}
1171         pv := ValueOf(s).Field(0)
1172         v = pv.Method(0)
1173         if tt := v.Type(); tt != tfunc {
1174                 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1175         }
1176         i = v.Call([]Value{ValueOf(10)})[0].Int()
1177         if i != 250 {
1178                 t.Errorf("Interface Method returned %d; want 250", i)
1179         }
1180         v = pv.MethodByName("Dist")
1181         if tt := v.Type(); tt != tfunc {
1182                 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1183         }
1184         i = v.Call([]Value{ValueOf(10)})[0].Int()
1185         if i != 250 {
1186                 t.Errorf("Interface MethodByName returned %d; want 250", i)
1187         }
1188 }
1189
1190 func TestInterfaceSet(t *testing.T) {
1191         p := &Point{3, 4}
1192
1193         var s struct {
1194                 I interface{}
1195                 P interface {
1196                         Dist(int) int
1197                 }
1198         }
1199         sv := ValueOf(&s).Elem()
1200         sv.Field(0).Set(ValueOf(p))
1201         if q := s.I.(*Point); q != p {
1202                 t.Errorf("i: have %p want %p", q, p)
1203         }
1204
1205         pv := sv.Field(1)
1206         pv.Set(ValueOf(p))
1207         if q := s.P.(*Point); q != p {
1208                 t.Errorf("i: have %p want %p", q, p)
1209         }
1210
1211         i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1212         if i != 250 {
1213                 t.Errorf("Interface Method returned %d; want 250", i)
1214         }
1215 }
1216
1217 type T1 struct {
1218         a string
1219         int
1220 }
1221
1222 func TestAnonymousFields(t *testing.T) {
1223         var field StructField
1224         var ok bool
1225         var t1 T1
1226         type1 := TypeOf(t1)
1227         if field, ok = type1.FieldByName("int"); !ok {
1228                 t.Error("no field 'int'")
1229         }
1230         if field.Index[0] != 1 {
1231                 t.Error("field index should be 1; is", field.Index)
1232         }
1233 }
1234
1235 type FTest struct {
1236         s     interface{}
1237         name  string
1238         index []int
1239         value int
1240 }
1241
1242 type D1 struct {
1243         d int
1244 }
1245 type D2 struct {
1246         d int
1247 }
1248
1249 type S0 struct {
1250         A, B, C int
1251         D1
1252         D2
1253 }
1254
1255 type S1 struct {
1256         B int
1257         S0
1258 }
1259
1260 type S2 struct {
1261         A int
1262         *S1
1263 }
1264
1265 type S1x struct {
1266         S1
1267 }
1268
1269 type S1y struct {
1270         S1
1271 }
1272
1273 type S3 struct {
1274         S1x
1275         S2
1276         D, E int
1277         *S1y
1278 }
1279
1280 type S4 struct {
1281         *S4
1282         A int
1283 }
1284
1285 var fieldTests = []FTest{
1286         {struct{}{}, "", nil, 0},
1287         {struct{}{}, "Foo", nil, 0},
1288         {S0{A: 'a'}, "A", []int{0}, 'a'},
1289         {S0{}, "D", nil, 0},
1290         {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
1291         {S1{B: 'b'}, "B", []int{0}, 'b'},
1292         {S1{}, "S0", []int{1}, 0},
1293         {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
1294         {S2{A: 'a'}, "A", []int{0}, 'a'},
1295         {S2{}, "S1", []int{1}, 0},
1296         {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
1297         {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
1298         {S2{}, "D", nil, 0},
1299         {S3{}, "S1", nil, 0},
1300         {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
1301         {S3{}, "B", nil, 0},
1302         {S3{D: 'd'}, "D", []int{2}, 0},
1303         {S3{E: 'e'}, "E", []int{3}, 'e'},
1304         {S4{A: 'a'}, "A", []int{1}, 'a'},
1305         {S4{}, "B", nil, 0},
1306 }
1307
1308 func TestFieldByIndex(t *testing.T) {
1309         for _, test := range fieldTests {
1310                 s := TypeOf(test.s)
1311                 f := s.FieldByIndex(test.index)
1312                 if f.Name != "" {
1313                         if test.index != nil {
1314                                 if f.Name != test.name {
1315                                         t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1316                                 }
1317                         } else {
1318                                 t.Errorf("%s.%s found", s.Name(), f.Name)
1319                         }
1320                 } else if len(test.index) > 0 {
1321                         t.Errorf("%s.%s not found", s.Name(), test.name)
1322                 }
1323
1324                 if test.value != 0 {
1325                         v := ValueOf(test.s).FieldByIndex(test.index)
1326                         if v.IsValid() {
1327                                 if x, ok := v.Interface().(int); ok {
1328                                         if x != test.value {
1329                                                 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1330                                         }
1331                                 } else {
1332                                         t.Errorf("%s%v value not an int", s.Name(), test.index)
1333                                 }
1334                         } else {
1335                                 t.Errorf("%s%v value not found", s.Name(), test.index)
1336                         }
1337                 }
1338         }
1339 }
1340
1341 func TestFieldByName(t *testing.T) {
1342         for _, test := range fieldTests {
1343                 s := TypeOf(test.s)
1344                 f, found := s.FieldByName(test.name)
1345                 if found {
1346                         if test.index != nil {
1347                                 // Verify field depth and index.
1348                                 if len(f.Index) != len(test.index) {
1349                                         t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1350                                 } else {
1351                                         for i, x := range f.Index {
1352                                                 if x != test.index[i] {
1353                                                         t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1354                                                 }
1355                                         }
1356                                 }
1357                         } else {
1358                                 t.Errorf("%s.%s found", s.Name(), f.Name)
1359                         }
1360                 } else if len(test.index) > 0 {
1361                         t.Errorf("%s.%s not found", s.Name(), test.name)
1362                 }
1363
1364                 if test.value != 0 {
1365                         v := ValueOf(test.s).FieldByName(test.name)
1366                         if v.IsValid() {
1367                                 if x, ok := v.Interface().(int); ok {
1368                                         if x != test.value {
1369                                                 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1370                                         }
1371                                 } else {
1372                                         t.Errorf("%s.%s value not an int", s.Name(), test.name)
1373                                 }
1374                         } else {
1375                                 t.Errorf("%s.%s value not found", s.Name(), test.name)
1376                         }
1377                 }
1378         }
1379 }
1380
1381 func TestImportPath(t *testing.T) {
1382         tests := []struct {
1383                 t    Type
1384                 path string
1385         }{
1386                 {TypeOf(&base64.Encoding{}).Elem(), "libgo_encoding.base64"},
1387                 {TypeOf(uint(0)), ""},
1388                 {TypeOf(map[string]int{}), ""},
1389                 {TypeOf((*error)(nil)).Elem(), ""},
1390         }
1391         for _, test := range tests {
1392                 if path := test.t.PkgPath(); path != test.path {
1393                         t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
1394                 }
1395         }
1396 }
1397
1398 func TestVariadicType(t *testing.T) {
1399         // Test example from Type documentation.
1400         var f func(x int, y ...float64)
1401         typ := TypeOf(f)
1402         if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
1403                 sl := typ.In(1)
1404                 if sl.Kind() == Slice {
1405                         if sl.Elem() == TypeOf(0.0) {
1406                                 // ok
1407                                 return
1408                         }
1409                 }
1410         }
1411
1412         // Failed
1413         t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
1414         s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1415         for i := 0; i < typ.NumIn(); i++ {
1416                 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1417         }
1418         t.Error(s)
1419 }
1420
1421 type inner struct {
1422         x int
1423 }
1424
1425 type outer struct {
1426         y int
1427         inner
1428 }
1429
1430 func (*inner) m() {}
1431 func (*outer) m() {}
1432
1433 func TestNestedMethods(t *testing.T) {
1434         typ := TypeOf((*outer)(nil))
1435         if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
1436                 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1437                 for i := 0; i < typ.NumMethod(); i++ {
1438                         m := typ.Method(i)
1439                         t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1440                 }
1441         }
1442 }
1443
1444 type InnerInt struct {
1445         X int
1446 }
1447
1448 type OuterInt struct {
1449         Y int
1450         InnerInt
1451 }
1452
1453 func (i *InnerInt) M() int {
1454         return i.X
1455 }
1456
1457 func TestEmbeddedMethods(t *testing.T) {
1458         typ := TypeOf((*OuterInt)(nil))
1459         if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
1460                 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
1461                 for i := 0; i < typ.NumMethod(); i++ {
1462                         m := typ.Method(i)
1463                         t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1464                 }
1465         }
1466
1467         i := &InnerInt{3}
1468         if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
1469                 t.Errorf("i.M() = %d, want 3", v)
1470         }
1471
1472         o := &OuterInt{1, InnerInt{2}}
1473         if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
1474                 t.Errorf("i.M() = %d, want 2", v)
1475         }
1476
1477         f := (*OuterInt).M
1478         if v := f(o); v != 2 {
1479                 t.Errorf("f(o) = %d, want 2", v)
1480         }
1481 }
1482
1483 func TestPtrTo(t *testing.T) {
1484         var i int
1485
1486         typ := TypeOf(i)
1487         for i = 0; i < 100; i++ {
1488                 typ = PtrTo(typ)
1489         }
1490         for i = 0; i < 100; i++ {
1491                 typ = typ.Elem()
1492         }
1493         if typ != TypeOf(i) {
1494                 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
1495         }
1496 }
1497
1498 func TestAddr(t *testing.T) {
1499         var p struct {
1500                 X, Y int
1501         }
1502
1503         v := ValueOf(&p)
1504         v = v.Elem()
1505         v = v.Addr()
1506         v = v.Elem()
1507         v = v.Field(0)
1508         v.SetInt(2)
1509         if p.X != 2 {
1510                 t.Errorf("Addr.Elem.Set failed to set value")
1511         }
1512
1513         // Again but take address of the ValueOf value.
1514         // Exercises generation of PtrTypes not present in the binary.
1515         q := &p
1516         v = ValueOf(&q).Elem()
1517         v = v.Addr()
1518         v = v.Elem()
1519         v = v.Elem()
1520         v = v.Addr()
1521         v = v.Elem()
1522         v = v.Field(0)
1523         v.SetInt(3)
1524         if p.X != 3 {
1525                 t.Errorf("Addr.Elem.Set failed to set value")
1526         }
1527
1528         // Starting without pointer we should get changed value
1529         // in interface.
1530         qq := p
1531         v = ValueOf(&qq).Elem()
1532         v0 := v
1533         v = v.Addr()
1534         v = v.Elem()
1535         v = v.Field(0)
1536         v.SetInt(4)
1537         if p.X != 3 { // should be unchanged from last time
1538                 t.Errorf("somehow value Set changed original p")
1539         }
1540         p = v0.Interface().(struct {
1541                 X, Y int
1542         })
1543         if p.X != 4 {
1544                 t.Errorf("Addr.Elem.Set valued to set value in top value")
1545         }
1546
1547         // Verify that taking the address of a type gives us a pointer
1548         // which we can convert back using the usual interface
1549         // notation.
1550         var s struct {
1551                 B *bool
1552         }
1553         ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
1554         *(ps.(**bool)) = new(bool)
1555         if s.B == nil {
1556                 t.Errorf("Addr.Interface direct assignment failed")
1557         }
1558 }
1559
1560 /* gccgo does do allocations here.
1561
1562 func noAlloc(t *testing.T, n int, f func(int)) {
1563         // once to prime everything
1564         f(-1)
1565         memstats := new(runtime.MemStats)
1566         runtime.ReadMemStats(memstats)
1567         oldmallocs := memstats.Mallocs
1568
1569         for j := 0; j < n; j++ {
1570                 f(j)
1571         }
1572         // A few allocs may happen in the testing package when GOMAXPROCS > 1, so don't
1573         // require zero mallocs.
1574         runtime.ReadMemStats(memstats)
1575         mallocs := memstats.Mallocs - oldmallocs
1576         if mallocs > 5 {
1577                 t.Fatalf("%d mallocs after %d iterations", mallocs, n)
1578         }
1579 }
1580
1581 func TestAllocations(t *testing.T) {
1582         noAlloc(t, 100, func(j int) {
1583                 var i interface{}
1584                 var v Value
1585                 i = 42 + j
1586                 v = ValueOf(i)
1587                 if int(v.Int()) != 42+j {
1588                         panic("wrong int")
1589                 }
1590         })
1591 }
1592
1593 */
1594
1595 func TestSmallNegativeInt(t *testing.T) {
1596         i := int16(-1)
1597         v := ValueOf(i)
1598         if v.Int() != -1 {
1599                 t.Errorf("int16(-1).Int() returned %v", v.Int())
1600         }
1601 }
1602
1603 func TestSlice(t *testing.T) {
1604         xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
1605         v := ValueOf(xs).Slice(3, 5).Interface().([]int)
1606         if len(v) != 2 {
1607                 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
1608         }
1609         if cap(v) != 5 {
1610                 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
1611         }
1612         if !DeepEqual(v[0:5], xs[3:]) {
1613                 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
1614         }
1615
1616         xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
1617         v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
1618         if len(v) != 3 {
1619                 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
1620         }
1621         if cap(v) != 6 {
1622                 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
1623         }
1624         if !DeepEqual(v[0:6], xa[2:]) {
1625                 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
1626         }
1627 }
1628
1629 func TestVariadic(t *testing.T) {
1630         var b bytes.Buffer
1631         V := ValueOf
1632
1633         b.Reset()
1634         V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
1635         if b.String() != "hello, 42 world" {
1636                 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
1637         }
1638
1639         b.Reset()
1640         V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
1641         if b.String() != "hello, 42 world" {
1642                 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
1643         }
1644 }
1645
1646 var tagGetTests = []struct {
1647         Tag   StructTag
1648         Key   string
1649         Value string
1650 }{
1651         {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
1652         {`protobuf:"PB(1,2)"`, `foo`, ``},
1653         {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
1654         {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
1655         {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
1656 }
1657
1658 func TestTagGet(t *testing.T) {
1659         for _, tt := range tagGetTests {
1660                 if v := tt.Tag.Get(tt.Key); v != tt.Value {
1661                         t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
1662                 }
1663         }
1664 }
1665
1666 func TestBytes(t *testing.T) {
1667         type B []byte
1668         x := B{1, 2, 3, 4}
1669         y := ValueOf(x).Bytes()
1670         if !bytes.Equal(x, y) {
1671                 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1672         }
1673         if &x[0] != &y[0] {
1674                 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1675         }
1676 }
1677
1678 func TestSetBytes(t *testing.T) {
1679         type B []byte
1680         var x B
1681         y := []byte{1, 2, 3, 4}
1682         ValueOf(&x).Elem().SetBytes(y)
1683         if !bytes.Equal(x, y) {
1684                 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1685         }
1686         if &x[0] != &y[0] {
1687                 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1688         }
1689 }
1690
1691 type Private struct {
1692         x int
1693         y **int
1694 }
1695
1696 func (p *Private) m() {
1697 }
1698
1699 type Public struct {
1700         X int
1701         Y **int
1702 }
1703
1704 func (p *Public) M() {
1705 }
1706
1707 func TestUnexported(t *testing.T) {
1708         var pub Public
1709         v := ValueOf(&pub)
1710         isValid(v.Elem().Field(0))
1711         isValid(v.Elem().Field(1))
1712         isValid(v.Elem().FieldByName("X"))
1713         isValid(v.Elem().FieldByName("Y"))
1714         isValid(v.Type().Method(0).Func)
1715         isNonNil(v.Elem().Field(0).Interface())
1716         isNonNil(v.Elem().Field(1).Interface())
1717         isNonNil(v.Elem().FieldByName("X").Interface())
1718         isNonNil(v.Elem().FieldByName("Y").Interface())
1719         isNonNil(v.Type().Method(0).Func.Interface())
1720
1721         var priv Private
1722         v = ValueOf(&priv)
1723         isValid(v.Elem().Field(0))
1724         isValid(v.Elem().Field(1))
1725         isValid(v.Elem().FieldByName("x"))
1726         isValid(v.Elem().FieldByName("y"))
1727         isValid(v.Type().Method(0).Func)
1728         shouldPanic(func() { v.Elem().Field(0).Interface() })
1729         shouldPanic(func() { v.Elem().Field(1).Interface() })
1730         shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
1731         shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
1732         shouldPanic(func() { v.Type().Method(0).Func.Interface() })
1733 }
1734
1735 func shouldPanic(f func()) {
1736         defer func() {
1737                 if recover() == nil {
1738                         panic("did not panic")
1739                 }
1740         }()
1741         f()
1742 }
1743
1744 func isNonNil(x interface{}) {
1745         if x == nil {
1746                 panic("nil interface")
1747         }
1748 }
1749
1750 func isValid(v Value) {
1751         if !v.IsValid() {
1752                 panic("zero Value")
1753         }
1754 }
1755
1756 func TestAlias(t *testing.T) {
1757         x := string("hello")
1758         v := ValueOf(&x).Elem()
1759         oldvalue := v.Interface()
1760         v.SetString("world")
1761         newvalue := v.Interface()
1762
1763         if oldvalue != "hello" || newvalue != "world" {
1764                 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
1765         }
1766 }