OSDN Git Service

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