]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/reflect/all_test.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.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 "container/vector"
9 "fmt"
10 "io"
11 "os"
12 . "reflect"
13 "testing"
14 "unsafe"
15 )
16
17 type integer int
18 type T struct {
19 a int
20 b float64
21 c string
22 d *int
23 }
24
25 type pair struct {
26 i interface{}
27 s string
28 }
29
30 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
31
32 func assert(t *testing.T, s, want string) {
33 if s != want {
34 t.Errorf("have %#q want %#q", s, want)
35 }
36 }
37
38 func typestring(i interface{}) string { return Typeof(i).String() }
39
40 var typeTests = []pair{
41 {struct{ x int }{}, "int"},
42 {struct{ x int8 }{}, "int8"},
43 {struct{ x int16 }{}, "int16"},
44 {struct{ x int32 }{}, "int32"},
45 {struct{ x int64 }{}, "int64"},
46 {struct{ x uint }{}, "uint"},
47 {struct{ x uint8 }{}, "uint8"},
48 {struct{ x uint16 }{}, "uint16"},
49 {struct{ x uint32 }{}, "uint32"},
50 {struct{ x uint64 }{}, "uint64"},
51 {struct{ x float }{}, "float"},
52 {struct{ x float32 }{}, "float32"},
53 {struct{ x float64 }{}, "float64"},
54 {struct{ x int8 }{}, "int8"},
55 {struct{ x (**int8) }{}, "**int8"},
56 {struct{ x (**integer) }{}, "**reflect_test.integer"},
57 {struct{ x ([32]int32) }{}, "[32]int32"},
58 {struct{ x ([]int8) }{}, "[]int8"},
59 {struct{ x (map[string]int32) }{}, "map[string] int32"},
60 {struct{ x (chan<- string) }{}, "chan<- string"},
61 {struct {
62 x struct {
63 c chan *int32
64 d float32
65 }
66 }{},
67 "struct { c chan *int32; d float32 }",
68 },
69 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
70 {struct {
71 x struct {
72 c func(chan *integer, *int8)
73 }
74 }{},
75 "struct { c func(chan *reflect_test.integer, *int8) }",
76 },
77 {struct {
78 x struct {
79 a int8
80 b int32
81 }
82 }{},
83 "struct { a int8; b int32 }",
84 },
85 {struct {
86 x struct {
87 a int8
88 b int8
89 c int32
90 }
91 }{},
92 "struct { a int8; b int8; c int32 }",
93 },
94 {struct {
95 x struct {
96 a int8
97 b int8
98 c int8
99 d int32
100 }
101 }{},
102 "struct { a int8; b int8; c int8; d int32 }",
103 },
104 {struct {
105 x struct {
106 a int8
107 b int8
108 c int8
109 d int8
110 e int32
111 }
112 }{},
113 "struct { a int8; b int8; c int8; d int8; e int32 }",
114 },
115 {struct {
116 x struct {
117 a int8
118 b int8
119 c int8
120 d int8
121 e int8
122 f int32
123 }
124 }{},
125 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
126 },
127 {struct {
128 x struct {
129 a int8 "hi there"
130 }
131 }{},
132 `struct { a int8 "hi there" }`,
133 },
134 {struct {
135 x struct {
136 a int8 "hi \x00there\t\n\"\\"
137 }
138 }{},
139 `struct { a int8 "hi \x00there\t\n\"\\" }`,
140 },
141 {struct {
142 x struct {
143 f func(args ...int)
144 }
145 }{},
146 "struct { f func(...int) }",
147 },
148 {struct {
149 x (interface {
150 a(func(func(int) int) func(func(int)) int)
151 b()
152 })
153 }{},
154 "interface { a(func(func(int) int) func(func(int)) int); b() }",
155 },
156 }
157
158 var valueTests = []pair{
159 {(int8)(0), "8"},
160 {(int16)(0), "16"},
161 {(int32)(0), "32"},
162 {(int64)(0), "64"},
163 {(uint8)(0), "8"},
164 {(uint16)(0), "16"},
165 {(uint32)(0), "32"},
166 {(uint64)(0), "64"},
167 {(float32)(0), "256.25"},
168 {(float64)(0), "512.125"},
169 {(string)(""), "stringy cheese"},
170 {(bool)(false), "true"},
171 {(*int8)(nil), "*int8(0)"},
172 {(**int8)(nil), "**int8(0)"},
173 {[5]int32{}, "[5]int32{0, 0, 0, 0, 0}"},
174 {(**integer)(nil), "**reflect_test.integer(0)"},
175 {(map[string]int32)(nil), "map[string] int32{<can't iterate on maps>}"},
176 {(chan<- string)(nil), "chan<- string"},
177 {struct {
178 c chan *int32
179 d float32
180 }{},
181 "struct { c chan *int32; d float32 }{chan *int32, 0}",
182 },
183 {(func(a int8, b int32))(nil), "func(int8, int32)(0)"},
184 {struct{ c func(chan *integer, *int8) }{},
185 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
186 },
187 {struct {
188 a int8
189 b int32
190 }{},
191 "struct { a int8; b int32 }{0, 0}",
192 },
193 {struct {
194 a int8
195 b int8
196 c int32
197 }{},
198 "struct { a int8; b int8; c int32 }{0, 0, 0}",
199 },
200 }
201
202 func testType(t *testing.T, i int, typ Type, want string) {
203 s := typ.String()
204 if s != want {
205 t.Errorf("#%d: have %#q, want %#q", i, s, want)
206 }
207 }
208
209 func TestTypes(t *testing.T) {
210 for i, tt := range typeTests {
211 testType(t, i, NewValue(tt.i).(*StructValue).Field(0).Type(), tt.s)
212 }
213 }
214
215 func TestSet(t *testing.T) {
216 for i, tt := range valueTests {
217 v := NewValue(tt.i)
218 switch v := v.(type) {
219 case *IntValue:
220 switch v.Type().Kind() {
221 case Int:
222 v.Set(132)
223 case Int8:
224 v.Set(8)
225 case Int16:
226 v.Set(16)
227 case Int32:
228 v.Set(32)
229 case Int64:
230 v.Set(64)
231 }
232 case *UintValue:
233 switch v.Type().Kind() {
234 case Uint:
235 v.Set(132)
236 case Uint8:
237 v.Set(8)
238 case Uint16:
239 v.Set(16)
240 case Uint32:
241 v.Set(32)
242 case Uint64:
243 v.Set(64)
244 }
245 case *FloatValue:
246 switch v.Type().Kind() {
247 case Float:
248 v.Set(128.5)
249 case Float32:
250 v.Set(256.25)
251 case Float64:
252 v.Set(512.125)
253 }
254 case *ComplexValue:
255 switch v.Type().Kind() {
256 case Complex:
257 v.Set(53200.0 + 100i)
258 case Complex64:
259 v.Set(532.125 + 10i)
260 case Complex128:
261 v.Set(564.25 + 1i)
262 }
263 case *StringValue:
264 v.Set("stringy cheese")
265 case *BoolValue:
266 v.Set(true)
267 }
268 s := valueToString(v)
269 if s != tt.s {
270 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
271 }
272 }
273 }
274
275 func TestSetValue(t *testing.T) {
276 for i, tt := range valueTests {
277 v := NewValue(tt.i)
278 switch v := v.(type) {
279 case *IntValue:
280 switch v.Type().Kind() {
281 case Int:
282 v.SetValue(NewValue(int(132)))
283 case Int8:
284 v.SetValue(NewValue(int8(8)))
285 case Int16:
286 v.SetValue(NewValue(int16(16)))
287 case Int32:
288 v.SetValue(NewValue(int32(32)))
289 case Int64:
290 v.SetValue(NewValue(int64(64)))
291 }
292 case *UintValue:
293 switch v.Type().Kind() {
294 case Uint:
295 v.SetValue(NewValue(uint(132)))
296 case Uint8:
297 v.SetValue(NewValue(uint8(8)))
298 case Uint16:
299 v.SetValue(NewValue(uint16(16)))
300 case Uint32:
301 v.SetValue(NewValue(uint32(32)))
302 case Uint64:
303 v.SetValue(NewValue(uint64(64)))
304 }
305 case *FloatValue:
306 switch v.Type().Kind() {
307 case Float:
308 v.SetValue(NewValue(float(128.5)))
309 case Float32:
310 v.SetValue(NewValue(float32(256.25)))
311 case Float64:
312 v.SetValue(NewValue(float64(512.125)))
313 }
314 case *ComplexValue:
315 switch v.Type().Kind() {
316 case Complex:
317 v.SetValue(NewValue(complex(53200.0 + 100i)))
318 case Complex64:
319 v.SetValue(NewValue(complex64(532.125 + 10i)))
320 case Complex128:
321 v.SetValue(NewValue(complex128(564.25 + 1i)))
322 }
323
324 case *StringValue:
325 v.SetValue(NewValue("stringy cheese"))
326 case *BoolValue:
327 v.SetValue(NewValue(true))
328 }
329 s := valueToString(v)
330 if s != tt.s {
331 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
332 }
333 }
334 }
335
336 var _i = 7
337
338 var valueToStringTests = []pair{
339 {123, "123"},
340 {123.5, "123.5"},
341 {byte(123), "123"},
342 {"abc", "abc"},
343 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
344 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
345 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
346 {&[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})"},
347 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
348 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
349 }
350
351 func TestValueToString(t *testing.T) {
352 for i, test := range valueToStringTests {
353 s := valueToString(NewValue(test.i))
354 if s != test.s {
355 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
356 }
357 }
358 }
359
360 func TestArrayElemSet(t *testing.T) {
361 v := NewValue([10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
362 v.(*ArrayValue).Elem(4).(*IntValue).Set(123)
363 s := valueToString(v)
364 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
365 if s != want {
366 t.Errorf("[10]int: have %#q want %#q", s, want)
367 }
368
369 v = NewValue([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
370 v.(*SliceValue).Elem(4).(*IntValue).Set(123)
371 s = valueToString(v)
372 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
373 if s != want1 {
374 t.Errorf("[]int: have %#q want %#q", s, want1)
375 }
376 }
377
378 func TestPtrPointTo(t *testing.T) {
379 var ip *int32
380 var i int32 = 1234
381 vip := NewValue(&ip)
382 vi := NewValue(i)
383 vip.(*PtrValue).Elem().(*PtrValue).PointTo(vi)
384 if *ip != 1234 {
385 t.Errorf("got %d, want 1234", *ip)
386 }
387
388 ip = nil
389 vp := NewValue(ip).(*PtrValue)
390 vp.PointTo(vp.Elem())
391 if ip != nil {
392 t.Errorf("got non-nil (%p), want nil", ip)
393 }
394 }
395
396 func TestPtrSetNil(t *testing.T) {
397 var i int32 = 1234
398 ip := &i
399 vip := NewValue(&ip)
400 vip.(*PtrValue).Elem().(*PtrValue).Set(nil)
401 if ip != nil {
402 t.Errorf("got non-nil (%d), want nil", *ip)
403 }
404 }
405
406 func TestMapSetNil(t *testing.T) {
407 m := make(map[string]int)
408 vm := NewValue(&m)
409 vm.(*PtrValue).Elem().(*MapValue).Set(nil)
410 if m != nil {
411 t.Errorf("got non-nil (%p), want nil", m)
412 }
413 }
414
415
416 func TestAll(t *testing.T) {
417 testType(t, 1, Typeof((int8)(0)), "int8")
418 testType(t, 2, Typeof((*int8)(nil)).(*PtrType).Elem(), "int8")
419
420 typ := Typeof((*struct {
421 c chan *int32
422 d float32
423 })(nil))
424 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
425 etyp := typ.(*PtrType).Elem()
426 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
427 styp := etyp.(*StructType)
428 f := styp.Field(0)
429 testType(t, 5, f.Type, "chan *int32")
430
431 f, present := styp.FieldByName("d")
432 if !present {
433 t.Errorf("FieldByName says present field is absent")
434 }
435 testType(t, 6, f.Type, "float32")
436
437 f, present = styp.FieldByName("absent")
438 if present {
439 t.Errorf("FieldByName says absent field is present")
440 }
441
442 typ = Typeof([32]int32{})
443 testType(t, 7, typ, "[32]int32")
444 testType(t, 8, typ.(*ArrayType).Elem(), "int32")
445
446 typ = Typeof((map[string]*int32)(nil))
447 testType(t, 9, typ, "map[string] *int32")
448 mtyp := typ.(*MapType)
449 testType(t, 10, mtyp.Key(), "string")
450 testType(t, 11, mtyp.Elem(), "*int32")
451
452 typ = Typeof((chan<- string)(nil))
453 testType(t, 12, typ, "chan<- string")
454 testType(t, 13, typ.(*ChanType).Elem(), "string")
455
456 // make sure tag strings are not part of element type
457 typ = Typeof(struct {
458 d []uint32 "TAG"
459 }{}).(*StructType).Field(0).Type
460 testType(t, 14, typ, "[]uint32")
461 }
462
463 func TestInterfaceGet(t *testing.T) {
464 var inter struct {
465 e interface{}
466 }
467 inter.e = 123.456
468 v1 := NewValue(&inter)
469 v2 := v1.(*PtrValue).Elem().(*StructValue).Field(0)
470 assert(t, v2.Type().String(), "interface { }")
471 i2 := v2.(*InterfaceValue).Interface()
472 v3 := NewValue(i2)
473 assert(t, v3.Type().String(), "float")
474 }
475
476 func TestInterfaceValue(t *testing.T) {
477 var inter struct {
478 e interface{}
479 }
480 inter.e = 123.456
481 v1 := NewValue(&inter)
482 v2 := v1.(*PtrValue).Elem().(*StructValue).Field(0)
483 assert(t, v2.Type().String(), "interface { }")
484 v3 := v2.(*InterfaceValue).Elem()
485 assert(t, v3.Type().String(), "float")
486
487 i3 := v2.Interface()
488 if _, ok := i3.(float); !ok {
489 t.Error("v2.Interface() did not return float, got ", Typeof(i3))
490 }
491 }
492
493 func TestFunctionValue(t *testing.T) {
494 v := NewValue(func() {})
495 if v.Interface() != v.Interface() {
496 t.Fatalf("TestFunction != itself")
497 }
498 assert(t, v.Type().String(), "func()")
499 }
500
501 func TestCopyArray(t *testing.T) {
502 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
503 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
504 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
505 va := NewValue(&a)
506 vb := NewValue(&b)
507 for i := 0; i < len(b); i++ {
508 if b[i] != c[i] {
509 t.Fatalf("b != c before test")
510 }
511 }
512 aa := va.(*PtrValue).Elem().(*SliceValue)
513 ab := vb.(*PtrValue).Elem().(*SliceValue)
514 for tocopy := 1; tocopy <= 7; tocopy++ {
515 aa.SetLen(tocopy)
516 ArrayCopy(ab, aa)
517 aa.SetLen(8)
518 for i := 0; i < tocopy; i++ {
519 if a[i] != b[i] {
520 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
521 tocopy, i, a[i], i, b[i])
522 }
523 }
524 for i := tocopy; i < len(b); i++ {
525 if b[i] != c[i] {
526 if i < len(a) {
527 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
528 tocopy, i, a[i], i, b[i], i, c[i])
529 } else {
530 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
531 tocopy, i, b[i], i, c[i])
532 }
533 } else {
534 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
535 }
536 }
537 }
538 }
539
540 func TestBigUnnamedStruct(t *testing.T) {
541 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
542 v := NewValue(b)
543 b1 := v.Interface().(struct {
544 a, b, c, d int64
545 })
546 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
547 t.Errorf("NewValue(%v).Interface().(*Big) = %v", b, b1)
548 }
549 }
550
551 type big struct {
552 a, b, c, d, e int64
553 }
554
555 func TestBigStruct(t *testing.T) {
556 b := big{1, 2, 3, 4, 5}
557 v := NewValue(b)
558 b1 := v.Interface().(big)
559 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
560 t.Errorf("NewValue(%v).Interface().(big) = %v", b, b1)
561 }
562 }
563
564 type Basic struct {
565 x int
566 y float32
567 }
568
569 type NotBasic Basic
570
571 type DeepEqualTest struct {
572 a, b interface{}
573 eq bool
574 }
575
576 var deepEqualTests = []DeepEqualTest{
577 // Equalities
578 {1, 1, true},
579 {int32(1), int32(1), true},
580 {0.5, 0.5, true},
581 {float32(0.5), float32(0.5), true},
582 {"hello", "hello", true},
583 {make([]int, 10), make([]int, 10), true},
584 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
585 {Basic{1, 0.5}, Basic{1, 0.5}, true},
586 {os.Error(nil), os.Error(nil), true},
587 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
588
589 // Inequalities
590 {1, 2, false},
591 {int32(1), int32(2), false},
592 {0.5, 0.6, false},
593 {float32(0.5), float32(0.6), false},
594 {"hello", "hey", false},
595 {make([]int, 10), make([]int, 11), false},
596 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
597 {Basic{1, 0.5}, Basic{1, 0.6}, false},
598 {Basic{1, 0}, Basic{2, 0}, false},
599 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
600 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
601 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
602 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
603 {nil, 1, false},
604 {1, nil, false},
605
606 // Mismatched types
607 {1, 1.0, false},
608 {int32(1), int64(1), false},
609 {0.5, "hello", false},
610 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
611 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
612 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
613 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
614 }
615
616 func TestDeepEqual(t *testing.T) {
617 for _, test := range deepEqualTests {
618 if r := DeepEqual(test.a, test.b); r != test.eq {
619 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
620 }
621 }
622 }
623
624 func TestTypeof(t *testing.T) {
625 for _, test := range deepEqualTests {
626 v := NewValue(test.a)
627 if v == nil {
628 continue
629 }
630 typ := Typeof(test.a)
631 if typ != v.Type() {
632 t.Errorf("Typeof(%v) = %v, but NewValue(%v).Type() = %v", test.a, typ, test.a, v.Type())
633 }
634 }
635 }
636
637 type Recursive struct {
638 x int
639 r *Recursive
640 }
641
642 func TestDeepEqualRecursiveStruct(t *testing.T) {
643 a, b := new(Recursive), new(Recursive)
644 *a = Recursive{12, a}
645 *b = Recursive{12, b}
646 if !DeepEqual(a, b) {
647 t.Error("DeepEqual(recursive same) = false, want true")
648 }
649 }
650
651 type _Complex struct {
652 a int
653 b [3]*_Complex
654 c *string
655 d map[float]float
656 }
657
658 func TestDeepEqualComplexStruct(t *testing.T) {
659 m := make(map[float]float)
660 stra, strb := "hello", "hello"
661 a, b := new(_Complex), new(_Complex)
662 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
663 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
664 if !DeepEqual(a, b) {
665 t.Error("DeepEqual(complex same) = false, want true")
666 }
667 }
668
669 func TestDeepEqualComplexStructInequality(t *testing.T) {
670 m := make(map[float]float)
671 stra, strb := "hello", "helloo" // Difference is here
672 a, b := new(_Complex), new(_Complex)
673 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
674 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
675 if DeepEqual(a, b) {
676 t.Error("DeepEqual(complex different) = true, want false")
677 }
678 }
679
680
681 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
682 s := NewValue(x).(*StructValue)
683 f := s.Type().(*StructType).Field(1)
684 if f.Offset != offs {
685 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
686 }
687 }
688
689 // Check that structure alignment & offsets viewed through reflect agree with those
690 // from the compiler itself.
691 func TestAlignment(t *testing.T) {
692 type T1inner struct {
693 a int
694 }
695 type T1 struct {
696 T1inner
697 f int
698 }
699 type T2inner struct {
700 a, b int
701 }
702 type T2 struct {
703 T2inner
704 f int
705 }
706
707 x := T1{T1inner{2}, 17}
708 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
709
710 x1 := T2{T2inner{2, 3}, 17}
711 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
712 }
713
714 type IsNiller interface {
715 IsNil() bool
716 }
717
718 func Nil(a interface{}, t *testing.T) {
719 n := NewValue(a).(*StructValue).Field(0).(IsNiller)
720 if !n.IsNil() {
721 t.Errorf("%v should be nil", a)
722 }
723 }
724
725 func NotNil(a interface{}, t *testing.T) {
726 n := NewValue(a).(*StructValue).Field(0).(IsNiller)
727 if n.IsNil() {
728 t.Errorf("value of type %v should not be nil", NewValue(a).Type().String())
729 }
730 }
731
732 func TestIsNil(t *testing.T) {
733 // These do not implement IsNil
734 doNotNil := []interface{}{int(0), float32(0), struct{ a int }{}}
735 for _, ts := range doNotNil {
736 ty := Typeof(ts)
737 v := MakeZero(ty)
738 if _, ok := v.(IsNiller); ok {
739 t.Errorf("%s is nilable; should not be", ts)
740 }
741 }
742
743 // These do implement IsNil.
744 // Wrap in extra struct to hide interface type.
745 doNil := []interface{}{
746 struct{ x *int }{},
747 struct{ x interface{} }{},
748 struct{ x map[string]int }{},
749 struct{ x func() bool }{},
750 struct{ x chan int }{},
751 struct{ x []string }{},
752 }
753 for _, ts := range doNil {
754 ty := Typeof(ts).(*StructType).Field(0).Type
755 v := MakeZero(ty)
756 if _, ok := v.(IsNiller); !ok {
757 t.Errorf("%s %T is not nilable; should be", ts, v)
758 }
759 }
760
761 // Check the implementations
762 var pi struct {
763 x *int
764 }
765 Nil(pi, t)
766 pi.x = new(int)
767 NotNil(pi, t)
768
769 var si struct {
770 x []int
771 }
772 Nil(si, t)
773 si.x = make([]int, 10)
774 NotNil(si, t)
775
776 var ci struct {
777 x chan int
778 }
779 Nil(ci, t)
780 ci.x = make(chan int)
781 NotNil(ci, t)
782
783 var mi struct {
784 x map[int]int
785 }
786 Nil(mi, t)
787 mi.x = make(map[int]int)
788 NotNil(mi, t)
789
790 var ii struct {
791 x interface{}
792 }
793 Nil(ii, t)
794 ii.x = 2
795 NotNil(ii, t)
796
797 var fi struct {
798 x func(t *testing.T)
799 }
800 Nil(fi, t)
801 fi.x = TestIsNil
802 NotNil(fi, t)
803 }
804
805 func TestInterfaceExtraction(t *testing.T) {
806 var s struct {
807 w io.Writer
808 }
809
810 s.w = os.Stdout
811 v := Indirect(NewValue(&s)).(*StructValue).Field(0).Interface()
812 if v != s.w.(interface{}) {
813 t.Error("Interface() on interface: ", v, s.w)
814 }
815 }
816
817 func TestInterfaceEditing(t *testing.T) {
818 // strings are bigger than one word,
819 // so the interface conversion allocates
820 // memory to hold a string and puts that
821 // pointer in the interface.
822 var i interface{} = "hello"
823
824 // if i pass the interface value by value
825 // to NewValue, i should get a fresh copy
826 // of the value.
827 v := NewValue(i)
828
829 // and setting that copy to "bye" should
830 // not change the value stored in i.
831 v.(*StringValue).Set("bye")
832 if i.(string) != "hello" {
833 t.Errorf(`Set("bye") changed i to %s`, i.(string))
834 }
835
836 // the same should be true of smaller items.
837 i = 123
838 v = NewValue(i)
839 v.(*IntValue).Set(234)
840 if i.(int) != 123 {
841 t.Errorf("Set(234) changed i to %d", i.(int))
842 }
843 }
844
845 func TestNilPtrValueSub(t *testing.T) {
846 var pi *int
847 if pv := NewValue(pi).(*PtrValue); pv.Elem() != nil {
848 t.Error("NewValue((*int)(nil)).(*PtrValue).Elem() != nil")
849 }
850 }
851
852 func TestMap(t *testing.T) {
853 m := map[string]int{"a": 1, "b": 2}
854 mv := NewValue(m).(*MapValue)
855 if n := mv.Len(); n != len(m) {
856 t.Errorf("Len = %d, want %d", n, len(m))
857 }
858 keys := mv.Keys()
859 i := 0
860 newmap := MakeMap(mv.Type().(*MapType))
861 for k, v := range m {
862 // Check that returned Keys match keys in range.
863 // These aren't required to be in the same order,
864 // but they are in this implementation, which makes
865 // the test easier.
866 if i >= len(keys) {
867 t.Errorf("Missing key #%d %q", i, k)
868 } else if kv := keys[i].(*StringValue); kv.Get() != k {
869 t.Errorf("Keys[%d] = %q, want %q", i, kv.Get(), k)
870 }
871 i++
872
873 // Check that value lookup is correct.
874 vv := mv.Elem(NewValue(k))
875 if vi := vv.(*IntValue).Get(); vi != int64(v) {
876 t.Errorf("Key %q: have value %d, want %d", vi, v)
877 }
878
879 // Copy into new map.
880 newmap.SetElem(NewValue(k), NewValue(v))
881 }
882 vv := mv.Elem(NewValue("not-present"))
883 if vv != nil {
884 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
885 }
886
887 newm := newmap.Interface().(map[string]int)
888 if len(newm) != len(m) {
889 t.Errorf("length after copy: newm=%d, m=%d", newm, m)
890 }
891
892 for k, v := range newm {
893 mv, ok := m[k]
894 if mv != v {
895 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
896 }
897 }
898
899 newmap.SetElem(NewValue("a"), nil)
900 v, ok := newm["a"]
901 if ok {
902 t.Errorf("newm[\"a\"] = %d after delete", v)
903 }
904
905 mv = NewValue(&m).(*PtrValue).Elem().(*MapValue)
906 mv.Set(nil)
907 if m != nil {
908 t.Errorf("mv.Set(nil) failed")
909 }
910 }
911
912 func TestChan(t *testing.T) {
913 for loop := 0; loop < 2; loop++ {
914 var c chan int
915 var cv *ChanValue
916
917 // check both ways to allocate channels
918 switch loop {
919 case 1:
920 c = make(chan int, 1)
921 cv = NewValue(c).(*ChanValue)
922 case 0:
923 cv = MakeChan(Typeof(c).(*ChanType), 1)
924 c = cv.Interface().(chan int)
925 }
926
927 // Send
928 cv.Send(NewValue(2))
929 if i := <-c; i != 2 {
930 t.Errorf("reflect Send 2, native recv %d", i)
931 }
932
933 // Recv
934 c <- 3
935 if i := cv.Recv().(*IntValue).Get(); i != 3 {
936 t.Errorf("native send 3, reflect Recv %d", i)
937 }
938
939 // TryRecv fail
940 val := cv.TryRecv()
941 if val != nil {
942 t.Errorf("TryRecv on empty chan: %s", valueToString(val))
943 }
944
945 // TryRecv success
946 c <- 4
947 val = cv.TryRecv()
948 if val == nil {
949 t.Errorf("TryRecv on ready chan got nil")
950 } else if i := val.(*IntValue).Get(); i != 4 {
951 t.Errorf("native send 4, TryRecv %d", i)
952 }
953
954 // TrySend fail
955 c <- 100
956 ok := cv.TrySend(NewValue(5))
957 i := <-c
958 if ok {
959 t.Errorf("TrySend on full chan succeeded: value %d", i)
960 }
961
962 // TrySend success
963 ok = cv.TrySend(NewValue(6))
964 if !ok {
965 t.Errorf("TrySend on empty chan failed")
966 } else {
967 if i = <-c; i != 6 {
968 t.Errorf("TrySend 6, recv %d", i)
969 }
970 }
971
972 // Close
973 c <- 123
974 cv.Close()
975 if cv.Closed() {
976 t.Errorf("closed too soon - 1")
977 }
978 if i := cv.Recv().(*IntValue).Get(); i != 123 {
979 t.Errorf("send 123 then close; Recv %d", i)
980 }
981 if cv.Closed() {
982 t.Errorf("closed too soon - 2")
983 }
984 if i := cv.Recv().(*IntValue).Get(); i != 0 {
985 t.Errorf("after close Recv %d", i)
986 }
987 if !cv.Closed() {
988 t.Errorf("not closed")
989 }
990 }
991
992 // check creation of unbuffered channel
993 var c chan int
994 cv := MakeChan(Typeof(c).(*ChanType), 0)
995 c = cv.Interface().(chan int)
996 if cv.TrySend(NewValue(7)) {
997 t.Errorf("TrySend on sync chan succeeded")
998 }
999 if cv.TryRecv() != nil {
1000 t.Errorf("TryRecv on sync chan succeeded")
1001 }
1002
1003 // len/cap
1004 cv = MakeChan(Typeof(c).(*ChanType), 10)
1005 c = cv.Interface().(chan int)
1006 for i := 0; i < 3; i++ {
1007 c <- i
1008 }
1009 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1010 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1011 }
1012
1013 }
1014
1015 // Difficult test for function call because of
1016 // implicit padding between arguments.
1017 func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1018 return b, c, d
1019 }
1020
1021 func TestFunc(t *testing.T) {
1022 ret := NewValue(dummy).(*FuncValue).Call([]Value{NewValue(byte(10)), NewValue(20), NewValue(byte(30))})
1023 if len(ret) != 3 {
1024 t.Fatalf("Call returned %d values, want 3", len(ret))
1025 }
1026
1027 i := ret[0].(*UintValue).Get()
1028 j := ret[1].(*IntValue).Get()
1029 k := ret[2].(*UintValue).Get()
1030 if i != 10 || j != 20 || k != 30 {
1031 t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1032 }
1033 }
1034
1035 type Point struct {
1036 x, y int
1037 }
1038
1039 func (p Point) Dist(scale int) int { return p.x*p.x*scale + p.y*p.y*scale }
1040
1041 func TestMethod(t *testing.T) {
1042 // Non-curried method of type.
1043 p := Point{3, 4}
1044 i := Typeof(p).Method(0).Func.Call([]Value{NewValue(p), NewValue(10)})[0].(*IntValue).Get()
1045 if i != 250 {
1046 t.Errorf("Type Method returned %d; want 250", i)
1047 }
1048
1049 i = Typeof(&p).Method(0).Func.Call([]Value{NewValue(&p), NewValue(10)})[0].(*IntValue).Get()
1050 if i != 250 {
1051 t.Errorf("Pointer Type Method returned %d; want 250", i)
1052 }
1053
1054 // Curried method of value.
1055 i = NewValue(p).Method(0).Call([]Value{NewValue(10)})[0].(*IntValue).Get()
1056 if i != 250 {
1057 t.Errorf("Value Method returned %d; want 250", i)
1058 }
1059
1060 // Curried method of interface value.
1061 // Have to wrap interface value in a struct to get at it.
1062 // Passing it to NewValue directly would
1063 // access the underlying Point, not the interface.
1064 var s = struct {
1065 x interface {
1066 Dist(int) int
1067 }
1068 }{p}
1069 pv := NewValue(s).(*StructValue).Field(0)
1070 i = pv.Method(0).Call([]Value{NewValue(10)})[0].(*IntValue).Get()
1071 if i != 250 {
1072 t.Errorf("Interface Method returned %d; want 250", i)
1073 }
1074 }
1075
1076 func TestInterfaceSet(t *testing.T) {
1077 p := &Point{3, 4}
1078
1079 var s struct {
1080 I interface{}
1081 P interface {
1082 Dist(int) int
1083 }
1084 }
1085 sv := NewValue(&s).(*PtrValue).Elem().(*StructValue)
1086 sv.Field(0).(*InterfaceValue).Set(NewValue(p))
1087 if q := s.I.(*Point); q != p {
1088 t.Errorf("i: have %p want %p", q, p)
1089 }
1090
1091 pv := sv.Field(1).(*InterfaceValue)
1092 pv.Set(NewValue(p))
1093 if q := s.P.(*Point); q != p {
1094 t.Errorf("i: have %p want %p", q, p)
1095 }
1096
1097 i := pv.Method(0).Call([]Value{NewValue(10)})[0].(*IntValue).Get()
1098 if i != 250 {
1099 t.Errorf("Interface Method returned %d; want 250", i)
1100 }
1101 }
1102
1103 type T1 struct {
1104 a string
1105 int
1106 }
1107
1108 func TestAnonymousFields(t *testing.T) {
1109 var field StructField
1110 var ok bool
1111 var t1 T1
1112 type1 := Typeof(t1).(*StructType)
1113 if field, ok = type1.FieldByName("int"); !ok {
1114 t.Error("no field 'int'")
1115 }
1116 if field.Index[0] != 1 {
1117 t.Error("field index should be 1; is", field.Index)
1118 }
1119 }
1120
1121 type FTest struct {
1122 s interface{}
1123 name string
1124 index []int
1125 value int
1126 }
1127
1128 type D1 struct {
1129 d int
1130 }
1131 type D2 struct {
1132 d int
1133 }
1134
1135 type S0 struct {
1136 a, b, c int
1137 D1
1138 D2
1139 }
1140
1141 type S1 struct {
1142 b int
1143 S0
1144 }
1145
1146 type S2 struct {
1147 a int
1148 *S1
1149 }
1150
1151 type S1x struct {
1152 S1
1153 }
1154
1155 type S1y struct {
1156 S1
1157 }
1158
1159 type S3 struct {
1160 S1x
1161 S2
1162 d, e int
1163 *S1y
1164 }
1165
1166 type S4 struct {
1167 *S4
1168 a int
1169 }
1170
1171 var fieldTests = []FTest{
1172 {struct{}{}, "", nil, 0},
1173 {struct{}{}, "foo", nil, 0},
1174 {S0{a: 'a'}, "a", []int{0}, 'a'},
1175 {S0{}, "d", nil, 0},
1176 {S1{S0: S0{a: 'a'}}, "a", []int{1, 0}, 'a'},
1177 {S1{b: 'b'}, "b", []int{0}, 'b'},
1178 {S1{}, "S0", []int{1}, 0},
1179 {S1{S0: S0{c: 'c'}}, "c", []int{1, 2}, 'c'},
1180 {S2{a: 'a'}, "a", []int{0}, 'a'},
1181 {S2{}, "S1", []int{1}, 0},
1182 {S2{S1: &S1{b: 'b'}}, "b", []int{1, 0}, 'b'},
1183 {S2{S1: &S1{S0: S0{c: 'c'}}}, "c", []int{1, 1, 2}, 'c'},
1184 {S2{}, "d", nil, 0},
1185 {S3{}, "S1", nil, 0},
1186 {S3{S2: S2{a: 'a'}}, "a", []int{1, 0}, 'a'},
1187 {S3{}, "b", nil, 0},
1188 {S3{d: 'd'}, "d", []int{2}, 0},
1189 {S3{e: 'e'}, "e", []int{3}, 'e'},
1190 {S4{a: 'a'}, "a", []int{1}, 'a'},
1191 {S4{}, "b", nil, 0},
1192 }
1193
1194 func TestFieldByIndex(t *testing.T) {
1195 for _, test := range fieldTests {
1196 s := Typeof(test.s).(*StructType)
1197 f := s.FieldByIndex(test.index)
1198 if f.Name != "" {
1199 if test.index != nil {
1200 if f.Name != test.name {
1201 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1202 }
1203 } else {
1204 t.Errorf("%s.%s found", s.Name(), f.Name)
1205 }
1206 } else if len(test.index) > 0 {
1207 t.Errorf("%s.%s not found", s.Name(), test.name)
1208 }
1209
1210 if test.value != 0 {
1211 v := NewValue(test.s).(*StructValue).FieldByIndex(test.index)
1212 if v != nil {
1213 if x, ok := v.Interface().(int); ok {
1214 if x != test.value {
1215 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1216 }
1217 } else {
1218 t.Errorf("%s%v value not an int", s.Name(), test.index)
1219 }
1220 } else {
1221 t.Errorf("%s%v value not found", s.Name(), test.index)
1222 }
1223 }
1224 }
1225 }
1226
1227 func TestFieldByName(t *testing.T) {
1228 for _, test := range fieldTests {
1229 s := Typeof(test.s).(*StructType)
1230 f, found := s.FieldByName(test.name)
1231 if found {
1232 if test.index != nil {
1233 // Verify field depth and index.
1234 if len(f.Index) != len(test.index) {
1235 t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1236 } else {
1237 for i, x := range f.Index {
1238 if x != test.index[i] {
1239 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1240 }
1241 }
1242 }
1243 } else {
1244 t.Errorf("%s.%s found", s.Name(), f.Name)
1245 }
1246 } else if len(test.index) > 0 {
1247 t.Errorf("%s.%s not found", s.Name(), test.name)
1248 }
1249
1250 if test.value != 0 {
1251 v := NewValue(test.s).(*StructValue).FieldByName(test.name)
1252 if v != nil {
1253 if x, ok := v.Interface().(int); ok {
1254 if x != test.value {
1255 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1256 }
1257 } else {
1258 t.Errorf("%s.%s value not an int", s.Name(), test.name)
1259 }
1260 } else {
1261 t.Errorf("%s.%s value not found", s.Name(), test.name)
1262 }
1263 }
1264 }
1265 }
1266
1267 func TestImportPath(t *testing.T) {
1268 if path := Typeof(vector.Vector{}).PkgPath(); path != "libgo_container.vector" {
1269 t.Errorf("Typeof(vector.Vector{}).PkgPath() = %q, want \"libgo_container.vector\"", path)
1270 }
1271 }
1272
1273 func TestDotDotDot(t *testing.T) {
1274 // Test example from FuncType.DotDotDot documentation.
1275 var f func(x int, y ...float)
1276 typ := Typeof(f).(*FuncType)
1277 if typ.NumIn() == 2 && typ.In(0) == Typeof(int(0)) {
1278 sl, ok := typ.In(1).(*SliceType)
1279 if ok {
1280 if sl.Elem() == Typeof(float(0)) {
1281 // ok
1282 return
1283 }
1284 }
1285 }
1286
1287 // Failed
1288 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float")
1289 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1290 for i := 0; i < typ.NumIn(); i++ {
1291 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1292 }
1293 t.Error(s)
1294 }
1295
1296 type inner struct {
1297 x int
1298 }
1299
1300 type outer struct {
1301 y int
1302 inner
1303 }
1304
1305 func (*inner) m() {}
1306 func (*outer) m() {}
1307
1308 func TestNestedMethods(t *testing.T) {
1309 typ := Typeof((*outer)(nil))
1310 if typ.NumMethod() != 1 || typ.Method(0).Func.Get() != NewValue((*outer).m).(*FuncValue).Get() {
1311 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1312 for i := 0; i < typ.NumMethod(); i++ {
1313 m := typ.Method(i)
1314 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Get())
1315 }
1316 }
1317 }
1318
1319 type innerInt struct {
1320 x int
1321 }
1322
1323 type outerInt struct {
1324 y int
1325 innerInt
1326 }
1327
1328 func (i *innerInt) m() int {
1329 return i.x
1330 }
1331
1332 func TestEmbeddedMethods(t *testing.T) {
1333 typ := Typeof((*outerInt)(nil))
1334 if typ.NumMethod() != 1 || typ.Method(0).Func.Get() != NewValue((*outerInt).m).(*FuncValue).Get() {
1335 t.Errorf("Wrong method table for outerInt: (m=%p)", (*outerInt).m)
1336 for i := 0; i < typ.NumMethod(); i++ {
1337 m := typ.Method(i)
1338 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Get())
1339 }
1340 }
1341
1342 i := &innerInt{3}
1343 if v := NewValue(i).Method(0).Call(nil)[0].(*IntValue).Get(); v != 3 {
1344 t.Errorf("i.m() = %d, want 3", v)
1345 }
1346
1347 o := &outerInt{1, innerInt{2}}
1348 if v := NewValue(o).Method(0).Call(nil)[0].(*IntValue).Get(); v != 2 {
1349 t.Errorf("i.m() = %d, want 2", v)
1350 }
1351
1352 f := (*outerInt).m
1353 if v := f(o); v != 2 {
1354 t.Errorf("f(o) = %d, want 2", v)
1355 }
1356 }