gcc/ChangeLog:
[official-gcc.git] / libgo / go / reflect / all_test.go
blobb8e7cd883cb351212eaac89ca027fbdbf89221a2
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.
5 package reflect_test
7 import (
8 "bytes"
9 "encoding/base64"
10 "flag"
11 "fmt"
12 "io"
13 "math"
14 "math/rand"
15 "os"
16 . "reflect"
17 "runtime"
18 "sort"
19 "strconv"
20 "strings"
21 "sync"
22 "testing"
23 "time"
24 "unsafe"
27 func TestBool(t *testing.T) {
28 v := ValueOf(true)
29 if v.Bool() != true {
30 t.Fatal("ValueOf(true).Bool() = false")
34 type integer int
35 type T struct {
36 a int
37 b float64
38 c string
39 d *int
42 type pair struct {
43 i interface{}
44 s string
47 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
49 func assert(t *testing.T, s, want string) {
50 if s != want {
51 t.Errorf("have %#q want %#q", s, want)
55 func typestring(i interface{}) string { return TypeOf(i).String() }
57 var typeTests = []pair{
58 {struct{ x int }{}, "int"},
59 {struct{ x int8 }{}, "int8"},
60 {struct{ x int16 }{}, "int16"},
61 {struct{ x int32 }{}, "int32"},
62 {struct{ x int64 }{}, "int64"},
63 {struct{ x uint }{}, "uint"},
64 {struct{ x uint8 }{}, "uint8"},
65 {struct{ x uint16 }{}, "uint16"},
66 {struct{ x uint32 }{}, "uint32"},
67 {struct{ x uint64 }{}, "uint64"},
68 {struct{ x float32 }{}, "float32"},
69 {struct{ x float64 }{}, "float64"},
70 {struct{ x int8 }{}, "int8"},
71 {struct{ x (**int8) }{}, "**int8"},
72 {struct{ x (**integer) }{}, "**reflect_test.integer"},
73 {struct{ x ([32]int32) }{}, "[32]int32"},
74 {struct{ x ([]int8) }{}, "[]int8"},
75 {struct{ x (map[string]int32) }{}, "map[string]int32"},
76 {struct{ x (chan<- string) }{}, "chan<- string"},
77 {struct {
78 x struct {
79 c chan *int32
80 d float32
82 }{},
83 "struct { c chan *int32; d float32 }",
85 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
86 {struct {
87 x struct {
88 c func(chan *integer, *int8)
90 }{},
91 "struct { c func(chan *reflect_test.integer, *int8) }",
93 {struct {
94 x struct {
95 a int8
96 b int32
98 }{},
99 "struct { a int8; b int32 }",
101 {struct {
102 x struct {
103 a int8
104 b int8
105 c int32
107 }{},
108 "struct { a int8; b int8; c int32 }",
110 {struct {
111 x struct {
112 a int8
113 b int8
114 c int8
115 d int32
117 }{},
118 "struct { a int8; b int8; c int8; d int32 }",
120 {struct {
121 x struct {
122 a int8
123 b int8
124 c int8
125 d int8
126 e int32
128 }{},
129 "struct { a int8; b int8; c int8; d int8; e int32 }",
131 {struct {
132 x struct {
133 a int8
134 b int8
135 c int8
136 d int8
137 e int8
138 f int32
140 }{},
141 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
143 {struct {
144 x struct {
145 a int8 `reflect:"hi there"`
147 }{},
148 `struct { a int8 "reflect:\"hi there\"" }`,
150 {struct {
151 x struct {
152 a int8 `reflect:"hi \x00there\t\n\"\\"`
154 }{},
155 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
157 {struct {
158 x struct {
159 f func(args ...int)
161 }{},
162 "struct { f func(...int) }",
164 {struct {
165 x (interface {
166 a(func(func(int) int) func(func(int)) int)
169 }{},
170 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
174 var valueTests = []pair{
175 {new(int), "132"},
176 {new(int8), "8"},
177 {new(int16), "16"},
178 {new(int32), "32"},
179 {new(int64), "64"},
180 {new(uint), "132"},
181 {new(uint8), "8"},
182 {new(uint16), "16"},
183 {new(uint32), "32"},
184 {new(uint64), "64"},
185 {new(float32), "256.25"},
186 {new(float64), "512.125"},
187 {new(complex64), "532.125+10i"},
188 {new(complex128), "564.25+1i"},
189 {new(string), "stringy cheese"},
190 {new(bool), "true"},
191 {new(*int8), "*int8(0)"},
192 {new(**int8), "**int8(0)"},
193 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
194 {new(**integer), "**reflect_test.integer(0)"},
195 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
196 {new(chan<- string), "chan<- string"},
197 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
198 {new(struct {
199 c chan *int32
200 d float32
202 "struct { c chan *int32; d float32 }{chan *int32, 0}",
204 {new(struct{ c func(chan *integer, *int8) }),
205 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
207 {new(struct {
208 a int8
209 b int32
211 "struct { a int8; b int32 }{0, 0}",
213 {new(struct {
214 a int8
215 b int8
216 c int32
218 "struct { a int8; b int8; c int32 }{0, 0, 0}",
222 func testType(t *testing.T, i int, typ Type, want string) {
223 s := typ.String()
224 if s != want {
225 t.Errorf("#%d: have %#q, want %#q", i, s, want)
229 func TestTypes(t *testing.T) {
230 for i, tt := range typeTests {
231 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
235 func TestSet(t *testing.T) {
236 for i, tt := range valueTests {
237 v := ValueOf(tt.i)
238 v = v.Elem()
239 switch v.Kind() {
240 case Int:
241 v.SetInt(132)
242 case Int8:
243 v.SetInt(8)
244 case Int16:
245 v.SetInt(16)
246 case Int32:
247 v.SetInt(32)
248 case Int64:
249 v.SetInt(64)
250 case Uint:
251 v.SetUint(132)
252 case Uint8:
253 v.SetUint(8)
254 case Uint16:
255 v.SetUint(16)
256 case Uint32:
257 v.SetUint(32)
258 case Uint64:
259 v.SetUint(64)
260 case Float32:
261 v.SetFloat(256.25)
262 case Float64:
263 v.SetFloat(512.125)
264 case Complex64:
265 v.SetComplex(532.125 + 10i)
266 case Complex128:
267 v.SetComplex(564.25 + 1i)
268 case String:
269 v.SetString("stringy cheese")
270 case Bool:
271 v.SetBool(true)
273 s := valueToString(v)
274 if s != tt.s {
275 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
280 func TestSetValue(t *testing.T) {
281 for i, tt := range valueTests {
282 v := ValueOf(tt.i).Elem()
283 switch v.Kind() {
284 case Int:
285 v.Set(ValueOf(int(132)))
286 case Int8:
287 v.Set(ValueOf(int8(8)))
288 case Int16:
289 v.Set(ValueOf(int16(16)))
290 case Int32:
291 v.Set(ValueOf(int32(32)))
292 case Int64:
293 v.Set(ValueOf(int64(64)))
294 case Uint:
295 v.Set(ValueOf(uint(132)))
296 case Uint8:
297 v.Set(ValueOf(uint8(8)))
298 case Uint16:
299 v.Set(ValueOf(uint16(16)))
300 case Uint32:
301 v.Set(ValueOf(uint32(32)))
302 case Uint64:
303 v.Set(ValueOf(uint64(64)))
304 case Float32:
305 v.Set(ValueOf(float32(256.25)))
306 case Float64:
307 v.Set(ValueOf(512.125))
308 case Complex64:
309 v.Set(ValueOf(complex64(532.125 + 10i)))
310 case Complex128:
311 v.Set(ValueOf(complex128(564.25 + 1i)))
312 case String:
313 v.Set(ValueOf("stringy cheese"))
314 case Bool:
315 v.Set(ValueOf(true))
317 s := valueToString(v)
318 if s != tt.s {
319 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
324 var _i = 7
326 var valueToStringTests = []pair{
327 {123, "123"},
328 {123.5, "123.5"},
329 {byte(123), "123"},
330 {"abc", "abc"},
331 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
332 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
333 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
334 {&[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})"},
335 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
336 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
339 func TestValueToString(t *testing.T) {
340 for i, test := range valueToStringTests {
341 s := valueToString(ValueOf(test.i))
342 if s != test.s {
343 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
348 func TestArrayElemSet(t *testing.T) {
349 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
350 v.Index(4).SetInt(123)
351 s := valueToString(v)
352 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
353 if s != want {
354 t.Errorf("[10]int: have %#q want %#q", s, want)
357 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
358 v.Index(4).SetInt(123)
359 s = valueToString(v)
360 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
361 if s != want1 {
362 t.Errorf("[]int: have %#q want %#q", s, want1)
366 func TestPtrPointTo(t *testing.T) {
367 var ip *int32
368 var i int32 = 1234
369 vip := ValueOf(&ip)
370 vi := ValueOf(&i).Elem()
371 vip.Elem().Set(vi.Addr())
372 if *ip != 1234 {
373 t.Errorf("got %d, want 1234", *ip)
376 ip = nil
377 vp := ValueOf(&ip).Elem()
378 vp.Set(Zero(vp.Type()))
379 if ip != nil {
380 t.Errorf("got non-nil (%p), want nil", ip)
384 func TestPtrSetNil(t *testing.T) {
385 var i int32 = 1234
386 ip := &i
387 vip := ValueOf(&ip)
388 vip.Elem().Set(Zero(vip.Elem().Type()))
389 if ip != nil {
390 t.Errorf("got non-nil (%d), want nil", *ip)
394 func TestMapSetNil(t *testing.T) {
395 m := make(map[string]int)
396 vm := ValueOf(&m)
397 vm.Elem().Set(Zero(vm.Elem().Type()))
398 if m != nil {
399 t.Errorf("got non-nil (%p), want nil", m)
403 func TestAll(t *testing.T) {
404 testType(t, 1, TypeOf((int8)(0)), "int8")
405 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
407 typ := TypeOf((*struct {
408 c chan *int32
409 d float32
410 })(nil))
411 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
412 etyp := typ.Elem()
413 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
414 styp := etyp
415 f := styp.Field(0)
416 testType(t, 5, f.Type, "chan *int32")
418 f, present := styp.FieldByName("d")
419 if !present {
420 t.Errorf("FieldByName says present field is absent")
422 testType(t, 6, f.Type, "float32")
424 f, present = styp.FieldByName("absent")
425 if present {
426 t.Errorf("FieldByName says absent field is present")
429 typ = TypeOf([32]int32{})
430 testType(t, 7, typ, "[32]int32")
431 testType(t, 8, typ.Elem(), "int32")
433 typ = TypeOf((map[string]*int32)(nil))
434 testType(t, 9, typ, "map[string]*int32")
435 mtyp := typ
436 testType(t, 10, mtyp.Key(), "string")
437 testType(t, 11, mtyp.Elem(), "*int32")
439 typ = TypeOf((chan<- string)(nil))
440 testType(t, 12, typ, "chan<- string")
441 testType(t, 13, typ.Elem(), "string")
443 // make sure tag strings are not part of element type
444 typ = TypeOf(struct {
445 d []uint32 `reflect:"TAG"`
446 }{}).Field(0).Type
447 testType(t, 14, typ, "[]uint32")
450 func TestInterfaceGet(t *testing.T) {
451 var inter struct {
452 E interface{}
454 inter.E = 123.456
455 v1 := ValueOf(&inter)
456 v2 := v1.Elem().Field(0)
457 assert(t, v2.Type().String(), "interface {}")
458 i2 := v2.Interface()
459 v3 := ValueOf(i2)
460 assert(t, v3.Type().String(), "float64")
463 func TestInterfaceValue(t *testing.T) {
464 var inter struct {
465 E interface{}
467 inter.E = 123.456
468 v1 := ValueOf(&inter)
469 v2 := v1.Elem().Field(0)
470 assert(t, v2.Type().String(), "interface {}")
471 v3 := v2.Elem()
472 assert(t, v3.Type().String(), "float64")
474 i3 := v2.Interface()
475 if _, ok := i3.(float64); !ok {
476 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
480 func TestFunctionValue(t *testing.T) {
481 var x interface{} = func() {}
482 v := ValueOf(x)
483 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
484 t.Fatalf("TestFunction returned wrong pointer")
486 assert(t, v.Type().String(), "func()")
489 var appendTests = []struct {
490 orig, extra []int
492 {make([]int, 2, 4), []int{22}},
493 {make([]int, 2, 4), []int{22, 33, 44}},
496 func sameInts(x, y []int) bool {
497 if len(x) != len(y) {
498 return false
500 for i, xx := range x {
501 if xx != y[i] {
502 return false
505 return true
508 func TestAppend(t *testing.T) {
509 for i, test := range appendTests {
510 origLen, extraLen := len(test.orig), len(test.extra)
511 want := append(test.orig, test.extra...)
512 // Convert extra from []int to []Value.
513 e0 := make([]Value, len(test.extra))
514 for j, e := range test.extra {
515 e0[j] = ValueOf(e)
517 // Convert extra from []int to *SliceValue.
518 e1 := ValueOf(test.extra)
519 // Test Append.
520 a0 := ValueOf(test.orig)
521 have0 := Append(a0, e0...).Interface().([]int)
522 if !sameInts(have0, want) {
523 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
525 // Check that the orig and extra slices were not modified.
526 if len(test.orig) != origLen {
527 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
529 if len(test.extra) != extraLen {
530 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
532 // Test AppendSlice.
533 a1 := ValueOf(test.orig)
534 have1 := AppendSlice(a1, e1).Interface().([]int)
535 if !sameInts(have1, want) {
536 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
538 // Check that the orig and extra slices were not modified.
539 if len(test.orig) != origLen {
540 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
542 if len(test.extra) != extraLen {
543 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
548 func TestCopy(t *testing.T) {
549 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
550 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
551 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
552 for i := 0; i < len(b); i++ {
553 if b[i] != c[i] {
554 t.Fatalf("b != c before test")
557 a1 := a
558 b1 := b
559 aa := ValueOf(&a1).Elem()
560 ab := ValueOf(&b1).Elem()
561 for tocopy := 1; tocopy <= 7; tocopy++ {
562 aa.SetLen(tocopy)
563 Copy(ab, aa)
564 aa.SetLen(8)
565 for i := 0; i < tocopy; i++ {
566 if a[i] != b[i] {
567 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
568 tocopy, i, a[i], i, b[i])
571 for i := tocopy; i < len(b); i++ {
572 if b[i] != c[i] {
573 if i < len(a) {
574 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
575 tocopy, i, a[i], i, b[i], i, c[i])
576 } else {
577 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
578 tocopy, i, b[i], i, c[i])
580 } else {
581 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
587 func TestCopyArray(t *testing.T) {
588 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
589 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
590 c := b
591 aa := ValueOf(&a).Elem()
592 ab := ValueOf(&b).Elem()
593 Copy(ab, aa)
594 for i := 0; i < len(a); i++ {
595 if a[i] != b[i] {
596 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
599 for i := len(a); i < len(b); i++ {
600 if b[i] != c[i] {
601 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
602 } else {
603 t.Logf("elem %d is okay\n", i)
608 func TestBigUnnamedStruct(t *testing.T) {
609 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
610 v := ValueOf(b)
611 b1 := v.Interface().(struct {
612 a, b, c, d int64
614 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
615 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
619 type big struct {
620 a, b, c, d, e int64
623 func TestBigStruct(t *testing.T) {
624 b := big{1, 2, 3, 4, 5}
625 v := ValueOf(b)
626 b1 := v.Interface().(big)
627 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
628 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
632 type Basic struct {
633 x int
634 y float32
637 type NotBasic Basic
639 type DeepEqualTest struct {
640 a, b interface{}
641 eq bool
644 // Simple functions for DeepEqual tests.
645 var (
646 fn1 func() // nil.
647 fn2 func() // nil.
648 fn3 = func() { fn1() } // Not nil.
651 type self struct{}
653 var deepEqualTests = []DeepEqualTest{
654 // Equalities
655 {nil, nil, true},
656 {1, 1, true},
657 {int32(1), int32(1), true},
658 {0.5, 0.5, true},
659 {float32(0.5), float32(0.5), true},
660 {"hello", "hello", true},
661 {make([]int, 10), make([]int, 10), true},
662 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
663 {Basic{1, 0.5}, Basic{1, 0.5}, true},
664 {error(nil), error(nil), true},
665 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
666 {fn1, fn2, true},
668 // Inequalities
669 {1, 2, false},
670 {int32(1), int32(2), false},
671 {0.5, 0.6, false},
672 {float32(0.5), float32(0.6), false},
673 {"hello", "hey", false},
674 {make([]int, 10), make([]int, 11), false},
675 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
676 {Basic{1, 0.5}, Basic{1, 0.6}, false},
677 {Basic{1, 0}, Basic{2, 0}, false},
678 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
679 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
680 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
681 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
682 {nil, 1, false},
683 {1, nil, false},
684 {fn1, fn3, false},
685 {fn3, fn3, false},
686 {[][]int{{1}}, [][]int{{2}}, false},
687 {math.NaN(), math.NaN(), false},
688 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
689 {&[1]float64{math.NaN()}, self{}, true},
690 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
691 {[]float64{math.NaN()}, self{}, true},
692 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
693 {map[float64]float64{math.NaN(): 1}, self{}, true},
695 // Nil vs empty: not the same.
696 {[]int{}, []int(nil), false},
697 {[]int{}, []int{}, true},
698 {[]int(nil), []int(nil), true},
699 {map[int]int{}, map[int]int(nil), false},
700 {map[int]int{}, map[int]int{}, true},
701 {map[int]int(nil), map[int]int(nil), true},
703 // Mismatched types
704 {1, 1.0, false},
705 {int32(1), int64(1), false},
706 {0.5, "hello", false},
707 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
708 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
709 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
710 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
713 func TestDeepEqual(t *testing.T) {
714 for _, test := range deepEqualTests {
715 if test.b == (self{}) {
716 test.b = test.a
718 if r := DeepEqual(test.a, test.b); r != test.eq {
719 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
724 func TestTypeOf(t *testing.T) {
725 // Special case for nil
726 if typ := TypeOf(nil); typ != nil {
727 t.Errorf("expected nil type for nil value; got %v", typ)
729 for _, test := range deepEqualTests {
730 v := ValueOf(test.a)
731 if !v.IsValid() {
732 continue
734 typ := TypeOf(test.a)
735 if typ != v.Type() {
736 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
741 type Recursive struct {
742 x int
743 r *Recursive
746 func TestDeepEqualRecursiveStruct(t *testing.T) {
747 a, b := new(Recursive), new(Recursive)
748 *a = Recursive{12, a}
749 *b = Recursive{12, b}
750 if !DeepEqual(a, b) {
751 t.Error("DeepEqual(recursive same) = false, want true")
755 type _Complex struct {
756 a int
757 b [3]*_Complex
758 c *string
759 d map[float64]float64
762 func TestDeepEqualComplexStruct(t *testing.T) {
763 m := make(map[float64]float64)
764 stra, strb := "hello", "hello"
765 a, b := new(_Complex), new(_Complex)
766 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
767 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
768 if !DeepEqual(a, b) {
769 t.Error("DeepEqual(complex same) = false, want true")
773 func TestDeepEqualComplexStructInequality(t *testing.T) {
774 m := make(map[float64]float64)
775 stra, strb := "hello", "helloo" // Difference is here
776 a, b := new(_Complex), new(_Complex)
777 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
778 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
779 if DeepEqual(a, b) {
780 t.Error("DeepEqual(complex different) = true, want false")
784 type UnexpT struct {
785 m map[int]int
788 func TestDeepEqualUnexportedMap(t *testing.T) {
789 // Check that DeepEqual can look at unexported fields.
790 x1 := UnexpT{map[int]int{1: 2}}
791 x2 := UnexpT{map[int]int{1: 2}}
792 if !DeepEqual(&x1, &x2) {
793 t.Error("DeepEqual(x1, x2) = false, want true")
796 y1 := UnexpT{map[int]int{2: 3}}
797 if DeepEqual(&x1, &y1) {
798 t.Error("DeepEqual(x1, y1) = true, want false")
802 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
803 s := ValueOf(x)
804 f := s.Type().Field(1)
805 if f.Offset != offs {
806 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
810 // Check that structure alignment & offsets viewed through reflect agree with those
811 // from the compiler itself.
812 func TestAlignment(t *testing.T) {
813 type T1inner struct {
814 a int
816 type T1 struct {
817 T1inner
818 f int
820 type T2inner struct {
821 a, b int
823 type T2 struct {
824 T2inner
825 f int
828 x := T1{T1inner{2}, 17}
829 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
831 x1 := T2{T2inner{2, 3}, 17}
832 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
835 func Nil(a interface{}, t *testing.T) {
836 n := ValueOf(a).Field(0)
837 if !n.IsNil() {
838 t.Errorf("%v should be nil", a)
842 func NotNil(a interface{}, t *testing.T) {
843 n := ValueOf(a).Field(0)
844 if n.IsNil() {
845 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
849 func TestIsNil(t *testing.T) {
850 // These implement IsNil.
851 // Wrap in extra struct to hide interface type.
852 doNil := []interface{}{
853 struct{ x *int }{},
854 struct{ x interface{} }{},
855 struct{ x map[string]int }{},
856 struct{ x func() bool }{},
857 struct{ x chan int }{},
858 struct{ x []string }{},
860 for _, ts := range doNil {
861 ty := TypeOf(ts).Field(0).Type
862 v := Zero(ty)
863 v.IsNil() // panics if not okay to call
866 // Check the implementations
867 var pi struct {
868 x *int
870 Nil(pi, t)
871 pi.x = new(int)
872 NotNil(pi, t)
874 var si struct {
875 x []int
877 Nil(si, t)
878 si.x = make([]int, 10)
879 NotNil(si, t)
881 var ci struct {
882 x chan int
884 Nil(ci, t)
885 ci.x = make(chan int)
886 NotNil(ci, t)
888 var mi struct {
889 x map[int]int
891 Nil(mi, t)
892 mi.x = make(map[int]int)
893 NotNil(mi, t)
895 var ii struct {
896 x interface{}
898 Nil(ii, t)
899 ii.x = 2
900 NotNil(ii, t)
902 var fi struct {
903 x func(t *testing.T)
905 Nil(fi, t)
906 fi.x = TestIsNil
907 NotNil(fi, t)
910 func TestInterfaceExtraction(t *testing.T) {
911 var s struct {
912 W io.Writer
915 s.W = os.Stdout
916 v := Indirect(ValueOf(&s)).Field(0).Interface()
917 if v != s.W.(interface{}) {
918 t.Error("Interface() on interface: ", v, s.W)
922 func TestNilPtrValueSub(t *testing.T) {
923 var pi *int
924 if pv := ValueOf(pi); pv.Elem().IsValid() {
925 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
929 func TestMap(t *testing.T) {
930 m := map[string]int{"a": 1, "b": 2}
931 mv := ValueOf(m)
932 if n := mv.Len(); n != len(m) {
933 t.Errorf("Len = %d, want %d", n, len(m))
935 keys := mv.MapKeys()
936 newmap := MakeMap(mv.Type())
937 for k, v := range m {
938 // Check that returned Keys match keys in range.
939 // These aren't required to be in the same order.
940 seen := false
941 for _, kv := range keys {
942 if kv.String() == k {
943 seen = true
944 break
947 if !seen {
948 t.Errorf("Missing key %q", k)
951 // Check that value lookup is correct.
952 vv := mv.MapIndex(ValueOf(k))
953 if vi := vv.Int(); vi != int64(v) {
954 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
957 // Copy into new map.
958 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
960 vv := mv.MapIndex(ValueOf("not-present"))
961 if vv.IsValid() {
962 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
965 newm := newmap.Interface().(map[string]int)
966 if len(newm) != len(m) {
967 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
970 for k, v := range newm {
971 mv, ok := m[k]
972 if mv != v {
973 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
977 newmap.SetMapIndex(ValueOf("a"), Value{})
978 v, ok := newm["a"]
979 if ok {
980 t.Errorf("newm[\"a\"] = %d after delete", v)
983 mv = ValueOf(&m).Elem()
984 mv.Set(Zero(mv.Type()))
985 if m != nil {
986 t.Errorf("mv.Set(nil) failed")
990 func TestNilMap(t *testing.T) {
991 var m map[string]int
992 mv := ValueOf(m)
993 keys := mv.MapKeys()
994 if len(keys) != 0 {
995 t.Errorf(">0 keys for nil map: %v", keys)
998 // Check that value for missing key is zero.
999 x := mv.MapIndex(ValueOf("hello"))
1000 if x.Kind() != Invalid {
1001 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1004 // Check big value too.
1005 var mbig map[string][10 << 20]byte
1006 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1007 if x.Kind() != Invalid {
1008 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1011 // Test that deletes from a nil map succeed.
1012 mv.SetMapIndex(ValueOf("hi"), Value{})
1015 func TestChan(t *testing.T) {
1016 for loop := 0; loop < 2; loop++ {
1017 var c chan int
1018 var cv Value
1020 // check both ways to allocate channels
1021 switch loop {
1022 case 1:
1023 c = make(chan int, 1)
1024 cv = ValueOf(c)
1025 case 0:
1026 cv = MakeChan(TypeOf(c), 1)
1027 c = cv.Interface().(chan int)
1030 // Send
1031 cv.Send(ValueOf(2))
1032 if i := <-c; i != 2 {
1033 t.Errorf("reflect Send 2, native recv %d", i)
1036 // Recv
1037 c <- 3
1038 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1039 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1042 // TryRecv fail
1043 val, ok := cv.TryRecv()
1044 if val.IsValid() || ok {
1045 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1048 // TryRecv success
1049 c <- 4
1050 val, ok = cv.TryRecv()
1051 if !val.IsValid() {
1052 t.Errorf("TryRecv on ready chan got nil")
1053 } else if i := val.Int(); i != 4 || !ok {
1054 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1057 // TrySend fail
1058 c <- 100
1059 ok = cv.TrySend(ValueOf(5))
1060 i := <-c
1061 if ok {
1062 t.Errorf("TrySend on full chan succeeded: value %d", i)
1065 // TrySend success
1066 ok = cv.TrySend(ValueOf(6))
1067 if !ok {
1068 t.Errorf("TrySend on empty chan failed")
1069 select {
1070 case x := <-c:
1071 t.Errorf("TrySend failed but it did send %d", x)
1072 default:
1074 } else {
1075 if i = <-c; i != 6 {
1076 t.Errorf("TrySend 6, recv %d", i)
1080 // Close
1081 c <- 123
1082 cv.Close()
1083 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1084 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1086 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1087 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1091 // check creation of unbuffered channel
1092 var c chan int
1093 cv := MakeChan(TypeOf(c), 0)
1094 c = cv.Interface().(chan int)
1095 if cv.TrySend(ValueOf(7)) {
1096 t.Errorf("TrySend on sync chan succeeded")
1098 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1099 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1102 // len/cap
1103 cv = MakeChan(TypeOf(c), 10)
1104 c = cv.Interface().(chan int)
1105 for i := 0; i < 3; i++ {
1106 c <- i
1108 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1109 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1113 // caseInfo describes a single case in a select test.
1114 type caseInfo struct {
1115 desc string
1116 canSelect bool
1117 recv Value
1118 closed bool
1119 helper func()
1120 panic bool
1123 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1125 func TestSelect(t *testing.T) {
1126 selectWatch.once.Do(func() { go selectWatcher() })
1128 var x exhaustive
1129 nch := 0
1130 newop := func(n int, cap int) (ch, val Value) {
1131 nch++
1132 if nch%101%2 == 1 {
1133 c := make(chan int, cap)
1134 ch = ValueOf(c)
1135 val = ValueOf(n)
1136 } else {
1137 c := make(chan string, cap)
1138 ch = ValueOf(c)
1139 val = ValueOf(fmt.Sprint(n))
1141 return
1144 for n := 0; x.Next(); n++ {
1145 if testing.Short() && n >= 1000 {
1146 break
1148 if n >= 100000 && !*allselect {
1149 break
1151 if n%100000 == 0 && testing.Verbose() {
1152 println("TestSelect", n)
1154 var cases []SelectCase
1155 var info []caseInfo
1157 // Ready send.
1158 if x.Maybe() {
1159 ch, val := newop(len(cases), 1)
1160 cases = append(cases, SelectCase{
1161 Dir: SelectSend,
1162 Chan: ch,
1163 Send: val,
1165 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1168 // Ready recv.
1169 if x.Maybe() {
1170 ch, val := newop(len(cases), 1)
1171 ch.Send(val)
1172 cases = append(cases, SelectCase{
1173 Dir: SelectRecv,
1174 Chan: ch,
1176 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1179 // Blocking send.
1180 if x.Maybe() {
1181 ch, val := newop(len(cases), 0)
1182 cases = append(cases, SelectCase{
1183 Dir: SelectSend,
1184 Chan: ch,
1185 Send: val,
1187 // Let it execute?
1188 if x.Maybe() {
1189 f := func() { ch.Recv() }
1190 info = append(info, caseInfo{desc: "blocking send", helper: f})
1191 } else {
1192 info = append(info, caseInfo{desc: "blocking send"})
1196 // Blocking recv.
1197 if x.Maybe() {
1198 ch, val := newop(len(cases), 0)
1199 cases = append(cases, SelectCase{
1200 Dir: SelectRecv,
1201 Chan: ch,
1203 // Let it execute?
1204 if x.Maybe() {
1205 f := func() { ch.Send(val) }
1206 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1207 } else {
1208 info = append(info, caseInfo{desc: "blocking recv"})
1212 // Zero Chan send.
1213 if x.Maybe() {
1214 // Maybe include value to send.
1215 var val Value
1216 if x.Maybe() {
1217 val = ValueOf(100)
1219 cases = append(cases, SelectCase{
1220 Dir: SelectSend,
1221 Send: val,
1223 info = append(info, caseInfo{desc: "zero Chan send"})
1226 // Zero Chan receive.
1227 if x.Maybe() {
1228 cases = append(cases, SelectCase{
1229 Dir: SelectRecv,
1231 info = append(info, caseInfo{desc: "zero Chan recv"})
1234 // nil Chan send.
1235 if x.Maybe() {
1236 cases = append(cases, SelectCase{
1237 Dir: SelectSend,
1238 Chan: ValueOf((chan int)(nil)),
1239 Send: ValueOf(101),
1241 info = append(info, caseInfo{desc: "nil Chan send"})
1244 // nil Chan recv.
1245 if x.Maybe() {
1246 cases = append(cases, SelectCase{
1247 Dir: SelectRecv,
1248 Chan: ValueOf((chan int)(nil)),
1250 info = append(info, caseInfo{desc: "nil Chan recv"})
1253 // closed Chan send.
1254 if x.Maybe() {
1255 ch := make(chan int)
1256 close(ch)
1257 cases = append(cases, SelectCase{
1258 Dir: SelectSend,
1259 Chan: ValueOf(ch),
1260 Send: ValueOf(101),
1262 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1265 // closed Chan recv.
1266 if x.Maybe() {
1267 ch, val := newop(len(cases), 0)
1268 ch.Close()
1269 val = Zero(val.Type())
1270 cases = append(cases, SelectCase{
1271 Dir: SelectRecv,
1272 Chan: ch,
1274 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1277 var helper func() // goroutine to help the select complete
1279 // Add default? Must be last case here, but will permute.
1280 // Add the default if the select would otherwise
1281 // block forever, and maybe add it anyway.
1282 numCanSelect := 0
1283 canProceed := false
1284 canBlock := true
1285 canPanic := false
1286 helpers := []int{}
1287 for i, c := range info {
1288 if c.canSelect {
1289 canProceed = true
1290 canBlock = false
1291 numCanSelect++
1292 if c.panic {
1293 canPanic = true
1295 } else if c.helper != nil {
1296 canProceed = true
1297 helpers = append(helpers, i)
1300 if !canProceed || x.Maybe() {
1301 cases = append(cases, SelectCase{
1302 Dir: SelectDefault,
1304 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1305 numCanSelect++
1306 } else if canBlock {
1307 // Select needs to communicate with another goroutine.
1308 cas := &info[helpers[x.Choose(len(helpers))]]
1309 helper = cas.helper
1310 cas.canSelect = true
1311 numCanSelect++
1314 // Permute cases and case info.
1315 // Doing too much here makes the exhaustive loop
1316 // too exhausting, so just do two swaps.
1317 for loop := 0; loop < 2; loop++ {
1318 i := x.Choose(len(cases))
1319 j := x.Choose(len(cases))
1320 cases[i], cases[j] = cases[j], cases[i]
1321 info[i], info[j] = info[j], info[i]
1324 if helper != nil {
1325 // We wait before kicking off a goroutine to satisfy a blocked select.
1326 // The pause needs to be big enough to let the select block before
1327 // we run the helper, but if we lose that race once in a while it's okay: the
1328 // select will just proceed immediately. Not a big deal.
1329 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1330 pause := 10 * time.Microsecond
1331 if testing.Short() {
1332 pause = 100 * time.Microsecond
1334 time.AfterFunc(pause, helper)
1337 // Run select.
1338 i, recv, recvOK, panicErr := runSelect(cases, info)
1339 if panicErr != nil && !canPanic {
1340 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1342 if panicErr == nil && canPanic && numCanSelect == 1 {
1343 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1345 if panicErr != nil {
1346 continue
1349 cas := info[i]
1350 if !cas.canSelect {
1351 recvStr := ""
1352 if recv.IsValid() {
1353 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1355 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1356 continue
1358 if cas.panic {
1359 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1360 continue
1363 if cases[i].Dir == SelectRecv {
1364 if !recv.IsValid() {
1365 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1367 if !cas.recv.IsValid() {
1368 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1370 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1371 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1372 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1374 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1376 } else {
1377 if recv.IsValid() || recvOK {
1378 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1384 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1385 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1386 // an error describing the select and panics the entire test binary.
1387 var selectWatch struct {
1388 sync.Mutex
1389 once sync.Once
1390 now time.Time
1391 info []caseInfo
1394 func selectWatcher() {
1395 for {
1396 time.Sleep(1 * time.Second)
1397 selectWatch.Lock()
1398 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1399 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1400 panic("select stuck")
1402 selectWatch.Unlock()
1406 // runSelect runs a single select test.
1407 // It returns the values returned by Select but also returns
1408 // a panic value if the Select panics.
1409 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1410 defer func() {
1411 panicErr = recover()
1413 selectWatch.Lock()
1414 selectWatch.info = nil
1415 selectWatch.Unlock()
1418 selectWatch.Lock()
1419 selectWatch.now = time.Now()
1420 selectWatch.info = info
1421 selectWatch.Unlock()
1423 chosen, recv, recvOK = Select(cases)
1424 return
1427 // fmtSelect formats the information about a single select test.
1428 func fmtSelect(info []caseInfo) string {
1429 var buf bytes.Buffer
1430 fmt.Fprintf(&buf, "\nselect {\n")
1431 for i, cas := range info {
1432 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1433 if cas.recv.IsValid() {
1434 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1436 if cas.canSelect {
1437 fmt.Fprintf(&buf, " canselect")
1439 if cas.panic {
1440 fmt.Fprintf(&buf, " panic")
1442 fmt.Fprintf(&buf, "\n")
1444 fmt.Fprintf(&buf, "}")
1445 return buf.String()
1448 type two [2]uintptr
1450 // Difficult test for function call because of
1451 // implicit padding between arguments.
1452 func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
1453 return b, c, d, e, f, g, h
1456 func TestFunc(t *testing.T) {
1457 ret := ValueOf(dummy).Call([]Value{
1458 ValueOf(byte(10)),
1459 ValueOf(20),
1460 ValueOf(byte(30)),
1461 ValueOf(two{40, 50}),
1462 ValueOf(byte(60)),
1463 ValueOf(float32(70)),
1464 ValueOf(byte(80)),
1466 if len(ret) != 7 {
1467 t.Fatalf("Call returned %d values, want 7", len(ret))
1470 i := byte(ret[0].Uint())
1471 j := int(ret[1].Int())
1472 k := byte(ret[2].Uint())
1473 l := ret[3].Interface().(two)
1474 m := byte(ret[4].Uint())
1475 n := float32(ret[5].Float())
1476 o := byte(ret[6].Uint())
1478 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1479 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1482 for i, v := range ret {
1483 if v.CanAddr() {
1484 t.Errorf("result %d is addressable", i)
1489 type emptyStruct struct{}
1491 type nonEmptyStruct struct {
1492 member int
1495 func returnEmpty() emptyStruct {
1496 return emptyStruct{}
1499 func takesEmpty(e emptyStruct) {
1502 func returnNonEmpty(i int) nonEmptyStruct {
1503 return nonEmptyStruct{member: i}
1506 func takesNonEmpty(n nonEmptyStruct) int {
1507 return n.member
1510 func TestCallWithStruct(t *testing.T) {
1511 r := ValueOf(returnEmpty).Call(nil)
1512 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1513 t.Errorf("returning empty struct returned %#v instead", r)
1515 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1516 if len(r) != 0 {
1517 t.Errorf("takesEmpty returned values: %#v", r)
1519 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1520 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1521 t.Errorf("returnNonEmpty returned %#v", r)
1523 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1524 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1525 t.Errorf("takesNonEmpty returned %#v", r)
1529 func BenchmarkCall(b *testing.B) {
1530 fv := ValueOf(func(a, b string) {})
1531 b.ReportAllocs()
1532 b.RunParallel(func(pb *testing.PB) {
1533 args := []Value{ValueOf("a"), ValueOf("b")}
1534 for pb.Next() {
1535 fv.Call(args)
1540 func TestMakeFunc(t *testing.T) {
1541 f := dummy
1542 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1543 ValueOf(&f).Elem().Set(fv)
1545 // Call g with small arguments so that there is
1546 // something predictable (and different from the
1547 // correct results) in those positions on the stack.
1548 g := dummy
1549 g(1, 2, 3, two{4, 5}, 6, 7, 8)
1551 // Call constructed function f.
1552 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1553 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1554 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1558 func TestMakeFuncInterface(t *testing.T) {
1559 fn := func(i int) int { return i }
1560 incr := func(in []Value) []Value {
1561 return []Value{ValueOf(int(in[0].Int() + 1))}
1563 fv := MakeFunc(TypeOf(fn), incr)
1564 ValueOf(&fn).Elem().Set(fv)
1565 if r := fn(2); r != 3 {
1566 t.Errorf("Call returned %d, want 3", r)
1568 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1569 t.Errorf("Call returned %d, want 15", r)
1571 if r := fv.Interface().(func(int) int)(26); r != 27 {
1572 t.Errorf("Call returned %d, want 27", r)
1576 func TestMakeFuncVariadic(t *testing.T) {
1577 // Test that variadic arguments are packed into a slice and passed as last arg
1578 fn := func(_ int, is ...int) []int { return nil }
1579 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
1580 ValueOf(&fn).Elem().Set(fv)
1582 r := fn(1, 2, 3)
1583 if r[0] != 2 || r[1] != 3 {
1584 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1587 r = fn(1, []int{2, 3}...)
1588 if r[0] != 2 || r[1] != 3 {
1589 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1592 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1593 if r[0] != 2 || r[1] != 3 {
1594 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1597 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1598 if r[0] != 2 || r[1] != 3 {
1599 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1602 f := fv.Interface().(func(int, ...int) []int)
1604 r = f(1, 2, 3)
1605 if r[0] != 2 || r[1] != 3 {
1606 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1608 r = f(1, []int{2, 3}...)
1609 if r[0] != 2 || r[1] != 3 {
1610 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1614 type Point struct {
1615 x, y int
1618 // This will be index 0.
1619 func (p Point) AnotherMethod(scale int) int {
1620 return -1
1623 // This will be index 1.
1624 func (p Point) Dist(scale int) int {
1625 //println("Point.Dist", p.x, p.y, scale)
1626 return p.x*p.x*scale + p.y*p.y*scale
1629 // This will be index 2.
1630 func (p Point) GCMethod(k int) int {
1631 runtime.GC()
1632 return k + p.x
1635 // This will be index 3.
1636 func (p Point) TotalDist(points ...Point) int {
1637 tot := 0
1638 for _, q := range points {
1639 dx := q.x - p.x
1640 dy := q.y - p.y
1641 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
1644 return tot
1647 func TestMethod(t *testing.T) {
1648 // Non-curried method of type.
1649 p := Point{3, 4}
1650 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1651 if i != 250 {
1652 t.Errorf("Type Method returned %d; want 250", i)
1655 m, ok := TypeOf(p).MethodByName("Dist")
1656 if !ok {
1657 t.Fatalf("method by name failed")
1659 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1660 if i != 275 {
1661 t.Errorf("Type MethodByName returned %d; want 275", i)
1664 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1665 if i != 300 {
1666 t.Errorf("Pointer Type Method returned %d; want 300", i)
1669 m, ok = TypeOf(&p).MethodByName("Dist")
1670 if !ok {
1671 t.Fatalf("ptr method by name failed")
1673 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1674 if i != 325 {
1675 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
1678 // Curried method of value.
1679 tfunc := TypeOf((func(int) int)(nil))
1680 v := ValueOf(p).Method(1)
1681 if tt := v.Type(); tt != tfunc {
1682 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1684 i = v.Call([]Value{ValueOf(14)})[0].Int()
1685 if i != 350 {
1686 t.Errorf("Value Method returned %d; want 350", i)
1688 v = ValueOf(p).MethodByName("Dist")
1689 if tt := v.Type(); tt != tfunc {
1690 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1692 i = v.Call([]Value{ValueOf(15)})[0].Int()
1693 if i != 375 {
1694 t.Errorf("Value MethodByName returned %d; want 375", i)
1697 // Curried method of pointer.
1698 v = ValueOf(&p).Method(1)
1699 if tt := v.Type(); tt != tfunc {
1700 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1702 i = v.Call([]Value{ValueOf(16)})[0].Int()
1703 if i != 400 {
1704 t.Errorf("Pointer Value Method returned %d; want 400", i)
1706 v = ValueOf(&p).MethodByName("Dist")
1707 if tt := v.Type(); tt != tfunc {
1708 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1710 i = v.Call([]Value{ValueOf(17)})[0].Int()
1711 if i != 425 {
1712 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1715 // Curried method of interface value.
1716 // Have to wrap interface value in a struct to get at it.
1717 // Passing it to ValueOf directly would
1718 // access the underlying Point, not the interface.
1719 var x interface {
1720 Dist(int) int
1721 } = p
1722 pv := ValueOf(&x).Elem()
1723 v = pv.Method(0)
1724 if tt := v.Type(); tt != tfunc {
1725 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1727 i = v.Call([]Value{ValueOf(18)})[0].Int()
1728 if i != 450 {
1729 t.Errorf("Interface Method returned %d; want 450", i)
1731 v = pv.MethodByName("Dist")
1732 if tt := v.Type(); tt != tfunc {
1733 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1735 i = v.Call([]Value{ValueOf(19)})[0].Int()
1736 if i != 475 {
1737 t.Errorf("Interface MethodByName returned %d; want 475", i)
1741 func TestMethodValue(t *testing.T) {
1742 p := Point{3, 4}
1743 var i int64
1745 // Curried method of value.
1746 tfunc := TypeOf((func(int) int)(nil))
1747 v := ValueOf(p).Method(1)
1748 if tt := v.Type(); tt != tfunc {
1749 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1751 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1752 if i != 250 {
1753 t.Errorf("Value Method returned %d; want 250", i)
1755 v = ValueOf(p).MethodByName("Dist")
1756 if tt := v.Type(); tt != tfunc {
1757 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1759 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1760 if i != 275 {
1761 t.Errorf("Value MethodByName returned %d; want 275", i)
1764 // Curried method of pointer.
1765 v = ValueOf(&p).Method(1)
1766 if tt := v.Type(); tt != tfunc {
1767 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1769 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1770 if i != 300 {
1771 t.Errorf("Pointer Value Method returned %d; want 300", i)
1773 v = ValueOf(&p).MethodByName("Dist")
1774 if tt := v.Type(); tt != tfunc {
1775 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1777 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1778 if i != 325 {
1779 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
1782 // Curried method of pointer to pointer.
1783 pp := &p
1784 v = ValueOf(&pp).Elem().Method(1)
1785 if tt := v.Type(); tt != tfunc {
1786 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
1788 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1789 if i != 350 {
1790 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
1792 v = ValueOf(&pp).Elem().MethodByName("Dist")
1793 if tt := v.Type(); tt != tfunc {
1794 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1796 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1797 if i != 375 {
1798 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
1801 // Curried method of interface value.
1802 // Have to wrap interface value in a struct to get at it.
1803 // Passing it to ValueOf directly would
1804 // access the underlying Point, not the interface.
1805 var s = struct {
1806 X interface {
1807 Dist(int) int
1809 }{p}
1810 pv := ValueOf(s).Field(0)
1811 v = pv.Method(0)
1812 if tt := v.Type(); tt != tfunc {
1813 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1815 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
1816 if i != 400 {
1817 t.Errorf("Interface Method returned %d; want 400", i)
1819 v = pv.MethodByName("Dist")
1820 if tt := v.Type(); tt != tfunc {
1821 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1823 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
1824 if i != 425 {
1825 t.Errorf("Interface MethodByName returned %d; want 425", i)
1829 func TestVariadicMethodValue(t *testing.T) {
1830 p := Point{3, 4}
1831 points := []Point{{20, 21}, {22, 23}, {24, 25}}
1832 want := int64(p.TotalDist(points[0], points[1], points[2]))
1834 // Curried method of value.
1835 tfunc := TypeOf((func(...Point) int)(nil))
1836 v := ValueOf(p).Method(3)
1837 if tt := v.Type(); tt != tfunc {
1838 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
1840 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
1841 if i != want {
1842 t.Errorf("Variadic Method returned %d; want %d", i, want)
1844 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
1845 if i != want {
1846 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
1849 f := v.Interface().(func(...Point) int)
1850 i = int64(f(points[0], points[1], points[2]))
1851 if i != want {
1852 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
1854 i = int64(f(points...))
1855 if i != want {
1856 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
1860 // Reflect version of $GOROOT/test/method5.go
1862 // Concrete types implementing M method.
1863 // Smaller than a word, word-sized, larger than a word.
1864 // Value and pointer receivers.
1866 type Tinter interface {
1867 M(int, byte) (byte, int)
1870 type Tsmallv byte
1872 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1874 type Tsmallp byte
1876 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1878 type Twordv uintptr
1880 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1882 type Twordp uintptr
1884 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1886 type Tbigv [2]uintptr
1888 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1890 type Tbigp [2]uintptr
1892 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1894 // Again, with an unexported method.
1896 type tsmallv byte
1898 func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1900 type tsmallp byte
1902 func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1904 type twordv uintptr
1906 func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1908 type twordp uintptr
1910 func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1912 type tbigv [2]uintptr
1914 func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1916 type tbigp [2]uintptr
1918 func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1920 type tinter interface {
1921 m(int, byte) (byte, int)
1924 // Embedding via pointer.
1926 type Tm1 struct {
1930 type Tm2 struct {
1931 *Tm3
1934 type Tm3 struct {
1935 *Tm4
1938 type Tm4 struct {
1941 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
1943 func TestMethod5(t *testing.T) {
1944 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1945 b, x := f(1000, 99)
1946 if b != 99 || x != 1000+inc {
1947 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1951 CheckV := func(name string, i Value, inc int) {
1952 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
1953 b := bx[0].Interface()
1954 x := bx[1].Interface()
1955 if b != byte(99) || x != 1000+inc {
1956 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1959 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1962 var TinterType = TypeOf(new(Tinter)).Elem()
1963 var tinterType = TypeOf(new(tinter)).Elem()
1965 CheckI := func(name string, i interface{}, inc int) {
1966 v := ValueOf(i)
1967 CheckV(name, v, inc)
1968 CheckV("(i="+name+")", v.Convert(TinterType), inc)
1971 sv := Tsmallv(1)
1972 CheckI("sv", sv, 1)
1973 CheckI("&sv", &sv, 1)
1975 sp := Tsmallp(2)
1976 CheckI("&sp", &sp, 2)
1978 wv := Twordv(3)
1979 CheckI("wv", wv, 3)
1980 CheckI("&wv", &wv, 3)
1982 wp := Twordp(4)
1983 CheckI("&wp", &wp, 4)
1985 bv := Tbigv([2]uintptr{5, 6})
1986 CheckI("bv", bv, 11)
1987 CheckI("&bv", &bv, 11)
1989 bp := Tbigp([2]uintptr{7, 8})
1990 CheckI("&bp", &bp, 15)
1992 t4 := Tm4{}
1993 t3 := Tm3{&t4}
1994 t2 := Tm2{&t3}
1995 t1 := Tm1{t2}
1996 CheckI("t4", t4, 40)
1997 CheckI("&t4", &t4, 40)
1998 CheckI("t3", t3, 40)
1999 CheckI("&t3", &t3, 40)
2000 CheckI("t2", t2, 40)
2001 CheckI("&t2", &t2, 40)
2002 CheckI("t1", t1, 40)
2003 CheckI("&t1", &t1, 40)
2005 methodShouldPanic := func(name string, i interface{}) {
2006 v := ValueOf(i)
2007 m := v.Method(0)
2008 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
2009 shouldPanic(func() { m.Interface() })
2011 v = v.Convert(tinterType)
2012 m = v.Method(0)
2013 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
2014 shouldPanic(func() { m.Interface() })
2017 _sv := tsmallv(1)
2018 methodShouldPanic("_sv", _sv)
2019 methodShouldPanic("&_sv", &_sv)
2021 _sp := tsmallp(2)
2022 methodShouldPanic("&_sp", &_sp)
2024 _wv := twordv(3)
2025 methodShouldPanic("_wv", _wv)
2026 methodShouldPanic("&_wv", &_wv)
2028 _wp := twordp(4)
2029 methodShouldPanic("&_wp", &_wp)
2031 _bv := tbigv([2]uintptr{5, 6})
2032 methodShouldPanic("_bv", _bv)
2033 methodShouldPanic("&_bv", &_bv)
2035 _bp := tbigp([2]uintptr{7, 8})
2036 methodShouldPanic("&_bp", &_bp)
2038 var tnil Tinter
2039 vnil := ValueOf(&tnil).Elem()
2040 shouldPanic(func() { vnil.Method(0) })
2043 func TestInterfaceSet(t *testing.T) {
2044 p := &Point{3, 4}
2046 var s struct {
2047 I interface{}
2048 P interface {
2049 Dist(int) int
2052 sv := ValueOf(&s).Elem()
2053 sv.Field(0).Set(ValueOf(p))
2054 if q := s.I.(*Point); q != p {
2055 t.Errorf("i: have %p want %p", q, p)
2058 pv := sv.Field(1)
2059 pv.Set(ValueOf(p))
2060 if q := s.P.(*Point); q != p {
2061 t.Errorf("i: have %p want %p", q, p)
2064 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2065 if i != 250 {
2066 t.Errorf("Interface Method returned %d; want 250", i)
2070 type T1 struct {
2071 a string
2075 func TestAnonymousFields(t *testing.T) {
2076 var field StructField
2077 var ok bool
2078 var t1 T1
2079 type1 := TypeOf(t1)
2080 if field, ok = type1.FieldByName("int"); !ok {
2081 t.Fatal("no field 'int'")
2083 if field.Index[0] != 1 {
2084 t.Error("field index should be 1; is", field.Index)
2088 type FTest struct {
2089 s interface{}
2090 name string
2091 index []int
2092 value int
2095 type D1 struct {
2096 d int
2098 type D2 struct {
2099 d int
2102 type S0 struct {
2103 A, B, C int
2108 type S1 struct {
2109 B int
2113 type S2 struct {
2114 A int
2118 type S1x struct {
2122 type S1y struct {
2126 type S3 struct {
2129 D, E int
2130 *S1y
2133 type S4 struct {
2135 A int
2138 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2139 type S5 struct {
2145 type S6 struct {
2146 X int
2149 type S7 S6
2151 type S8 struct {
2155 type S9 struct {
2156 X int
2157 Y int
2160 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2161 type S10 struct {
2167 type S11 struct {
2171 type S12 struct {
2175 type S13 struct {
2179 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2180 type S14 struct {
2185 type S15 struct {
2189 type S16 struct {
2193 var fieldTests = []FTest{
2194 {struct{}{}, "", nil, 0},
2195 {struct{}{}, "Foo", nil, 0},
2196 {S0{A: 'a'}, "A", []int{0}, 'a'},
2197 {S0{}, "D", nil, 0},
2198 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2199 {S1{B: 'b'}, "B", []int{0}, 'b'},
2200 {S1{}, "S0", []int{1}, 0},
2201 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2202 {S2{A: 'a'}, "A", []int{0}, 'a'},
2203 {S2{}, "S1", []int{1}, 0},
2204 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2205 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2206 {S2{}, "D", nil, 0},
2207 {S3{}, "S1", nil, 0},
2208 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2209 {S3{}, "B", nil, 0},
2210 {S3{D: 'd'}, "D", []int{2}, 0},
2211 {S3{E: 'e'}, "E", []int{3}, 'e'},
2212 {S4{A: 'a'}, "A", []int{1}, 'a'},
2213 {S4{}, "B", nil, 0},
2214 {S5{}, "X", nil, 0},
2215 {S5{}, "Y", []int{2, 0, 1}, 0},
2216 {S10{}, "X", nil, 0},
2217 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2218 {S14{}, "X", nil, 0},
2221 func TestFieldByIndex(t *testing.T) {
2222 for _, test := range fieldTests {
2223 s := TypeOf(test.s)
2224 f := s.FieldByIndex(test.index)
2225 if f.Name != "" {
2226 if test.index != nil {
2227 if f.Name != test.name {
2228 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2230 } else {
2231 t.Errorf("%s.%s found", s.Name(), f.Name)
2233 } else if len(test.index) > 0 {
2234 t.Errorf("%s.%s not found", s.Name(), test.name)
2237 if test.value != 0 {
2238 v := ValueOf(test.s).FieldByIndex(test.index)
2239 if v.IsValid() {
2240 if x, ok := v.Interface().(int); ok {
2241 if x != test.value {
2242 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2244 } else {
2245 t.Errorf("%s%v value not an int", s.Name(), test.index)
2247 } else {
2248 t.Errorf("%s%v value not found", s.Name(), test.index)
2254 func TestFieldByName(t *testing.T) {
2255 for _, test := range fieldTests {
2256 s := TypeOf(test.s)
2257 f, found := s.FieldByName(test.name)
2258 if found {
2259 if test.index != nil {
2260 // Verify field depth and index.
2261 if len(f.Index) != len(test.index) {
2262 t.Errorf("%s.%s depth %d; want %d: %v vs %v", s.Name(), test.name, len(f.Index), len(test.index), f.Index, test.index)
2263 } else {
2264 for i, x := range f.Index {
2265 if x != test.index[i] {
2266 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2270 } else {
2271 t.Errorf("%s.%s found", s.Name(), f.Name)
2273 } else if len(test.index) > 0 {
2274 t.Errorf("%s.%s not found", s.Name(), test.name)
2277 if test.value != 0 {
2278 v := ValueOf(test.s).FieldByName(test.name)
2279 if v.IsValid() {
2280 if x, ok := v.Interface().(int); ok {
2281 if x != test.value {
2282 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2284 } else {
2285 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2287 } else {
2288 t.Errorf("%s.%s value not found", s.Name(), test.name)
2294 func TestImportPath(t *testing.T) {
2295 tests := []struct {
2296 t Type
2297 path string
2299 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2300 {TypeOf(int(0)), ""},
2301 {TypeOf(int8(0)), ""},
2302 {TypeOf(int16(0)), ""},
2303 {TypeOf(int32(0)), ""},
2304 {TypeOf(int64(0)), ""},
2305 {TypeOf(uint(0)), ""},
2306 {TypeOf(uint8(0)), ""},
2307 {TypeOf(uint16(0)), ""},
2308 {TypeOf(uint32(0)), ""},
2309 {TypeOf(uint64(0)), ""},
2310 {TypeOf(uintptr(0)), ""},
2311 {TypeOf(float32(0)), ""},
2312 {TypeOf(float64(0)), ""},
2313 {TypeOf(complex64(0)), ""},
2314 {TypeOf(complex128(0)), ""},
2315 {TypeOf(byte(0)), ""},
2316 {TypeOf(rune(0)), ""},
2317 {TypeOf([]byte(nil)), ""},
2318 {TypeOf([]rune(nil)), ""},
2319 {TypeOf(string("")), ""},
2320 {TypeOf((*interface{})(nil)).Elem(), ""},
2321 {TypeOf((*byte)(nil)), ""},
2322 {TypeOf((*rune)(nil)), ""},
2323 {TypeOf((*int64)(nil)), ""},
2324 {TypeOf(map[string]int{}), ""},
2325 {TypeOf((*error)(nil)).Elem(), ""},
2327 for _, test := range tests {
2328 if path := test.t.PkgPath(); path != test.path {
2329 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2334 func TestVariadicType(t *testing.T) {
2335 // Test example from Type documentation.
2336 var f func(x int, y ...float64)
2337 typ := TypeOf(f)
2338 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2339 sl := typ.In(1)
2340 if sl.Kind() == Slice {
2341 if sl.Elem() == TypeOf(0.0) {
2342 // ok
2343 return
2348 // Failed
2349 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2350 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2351 for i := 0; i < typ.NumIn(); i++ {
2352 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2354 t.Error(s)
2357 type inner struct {
2358 x int
2361 type outer struct {
2362 y int
2363 inner
2366 func (*inner) m() {}
2367 func (*outer) m() {}
2369 func TestNestedMethods(t *testing.T) {
2370 t.Skip("fails on gccgo due to function wrappers")
2371 typ := TypeOf((*outer)(nil))
2372 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
2373 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
2374 for i := 0; i < typ.NumMethod(); i++ {
2375 m := typ.Method(i)
2376 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2381 type InnerInt struct {
2382 X int
2385 type OuterInt struct {
2386 Y int
2387 InnerInt
2390 func (i *InnerInt) M() int {
2391 return i.X
2394 func TestEmbeddedMethods(t *testing.T) {
2395 /* This part of the test fails on gccgo due to function wrappers.
2396 typ := TypeOf((*OuterInt)(nil))
2397 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2398 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2399 for i := 0; i < typ.NumMethod(); i++ {
2400 m := typ.Method(i)
2401 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2406 i := &InnerInt{3}
2407 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
2408 t.Errorf("i.M() = %d, want 3", v)
2411 o := &OuterInt{1, InnerInt{2}}
2412 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
2413 t.Errorf("i.M() = %d, want 2", v)
2416 f := (*OuterInt).M
2417 if v := f(o); v != 2 {
2418 t.Errorf("f(o) = %d, want 2", v)
2422 func TestPtrTo(t *testing.T) {
2423 var i int
2425 typ := TypeOf(i)
2426 for i = 0; i < 100; i++ {
2427 typ = PtrTo(typ)
2429 for i = 0; i < 100; i++ {
2430 typ = typ.Elem()
2432 if typ != TypeOf(i) {
2433 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
2437 func TestPtrToGC(t *testing.T) {
2438 type T *uintptr
2439 tt := TypeOf(T(nil))
2440 pt := PtrTo(tt)
2441 const n = 100
2442 var x []interface{}
2443 for i := 0; i < n; i++ {
2444 v := New(pt)
2445 p := new(*uintptr)
2446 *p = new(uintptr)
2447 **p = uintptr(i)
2448 v.Elem().Set(ValueOf(p).Convert(pt))
2449 x = append(x, v.Interface())
2451 runtime.GC()
2453 for i, xi := range x {
2454 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2455 if k != uintptr(i) {
2456 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2461 func TestAddr(t *testing.T) {
2462 var p struct {
2463 X, Y int
2466 v := ValueOf(&p)
2467 v = v.Elem()
2468 v = v.Addr()
2469 v = v.Elem()
2470 v = v.Field(0)
2471 v.SetInt(2)
2472 if p.X != 2 {
2473 t.Errorf("Addr.Elem.Set failed to set value")
2476 // Again but take address of the ValueOf value.
2477 // Exercises generation of PtrTypes not present in the binary.
2478 q := &p
2479 v = ValueOf(&q).Elem()
2480 v = v.Addr()
2481 v = v.Elem()
2482 v = v.Elem()
2483 v = v.Addr()
2484 v = v.Elem()
2485 v = v.Field(0)
2486 v.SetInt(3)
2487 if p.X != 3 {
2488 t.Errorf("Addr.Elem.Set failed to set value")
2491 // Starting without pointer we should get changed value
2492 // in interface.
2493 qq := p
2494 v = ValueOf(&qq).Elem()
2495 v0 := v
2496 v = v.Addr()
2497 v = v.Elem()
2498 v = v.Field(0)
2499 v.SetInt(4)
2500 if p.X != 3 { // should be unchanged from last time
2501 t.Errorf("somehow value Set changed original p")
2503 p = v0.Interface().(struct {
2504 X, Y int
2506 if p.X != 4 {
2507 t.Errorf("Addr.Elem.Set valued to set value in top value")
2510 // Verify that taking the address of a type gives us a pointer
2511 // which we can convert back using the usual interface
2512 // notation.
2513 var s struct {
2514 B *bool
2516 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2517 *(ps.(**bool)) = new(bool)
2518 if s.B == nil {
2519 t.Errorf("Addr.Interface direct assignment failed")
2523 /* gccgo does do allocations here.
2525 func noAlloc(t *testing.T, n int, f func(int)) {
2526 if testing.Short() {
2527 t.Skip("skipping malloc count in short mode")
2529 if runtime.GOMAXPROCS(0) > 1 {
2530 t.Skip("skipping; GOMAXPROCS>1")
2532 i := -1
2533 allocs := testing.AllocsPerRun(n, func() {
2534 f(i)
2537 if allocs > 0 {
2538 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2542 func TestAllocations(t *testing.T) {
2543 noAlloc(t, 100, func(j int) {
2544 var i interface{}
2545 var v Value
2547 // We can uncomment this when compiler escape analysis
2548 // is good enough to see that the integer assigned to i
2549 // does not escape and therefore need not be allocated.
2551 // i = 42 + j
2552 // v = ValueOf(i)
2553 // if int(v.Int()) != 42+j {
2554 // panic("wrong int")
2555 // }
2557 i = func(j int) int { return j }
2558 v = ValueOf(i)
2559 if v.Interface().(func(int) int)(j) != j {
2560 panic("wrong result")
2567 func TestSmallNegativeInt(t *testing.T) {
2568 i := int16(-1)
2569 v := ValueOf(i)
2570 if v.Int() != -1 {
2571 t.Errorf("int16(-1).Int() returned %v", v.Int())
2575 func TestIndex(t *testing.T) {
2576 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2577 v := ValueOf(xs).Index(3).Interface().(byte)
2578 if v != xs[3] {
2579 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2581 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2582 v = ValueOf(xa).Index(2).Interface().(byte)
2583 if v != xa[2] {
2584 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2586 s := "0123456789"
2587 v = ValueOf(s).Index(3).Interface().(byte)
2588 if v != s[3] {
2589 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2593 func TestSlice(t *testing.T) {
2594 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2595 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
2596 if len(v) != 2 {
2597 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2599 if cap(v) != 5 {
2600 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2602 if !DeepEqual(v[0:5], xs[3:]) {
2603 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
2605 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2606 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
2607 if len(v) != 3 {
2608 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2610 if cap(v) != 6 {
2611 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2613 if !DeepEqual(v[0:6], xa[2:]) {
2614 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
2616 s := "0123456789"
2617 vs := ValueOf(s).Slice(3, 5).Interface().(string)
2618 if vs != s[3:5] {
2619 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2622 rv := ValueOf(&xs).Elem()
2623 rv = rv.Slice(3, 4)
2624 ptr2 := rv.Pointer()
2625 rv = rv.Slice(5, 5)
2626 ptr3 := rv.Pointer()
2627 if ptr3 != ptr2 {
2628 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
2632 func TestSlice3(t *testing.T) {
2633 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2634 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
2635 if len(v) != 2 {
2636 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
2638 if cap(v) != 4 {
2639 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
2641 if !DeepEqual(v[0:4], xs[3:7:7]) {
2642 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
2644 rv := ValueOf(&xs).Elem()
2645 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2646 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2647 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2649 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2650 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
2651 if len(v) != 3 {
2652 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
2654 if cap(v) != 4 {
2655 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
2657 if !DeepEqual(v[0:4], xa[2:6:6]) {
2658 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
2660 rv = ValueOf(&xa).Elem()
2661 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2662 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2663 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2665 s := "hello world"
2666 rv = ValueOf(&s).Elem()
2667 shouldPanic(func() { rv.Slice3(1, 2, 3) })
2669 rv = ValueOf(&xs).Elem()
2670 rv = rv.Slice3(3, 5, 7)
2671 ptr2 := rv.Pointer()
2672 rv = rv.Slice3(4, 4, 4)
2673 ptr3 := rv.Pointer()
2674 if ptr3 != ptr2 {
2675 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
2679 func TestSetLenCap(t *testing.T) {
2680 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2681 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2683 vs := ValueOf(&xs).Elem()
2684 shouldPanic(func() { vs.SetLen(10) })
2685 shouldPanic(func() { vs.SetCap(10) })
2686 shouldPanic(func() { vs.SetLen(-1) })
2687 shouldPanic(func() { vs.SetCap(-1) })
2688 shouldPanic(func() { vs.SetCap(6) }) // smaller than len
2689 vs.SetLen(5)
2690 if len(xs) != 5 || cap(xs) != 8 {
2691 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
2693 vs.SetCap(6)
2694 if len(xs) != 5 || cap(xs) != 6 {
2695 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
2697 vs.SetCap(5)
2698 if len(xs) != 5 || cap(xs) != 5 {
2699 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
2701 shouldPanic(func() { vs.SetCap(4) }) // smaller than len
2702 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
2704 va := ValueOf(&xa).Elem()
2705 shouldPanic(func() { va.SetLen(8) })
2706 shouldPanic(func() { va.SetCap(8) })
2709 func TestVariadic(t *testing.T) {
2710 var b bytes.Buffer
2711 V := ValueOf
2713 b.Reset()
2714 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
2715 if b.String() != "hello, 42 world" {
2716 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
2719 b.Reset()
2720 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
2721 if b.String() != "hello, 42 world" {
2722 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
2726 func TestFuncArg(t *testing.T) {
2727 f1 := func(i int, f func(int) int) int { return f(i) }
2728 f2 := func(i int) int { return i + 1 }
2729 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
2730 if r[0].Int() != 101 {
2731 t.Errorf("function returned %d, want 101", r[0].Int())
2735 func TestStructArg(t *testing.T) {
2736 type padded struct {
2737 B string
2738 C int32
2740 var (
2741 gotA padded
2742 gotB uint32
2743 wantA = padded{"3", 4}
2744 wantB = uint32(5)
2746 f := func(a padded, b uint32) {
2747 gotA, gotB = a, b
2749 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
2750 if gotA != wantA || gotB != wantB {
2751 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
2755 var tagGetTests = []struct {
2756 Tag StructTag
2757 Key string
2758 Value string
2760 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2761 {`protobuf:"PB(1,2)"`, `foo`, ``},
2762 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2763 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2764 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2765 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
2766 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
2769 func TestTagGet(t *testing.T) {
2770 for _, tt := range tagGetTests {
2771 if v := tt.Tag.Get(tt.Key); v != tt.Value {
2772 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
2777 func TestBytes(t *testing.T) {
2778 type B []byte
2779 x := B{1, 2, 3, 4}
2780 y := ValueOf(x).Bytes()
2781 if !bytes.Equal(x, y) {
2782 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2784 if &x[0] != &y[0] {
2785 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2789 func TestSetBytes(t *testing.T) {
2790 type B []byte
2791 var x B
2792 y := []byte{1, 2, 3, 4}
2793 ValueOf(&x).Elem().SetBytes(y)
2794 if !bytes.Equal(x, y) {
2795 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2797 if &x[0] != &y[0] {
2798 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2802 type Private struct {
2803 x int
2804 y **int
2805 Z int
2808 func (p *Private) m() {
2811 type private struct {
2812 Z int
2813 z int
2814 S string
2815 A [1]Private
2816 T []Private
2819 func (p *private) P() {
2822 type Public struct {
2823 X int
2824 Y **int
2825 private
2828 func (p *Public) M() {
2831 func TestUnexported(t *testing.T) {
2832 var pub Public
2833 pub.S = "S"
2834 pub.T = pub.A[:]
2835 v := ValueOf(&pub)
2836 isValid(v.Elem().Field(0))
2837 isValid(v.Elem().Field(1))
2838 isValid(v.Elem().Field(2))
2839 isValid(v.Elem().FieldByName("X"))
2840 isValid(v.Elem().FieldByName("Y"))
2841 isValid(v.Elem().FieldByName("Z"))
2842 isValid(v.Type().Method(0).Func)
2843 m, _ := v.Type().MethodByName("M")
2844 isValid(m.Func)
2845 m, _ = v.Type().MethodByName("P")
2846 isValid(m.Func)
2847 isNonNil(v.Elem().Field(0).Interface())
2848 isNonNil(v.Elem().Field(1).Interface())
2849 isNonNil(v.Elem().Field(2).Field(2).Index(0))
2850 isNonNil(v.Elem().FieldByName("X").Interface())
2851 isNonNil(v.Elem().FieldByName("Y").Interface())
2852 isNonNil(v.Elem().FieldByName("Z").Interface())
2853 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
2854 isNonNil(v.Type().Method(0).Func.Interface())
2855 m, _ = v.Type().MethodByName("P")
2856 isNonNil(m.Func.Interface())
2858 var priv Private
2859 v = ValueOf(&priv)
2860 isValid(v.Elem().Field(0))
2861 isValid(v.Elem().Field(1))
2862 isValid(v.Elem().FieldByName("x"))
2863 isValid(v.Elem().FieldByName("y"))
2864 isValid(v.Type().Method(0).Func)
2865 shouldPanic(func() { v.Elem().Field(0).Interface() })
2866 shouldPanic(func() { v.Elem().Field(1).Interface() })
2867 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
2868 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
2869 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
2872 func TestSetPanic(t *testing.T) {
2873 ok := func(f func()) { f() }
2874 bad := shouldPanic
2875 clear := func(v Value) { v.Set(Zero(v.Type())) }
2877 type t0 struct {
2878 W int
2881 type t1 struct {
2882 Y int
2886 type T2 struct {
2887 Z int
2888 namedT0 t0
2891 type T struct {
2892 X int
2895 NamedT1 t1
2896 NamedT2 T2
2897 namedT1 t1
2898 namedT2 T2
2901 // not addressable
2902 v := ValueOf(T{})
2903 bad(func() { clear(v.Field(0)) }) // .X
2904 bad(func() { clear(v.Field(1)) }) // .t1
2905 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
2906 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
2907 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
2908 bad(func() { clear(v.Field(2)) }) // .T2
2909 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
2910 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
2911 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
2912 bad(func() { clear(v.Field(3)) }) // .NamedT1
2913 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
2914 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
2915 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
2916 bad(func() { clear(v.Field(4)) }) // .NamedT2
2917 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
2918 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
2919 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
2920 bad(func() { clear(v.Field(5)) }) // .namedT1
2921 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
2922 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
2923 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
2924 bad(func() { clear(v.Field(6)) }) // .namedT2
2925 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
2926 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
2927 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
2929 // addressable
2930 v = ValueOf(&T{}).Elem()
2931 ok(func() { clear(v.Field(0)) }) // .X
2932 bad(func() { clear(v.Field(1)) }) // .t1
2933 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
2934 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
2935 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
2936 ok(func() { clear(v.Field(2)) }) // .T2
2937 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
2938 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
2939 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
2940 ok(func() { clear(v.Field(3)) }) // .NamedT1
2941 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
2942 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
2943 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
2944 ok(func() { clear(v.Field(4)) }) // .NamedT2
2945 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
2946 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
2947 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
2948 bad(func() { clear(v.Field(5)) }) // .namedT1
2949 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
2950 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
2951 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
2952 bad(func() { clear(v.Field(6)) }) // .namedT2
2953 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
2954 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
2955 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
2958 type timp int
2960 func (t timp) W() {}
2961 func (t timp) Y() {}
2962 func (t timp) w() {}
2963 func (t timp) y() {}
2965 func TestCallPanic(t *testing.T) {
2966 type t0 interface {
2970 type T1 interface {
2974 type T2 struct {
2978 type T struct {
2979 t0 // 0
2980 T1 // 1
2982 NamedT0 t0 // 2
2983 NamedT1 T1 // 3
2984 NamedT2 T2 // 4
2986 namedT0 t0 // 5
2987 namedT1 T1 // 6
2988 namedT2 T2 // 7
2990 ok := func(f func()) { f() }
2991 bad := shouldPanic
2992 call := func(v Value) { v.Call(nil) }
2994 i := timp(0)
2995 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
2996 ok(func() { call(v.Field(0).Method(0)) }) // .t0.W
2997 ok(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
2998 bad(func() { call(v.Field(0).Method(1)) }) // .t0.w
2999 bad(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3000 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3001 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3002 bad(func() { call(v.Field(1).Method(1)) }) // .T1.y
3003 bad(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3005 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3006 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3007 bad(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3008 bad(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3010 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3011 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3012 bad(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3013 bad(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3015 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3016 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3017 ok(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3018 ok(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3020 bad(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3021 bad(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3022 bad(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3023 bad(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3025 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3026 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3027 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3028 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3030 bad(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3031 bad(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3032 bad(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3033 bad(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3036 func shouldPanic(f func()) {
3037 defer func() {
3038 if recover() == nil {
3039 panic("did not panic")
3045 func isNonNil(x interface{}) {
3046 if x == nil {
3047 panic("nil interface")
3051 func isValid(v Value) {
3052 if !v.IsValid() {
3053 panic("zero Value")
3057 func TestAlias(t *testing.T) {
3058 x := string("hello")
3059 v := ValueOf(&x).Elem()
3060 oldvalue := v.Interface()
3061 v.SetString("world")
3062 newvalue := v.Interface()
3064 if oldvalue != "hello" || newvalue != "world" {
3065 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3069 var V = ValueOf
3071 func EmptyInterfaceV(x interface{}) Value {
3072 return ValueOf(&x).Elem()
3075 func ReaderV(x io.Reader) Value {
3076 return ValueOf(&x).Elem()
3079 func ReadWriterV(x io.ReadWriter) Value {
3080 return ValueOf(&x).Elem()
3083 type Empty struct{}
3084 type MyString string
3085 type MyBytes []byte
3086 type MyRunes []int32
3087 type MyFunc func()
3088 type MyByte byte
3090 var convertTests = []struct {
3091 in Value
3092 out Value
3094 // numbers
3096 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3098 package main
3100 import "fmt"
3102 var numbers = []string{
3103 "int8", "uint8", "int16", "uint16",
3104 "int32", "uint32", "int64", "uint64",
3105 "int", "uint", "uintptr",
3106 "float32", "float64",
3109 func main() {
3110 // all pairs but in an unusual order,
3111 // to emit all the int8, uint8 cases
3112 // before n grows too big.
3113 n := 1
3114 for i, f := range numbers {
3115 for _, g := range numbers[i:] {
3116 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3118 if f != g {
3119 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3126 {V(int8(1)), V(int8(1))},
3127 {V(int8(2)), V(uint8(2))},
3128 {V(uint8(3)), V(int8(3))},
3129 {V(int8(4)), V(int16(4))},
3130 {V(int16(5)), V(int8(5))},
3131 {V(int8(6)), V(uint16(6))},
3132 {V(uint16(7)), V(int8(7))},
3133 {V(int8(8)), V(int32(8))},
3134 {V(int32(9)), V(int8(9))},
3135 {V(int8(10)), V(uint32(10))},
3136 {V(uint32(11)), V(int8(11))},
3137 {V(int8(12)), V(int64(12))},
3138 {V(int64(13)), V(int8(13))},
3139 {V(int8(14)), V(uint64(14))},
3140 {V(uint64(15)), V(int8(15))},
3141 {V(int8(16)), V(int(16))},
3142 {V(int(17)), V(int8(17))},
3143 {V(int8(18)), V(uint(18))},
3144 {V(uint(19)), V(int8(19))},
3145 {V(int8(20)), V(uintptr(20))},
3146 {V(uintptr(21)), V(int8(21))},
3147 {V(int8(22)), V(float32(22))},
3148 {V(float32(23)), V(int8(23))},
3149 {V(int8(24)), V(float64(24))},
3150 {V(float64(25)), V(int8(25))},
3151 {V(uint8(26)), V(uint8(26))},
3152 {V(uint8(27)), V(int16(27))},
3153 {V(int16(28)), V(uint8(28))},
3154 {V(uint8(29)), V(uint16(29))},
3155 {V(uint16(30)), V(uint8(30))},
3156 {V(uint8(31)), V(int32(31))},
3157 {V(int32(32)), V(uint8(32))},
3158 {V(uint8(33)), V(uint32(33))},
3159 {V(uint32(34)), V(uint8(34))},
3160 {V(uint8(35)), V(int64(35))},
3161 {V(int64(36)), V(uint8(36))},
3162 {V(uint8(37)), V(uint64(37))},
3163 {V(uint64(38)), V(uint8(38))},
3164 {V(uint8(39)), V(int(39))},
3165 {V(int(40)), V(uint8(40))},
3166 {V(uint8(41)), V(uint(41))},
3167 {V(uint(42)), V(uint8(42))},
3168 {V(uint8(43)), V(uintptr(43))},
3169 {V(uintptr(44)), V(uint8(44))},
3170 {V(uint8(45)), V(float32(45))},
3171 {V(float32(46)), V(uint8(46))},
3172 {V(uint8(47)), V(float64(47))},
3173 {V(float64(48)), V(uint8(48))},
3174 {V(int16(49)), V(int16(49))},
3175 {V(int16(50)), V(uint16(50))},
3176 {V(uint16(51)), V(int16(51))},
3177 {V(int16(52)), V(int32(52))},
3178 {V(int32(53)), V(int16(53))},
3179 {V(int16(54)), V(uint32(54))},
3180 {V(uint32(55)), V(int16(55))},
3181 {V(int16(56)), V(int64(56))},
3182 {V(int64(57)), V(int16(57))},
3183 {V(int16(58)), V(uint64(58))},
3184 {V(uint64(59)), V(int16(59))},
3185 {V(int16(60)), V(int(60))},
3186 {V(int(61)), V(int16(61))},
3187 {V(int16(62)), V(uint(62))},
3188 {V(uint(63)), V(int16(63))},
3189 {V(int16(64)), V(uintptr(64))},
3190 {V(uintptr(65)), V(int16(65))},
3191 {V(int16(66)), V(float32(66))},
3192 {V(float32(67)), V(int16(67))},
3193 {V(int16(68)), V(float64(68))},
3194 {V(float64(69)), V(int16(69))},
3195 {V(uint16(70)), V(uint16(70))},
3196 {V(uint16(71)), V(int32(71))},
3197 {V(int32(72)), V(uint16(72))},
3198 {V(uint16(73)), V(uint32(73))},
3199 {V(uint32(74)), V(uint16(74))},
3200 {V(uint16(75)), V(int64(75))},
3201 {V(int64(76)), V(uint16(76))},
3202 {V(uint16(77)), V(uint64(77))},
3203 {V(uint64(78)), V(uint16(78))},
3204 {V(uint16(79)), V(int(79))},
3205 {V(int(80)), V(uint16(80))},
3206 {V(uint16(81)), V(uint(81))},
3207 {V(uint(82)), V(uint16(82))},
3208 {V(uint16(83)), V(uintptr(83))},
3209 {V(uintptr(84)), V(uint16(84))},
3210 {V(uint16(85)), V(float32(85))},
3211 {V(float32(86)), V(uint16(86))},
3212 {V(uint16(87)), V(float64(87))},
3213 {V(float64(88)), V(uint16(88))},
3214 {V(int32(89)), V(int32(89))},
3215 {V(int32(90)), V(uint32(90))},
3216 {V(uint32(91)), V(int32(91))},
3217 {V(int32(92)), V(int64(92))},
3218 {V(int64(93)), V(int32(93))},
3219 {V(int32(94)), V(uint64(94))},
3220 {V(uint64(95)), V(int32(95))},
3221 {V(int32(96)), V(int(96))},
3222 {V(int(97)), V(int32(97))},
3223 {V(int32(98)), V(uint(98))},
3224 {V(uint(99)), V(int32(99))},
3225 {V(int32(100)), V(uintptr(100))},
3226 {V(uintptr(101)), V(int32(101))},
3227 {V(int32(102)), V(float32(102))},
3228 {V(float32(103)), V(int32(103))},
3229 {V(int32(104)), V(float64(104))},
3230 {V(float64(105)), V(int32(105))},
3231 {V(uint32(106)), V(uint32(106))},
3232 {V(uint32(107)), V(int64(107))},
3233 {V(int64(108)), V(uint32(108))},
3234 {V(uint32(109)), V(uint64(109))},
3235 {V(uint64(110)), V(uint32(110))},
3236 {V(uint32(111)), V(int(111))},
3237 {V(int(112)), V(uint32(112))},
3238 {V(uint32(113)), V(uint(113))},
3239 {V(uint(114)), V(uint32(114))},
3240 {V(uint32(115)), V(uintptr(115))},
3241 {V(uintptr(116)), V(uint32(116))},
3242 {V(uint32(117)), V(float32(117))},
3243 {V(float32(118)), V(uint32(118))},
3244 {V(uint32(119)), V(float64(119))},
3245 {V(float64(120)), V(uint32(120))},
3246 {V(int64(121)), V(int64(121))},
3247 {V(int64(122)), V(uint64(122))},
3248 {V(uint64(123)), V(int64(123))},
3249 {V(int64(124)), V(int(124))},
3250 {V(int(125)), V(int64(125))},
3251 {V(int64(126)), V(uint(126))},
3252 {V(uint(127)), V(int64(127))},
3253 {V(int64(128)), V(uintptr(128))},
3254 {V(uintptr(129)), V(int64(129))},
3255 {V(int64(130)), V(float32(130))},
3256 {V(float32(131)), V(int64(131))},
3257 {V(int64(132)), V(float64(132))},
3258 {V(float64(133)), V(int64(133))},
3259 {V(uint64(134)), V(uint64(134))},
3260 {V(uint64(135)), V(int(135))},
3261 {V(int(136)), V(uint64(136))},
3262 {V(uint64(137)), V(uint(137))},
3263 {V(uint(138)), V(uint64(138))},
3264 {V(uint64(139)), V(uintptr(139))},
3265 {V(uintptr(140)), V(uint64(140))},
3266 {V(uint64(141)), V(float32(141))},
3267 {V(float32(142)), V(uint64(142))},
3268 {V(uint64(143)), V(float64(143))},
3269 {V(float64(144)), V(uint64(144))},
3270 {V(int(145)), V(int(145))},
3271 {V(int(146)), V(uint(146))},
3272 {V(uint(147)), V(int(147))},
3273 {V(int(148)), V(uintptr(148))},
3274 {V(uintptr(149)), V(int(149))},
3275 {V(int(150)), V(float32(150))},
3276 {V(float32(151)), V(int(151))},
3277 {V(int(152)), V(float64(152))},
3278 {V(float64(153)), V(int(153))},
3279 {V(uint(154)), V(uint(154))},
3280 {V(uint(155)), V(uintptr(155))},
3281 {V(uintptr(156)), V(uint(156))},
3282 {V(uint(157)), V(float32(157))},
3283 {V(float32(158)), V(uint(158))},
3284 {V(uint(159)), V(float64(159))},
3285 {V(float64(160)), V(uint(160))},
3286 {V(uintptr(161)), V(uintptr(161))},
3287 {V(uintptr(162)), V(float32(162))},
3288 {V(float32(163)), V(uintptr(163))},
3289 {V(uintptr(164)), V(float64(164))},
3290 {V(float64(165)), V(uintptr(165))},
3291 {V(float32(166)), V(float32(166))},
3292 {V(float32(167)), V(float64(167))},
3293 {V(float64(168)), V(float32(168))},
3294 {V(float64(169)), V(float64(169))},
3296 // truncation
3297 {V(float64(1.5)), V(int(1))},
3299 // complex
3300 {V(complex64(1i)), V(complex64(1i))},
3301 {V(complex64(2i)), V(complex128(2i))},
3302 {V(complex128(3i)), V(complex64(3i))},
3303 {V(complex128(4i)), V(complex128(4i))},
3305 // string
3306 {V(string("hello")), V(string("hello"))},
3307 {V(string("bytes1")), V([]byte("bytes1"))},
3308 {V([]byte("bytes2")), V(string("bytes2"))},
3309 {V([]byte("bytes3")), V([]byte("bytes3"))},
3310 {V(string("runes♝")), V([]rune("runes♝"))},
3311 {V([]rune("runes♕")), V(string("runes♕"))},
3312 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3313 {V(int('a')), V(string("a"))},
3314 {V(int8('a')), V(string("a"))},
3315 {V(int16('a')), V(string("a"))},
3316 {V(int32('a')), V(string("a"))},
3317 {V(int64('a')), V(string("a"))},
3318 {V(uint('a')), V(string("a"))},
3319 {V(uint8('a')), V(string("a"))},
3320 {V(uint16('a')), V(string("a"))},
3321 {V(uint32('a')), V(string("a"))},
3322 {V(uint64('a')), V(string("a"))},
3323 {V(uintptr('a')), V(string("a"))},
3324 {V(int(-1)), V(string("\uFFFD"))},
3325 {V(int8(-2)), V(string("\uFFFD"))},
3326 {V(int16(-3)), V(string("\uFFFD"))},
3327 {V(int32(-4)), V(string("\uFFFD"))},
3328 {V(int64(-5)), V(string("\uFFFD"))},
3329 {V(uint(0x110001)), V(string("\uFFFD"))},
3330 {V(uint32(0x110002)), V(string("\uFFFD"))},
3331 {V(uint64(0x110003)), V(string("\uFFFD"))},
3332 {V(uintptr(0x110004)), V(string("\uFFFD"))},
3334 // named string
3335 {V(MyString("hello")), V(string("hello"))},
3336 {V(string("hello")), V(MyString("hello"))},
3337 {V(string("hello")), V(string("hello"))},
3338 {V(MyString("hello")), V(MyString("hello"))},
3339 {V(MyString("bytes1")), V([]byte("bytes1"))},
3340 {V([]byte("bytes2")), V(MyString("bytes2"))},
3341 {V([]byte("bytes3")), V([]byte("bytes3"))},
3342 {V(MyString("runes♝")), V([]rune("runes♝"))},
3343 {V([]rune("runes♕")), V(MyString("runes♕"))},
3344 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3345 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3346 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3347 {V(int('a')), V(MyString("a"))},
3348 {V(int8('a')), V(MyString("a"))},
3349 {V(int16('a')), V(MyString("a"))},
3350 {V(int32('a')), V(MyString("a"))},
3351 {V(int64('a')), V(MyString("a"))},
3352 {V(uint('a')), V(MyString("a"))},
3353 {V(uint8('a')), V(MyString("a"))},
3354 {V(uint16('a')), V(MyString("a"))},
3355 {V(uint32('a')), V(MyString("a"))},
3356 {V(uint64('a')), V(MyString("a"))},
3357 {V(uintptr('a')), V(MyString("a"))},
3358 {V(int(-1)), V(MyString("\uFFFD"))},
3359 {V(int8(-2)), V(MyString("\uFFFD"))},
3360 {V(int16(-3)), V(MyString("\uFFFD"))},
3361 {V(int32(-4)), V(MyString("\uFFFD"))},
3362 {V(int64(-5)), V(MyString("\uFFFD"))},
3363 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3364 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3365 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3366 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3368 // named []byte
3369 {V(string("bytes1")), V(MyBytes("bytes1"))},
3370 {V(MyBytes("bytes2")), V(string("bytes2"))},
3371 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3372 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3373 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3375 // named []rune
3376 {V(string("runes♝")), V(MyRunes("runes♝"))},
3377 {V(MyRunes("runes♕")), V(string("runes♕"))},
3378 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3379 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3380 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3382 // named types and equal underlying types
3383 {V(new(int)), V(new(integer))},
3384 {V(new(integer)), V(new(int))},
3385 {V(Empty{}), V(struct{}{})},
3386 {V(new(Empty)), V(new(struct{}))},
3387 {V(struct{}{}), V(Empty{})},
3388 {V(new(struct{})), V(new(Empty))},
3389 {V(Empty{}), V(Empty{})},
3390 {V(MyBytes{}), V([]byte{})},
3391 {V([]byte{}), V(MyBytes{})},
3392 {V((func())(nil)), V(MyFunc(nil))},
3393 {V((MyFunc)(nil)), V((func())(nil))},
3395 // can convert *byte and *MyByte
3396 {V((*byte)(nil)), V((*MyByte)(nil))},
3397 {V((*MyByte)(nil)), V((*byte)(nil))},
3399 // cannot convert mismatched array sizes
3400 {V([2]byte{}), V([2]byte{})},
3401 {V([3]byte{}), V([3]byte{})},
3403 // cannot convert other instances
3404 {V((**byte)(nil)), V((**byte)(nil))},
3405 {V((**MyByte)(nil)), V((**MyByte)(nil))},
3406 {V((chan byte)(nil)), V((chan byte)(nil))},
3407 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3408 {V(([]byte)(nil)), V(([]byte)(nil))},
3409 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
3410 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3411 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
3412 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3413 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
3414 {V([2]byte{}), V([2]byte{})},
3415 {V([2]MyByte{}), V([2]MyByte{})},
3417 // other
3418 {V((***int)(nil)), V((***int)(nil))},
3419 {V((***byte)(nil)), V((***byte)(nil))},
3420 {V((***int32)(nil)), V((***int32)(nil))},
3421 {V((***int64)(nil)), V((***int64)(nil))},
3422 {V((chan int)(nil)), V((<-chan int)(nil))},
3423 {V((chan int)(nil)), V((chan<- int)(nil))},
3424 {V((chan string)(nil)), V((<-chan string)(nil))},
3425 {V((chan string)(nil)), V((chan<- string)(nil))},
3426 {V((chan byte)(nil)), V((chan byte)(nil))},
3427 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3428 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3429 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3430 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3431 {V([]uint(nil)), V([]uint(nil))},
3432 {V([]int(nil)), V([]int(nil))},
3433 {V(new(interface{})), V(new(interface{}))},
3434 {V(new(io.Reader)), V(new(io.Reader))},
3435 {V(new(io.Writer)), V(new(io.Writer))},
3437 // interfaces
3438 {V(int(1)), EmptyInterfaceV(int(1))},
3439 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3440 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3441 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3442 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
3445 func TestConvert(t *testing.T) {
3446 canConvert := map[[2]Type]bool{}
3447 all := map[Type]bool{}
3449 for _, tt := range convertTests {
3450 t1 := tt.in.Type()
3451 if !t1.ConvertibleTo(t1) {
3452 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
3453 continue
3456 t2 := tt.out.Type()
3457 if !t1.ConvertibleTo(t2) {
3458 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
3459 continue
3462 all[t1] = true
3463 all[t2] = true
3464 canConvert[[2]Type{t1, t2}] = true
3466 // vout1 represents the in value converted to the in type.
3467 v1 := tt.in
3468 vout1 := v1.Convert(t1)
3469 out1 := vout1.Interface()
3470 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
3471 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
3474 // vout2 represents the in value converted to the out type.
3475 vout2 := v1.Convert(t2)
3476 out2 := vout2.Interface()
3477 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
3478 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
3481 // vout3 represents a new value of the out type, set to vout2. This makes
3482 // sure the converted value vout2 is really usable as a regular value.
3483 vout3 := New(t2).Elem()
3484 vout3.Set(vout2)
3485 out3 := vout3.Interface()
3486 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
3487 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
3490 if IsRO(v1) {
3491 t.Errorf("table entry %v is RO, should not be", v1)
3493 if IsRO(vout1) {
3494 t.Errorf("self-conversion output %v is RO, should not be", vout1)
3496 if IsRO(vout2) {
3497 t.Errorf("conversion output %v is RO, should not be", vout2)
3499 if IsRO(vout3) {
3500 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
3502 if !IsRO(MakeRO(v1).Convert(t1)) {
3503 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3505 if !IsRO(MakeRO(v1).Convert(t2)) {
3506 t.Errorf("RO conversion output %v is not RO, should be", v1)
3510 // Assume that of all the types we saw during the tests,
3511 // if there wasn't an explicit entry for a conversion between
3512 // a pair of types, then it's not to be allowed. This checks for
3513 // things like 'int64' converting to '*int'.
3514 for t1 := range all {
3515 for t2 := range all {
3516 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3517 if ok := t1.ConvertibleTo(t2); ok != expectOK {
3518 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3524 type ComparableStruct struct {
3525 X int
3528 type NonComparableStruct struct {
3529 X int
3530 Y map[string]int
3533 var comparableTests = []struct {
3534 typ Type
3535 ok bool
3537 {TypeOf(1), true},
3538 {TypeOf("hello"), true},
3539 {TypeOf(new(byte)), true},
3540 {TypeOf((func())(nil)), false},
3541 {TypeOf([]byte{}), false},
3542 {TypeOf(map[string]int{}), false},
3543 {TypeOf(make(chan int)), true},
3544 {TypeOf(1.5), true},
3545 {TypeOf(false), true},
3546 {TypeOf(1i), true},
3547 {TypeOf(ComparableStruct{}), true},
3548 {TypeOf(NonComparableStruct{}), false},
3549 {TypeOf([10]map[string]int{}), false},
3550 {TypeOf([10]string{}), true},
3551 {TypeOf(new(interface{})).Elem(), true},
3554 func TestComparable(t *testing.T) {
3555 for _, tt := range comparableTests {
3556 if ok := tt.typ.Comparable(); ok != tt.ok {
3557 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
3562 func TestOverflow(t *testing.T) {
3563 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3564 t.Errorf("%v wrongly overflows float64", 1e300)
3567 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3568 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3569 t.Errorf("%v wrongly overflows float32", maxFloat32)
3571 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3572 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3573 t.Errorf("%v should overflow float32", ovfFloat32)
3575 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3576 t.Errorf("%v should overflow float32", -ovfFloat32)
3579 maxInt32 := int64(0x7fffffff)
3580 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3581 t.Errorf("%v wrongly overflows int32", maxInt32)
3583 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3584 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3586 ovfInt32 := int64(1 << 31)
3587 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3588 t.Errorf("%v should overflow int32", ovfInt32)
3591 maxUint32 := uint64(0xffffffff)
3592 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3593 t.Errorf("%v wrongly overflows uint32", maxUint32)
3595 ovfUint32 := uint64(1 << 32)
3596 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3597 t.Errorf("%v should overflow uint32", ovfUint32)
3601 func checkSameType(t *testing.T, x, y interface{}) {
3602 if TypeOf(x) != TypeOf(y) {
3603 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3607 func TestArrayOf(t *testing.T) {
3608 // check construction and use of type not in binary
3609 for _, table := range []struct {
3610 n int
3611 value func(i int) interface{}
3612 comparable bool
3613 want string
3616 n: 0,
3617 value: func(i int) interface{} { type Tint int; return Tint(i) },
3618 comparable: true,
3619 want: "[]",
3622 n: 10,
3623 value: func(i int) interface{} { type Tint int; return Tint(i) },
3624 comparable: true,
3625 want: "[0 1 2 3 4 5 6 7 8 9]",
3628 n: 10,
3629 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
3630 comparable: true,
3631 want: "[0 1 2 3 4 5 6 7 8 9]",
3634 n: 10,
3635 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
3636 comparable: true,
3637 want: "[0 1 2 3 4 5 6 7 8 9]",
3640 n: 10,
3641 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
3642 comparable: true,
3643 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
3646 n: 10,
3647 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
3648 comparable: false,
3649 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3652 n: 10,
3653 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
3654 comparable: true,
3655 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3658 n: 10,
3659 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
3660 comparable: true,
3661 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3664 n: 10,
3665 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
3666 comparable: false,
3667 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3670 n: 10,
3671 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
3672 comparable: true,
3673 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
3676 n: 10,
3677 value: func(i int) interface{} {
3678 type TstructUV struct {
3679 U int
3680 V float64
3682 return TstructUV{i, float64(i)}
3684 comparable: true,
3685 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
3688 at := ArrayOf(table.n, TypeOf(table.value(0)))
3689 v := New(at).Elem()
3690 vok := New(at).Elem()
3691 vnot := New(at).Elem()
3692 for i := 0; i < v.Len(); i++ {
3693 v.Index(i).Set(ValueOf(table.value(i)))
3694 vok.Index(i).Set(ValueOf(table.value(i)))
3695 j := i
3696 if i+1 == v.Len() {
3697 j = i + 1
3699 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
3701 s := fmt.Sprint(v.Interface())
3702 if s != table.want {
3703 t.Errorf("constructed array = %s, want %s", s, table.want)
3706 if table.comparable != at.Comparable() {
3707 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
3709 if table.comparable {
3710 if table.n > 0 {
3711 if DeepEqual(vnot.Interface(), v.Interface()) {
3712 t.Errorf(
3713 "arrays (%#v) compare ok (but should not)",
3714 v.Interface(),
3718 if !DeepEqual(vok.Interface(), v.Interface()) {
3719 t.Errorf(
3720 "arrays (%#v) compare NOT-ok (but should)",
3721 v.Interface(),
3727 // check that type already in binary is found
3728 type T int
3729 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
3732 func TestArrayOfGC(t *testing.T) {
3733 type T *uintptr
3734 tt := TypeOf(T(nil))
3735 const n = 100
3736 var x []interface{}
3737 for i := 0; i < n; i++ {
3738 v := New(ArrayOf(n, tt)).Elem()
3739 for j := 0; j < v.Len(); j++ {
3740 p := new(uintptr)
3741 *p = uintptr(i*n + j)
3742 v.Index(j).Set(ValueOf(p).Convert(tt))
3744 x = append(x, v.Interface())
3746 runtime.GC()
3748 for i, xi := range x {
3749 v := ValueOf(xi)
3750 for j := 0; j < v.Len(); j++ {
3751 k := v.Index(j).Elem().Interface()
3752 if k != uintptr(i*n+j) {
3753 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3759 func TestArrayOfAlg(t *testing.T) {
3760 at := ArrayOf(6, TypeOf(byte(0)))
3761 v1 := New(at).Elem()
3762 v2 := New(at).Elem()
3763 if v1.Interface() != v1.Interface() {
3764 t.Errorf("constructed array %v not equal to itself", v1.Interface())
3766 v1.Index(5).Set(ValueOf(byte(1)))
3767 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
3768 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
3771 at = ArrayOf(6, TypeOf([]int(nil)))
3772 v1 = New(at).Elem()
3773 shouldPanic(func() { _ = v1.Interface() == v1.Interface() })
3776 func TestArrayOfGenericAlg(t *testing.T) {
3777 at1 := ArrayOf(5, TypeOf(string("")))
3778 at := ArrayOf(6, at1)
3779 v1 := New(at).Elem()
3780 v2 := New(at).Elem()
3781 if v1.Interface() != v1.Interface() {
3782 t.Errorf("constructed array %v not equal to itself", v1.Interface())
3785 v1.Index(0).Index(0).Set(ValueOf("abc"))
3786 v2.Index(0).Index(0).Set(ValueOf("efg"))
3787 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
3788 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
3791 v1.Index(0).Index(0).Set(ValueOf("abc"))
3792 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
3793 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
3794 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
3797 // Test hash
3798 m := MakeMap(MapOf(at, TypeOf(int(0))))
3799 m.SetMapIndex(v1, ValueOf(1))
3800 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
3801 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
3805 func TestArrayOfDirectIface(t *testing.T) {
3806 t.Skip("skipping test because gccgo uses a different directiface value")
3808 type T [1]*byte
3809 i1 := Zero(TypeOf(T{})).Interface()
3810 v1 := ValueOf(&i1).Elem()
3811 p1 := v1.InterfaceData()[1]
3813 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
3814 v2 := ValueOf(&i2).Elem()
3815 p2 := v2.InterfaceData()[1]
3817 if p1 != 0 {
3818 t.Errorf("got p1=%v. want=%v", p1, nil)
3821 if p2 != 0 {
3822 t.Errorf("got p2=%v. want=%v", p2, nil)
3826 type T [0]*byte
3827 i1 := Zero(TypeOf(T{})).Interface()
3828 v1 := ValueOf(&i1).Elem()
3829 p1 := v1.InterfaceData()[1]
3831 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
3832 v2 := ValueOf(&i2).Elem()
3833 p2 := v2.InterfaceData()[1]
3835 if p1 == 0 {
3836 t.Errorf("got p1=%v. want=not-%v", p1, nil)
3839 if p2 == 0 {
3840 t.Errorf("got p2=%v. want=not-%v", p2, nil)
3845 func TestSliceOf(t *testing.T) {
3846 // check construction and use of type not in binary
3847 type T int
3848 st := SliceOf(TypeOf(T(1)))
3849 v := MakeSlice(st, 10, 10)
3850 runtime.GC()
3851 for i := 0; i < v.Len(); i++ {
3852 v.Index(i).Set(ValueOf(T(i)))
3853 runtime.GC()
3855 s := fmt.Sprint(v.Interface())
3856 want := "[0 1 2 3 4 5 6 7 8 9]"
3857 if s != want {
3858 t.Errorf("constructed slice = %s, want %s", s, want)
3861 // check that type already in binary is found
3862 type T1 int
3863 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
3866 func TestSliceOverflow(t *testing.T) {
3867 // check that MakeSlice panics when size of slice overflows uint
3868 const S = 1e6
3869 s := uint(S)
3870 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
3871 if l*s >= s {
3872 t.Fatal("slice size does not overflow")
3874 var x [S]byte
3875 st := SliceOf(TypeOf(x))
3876 defer func() {
3877 err := recover()
3878 if err == nil {
3879 t.Fatal("slice overflow does not panic")
3882 MakeSlice(st, int(l), int(l))
3885 func TestSliceOfGC(t *testing.T) {
3886 type T *uintptr
3887 tt := TypeOf(T(nil))
3888 st := SliceOf(tt)
3889 const n = 100
3890 var x []interface{}
3891 for i := 0; i < n; i++ {
3892 v := MakeSlice(st, n, n)
3893 for j := 0; j < v.Len(); j++ {
3894 p := new(uintptr)
3895 *p = uintptr(i*n + j)
3896 v.Index(j).Set(ValueOf(p).Convert(tt))
3898 x = append(x, v.Interface())
3900 runtime.GC()
3902 for i, xi := range x {
3903 v := ValueOf(xi)
3904 for j := 0; j < v.Len(); j++ {
3905 k := v.Index(j).Elem().Interface()
3906 if k != uintptr(i*n+j) {
3907 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3913 func TestChanOf(t *testing.T) {
3914 // check construction and use of type not in binary
3915 type T string
3916 ct := ChanOf(BothDir, TypeOf(T("")))
3917 v := MakeChan(ct, 2)
3918 runtime.GC()
3919 v.Send(ValueOf(T("hello")))
3920 runtime.GC()
3921 v.Send(ValueOf(T("world")))
3922 runtime.GC()
3924 sv1, _ := v.Recv()
3925 sv2, _ := v.Recv()
3926 s1 := sv1.String()
3927 s2 := sv2.String()
3928 if s1 != "hello" || s2 != "world" {
3929 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
3932 // check that type already in binary is found
3933 type T1 int
3934 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
3937 func TestChanOfDir(t *testing.T) {
3938 // check construction and use of type not in binary
3939 type T string
3940 crt := ChanOf(RecvDir, TypeOf(T("")))
3941 cst := ChanOf(SendDir, TypeOf(T("")))
3943 // check that type already in binary is found
3944 type T1 int
3945 checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil))
3946 checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil))
3948 // check String form of ChanDir
3949 if crt.ChanDir().String() != "<-chan" {
3950 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
3952 if cst.ChanDir().String() != "chan<-" {
3953 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
3957 func TestChanOfGC(t *testing.T) {
3958 done := make(chan bool, 1)
3959 go func() {
3960 select {
3961 case <-done:
3962 case <-time.After(5 * time.Second):
3963 panic("deadlock in TestChanOfGC")
3967 defer func() {
3968 done <- true
3971 type T *uintptr
3972 tt := TypeOf(T(nil))
3973 ct := ChanOf(BothDir, tt)
3975 // NOTE: The garbage collector handles allocated channels specially,
3976 // so we have to save pointers to channels in x; the pointer code will
3977 // use the gc info in the newly constructed chan type.
3978 const n = 100
3979 var x []interface{}
3980 for i := 0; i < n; i++ {
3981 v := MakeChan(ct, n)
3982 for j := 0; j < n; j++ {
3983 p := new(uintptr)
3984 *p = uintptr(i*n + j)
3985 v.Send(ValueOf(p).Convert(tt))
3987 pv := New(ct)
3988 pv.Elem().Set(v)
3989 x = append(x, pv.Interface())
3991 runtime.GC()
3993 for i, xi := range x {
3994 v := ValueOf(xi).Elem()
3995 for j := 0; j < n; j++ {
3996 pv, _ := v.Recv()
3997 k := pv.Elem().Interface()
3998 if k != uintptr(i*n+j) {
3999 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4005 func TestMapOf(t *testing.T) {
4006 // check construction and use of type not in binary
4007 type K string
4008 type V float64
4010 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
4011 runtime.GC()
4012 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
4013 runtime.GC()
4015 s := fmt.Sprint(v.Interface())
4016 want := "map[a:1]"
4017 if s != want {
4018 t.Errorf("constructed map = %s, want %s", s, want)
4021 // check that type already in binary is found
4022 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
4024 // check that invalid key type panics
4025 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
4028 func TestMapOfGCKeys(t *testing.T) {
4029 type T *uintptr
4030 tt := TypeOf(T(nil))
4031 mt := MapOf(tt, TypeOf(false))
4033 // NOTE: The garbage collector handles allocated maps specially,
4034 // so we have to save pointers to maps in x; the pointer code will
4035 // use the gc info in the newly constructed map type.
4036 const n = 100
4037 var x []interface{}
4038 for i := 0; i < n; i++ {
4039 v := MakeMap(mt)
4040 for j := 0; j < n; j++ {
4041 p := new(uintptr)
4042 *p = uintptr(i*n + j)
4043 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
4045 pv := New(mt)
4046 pv.Elem().Set(v)
4047 x = append(x, pv.Interface())
4049 runtime.GC()
4051 for i, xi := range x {
4052 v := ValueOf(xi).Elem()
4053 var out []int
4054 for _, kv := range v.MapKeys() {
4055 out = append(out, int(kv.Elem().Interface().(uintptr)))
4057 sort.Ints(out)
4058 for j, k := range out {
4059 if k != i*n+j {
4060 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4066 func TestMapOfGCValues(t *testing.T) {
4067 type T *uintptr
4068 tt := TypeOf(T(nil))
4069 mt := MapOf(TypeOf(1), tt)
4071 // NOTE: The garbage collector handles allocated maps specially,
4072 // so we have to save pointers to maps in x; the pointer code will
4073 // use the gc info in the newly constructed map type.
4074 const n = 100
4075 var x []interface{}
4076 for i := 0; i < n; i++ {
4077 v := MakeMap(mt)
4078 for j := 0; j < n; j++ {
4079 p := new(uintptr)
4080 *p = uintptr(i*n + j)
4081 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
4083 pv := New(mt)
4084 pv.Elem().Set(v)
4085 x = append(x, pv.Interface())
4087 runtime.GC()
4089 for i, xi := range x {
4090 v := ValueOf(xi).Elem()
4091 for j := 0; j < n; j++ {
4092 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
4093 if k != uintptr(i*n+j) {
4094 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4100 func TestTypelinksSorted(t *testing.T) {
4101 var last string
4102 for i, n := range TypeLinks() {
4103 if n < last {
4104 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
4106 last = n
4110 func TestFuncOf(t *testing.T) {
4111 // check construction and use of type not in binary
4112 type K string
4113 type V float64
4115 fn := func(args []Value) []Value {
4116 if len(args) != 1 {
4117 t.Errorf("args == %v, want exactly one arg", args)
4118 } else if args[0].Type() != TypeOf(K("")) {
4119 t.Errorf("args[0] is type %v, want %v", args[0].Type, TypeOf(K("")))
4120 } else if args[0].String() != "gopher" {
4121 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
4123 return []Value{ValueOf(V(3.14))}
4125 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
4127 outs := v.Call([]Value{ValueOf(K("gopher"))})
4128 if len(outs) != 1 {
4129 t.Fatalf("v.Call returned %v, want exactly one result", outs)
4130 } else if outs[0].Type() != TypeOf(V(0)) {
4131 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type, TypeOf(V(0)))
4133 f := outs[0].Float()
4134 if f != 3.14 {
4135 t.Errorf("constructed func returned %f, want %f", f, 3.14)
4138 // check that types already in binary are found
4139 type T1 int
4140 testCases := []struct {
4141 in, out []Type
4142 variadic bool
4143 want interface{}
4145 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
4146 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
4147 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
4148 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
4149 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
4151 for _, tt := range testCases {
4152 checkSameType(t, Zero(FuncOf(tt.in, tt.out, tt.variadic)).Interface(), tt.want)
4155 // check that variadic requires last element be a slice.
4156 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
4157 shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
4158 shouldPanic(func() { FuncOf(nil, nil, true) })
4161 type B1 struct {
4162 X int
4163 Y int
4164 Z int
4167 func BenchmarkFieldByName1(b *testing.B) {
4168 t := TypeOf(B1{})
4169 for i := 0; i < b.N; i++ {
4170 t.FieldByName("Z")
4174 func BenchmarkFieldByName2(b *testing.B) {
4175 t := TypeOf(S3{})
4176 for i := 0; i < b.N; i++ {
4177 t.FieldByName("B")
4181 type R0 struct {
4188 type R1 struct {
4195 type R2 R1
4196 type R3 R1
4197 type R4 R1
4199 type R5 struct {
4201 *R10
4202 *R11
4203 *R12
4206 type R6 R5
4207 type R7 R5
4208 type R8 R5
4210 type R9 struct {
4211 *R13
4212 *R14
4213 *R15
4214 *R16
4217 type R10 R9
4218 type R11 R9
4219 type R12 R9
4221 type R13 struct {
4222 *R17
4223 *R18
4224 *R19
4225 *R20
4228 type R14 R13
4229 type R15 R13
4230 type R16 R13
4232 type R17 struct {
4233 *R21
4234 *R22
4235 *R23
4236 *R24
4239 type R18 R17
4240 type R19 R17
4241 type R20 R17
4243 type R21 struct {
4244 X int
4247 type R22 R21
4248 type R23 R21
4249 type R24 R21
4251 func TestEmbed(t *testing.T) {
4252 typ := TypeOf(R0{})
4253 f, ok := typ.FieldByName("X")
4254 if ok {
4255 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
4259 func BenchmarkFieldByName3(b *testing.B) {
4260 t := TypeOf(R0{})
4261 for i := 0; i < b.N; i++ {
4262 t.FieldByName("X")
4266 type S struct {
4267 i1 int64
4268 i2 int64
4271 func BenchmarkInterfaceBig(b *testing.B) {
4272 v := ValueOf(S{})
4273 for i := 0; i < b.N; i++ {
4274 v.Interface()
4276 b.StopTimer()
4279 func TestAllocsInterfaceBig(t *testing.T) {
4280 if testing.Short() {
4281 t.Skip("skipping malloc count in short mode")
4283 v := ValueOf(S{})
4284 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
4285 t.Error("allocs:", allocs)
4289 func BenchmarkInterfaceSmall(b *testing.B) {
4290 v := ValueOf(int64(0))
4291 for i := 0; i < b.N; i++ {
4292 v.Interface()
4296 func TestAllocsInterfaceSmall(t *testing.T) {
4297 if testing.Short() {
4298 t.Skip("skipping malloc count in short mode")
4300 v := ValueOf(int64(0))
4301 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
4302 t.Error("allocs:", allocs)
4306 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
4307 // The basic usage is:
4309 // for x.Next() {
4310 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
4311 // }
4313 // Each iteration of the loop returns a different set of results, until all
4314 // possible result sets have been explored. It is okay for different code paths
4315 // to make different method call sequences on x, but there must be no
4316 // other source of non-determinism in the call sequences.
4318 // When faced with a new decision, x chooses randomly. Future explorations
4319 // of that path will choose successive values for the result. Thus, stopping
4320 // the loop after a fixed number of iterations gives somewhat stochastic
4321 // testing.
4323 // Example:
4325 // for x.Next() {
4326 // v := make([]bool, x.Choose(4))
4327 // for i := range v {
4328 // v[i] = x.Maybe()
4329 // }
4330 // fmt.Println(v)
4331 // }
4333 // prints (in some order):
4335 // []
4336 // [false]
4337 // [true]
4338 // [false false]
4339 // [false true]
4340 // ...
4341 // [true true]
4342 // [false false false]
4343 // ...
4344 // [true true true]
4345 // [false false false false]
4346 // ...
4347 // [true true true true]
4349 type exhaustive struct {
4350 r *rand.Rand
4351 pos int
4352 last []choice
4355 type choice struct {
4356 off int
4357 n int
4358 max int
4361 func (x *exhaustive) Next() bool {
4362 if x.r == nil {
4363 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
4365 x.pos = 0
4366 if x.last == nil {
4367 x.last = []choice{}
4368 return true
4370 for i := len(x.last) - 1; i >= 0; i-- {
4371 c := &x.last[i]
4372 if c.n+1 < c.max {
4373 c.n++
4374 x.last = x.last[:i+1]
4375 return true
4378 return false
4381 func (x *exhaustive) Choose(max int) int {
4382 if x.pos >= len(x.last) {
4383 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
4385 c := &x.last[x.pos]
4386 x.pos++
4387 if c.max != max {
4388 panic("inconsistent use of exhaustive tester")
4390 return (c.n + c.off) % max
4393 func (x *exhaustive) Maybe() bool {
4394 return x.Choose(2) == 1
4397 func GCFunc(args []Value) []Value {
4398 runtime.GC()
4399 return []Value{}
4402 func TestReflectFuncTraceback(t *testing.T) {
4403 f := MakeFunc(TypeOf(func() {}), GCFunc)
4404 f.Call([]Value{})
4407 func TestReflectMethodTraceback(t *testing.T) {
4408 p := Point{3, 4}
4409 m := ValueOf(p).MethodByName("GCMethod")
4410 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
4411 if i != 8 {
4412 t.Errorf("Call returned %d; want 8", i)
4416 func TestBigZero(t *testing.T) {
4417 const size = 1 << 10
4418 var v [size]byte
4419 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
4420 for i := 0; i < size; i++ {
4421 if z[i] != 0 {
4422 t.Fatalf("Zero object not all zero, index %d", i)
4427 func TestFieldByIndexNil(t *testing.T) {
4428 type P struct {
4429 F int
4431 type T struct {
4434 v := ValueOf(T{})
4436 v.FieldByName("P") // should be fine
4438 defer func() {
4439 if err := recover(); err == nil {
4440 t.Fatalf("no error")
4441 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
4442 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
4445 v.FieldByName("F") // should panic
4447 t.Fatalf("did not panic")
4450 // Given
4451 // type Outer struct {
4452 // *Inner
4453 // ...
4454 // }
4455 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
4456 // The implementation is logically:
4457 // func (p *Outer) M() {
4458 // (p.Inner).M()
4459 // }
4460 // but since the only change here is the replacement of one pointer receiver with another,
4461 // the actual generated code overwrites the original receiver with the p.Inner pointer and
4462 // then jumps to the M method expecting the *Inner receiver.
4464 // During reflect.Value.Call, we create an argument frame and the associated data structures
4465 // to describe it to the garbage collector, populate the frame, call reflect.call to
4466 // run a function call using that frame, and then copy the results back out of the frame.
4467 // The reflect.call function does a memmove of the frame structure onto the
4468 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
4469 // the frame structure (to preserve the outputs).
4471 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
4472 // were for the full stack frame. However, in the case where the called function was
4473 // one of these wrappers, the rewritten receiver is almost certainly a different type
4474 // than the original receiver. This is not a problem on the stack, where we use the
4475 // program counter to determine the type information and understand that
4476 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
4477 // memory word is now an *Inner. But in the statically typed argument frame created
4478 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
4479 // off the stack into the frame will store an *Inner there, and then if a garbage collection
4480 // happens to scan that argument frame before it is discarded, it will scan the *Inner
4481 // memory as if it were an *Outer. If the two have different memory layouts, the
4482 // collection will intepret the memory incorrectly.
4484 // One such possible incorrect interpretation is to treat two arbitrary memory words
4485 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
4486 // an interface requires dereferencing the itab word, the misinterpretation will try to
4487 // deference Inner.P1, causing a crash during garbage collection.
4489 // This came up in a real program in issue 7725.
4491 type Outer struct {
4492 *Inner
4493 R io.Reader
4496 type Inner struct {
4497 X *Outer
4498 P1 uintptr
4499 P2 uintptr
4502 func (pi *Inner) M() {
4503 // Clear references to pi so that the only way the
4504 // garbage collection will find the pointer is in the
4505 // argument frame, typed as a *Outer.
4506 pi.X.Inner = nil
4508 // Set up an interface value that will cause a crash.
4509 // P1 = 1 is a non-zero, so the interface looks non-nil.
4510 // P2 = pi ensures that the data word points into the
4511 // allocated heap; if not the collection skips the interface
4512 // value as irrelevant, without dereferencing P1.
4513 pi.P1 = 1
4514 pi.P2 = uintptr(unsafe.Pointer(pi))
4517 func TestCallMethodJump(t *testing.T) {
4518 // In reflect.Value.Call, trigger a garbage collection after reflect.call
4519 // returns but before the args frame has been discarded.
4520 // This is a little clumsy but makes the failure repeatable.
4521 *CallGC = true
4523 p := &Outer{Inner: new(Inner)}
4524 p.Inner.X = p
4525 ValueOf(p).Method(0).Call(nil)
4527 // Stop garbage collecting during reflect.call.
4528 *CallGC = false
4531 func TestMakeFuncStackCopy(t *testing.T) {
4532 target := func(in []Value) []Value {
4533 runtime.GC()
4534 useStack(16)
4535 return []Value{ValueOf(9)}
4538 var concrete func(*int, int) int
4539 fn := MakeFunc(ValueOf(concrete).Type(), target)
4540 ValueOf(&concrete).Elem().Set(fn)
4541 x := concrete(nil, 7)
4542 if x != 9 {
4543 t.Errorf("have %#q want 9", x)
4547 // use about n KB of stack
4548 func useStack(n int) {
4549 if n == 0 {
4550 return
4552 var b [1024]byte // makes frame about 1KB
4553 useStack(n - 1 + int(b[99]))
4556 type Impl struct{}
4558 func (Impl) f() {}
4560 func TestValueString(t *testing.T) {
4561 rv := ValueOf(Impl{})
4562 if rv.String() != "<reflect_test.Impl Value>" {
4563 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
4566 method := rv.Method(0)
4567 if method.String() != "<func() Value>" {
4568 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
4572 func TestInvalid(t *testing.T) {
4573 // Used to have inconsistency between IsValid() and Kind() != Invalid.
4574 type T struct{ v interface{} }
4576 v := ValueOf(T{}).Field(0)
4577 if v.IsValid() != true || v.Kind() != Interface {
4578 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
4580 v = v.Elem()
4581 if v.IsValid() != false || v.Kind() != Invalid {
4582 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
4586 // Issue 8917.
4587 func TestLargeGCProg(t *testing.T) {
4588 fv := ValueOf(func([256]*byte) {})
4589 fv.Call([]Value{ValueOf([256]*byte{})})
4592 // Issue 9179.
4593 func TestCallGC(t *testing.T) {
4594 f := func(a, b, c, d, e string) {
4596 g := func(in []Value) []Value {
4597 runtime.GC()
4598 return nil
4600 typ := ValueOf(f).Type()
4601 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
4602 f2("four", "five5", "six666", "seven77", "eight888")
4605 type funcLayoutTest struct {
4606 rcvr, t Type
4607 size, argsize, retOffset uintptr
4608 stack []byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized)
4609 gc []byte
4612 var funcLayoutTests []funcLayoutTest
4614 func init() {
4615 var argAlign uintptr = PtrSize
4616 if runtime.GOARCH == "amd64p32" {
4617 argAlign = 2 * PtrSize
4619 roundup := func(x uintptr, a uintptr) uintptr {
4620 return (x + a - 1) / a * a
4623 funcLayoutTests = append(funcLayoutTests,
4624 funcLayoutTest{
4625 nil,
4626 ValueOf(func(a, b string) string { return "" }).Type(),
4627 6 * PtrSize,
4628 4 * PtrSize,
4629 4 * PtrSize,
4630 []byte{1, 0, 1},
4631 []byte{1, 0, 1, 0, 1},
4634 var r []byte
4635 if PtrSize == 4 {
4636 r = []byte{0, 0, 0, 1}
4637 } else {
4638 r = []byte{0, 0, 1}
4640 funcLayoutTests = append(funcLayoutTests,
4641 funcLayoutTest{
4642 nil,
4643 ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
4644 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
4645 roundup(3*4, PtrSize) + PtrSize + 2,
4646 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
4651 funcLayoutTests = append(funcLayoutTests,
4652 funcLayoutTest{
4653 nil,
4654 ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
4655 4 * PtrSize,
4656 4 * PtrSize,
4657 4 * PtrSize,
4658 []byte{1, 0, 1, 1},
4659 []byte{1, 0, 1, 1},
4662 type S struct {
4663 a, b uintptr
4664 c, d *byte
4666 funcLayoutTests = append(funcLayoutTests,
4667 funcLayoutTest{
4668 nil,
4669 ValueOf(func(a S) {}).Type(),
4670 4 * PtrSize,
4671 4 * PtrSize,
4672 4 * PtrSize,
4673 []byte{0, 0, 1, 1},
4674 []byte{0, 0, 1, 1},
4677 funcLayoutTests = append(funcLayoutTests,
4678 funcLayoutTest{
4679 ValueOf((*byte)(nil)).Type(),
4680 ValueOf(func(a uintptr, b *int) {}).Type(),
4681 roundup(3*PtrSize, argAlign),
4682 3 * PtrSize,
4683 roundup(3*PtrSize, argAlign),
4684 []byte{1, 0, 1},
4685 []byte{1, 0, 1},
4688 funcLayoutTests = append(funcLayoutTests,
4689 funcLayoutTest{
4690 nil,
4691 ValueOf(func(a uintptr) {}).Type(),
4692 roundup(PtrSize, argAlign),
4693 PtrSize,
4694 roundup(PtrSize, argAlign),
4695 []byte{},
4696 []byte{},
4699 funcLayoutTests = append(funcLayoutTests,
4700 funcLayoutTest{
4701 nil,
4702 ValueOf(func() uintptr { return 0 }).Type(),
4703 PtrSize,
4706 []byte{},
4707 []byte{},
4710 funcLayoutTests = append(funcLayoutTests,
4711 funcLayoutTest{
4712 ValueOf(uintptr(0)).Type(),
4713 ValueOf(func(a uintptr) {}).Type(),
4714 2 * PtrSize,
4715 2 * PtrSize,
4716 2 * PtrSize,
4717 []byte{1},
4718 []byte{1},
4719 // Note: this one is tricky, as the receiver is not a pointer. But we
4720 // pass the receiver by reference to the autogenerated pointer-receiver
4721 // version of the function.
4725 func TestFuncLayout(t *testing.T) {
4726 t.Skip("gccgo does not use funcLayout")
4727 for _, lt := range funcLayoutTests {
4728 typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr)
4729 if typ.Size() != lt.size {
4730 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size)
4732 if argsize != lt.argsize {
4733 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize)
4735 if retOffset != lt.retOffset {
4736 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset)
4738 if !bytes.Equal(stack, lt.stack) {
4739 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack)
4741 if !bytes.Equal(gc, lt.gc) {
4742 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc)
4744 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
4745 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs)
4750 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
4751 heapBits := GCBits(New(typ).Interface())
4752 if !bytes.Equal(heapBits, bits) {
4753 t.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ, heapBits, bits)
4757 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
4758 // Creating a slice causes the runtime to repeat a bitmap,
4759 // which exercises a different path from making the compiler
4760 // repeat a bitmap for a small array or executing a repeat in
4761 // a GC program.
4762 val := MakeSlice(typ, 0, cap)
4763 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
4764 heapBits := GCBits(data.Interface())
4765 // Repeat the bitmap for the slice size, trimming scalars in
4766 // the last element.
4767 bits = rep(cap, bits)
4768 for len(bits) > 2 && bits[len(bits)-1] == 0 {
4769 bits = bits[:len(bits)-1]
4771 if !bytes.Equal(heapBits, bits) {
4772 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
4776 func TestGCBits(t *testing.T) {
4777 t.Skip("gccgo does not use gcbits yet")
4779 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
4781 // Building blocks for types seen by the compiler (like [2]Xscalar).
4782 // The compiler will create the type structures for the derived types,
4783 // including their GC metadata.
4784 type Xscalar struct{ x uintptr }
4785 type Xptr struct{ x *byte }
4786 type Xptrscalar struct {
4787 *byte
4788 uintptr
4790 type Xscalarptr struct {
4791 uintptr
4792 *byte
4794 type Xbigptrscalar struct {
4795 _ [100]*byte
4796 _ [100]uintptr
4799 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
4801 // Building blocks for types constructed by reflect.
4802 // This code is in a separate block so that code below
4803 // cannot accidentally refer to these.
4804 // The compiler must NOT see types derived from these
4805 // (for example, [2]Scalar must NOT appear in the program),
4806 // or else reflect will use it instead of having to construct one.
4807 // The goal is to test the construction.
4808 type Scalar struct{ x uintptr }
4809 type Ptr struct{ x *byte }
4810 type Ptrscalar struct {
4811 *byte
4812 uintptr
4814 type Scalarptr struct {
4815 uintptr
4816 *byte
4818 type Bigptrscalar struct {
4819 _ [100]*byte
4820 _ [100]uintptr
4822 type Int64 int64
4823 Tscalar = TypeOf(Scalar{})
4824 Tint64 = TypeOf(Int64(0))
4825 Tptr = TypeOf(Ptr{})
4826 Tscalarptr = TypeOf(Scalarptr{})
4827 Tptrscalar = TypeOf(Ptrscalar{})
4828 Tbigptrscalar = TypeOf(Bigptrscalar{})
4831 empty := []byte{}
4833 verifyGCBits(t, TypeOf(Xscalar{}), empty)
4834 verifyGCBits(t, Tscalar, empty)
4835 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
4836 verifyGCBits(t, Tptr, lit(1))
4837 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
4838 verifyGCBits(t, Tscalarptr, lit(0, 1))
4839 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
4840 verifyGCBits(t, Tptrscalar, lit(1))
4842 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
4843 verifyGCBits(t, ArrayOf(0, Tptr), empty)
4844 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
4845 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
4846 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
4847 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
4848 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
4849 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
4850 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
4851 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
4852 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
4853 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
4854 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
4855 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
4856 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
4857 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
4858 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
4859 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
4860 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
4861 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
4862 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
4863 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
4864 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
4865 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
4866 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
4867 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
4869 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
4870 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
4871 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
4872 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
4873 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
4874 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
4875 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
4876 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
4877 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
4878 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
4879 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
4880 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
4881 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
4882 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
4883 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
4884 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
4885 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
4886 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
4887 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
4888 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
4889 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
4890 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
4891 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
4892 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
4893 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
4894 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
4896 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
4897 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
4899 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
4900 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
4902 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
4903 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
4905 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
4906 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
4908 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
4909 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
4911 hdr := make([]byte, 8/PtrSize)
4913 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
4914 verifyGCBits(t, MapBucketOf(k, e), want)
4915 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
4917 verifyMapBucket(t,
4918 Tscalar, Tptr,
4919 map[Xscalar]Xptr(nil),
4920 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
4921 verifyMapBucket(t,
4922 Tscalarptr, Tptr,
4923 map[Xscalarptr]Xptr(nil),
4924 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
4925 verifyMapBucket(t, Tint64, Tptr,
4926 map[int64]Xptr(nil),
4927 join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), naclpad(), lit(1)))
4928 verifyMapBucket(t,
4929 Tscalar, Tscalar,
4930 map[Xscalar]Xscalar(nil),
4931 empty)
4932 verifyMapBucket(t,
4933 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
4934 map[[2]Xscalarptr][3]Xptrscalar(nil),
4935 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
4936 verifyMapBucket(t,
4937 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
4938 map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
4939 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
4940 verifyMapBucket(t,
4941 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
4942 map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
4943 join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
4944 verifyMapBucket(t,
4945 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
4946 map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
4947 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
4948 verifyMapBucket(t,
4949 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
4950 map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
4951 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
4954 func naclpad() []byte {
4955 if runtime.GOARCH == "amd64p32" {
4956 return lit(0)
4958 return nil
4961 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
4962 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
4963 func lit(x ...byte) []byte { return x }
4965 func TestTypeOfTypeOf(t *testing.T) {
4966 // Check that all the type constructors return concrete *rtype implementations.
4967 // It's difficult to test directly because the reflect package is only at arm's length.
4968 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
4969 check := func(name string, typ Type) {
4970 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
4971 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
4975 type T struct{ int }
4976 check("TypeOf", TypeOf(T{}))
4978 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
4979 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
4980 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
4981 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
4982 check("PtrTo", PtrTo(TypeOf(T{})))
4983 check("SliceOf", SliceOf(TypeOf(T{})))
4986 type XM struct{}
4988 func (*XM) String() string { return "" }
4990 func TestPtrToMethods(t *testing.T) {
4991 var y struct{ XM }
4992 yp := New(TypeOf(y)).Interface()
4993 _, ok := yp.(fmt.Stringer)
4994 if !ok {
4995 t.Fatal("does not implement Stringer, but should")
4999 func TestMapAlloc(t *testing.T) {
5000 if runtime.Compiler == "gccgo" {
5001 t.Skip("skipping on gccgo until we have escape analysis")
5003 m := ValueOf(make(map[int]int, 10))
5004 k := ValueOf(5)
5005 v := ValueOf(7)
5006 allocs := testing.AllocsPerRun(100, func() {
5007 m.SetMapIndex(k, v)
5009 if allocs > 0.5 {
5010 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
5014 func TestChanAlloc(t *testing.T) {
5015 if runtime.Compiler == "gccgo" {
5016 t.Skip("skipping on gccgo until we have escape analysis")
5018 // Note: for a chan int, the return Value must be allocated, so we
5019 // use a chan *int instead.
5020 c := ValueOf(make(chan *int, 1))
5021 v := ValueOf(new(int))
5022 allocs := testing.AllocsPerRun(100, func() {
5023 c.Send(v)
5024 _, _ = c.Recv()
5026 if allocs < 0.5 || allocs > 1.5 {
5027 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
5029 // Note: there is one allocation in reflect.recv which seems to be
5030 // a limitation of escape analysis. If that is ever fixed the
5031 // allocs < 0.5 condition will trigger and this test should be fixed.