1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package reflect_test 6 7import ( 8 "bytes" 9 "encoding/base64" 10 "flag" 11 "fmt" 12 "io" 13 "math" 14 "math/rand" 15 "os" 16 . "reflect" 17 "runtime" 18 "sort" 19 "strconv" 20 "strings" 21 "sync" 22 "sync/atomic" 23 "testing" 24 "time" 25 "unicode" 26 "unicode/utf8" 27 "unsafe" 28) 29 30var sink interface{} 31 32func TestBool(t *testing.T) { 33 v := ValueOf(true) 34 if v.Bool() != true { 35 t.Fatal("ValueOf(true).Bool() = false") 36 } 37} 38 39type integer int 40type T struct { 41 a int 42 b float64 43 c string 44 d *int 45} 46 47type pair struct { 48 i interface{} 49 s string 50} 51 52func assert(t *testing.T, s, want string) { 53 if s != want { 54 t.Errorf("have %#q want %#q", s, want) 55 } 56} 57 58var typeTests = []pair{ 59 {struct{ x int }{}, "int"}, 60 {struct{ x int8 }{}, "int8"}, 61 {struct{ x int16 }{}, "int16"}, 62 {struct{ x int32 }{}, "int32"}, 63 {struct{ x int64 }{}, "int64"}, 64 {struct{ x uint }{}, "uint"}, 65 {struct{ x uint8 }{}, "uint8"}, 66 {struct{ x uint16 }{}, "uint16"}, 67 {struct{ x uint32 }{}, "uint32"}, 68 {struct{ x uint64 }{}, "uint64"}, 69 {struct{ x float32 }{}, "float32"}, 70 {struct{ x float64 }{}, "float64"}, 71 {struct{ x int8 }{}, "int8"}, 72 {struct{ x (**int8) }{}, "**int8"}, 73 {struct{ x (**integer) }{}, "**reflect_test.integer"}, 74 {struct{ x ([32]int32) }{}, "[32]int32"}, 75 {struct{ x ([]int8) }{}, "[]int8"}, 76 {struct{ x (map[string]int32) }{}, "map[string]int32"}, 77 {struct{ x (chan<- string) }{}, "chan<- string"}, 78 {struct { 79 x struct { 80 c chan *int32 81 d float32 82 } 83 }{}, 84 "struct { c chan *int32; d float32 }", 85 }, 86 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"}, 87 {struct { 88 x struct { 89 c func(chan *integer, *int8) 90 } 91 }{}, 92 "struct { c func(chan *reflect_test.integer, *int8) }", 93 }, 94 {struct { 95 x struct { 96 a int8 97 b int32 98 } 99 }{}, 100 "struct { a int8; b int32 }", 101 }, 102 {struct { 103 x struct { 104 a int8 105 b int8 106 c int32 107 } 108 }{}, 109 "struct { a int8; b int8; c int32 }", 110 }, 111 {struct { 112 x struct { 113 a int8 114 b int8 115 c int8 116 d int32 117 } 118 }{}, 119 "struct { a int8; b int8; c int8; d int32 }", 120 }, 121 {struct { 122 x struct { 123 a int8 124 b int8 125 c int8 126 d int8 127 e int32 128 } 129 }{}, 130 "struct { a int8; b int8; c int8; d int8; e int32 }", 131 }, 132 {struct { 133 x struct { 134 a int8 135 b int8 136 c int8 137 d int8 138 e int8 139 f int32 140 } 141 }{}, 142 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }", 143 }, 144 {struct { 145 x struct { 146 a int8 `reflect:"hi there"` 147 } 148 }{}, 149 `struct { a int8 "reflect:\"hi there\"" }`, 150 }, 151 {struct { 152 x struct { 153 a int8 `reflect:"hi \x00there\t\n\"\\"` 154 } 155 }{}, 156 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`, 157 }, 158 {struct { 159 x struct { 160 f func(args ...int) 161 } 162 }{}, 163 "struct { f func(...int) }", 164 }, 165 {struct { 166 x (interface { 167 a(func(func(int) int) func(func(int)) int) 168 b() 169 }) 170 }{}, 171 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }", 172 }, 173 {struct { 174 x struct { 175 int32 176 int64 177 } 178 }{}, 179 "struct { int32; int64 }", 180 }, 181} 182 183var valueTests = []pair{ 184 {new(int), "132"}, 185 {new(int8), "8"}, 186 {new(int16), "16"}, 187 {new(int32), "32"}, 188 {new(int64), "64"}, 189 {new(uint), "132"}, 190 {new(uint8), "8"}, 191 {new(uint16), "16"}, 192 {new(uint32), "32"}, 193 {new(uint64), "64"}, 194 {new(float32), "256.25"}, 195 {new(float64), "512.125"}, 196 {new(complex64), "532.125+10i"}, 197 {new(complex128), "564.25+1i"}, 198 {new(string), "stringy cheese"}, 199 {new(bool), "true"}, 200 {new(*int8), "*int8(0)"}, 201 {new(**int8), "**int8(0)"}, 202 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"}, 203 {new(**integer), "**reflect_test.integer(0)"}, 204 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"}, 205 {new(chan<- string), "chan<- string"}, 206 {new(func(a int8, b int32)), "func(int8, int32)(0)"}, 207 {new(struct { 208 c chan *int32 209 d float32 210 }), 211 "struct { c chan *int32; d float32 }{chan *int32, 0}", 212 }, 213 {new(struct{ c func(chan *integer, *int8) }), 214 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}", 215 }, 216 {new(struct { 217 a int8 218 b int32 219 }), 220 "struct { a int8; b int32 }{0, 0}", 221 }, 222 {new(struct { 223 a int8 224 b int8 225 c int32 226 }), 227 "struct { a int8; b int8; c int32 }{0, 0, 0}", 228 }, 229} 230 231func testType(t *testing.T, i int, typ Type, want string) { 232 s := typ.String() 233 if s != want { 234 t.Errorf("#%d: have %#q, want %#q", i, s, want) 235 } 236} 237 238func TestTypes(t *testing.T) { 239 for i, tt := range typeTests { 240 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s) 241 } 242} 243 244func TestSet(t *testing.T) { 245 for i, tt := range valueTests { 246 v := ValueOf(tt.i) 247 v = v.Elem() 248 switch v.Kind() { 249 case Int: 250 v.SetInt(132) 251 case Int8: 252 v.SetInt(8) 253 case Int16: 254 v.SetInt(16) 255 case Int32: 256 v.SetInt(32) 257 case Int64: 258 v.SetInt(64) 259 case Uint: 260 v.SetUint(132) 261 case Uint8: 262 v.SetUint(8) 263 case Uint16: 264 v.SetUint(16) 265 case Uint32: 266 v.SetUint(32) 267 case Uint64: 268 v.SetUint(64) 269 case Float32: 270 v.SetFloat(256.25) 271 case Float64: 272 v.SetFloat(512.125) 273 case Complex64: 274 v.SetComplex(532.125 + 10i) 275 case Complex128: 276 v.SetComplex(564.25 + 1i) 277 case String: 278 v.SetString("stringy cheese") 279 case Bool: 280 v.SetBool(true) 281 } 282 s := valueToString(v) 283 if s != tt.s { 284 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) 285 } 286 } 287} 288 289func TestSetValue(t *testing.T) { 290 for i, tt := range valueTests { 291 v := ValueOf(tt.i).Elem() 292 switch v.Kind() { 293 case Int: 294 v.Set(ValueOf(int(132))) 295 case Int8: 296 v.Set(ValueOf(int8(8))) 297 case Int16: 298 v.Set(ValueOf(int16(16))) 299 case Int32: 300 v.Set(ValueOf(int32(32))) 301 case Int64: 302 v.Set(ValueOf(int64(64))) 303 case Uint: 304 v.Set(ValueOf(uint(132))) 305 case Uint8: 306 v.Set(ValueOf(uint8(8))) 307 case Uint16: 308 v.Set(ValueOf(uint16(16))) 309 case Uint32: 310 v.Set(ValueOf(uint32(32))) 311 case Uint64: 312 v.Set(ValueOf(uint64(64))) 313 case Float32: 314 v.Set(ValueOf(float32(256.25))) 315 case Float64: 316 v.Set(ValueOf(512.125)) 317 case Complex64: 318 v.Set(ValueOf(complex64(532.125 + 10i))) 319 case Complex128: 320 v.Set(ValueOf(complex128(564.25 + 1i))) 321 case String: 322 v.Set(ValueOf("stringy cheese")) 323 case Bool: 324 v.Set(ValueOf(true)) 325 } 326 s := valueToString(v) 327 if s != tt.s { 328 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s) 329 } 330 } 331} 332 333func TestCanSetField(t *testing.T) { 334 type embed struct{ x, X int } 335 type Embed struct{ x, X int } 336 type S1 struct { 337 embed 338 x, X int 339 } 340 type S2 struct { 341 *embed 342 x, X int 343 } 344 type S3 struct { 345 Embed 346 x, X int 347 } 348 type S4 struct { 349 *Embed 350 x, X int 351 } 352 353 type testCase struct { 354 index []int 355 canSet bool 356 } 357 tests := []struct { 358 val Value 359 cases []testCase 360 }{{ 361 val: ValueOf(&S1{}), 362 cases: []testCase{ 363 {[]int{0}, false}, 364 {[]int{0, 0}, false}, 365 {[]int{0, 1}, true}, 366 {[]int{1}, false}, 367 {[]int{2}, true}, 368 }, 369 }, { 370 val: ValueOf(&S2{embed: &embed{}}), 371 cases: []testCase{ 372 {[]int{0}, false}, 373 {[]int{0, 0}, false}, 374 {[]int{0, 1}, true}, 375 {[]int{1}, false}, 376 {[]int{2}, true}, 377 }, 378 }, { 379 val: ValueOf(&S3{}), 380 cases: []testCase{ 381 {[]int{0}, true}, 382 {[]int{0, 0}, false}, 383 {[]int{0, 1}, true}, 384 {[]int{1}, false}, 385 {[]int{2}, true}, 386 }, 387 }, { 388 val: ValueOf(&S4{Embed: &Embed{}}), 389 cases: []testCase{ 390 {[]int{0}, true}, 391 {[]int{0, 0}, false}, 392 {[]int{0, 1}, true}, 393 {[]int{1}, false}, 394 {[]int{2}, true}, 395 }, 396 }} 397 398 for _, tt := range tests { 399 t.Run(tt.val.Type().Name(), func(t *testing.T) { 400 for _, tc := range tt.cases { 401 f := tt.val 402 for _, i := range tc.index { 403 if f.Kind() == Ptr { 404 f = f.Elem() 405 } 406 f = f.Field(i) 407 } 408 if got := f.CanSet(); got != tc.canSet { 409 t.Errorf("CanSet() = %v, want %v", got, tc.canSet) 410 } 411 } 412 }) 413 } 414} 415 416var _i = 7 417 418var valueToStringTests = []pair{ 419 {123, "123"}, 420 {123.5, "123.5"}, 421 {byte(123), "123"}, 422 {"abc", "abc"}, 423 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"}, 424 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"}, 425 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, 426 {&[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})"}, 427 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"}, 428 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"}, 429} 430 431func TestValueToString(t *testing.T) { 432 for i, test := range valueToStringTests { 433 s := valueToString(ValueOf(test.i)) 434 if s != test.s { 435 t.Errorf("#%d: have %#q, want %#q", i, s, test.s) 436 } 437 } 438} 439 440func TestArrayElemSet(t *testing.T) { 441 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem() 442 v.Index(4).SetInt(123) 443 s := valueToString(v) 444 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}" 445 if s != want { 446 t.Errorf("[10]int: have %#q want %#q", s, want) 447 } 448 449 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) 450 v.Index(4).SetInt(123) 451 s = valueToString(v) 452 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}" 453 if s != want1 { 454 t.Errorf("[]int: have %#q want %#q", s, want1) 455 } 456} 457 458func TestPtrPointTo(t *testing.T) { 459 var ip *int32 460 var i int32 = 1234 461 vip := ValueOf(&ip) 462 vi := ValueOf(&i).Elem() 463 vip.Elem().Set(vi.Addr()) 464 if *ip != 1234 { 465 t.Errorf("got %d, want 1234", *ip) 466 } 467 468 ip = nil 469 vp := ValueOf(&ip).Elem() 470 vp.Set(Zero(vp.Type())) 471 if ip != nil { 472 t.Errorf("got non-nil (%p), want nil", ip) 473 } 474} 475 476func TestPtrSetNil(t *testing.T) { 477 var i int32 = 1234 478 ip := &i 479 vip := ValueOf(&ip) 480 vip.Elem().Set(Zero(vip.Elem().Type())) 481 if ip != nil { 482 t.Errorf("got non-nil (%d), want nil", *ip) 483 } 484} 485 486func TestMapSetNil(t *testing.T) { 487 m := make(map[string]int) 488 vm := ValueOf(&m) 489 vm.Elem().Set(Zero(vm.Elem().Type())) 490 if m != nil { 491 t.Errorf("got non-nil (%p), want nil", m) 492 } 493} 494 495func TestAll(t *testing.T) { 496 testType(t, 1, TypeOf((int8)(0)), "int8") 497 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8") 498 499 typ := TypeOf((*struct { 500 c chan *int32 501 d float32 502 })(nil)) 503 testType(t, 3, typ, "*struct { c chan *int32; d float32 }") 504 etyp := typ.Elem() 505 testType(t, 4, etyp, "struct { c chan *int32; d float32 }") 506 styp := etyp 507 f := styp.Field(0) 508 testType(t, 5, f.Type, "chan *int32") 509 510 f, present := styp.FieldByName("d") 511 if !present { 512 t.Errorf("FieldByName says present field is absent") 513 } 514 testType(t, 6, f.Type, "float32") 515 516 f, present = styp.FieldByName("absent") 517 if present { 518 t.Errorf("FieldByName says absent field is present") 519 } 520 521 typ = TypeOf([32]int32{}) 522 testType(t, 7, typ, "[32]int32") 523 testType(t, 8, typ.Elem(), "int32") 524 525 typ = TypeOf((map[string]*int32)(nil)) 526 testType(t, 9, typ, "map[string]*int32") 527 mtyp := typ 528 testType(t, 10, mtyp.Key(), "string") 529 testType(t, 11, mtyp.Elem(), "*int32") 530 531 typ = TypeOf((chan<- string)(nil)) 532 testType(t, 12, typ, "chan<- string") 533 testType(t, 13, typ.Elem(), "string") 534 535 // make sure tag strings are not part of element type 536 typ = TypeOf(struct { 537 d []uint32 `reflect:"TAG"` 538 }{}).Field(0).Type 539 testType(t, 14, typ, "[]uint32") 540} 541 542func TestInterfaceGet(t *testing.T) { 543 var inter struct { 544 E interface{} 545 } 546 inter.E = 123.456 547 v1 := ValueOf(&inter) 548 v2 := v1.Elem().Field(0) 549 assert(t, v2.Type().String(), "interface {}") 550 i2 := v2.Interface() 551 v3 := ValueOf(i2) 552 assert(t, v3.Type().String(), "float64") 553} 554 555func TestInterfaceValue(t *testing.T) { 556 var inter struct { 557 E interface{} 558 } 559 inter.E = 123.456 560 v1 := ValueOf(&inter) 561 v2 := v1.Elem().Field(0) 562 assert(t, v2.Type().String(), "interface {}") 563 v3 := v2.Elem() 564 assert(t, v3.Type().String(), "float64") 565 566 i3 := v2.Interface() 567 if _, ok := i3.(float64); !ok { 568 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3)) 569 } 570} 571 572func TestFunctionValue(t *testing.T) { 573 var x interface{} = func() {} 574 v := ValueOf(x) 575 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) { 576 t.Fatalf("TestFunction returned wrong pointer") 577 } 578 assert(t, v.Type().String(), "func()") 579} 580 581var appendTests = []struct { 582 orig, extra []int 583}{ 584 {make([]int, 2, 4), []int{22}}, 585 {make([]int, 2, 4), []int{22, 33, 44}}, 586} 587 588func sameInts(x, y []int) bool { 589 if len(x) != len(y) { 590 return false 591 } 592 for i, xx := range x { 593 if xx != y[i] { 594 return false 595 } 596 } 597 return true 598} 599 600func TestAppend(t *testing.T) { 601 for i, test := range appendTests { 602 origLen, extraLen := len(test.orig), len(test.extra) 603 want := append(test.orig, test.extra...) 604 // Convert extra from []int to []Value. 605 e0 := make([]Value, len(test.extra)) 606 for j, e := range test.extra { 607 e0[j] = ValueOf(e) 608 } 609 // Convert extra from []int to *SliceValue. 610 e1 := ValueOf(test.extra) 611 // Test Append. 612 a0 := ValueOf(test.orig) 613 have0 := Append(a0, e0...).Interface().([]int) 614 if !sameInts(have0, want) { 615 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0) 616 } 617 // Check that the orig and extra slices were not modified. 618 if len(test.orig) != origLen { 619 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen) 620 } 621 if len(test.extra) != extraLen { 622 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen) 623 } 624 // Test AppendSlice. 625 a1 := ValueOf(test.orig) 626 have1 := AppendSlice(a1, e1).Interface().([]int) 627 if !sameInts(have1, want) { 628 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want) 629 } 630 // Check that the orig and extra slices were not modified. 631 if len(test.orig) != origLen { 632 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen) 633 } 634 if len(test.extra) != extraLen { 635 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen) 636 } 637 } 638} 639 640func TestCopy(t *testing.T) { 641 a := []int{1, 2, 3, 4, 10, 9, 8, 7} 642 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} 643 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} 644 for i := 0; i < len(b); i++ { 645 if b[i] != c[i] { 646 t.Fatalf("b != c before test") 647 } 648 } 649 a1 := a 650 b1 := b 651 aa := ValueOf(&a1).Elem() 652 ab := ValueOf(&b1).Elem() 653 for tocopy := 1; tocopy <= 7; tocopy++ { 654 aa.SetLen(tocopy) 655 Copy(ab, aa) 656 aa.SetLen(8) 657 for i := 0; i < tocopy; i++ { 658 if a[i] != b[i] { 659 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d", 660 tocopy, i, a[i], i, b[i]) 661 } 662 } 663 for i := tocopy; i < len(b); i++ { 664 if b[i] != c[i] { 665 if i < len(a) { 666 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d", 667 tocopy, i, a[i], i, b[i], i, c[i]) 668 } else { 669 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d", 670 tocopy, i, b[i], i, c[i]) 671 } 672 } else { 673 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i) 674 } 675 } 676 } 677} 678 679func TestCopyString(t *testing.T) { 680 t.Run("Slice", func(t *testing.T) { 681 s := bytes.Repeat([]byte{'_'}, 8) 682 val := ValueOf(s) 683 684 n := Copy(val, ValueOf("")) 685 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) { 686 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting) 687 } 688 689 n = Copy(val, ValueOf("hello")) 690 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) { 691 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting) 692 } 693 694 n = Copy(val, ValueOf("helloworld")) 695 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) { 696 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting) 697 } 698 }) 699 t.Run("Array", func(t *testing.T) { 700 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'} 701 val := ValueOf(&s).Elem() 702 703 n := Copy(val, ValueOf("")) 704 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) { 705 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting) 706 } 707 708 n = Copy(val, ValueOf("hello")) 709 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) { 710 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting) 711 } 712 713 n = Copy(val, ValueOf("helloworld")) 714 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) { 715 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting) 716 } 717 }) 718} 719 720func TestCopyArray(t *testing.T) { 721 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7} 722 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44} 723 c := b 724 aa := ValueOf(&a).Elem() 725 ab := ValueOf(&b).Elem() 726 Copy(ab, aa) 727 for i := 0; i < len(a); i++ { 728 if a[i] != b[i] { 729 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i]) 730 } 731 } 732 for i := len(a); i < len(b); i++ { 733 if b[i] != c[i] { 734 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i]) 735 } else { 736 t.Logf("elem %d is okay\n", i) 737 } 738 } 739} 740 741func TestBigUnnamedStruct(t *testing.T) { 742 b := struct{ a, b, c, d int64 }{1, 2, 3, 4} 743 v := ValueOf(b) 744 b1 := v.Interface().(struct { 745 a, b, c, d int64 746 }) 747 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d { 748 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1) 749 } 750} 751 752type big struct { 753 a, b, c, d, e int64 754} 755 756func TestBigStruct(t *testing.T) { 757 b := big{1, 2, 3, 4, 5} 758 v := ValueOf(b) 759 b1 := v.Interface().(big) 760 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e { 761 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1) 762 } 763} 764 765type Basic struct { 766 x int 767 y float32 768} 769 770type NotBasic Basic 771 772type DeepEqualTest struct { 773 a, b interface{} 774 eq bool 775} 776 777// Simple functions for DeepEqual tests. 778var ( 779 fn1 func() // nil. 780 fn2 func() // nil. 781 fn3 = func() { fn1() } // Not nil. 782) 783 784type self struct{} 785 786type Loop *Loop 787type Loopy interface{} 788 789var loop1, loop2 Loop 790var loopy1, loopy2 Loopy 791 792func init() { 793 loop1 = &loop2 794 loop2 = &loop1 795 796 loopy1 = &loopy2 797 loopy2 = &loopy1 798} 799 800var deepEqualTests = []DeepEqualTest{ 801 // Equalities 802 {nil, nil, true}, 803 {1, 1, true}, 804 {int32(1), int32(1), true}, 805 {0.5, 0.5, true}, 806 {float32(0.5), float32(0.5), true}, 807 {"hello", "hello", true}, 808 {make([]int, 10), make([]int, 10), true}, 809 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true}, 810 {Basic{1, 0.5}, Basic{1, 0.5}, true}, 811 {error(nil), error(nil), true}, 812 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true}, 813 {fn1, fn2, true}, 814 815 // Inequalities 816 {1, 2, false}, 817 {int32(1), int32(2), false}, 818 {0.5, 0.6, false}, 819 {float32(0.5), float32(0.6), false}, 820 {"hello", "hey", false}, 821 {make([]int, 10), make([]int, 11), false}, 822 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false}, 823 {Basic{1, 0.5}, Basic{1, 0.6}, false}, 824 {Basic{1, 0}, Basic{2, 0}, false}, 825 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false}, 826 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false}, 827 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false}, 828 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false}, 829 {nil, 1, false}, 830 {1, nil, false}, 831 {fn1, fn3, false}, 832 {fn3, fn3, false}, 833 {[][]int{{1}}, [][]int{{2}}, false}, 834 {math.NaN(), math.NaN(), false}, 835 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false}, 836 {&[1]float64{math.NaN()}, self{}, true}, 837 {[]float64{math.NaN()}, []float64{math.NaN()}, false}, 838 {[]float64{math.NaN()}, self{}, true}, 839 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false}, 840 {map[float64]float64{math.NaN(): 1}, self{}, true}, 841 842 // Nil vs empty: not the same. 843 {[]int{}, []int(nil), false}, 844 {[]int{}, []int{}, true}, 845 {[]int(nil), []int(nil), true}, 846 {map[int]int{}, map[int]int(nil), false}, 847 {map[int]int{}, map[int]int{}, true}, 848 {map[int]int(nil), map[int]int(nil), true}, 849 850 // Mismatched types 851 {1, 1.0, false}, 852 {int32(1), int64(1), false}, 853 {0.5, "hello", false}, 854 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false}, 855 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false}, 856 {Basic{1, 0.5}, NotBasic{1, 0.5}, false}, 857 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false}, 858 859 // Possible loops. 860 {&loop1, &loop1, true}, 861 {&loop1, &loop2, true}, 862 {&loopy1, &loopy1, true}, 863 {&loopy1, &loopy2, true}, 864} 865 866func TestDeepEqual(t *testing.T) { 867 for _, test := range deepEqualTests { 868 if test.b == (self{}) { 869 test.b = test.a 870 } 871 if r := DeepEqual(test.a, test.b); r != test.eq { 872 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq) 873 } 874 } 875} 876 877func TestTypeOf(t *testing.T) { 878 // Special case for nil 879 if typ := TypeOf(nil); typ != nil { 880 t.Errorf("expected nil type for nil value; got %v", typ) 881 } 882 for _, test := range deepEqualTests { 883 v := ValueOf(test.a) 884 if !v.IsValid() { 885 continue 886 } 887 typ := TypeOf(test.a) 888 if typ != v.Type() { 889 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type()) 890 } 891 } 892} 893 894type Recursive struct { 895 x int 896 r *Recursive 897} 898 899func TestDeepEqualRecursiveStruct(t *testing.T) { 900 a, b := new(Recursive), new(Recursive) 901 *a = Recursive{12, a} 902 *b = Recursive{12, b} 903 if !DeepEqual(a, b) { 904 t.Error("DeepEqual(recursive same) = false, want true") 905 } 906} 907 908type _Complex struct { 909 a int 910 b [3]*_Complex 911 c *string 912 d map[float64]float64 913} 914 915func TestDeepEqualComplexStruct(t *testing.T) { 916 m := make(map[float64]float64) 917 stra, strb := "hello", "hello" 918 a, b := new(_Complex), new(_Complex) 919 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m} 920 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m} 921 if !DeepEqual(a, b) { 922 t.Error("DeepEqual(complex same) = false, want true") 923 } 924} 925 926func TestDeepEqualComplexStructInequality(t *testing.T) { 927 m := make(map[float64]float64) 928 stra, strb := "hello", "helloo" // Difference is here 929 a, b := new(_Complex), new(_Complex) 930 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m} 931 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m} 932 if DeepEqual(a, b) { 933 t.Error("DeepEqual(complex different) = true, want false") 934 } 935} 936 937type UnexpT struct { 938 m map[int]int 939} 940 941func TestDeepEqualUnexportedMap(t *testing.T) { 942 // Check that DeepEqual can look at unexported fields. 943 x1 := UnexpT{map[int]int{1: 2}} 944 x2 := UnexpT{map[int]int{1: 2}} 945 if !DeepEqual(&x1, &x2) { 946 t.Error("DeepEqual(x1, x2) = false, want true") 947 } 948 949 y1 := UnexpT{map[int]int{2: 3}} 950 if DeepEqual(&x1, &y1) { 951 t.Error("DeepEqual(x1, y1) = true, want false") 952 } 953} 954 955func check2ndField(x interface{}, offs uintptr, t *testing.T) { 956 s := ValueOf(x) 957 f := s.Type().Field(1) 958 if f.Offset != offs { 959 t.Error("mismatched offsets in structure alignment:", f.Offset, offs) 960 } 961} 962 963// Check that structure alignment & offsets viewed through reflect agree with those 964// from the compiler itself. 965func TestAlignment(t *testing.T) { 966 type T1inner struct { 967 a int 968 } 969 type T1 struct { 970 T1inner 971 f int 972 } 973 type T2inner struct { 974 a, b int 975 } 976 type T2 struct { 977 T2inner 978 f int 979 } 980 981 x := T1{T1inner{2}, 17} 982 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t) 983 984 x1 := T2{T2inner{2, 3}, 17} 985 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t) 986} 987 988func Nil(a interface{}, t *testing.T) { 989 n := ValueOf(a).Field(0) 990 if !n.IsNil() { 991 t.Errorf("%v should be nil", a) 992 } 993} 994 995func NotNil(a interface{}, t *testing.T) { 996 n := ValueOf(a).Field(0) 997 if n.IsNil() { 998 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String()) 999 } 1000} 1001 1002func TestIsNil(t *testing.T) { 1003 // These implement IsNil. 1004 // Wrap in extra struct to hide interface type. 1005 doNil := []interface{}{ 1006 struct{ x *int }{}, 1007 struct{ x interface{} }{}, 1008 struct{ x map[string]int }{}, 1009 struct{ x func() bool }{}, 1010 struct{ x chan int }{}, 1011 struct{ x []string }{}, 1012 } 1013 for _, ts := range doNil { 1014 ty := TypeOf(ts).Field(0).Type 1015 v := Zero(ty) 1016 v.IsNil() // panics if not okay to call 1017 } 1018 1019 // Check the implementations 1020 var pi struct { 1021 x *int 1022 } 1023 Nil(pi, t) 1024 pi.x = new(int) 1025 NotNil(pi, t) 1026 1027 var si struct { 1028 x []int 1029 } 1030 Nil(si, t) 1031 si.x = make([]int, 10) 1032 NotNil(si, t) 1033 1034 var ci struct { 1035 x chan int 1036 } 1037 Nil(ci, t) 1038 ci.x = make(chan int) 1039 NotNil(ci, t) 1040 1041 var mi struct { 1042 x map[int]int 1043 } 1044 Nil(mi, t) 1045 mi.x = make(map[int]int) 1046 NotNil(mi, t) 1047 1048 var ii struct { 1049 x interface{} 1050 } 1051 Nil(ii, t) 1052 ii.x = 2 1053 NotNil(ii, t) 1054 1055 var fi struct { 1056 x func(t *testing.T) 1057 } 1058 Nil(fi, t) 1059 fi.x = TestIsNil 1060 NotNil(fi, t) 1061} 1062 1063func TestInterfaceExtraction(t *testing.T) { 1064 var s struct { 1065 W io.Writer 1066 } 1067 1068 s.W = os.Stdout 1069 v := Indirect(ValueOf(&s)).Field(0).Interface() 1070 if v != s.W.(interface{}) { 1071 t.Error("Interface() on interface: ", v, s.W) 1072 } 1073} 1074 1075func TestNilPtrValueSub(t *testing.T) { 1076 var pi *int 1077 if pv := ValueOf(pi); pv.Elem().IsValid() { 1078 t.Error("ValueOf((*int)(nil)).Elem().IsValid()") 1079 } 1080} 1081 1082func TestMap(t *testing.T) { 1083 m := map[string]int{"a": 1, "b": 2} 1084 mv := ValueOf(m) 1085 if n := mv.Len(); n != len(m) { 1086 t.Errorf("Len = %d, want %d", n, len(m)) 1087 } 1088 keys := mv.MapKeys() 1089 newmap := MakeMap(mv.Type()) 1090 for k, v := range m { 1091 // Check that returned Keys match keys in range. 1092 // These aren't required to be in the same order. 1093 seen := false 1094 for _, kv := range keys { 1095 if kv.String() == k { 1096 seen = true 1097 break 1098 } 1099 } 1100 if !seen { 1101 t.Errorf("Missing key %q", k) 1102 } 1103 1104 // Check that value lookup is correct. 1105 vv := mv.MapIndex(ValueOf(k)) 1106 if vi := vv.Int(); vi != int64(v) { 1107 t.Errorf("Key %q: have value %d, want %d", k, vi, v) 1108 } 1109 1110 // Copy into new map. 1111 newmap.SetMapIndex(ValueOf(k), ValueOf(v)) 1112 } 1113 vv := mv.MapIndex(ValueOf("not-present")) 1114 if vv.IsValid() { 1115 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv)) 1116 } 1117 1118 newm := newmap.Interface().(map[string]int) 1119 if len(newm) != len(m) { 1120 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m)) 1121 } 1122 1123 for k, v := range newm { 1124 mv, ok := m[k] 1125 if mv != v { 1126 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok) 1127 } 1128 } 1129 1130 newmap.SetMapIndex(ValueOf("a"), Value{}) 1131 v, ok := newm["a"] 1132 if ok { 1133 t.Errorf("newm[\"a\"] = %d after delete", v) 1134 } 1135 1136 mv = ValueOf(&m).Elem() 1137 mv.Set(Zero(mv.Type())) 1138 if m != nil { 1139 t.Errorf("mv.Set(nil) failed") 1140 } 1141} 1142 1143func TestNilMap(t *testing.T) { 1144 var m map[string]int 1145 mv := ValueOf(m) 1146 keys := mv.MapKeys() 1147 if len(keys) != 0 { 1148 t.Errorf(">0 keys for nil map: %v", keys) 1149 } 1150 1151 // Check that value for missing key is zero. 1152 x := mv.MapIndex(ValueOf("hello")) 1153 if x.Kind() != Invalid { 1154 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x) 1155 } 1156 1157 // Check big value too. 1158 var mbig map[string][10 << 20]byte 1159 x = ValueOf(mbig).MapIndex(ValueOf("hello")) 1160 if x.Kind() != Invalid { 1161 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x) 1162 } 1163 1164 // Test that deletes from a nil map succeed. 1165 mv.SetMapIndex(ValueOf("hi"), Value{}) 1166} 1167 1168func TestChan(t *testing.T) { 1169 for loop := 0; loop < 2; loop++ { 1170 var c chan int 1171 var cv Value 1172 1173 // check both ways to allocate channels 1174 switch loop { 1175 case 1: 1176 c = make(chan int, 1) 1177 cv = ValueOf(c) 1178 case 0: 1179 cv = MakeChan(TypeOf(c), 1) 1180 c = cv.Interface().(chan int) 1181 } 1182 1183 // Send 1184 cv.Send(ValueOf(2)) 1185 if i := <-c; i != 2 { 1186 t.Errorf("reflect Send 2, native recv %d", i) 1187 } 1188 1189 // Recv 1190 c <- 3 1191 if i, ok := cv.Recv(); i.Int() != 3 || !ok { 1192 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok) 1193 } 1194 1195 // TryRecv fail 1196 val, ok := cv.TryRecv() 1197 if val.IsValid() || ok { 1198 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok) 1199 } 1200 1201 // TryRecv success 1202 c <- 4 1203 val, ok = cv.TryRecv() 1204 if !val.IsValid() { 1205 t.Errorf("TryRecv on ready chan got nil") 1206 } else if i := val.Int(); i != 4 || !ok { 1207 t.Errorf("native send 4, TryRecv %d, %t", i, ok) 1208 } 1209 1210 // TrySend fail 1211 c <- 100 1212 ok = cv.TrySend(ValueOf(5)) 1213 i := <-c 1214 if ok { 1215 t.Errorf("TrySend on full chan succeeded: value %d", i) 1216 } 1217 1218 // TrySend success 1219 ok = cv.TrySend(ValueOf(6)) 1220 if !ok { 1221 t.Errorf("TrySend on empty chan failed") 1222 select { 1223 case x := <-c: 1224 t.Errorf("TrySend failed but it did send %d", x) 1225 default: 1226 } 1227 } else { 1228 if i = <-c; i != 6 { 1229 t.Errorf("TrySend 6, recv %d", i) 1230 } 1231 } 1232 1233 // Close 1234 c <- 123 1235 cv.Close() 1236 if i, ok := cv.Recv(); i.Int() != 123 || !ok { 1237 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok) 1238 } 1239 if i, ok := cv.Recv(); i.Int() != 0 || ok { 1240 t.Errorf("after close Recv %d, %t", i.Int(), ok) 1241 } 1242 } 1243 1244 // check creation of unbuffered channel 1245 var c chan int 1246 cv := MakeChan(TypeOf(c), 0) 1247 c = cv.Interface().(chan int) 1248 if cv.TrySend(ValueOf(7)) { 1249 t.Errorf("TrySend on sync chan succeeded") 1250 } 1251 if v, ok := cv.TryRecv(); v.IsValid() || ok { 1252 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok) 1253 } 1254 1255 // len/cap 1256 cv = MakeChan(TypeOf(c), 10) 1257 c = cv.Interface().(chan int) 1258 for i := 0; i < 3; i++ { 1259 c <- i 1260 } 1261 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) { 1262 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c)) 1263 } 1264} 1265 1266// caseInfo describes a single case in a select test. 1267type caseInfo struct { 1268 desc string 1269 canSelect bool 1270 recv Value 1271 closed bool 1272 helper func() 1273 panic bool 1274} 1275 1276var allselect = flag.Bool("allselect", false, "exhaustive select test") 1277 1278func TestSelect(t *testing.T) { 1279 selectWatch.once.Do(func() { go selectWatcher() }) 1280 1281 var x exhaustive 1282 nch := 0 1283 newop := func(n int, cap int) (ch, val Value) { 1284 nch++ 1285 if nch%101%2 == 1 { 1286 c := make(chan int, cap) 1287 ch = ValueOf(c) 1288 val = ValueOf(n) 1289 } else { 1290 c := make(chan string, cap) 1291 ch = ValueOf(c) 1292 val = ValueOf(fmt.Sprint(n)) 1293 } 1294 return 1295 } 1296 1297 for n := 0; x.Next(); n++ { 1298 if testing.Short() && n >= 1000 { 1299 break 1300 } 1301 if n >= 100000 && !*allselect { 1302 break 1303 } 1304 if n%100000 == 0 && testing.Verbose() { 1305 println("TestSelect", n) 1306 } 1307 var cases []SelectCase 1308 var info []caseInfo 1309 1310 // Ready send. 1311 if x.Maybe() { 1312 ch, val := newop(len(cases), 1) 1313 cases = append(cases, SelectCase{ 1314 Dir: SelectSend, 1315 Chan: ch, 1316 Send: val, 1317 }) 1318 info = append(info, caseInfo{desc: "ready send", canSelect: true}) 1319 } 1320 1321 // Ready recv. 1322 if x.Maybe() { 1323 ch, val := newop(len(cases), 1) 1324 ch.Send(val) 1325 cases = append(cases, SelectCase{ 1326 Dir: SelectRecv, 1327 Chan: ch, 1328 }) 1329 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val}) 1330 } 1331 1332 // Blocking send. 1333 if x.Maybe() { 1334 ch, val := newop(len(cases), 0) 1335 cases = append(cases, SelectCase{ 1336 Dir: SelectSend, 1337 Chan: ch, 1338 Send: val, 1339 }) 1340 // Let it execute? 1341 if x.Maybe() { 1342 f := func() { ch.Recv() } 1343 info = append(info, caseInfo{desc: "blocking send", helper: f}) 1344 } else { 1345 info = append(info, caseInfo{desc: "blocking send"}) 1346 } 1347 } 1348 1349 // Blocking recv. 1350 if x.Maybe() { 1351 ch, val := newop(len(cases), 0) 1352 cases = append(cases, SelectCase{ 1353 Dir: SelectRecv, 1354 Chan: ch, 1355 }) 1356 // Let it execute? 1357 if x.Maybe() { 1358 f := func() { ch.Send(val) } 1359 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f}) 1360 } else { 1361 info = append(info, caseInfo{desc: "blocking recv"}) 1362 } 1363 } 1364 1365 // Zero Chan send. 1366 if x.Maybe() { 1367 // Maybe include value to send. 1368 var val Value 1369 if x.Maybe() { 1370 val = ValueOf(100) 1371 } 1372 cases = append(cases, SelectCase{ 1373 Dir: SelectSend, 1374 Send: val, 1375 }) 1376 info = append(info, caseInfo{desc: "zero Chan send"}) 1377 } 1378 1379 // Zero Chan receive. 1380 if x.Maybe() { 1381 cases = append(cases, SelectCase{ 1382 Dir: SelectRecv, 1383 }) 1384 info = append(info, caseInfo{desc: "zero Chan recv"}) 1385 } 1386 1387 // nil Chan send. 1388 if x.Maybe() { 1389 cases = append(cases, SelectCase{ 1390 Dir: SelectSend, 1391 Chan: ValueOf((chan int)(nil)), 1392 Send: ValueOf(101), 1393 }) 1394 info = append(info, caseInfo{desc: "nil Chan send"}) 1395 } 1396 1397 // nil Chan recv. 1398 if x.Maybe() { 1399 cases = append(cases, SelectCase{ 1400 Dir: SelectRecv, 1401 Chan: ValueOf((chan int)(nil)), 1402 }) 1403 info = append(info, caseInfo{desc: "nil Chan recv"}) 1404 } 1405 1406 // closed Chan send. 1407 if x.Maybe() { 1408 ch := make(chan int) 1409 close(ch) 1410 cases = append(cases, SelectCase{ 1411 Dir: SelectSend, 1412 Chan: ValueOf(ch), 1413 Send: ValueOf(101), 1414 }) 1415 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true}) 1416 } 1417 1418 // closed Chan recv. 1419 if x.Maybe() { 1420 ch, val := newop(len(cases), 0) 1421 ch.Close() 1422 val = Zero(val.Type()) 1423 cases = append(cases, SelectCase{ 1424 Dir: SelectRecv, 1425 Chan: ch, 1426 }) 1427 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val}) 1428 } 1429 1430 var helper func() // goroutine to help the select complete 1431 1432 // Add default? Must be last case here, but will permute. 1433 // Add the default if the select would otherwise 1434 // block forever, and maybe add it anyway. 1435 numCanSelect := 0 1436 canProceed := false 1437 canBlock := true 1438 canPanic := false 1439 helpers := []int{} 1440 for i, c := range info { 1441 if c.canSelect { 1442 canProceed = true 1443 canBlock = false 1444 numCanSelect++ 1445 if c.panic { 1446 canPanic = true 1447 } 1448 } else if c.helper != nil { 1449 canProceed = true 1450 helpers = append(helpers, i) 1451 } 1452 } 1453 if !canProceed || x.Maybe() { 1454 cases = append(cases, SelectCase{ 1455 Dir: SelectDefault, 1456 }) 1457 info = append(info, caseInfo{desc: "default", canSelect: canBlock}) 1458 numCanSelect++ 1459 } else if canBlock { 1460 // Select needs to communicate with another goroutine. 1461 cas := &info[helpers[x.Choose(len(helpers))]] 1462 helper = cas.helper 1463 cas.canSelect = true 1464 numCanSelect++ 1465 } 1466 1467 // Permute cases and case info. 1468 // Doing too much here makes the exhaustive loop 1469 // too exhausting, so just do two swaps. 1470 for loop := 0; loop < 2; loop++ { 1471 i := x.Choose(len(cases)) 1472 j := x.Choose(len(cases)) 1473 cases[i], cases[j] = cases[j], cases[i] 1474 info[i], info[j] = info[j], info[i] 1475 } 1476 1477 if helper != nil { 1478 // We wait before kicking off a goroutine to satisfy a blocked select. 1479 // The pause needs to be big enough to let the select block before 1480 // we run the helper, but if we lose that race once in a while it's okay: the 1481 // select will just proceed immediately. Not a big deal. 1482 // For short tests we can grow [sic] the timeout a bit without fear of taking too long 1483 pause := 10 * time.Microsecond 1484 if testing.Short() { 1485 pause = 100 * time.Microsecond 1486 } 1487 time.AfterFunc(pause, helper) 1488 } 1489 1490 // Run select. 1491 i, recv, recvOK, panicErr := runSelect(cases, info) 1492 if panicErr != nil && !canPanic { 1493 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr) 1494 } 1495 if panicErr == nil && canPanic && numCanSelect == 1 { 1496 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i) 1497 } 1498 if panicErr != nil { 1499 continue 1500 } 1501 1502 cas := info[i] 1503 if !cas.canSelect { 1504 recvStr := "" 1505 if recv.IsValid() { 1506 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK) 1507 } 1508 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr) 1509 continue 1510 } 1511 if cas.panic { 1512 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i) 1513 continue 1514 } 1515 1516 if cases[i].Dir == SelectRecv { 1517 if !recv.IsValid() { 1518 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed) 1519 } 1520 if !cas.recv.IsValid() { 1521 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i) 1522 } 1523 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed { 1524 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed { 1525 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface()) 1526 } 1527 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed) 1528 } 1529 } else { 1530 if recv.IsValid() || recvOK { 1531 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false) 1532 } 1533 } 1534 } 1535} 1536 1537// selectWatch and the selectWatcher are a watchdog mechanism for running Select. 1538// If the selectWatcher notices that the select has been blocked for >1 second, it prints 1539// an error describing the select and panics the entire test binary. 1540var selectWatch struct { 1541 sync.Mutex 1542 once sync.Once 1543 now time.Time 1544 info []caseInfo 1545} 1546 1547func selectWatcher() { 1548 for { 1549 time.Sleep(1 * time.Second) 1550 selectWatch.Lock() 1551 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second { 1552 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info)) 1553 panic("select stuck") 1554 } 1555 selectWatch.Unlock() 1556 } 1557} 1558 1559// runSelect runs a single select test. 1560// It returns the values returned by Select but also returns 1561// a panic value if the Select panics. 1562func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) { 1563 defer func() { 1564 panicErr = recover() 1565 1566 selectWatch.Lock() 1567 selectWatch.info = nil 1568 selectWatch.Unlock() 1569 }() 1570 1571 selectWatch.Lock() 1572 selectWatch.now = time.Now() 1573 selectWatch.info = info 1574 selectWatch.Unlock() 1575 1576 chosen, recv, recvOK = Select(cases) 1577 return 1578} 1579 1580// fmtSelect formats the information about a single select test. 1581func fmtSelect(info []caseInfo) string { 1582 var buf bytes.Buffer 1583 fmt.Fprintf(&buf, "\nselect {\n") 1584 for i, cas := range info { 1585 fmt.Fprintf(&buf, "%d: %s", i, cas.desc) 1586 if cas.recv.IsValid() { 1587 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface()) 1588 } 1589 if cas.canSelect { 1590 fmt.Fprintf(&buf, " canselect") 1591 } 1592 if cas.panic { 1593 fmt.Fprintf(&buf, " panic") 1594 } 1595 fmt.Fprintf(&buf, "\n") 1596 } 1597 fmt.Fprintf(&buf, "}") 1598 return buf.String() 1599} 1600 1601type two [2]uintptr 1602 1603// Difficult test for function call because of 1604// implicit padding between arguments. 1605func 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) { 1606 return b, c, d, e, f, g, h 1607} 1608 1609func TestFunc(t *testing.T) { 1610 ret := ValueOf(dummy).Call([]Value{ 1611 ValueOf(byte(10)), 1612 ValueOf(20), 1613 ValueOf(byte(30)), 1614 ValueOf(two{40, 50}), 1615 ValueOf(byte(60)), 1616 ValueOf(float32(70)), 1617 ValueOf(byte(80)), 1618 }) 1619 if len(ret) != 7 { 1620 t.Fatalf("Call returned %d values, want 7", len(ret)) 1621 } 1622 1623 i := byte(ret[0].Uint()) 1624 j := int(ret[1].Int()) 1625 k := byte(ret[2].Uint()) 1626 l := ret[3].Interface().(two) 1627 m := byte(ret[4].Uint()) 1628 n := float32(ret[5].Float()) 1629 o := byte(ret[6].Uint()) 1630 1631 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 { 1632 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) 1633 } 1634 1635 for i, v := range ret { 1636 if v.CanAddr() { 1637 t.Errorf("result %d is addressable", i) 1638 } 1639 } 1640} 1641 1642func TestCallConvert(t *testing.T) { 1643 v := ValueOf(new(io.ReadWriter)).Elem() 1644 f := ValueOf(func(r io.Reader) io.Reader { return r }) 1645 out := f.Call([]Value{v}) 1646 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() { 1647 t.Errorf("expected [nil], got %v", out) 1648 } 1649} 1650 1651type emptyStruct struct{} 1652 1653type nonEmptyStruct struct { 1654 member int 1655} 1656 1657func returnEmpty() emptyStruct { 1658 return emptyStruct{} 1659} 1660 1661func takesEmpty(e emptyStruct) { 1662} 1663 1664func returnNonEmpty(i int) nonEmptyStruct { 1665 return nonEmptyStruct{member: i} 1666} 1667 1668func takesNonEmpty(n nonEmptyStruct) int { 1669 return n.member 1670} 1671 1672func TestCallWithStruct(t *testing.T) { 1673 r := ValueOf(returnEmpty).Call(nil) 1674 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) { 1675 t.Errorf("returning empty struct returned %#v instead", r) 1676 } 1677 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})}) 1678 if len(r) != 0 { 1679 t.Errorf("takesEmpty returned values: %#v", r) 1680 } 1681 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)}) 1682 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 { 1683 t.Errorf("returnNonEmpty returned %#v", r) 1684 } 1685 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})}) 1686 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 { 1687 t.Errorf("takesNonEmpty returned %#v", r) 1688 } 1689} 1690 1691func TestCallReturnsEmpty(t *testing.T) { 1692 if runtime.Compiler == "gccgo" { 1693 t.Skip("skipping on gccgo: imprecise stack can keep i live") 1694 } 1695 // Issue 21717: past-the-end pointer write in Call with 1696 // nonzero-sized frame and zero-sized return value. 1697 runtime.GC() 1698 var finalized uint32 1699 f := func() (emptyStruct, *int) { 1700 i := new(int) 1701 runtime.SetFinalizer(i, func(*int) { atomic.StoreUint32(&finalized, 1) }) 1702 return emptyStruct{}, i 1703 } 1704 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run. 1705 timeout := time.After(5 * time.Second) 1706 for atomic.LoadUint32(&finalized) == 0 { 1707 select { 1708 case <-timeout: 1709 t.Fatal("finalizer did not run") 1710 default: 1711 } 1712 runtime.Gosched() 1713 runtime.GC() 1714 } 1715 runtime.KeepAlive(v) 1716} 1717 1718func BenchmarkCall(b *testing.B) { 1719 fv := ValueOf(func(a, b string) {}) 1720 b.ReportAllocs() 1721 b.RunParallel(func(pb *testing.PB) { 1722 args := []Value{ValueOf("a"), ValueOf("b")} 1723 for pb.Next() { 1724 fv.Call(args) 1725 } 1726 }) 1727} 1728 1729func BenchmarkCallArgCopy(b *testing.B) { 1730 byteArray := func(n int) Value { 1731 return Zero(ArrayOf(n, TypeOf(byte(0)))) 1732 } 1733 sizes := [...]struct { 1734 fv Value 1735 arg Value 1736 }{ 1737 {ValueOf(func(a [128]byte) {}), byteArray(128)}, 1738 {ValueOf(func(a [256]byte) {}), byteArray(256)}, 1739 {ValueOf(func(a [1024]byte) {}), byteArray(1024)}, 1740 {ValueOf(func(a [4096]byte) {}), byteArray(4096)}, 1741 {ValueOf(func(a [65536]byte) {}), byteArray(65536)}, 1742 } 1743 for _, size := range sizes { 1744 bench := func(b *testing.B) { 1745 args := []Value{size.arg} 1746 b.SetBytes(int64(size.arg.Len())) 1747 b.ResetTimer() 1748 b.RunParallel(func(pb *testing.PB) { 1749 for pb.Next() { 1750 size.fv.Call(args) 1751 } 1752 }) 1753 } 1754 name := fmt.Sprintf("size=%v", size.arg.Len()) 1755 b.Run(name, bench) 1756 } 1757} 1758 1759func TestMakeFunc(t *testing.T) { 1760 f := dummy 1761 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in }) 1762 ValueOf(&f).Elem().Set(fv) 1763 1764 // Call g with small arguments so that there is 1765 // something predictable (and different from the 1766 // correct results) in those positions on the stack. 1767 g := dummy 1768 g(1, 2, 3, two{4, 5}, 6, 7, 8) 1769 1770 // Call constructed function f. 1771 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80) 1772 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 { 1773 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) 1774 } 1775} 1776 1777func TestMakeFuncInterface(t *testing.T) { 1778 fn := func(i int) int { return i } 1779 incr := func(in []Value) []Value { 1780 return []Value{ValueOf(int(in[0].Int() + 1))} 1781 } 1782 fv := MakeFunc(TypeOf(fn), incr) 1783 ValueOf(&fn).Elem().Set(fv) 1784 if r := fn(2); r != 3 { 1785 t.Errorf("Call returned %d, want 3", r) 1786 } 1787 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 { 1788 t.Errorf("Call returned %d, want 15", r) 1789 } 1790 if r := fv.Interface().(func(int) int)(26); r != 27 { 1791 t.Errorf("Call returned %d, want 27", r) 1792 } 1793} 1794 1795func TestMakeFuncVariadic(t *testing.T) { 1796 // Test that variadic arguments are packed into a slice and passed as last arg 1797 fn := func(_ int, is ...int) []int { return nil } 1798 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] }) 1799 ValueOf(&fn).Elem().Set(fv) 1800 1801 r := fn(1, 2, 3) 1802 if r[0] != 2 || r[1] != 3 { 1803 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1804 } 1805 1806 r = fn(1, []int{2, 3}...) 1807 if r[0] != 2 || r[1] != 3 { 1808 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1809 } 1810 1811 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int) 1812 if r[0] != 2 || r[1] != 3 { 1813 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1814 } 1815 1816 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int) 1817 if r[0] != 2 || r[1] != 3 { 1818 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1819 } 1820 1821 f := fv.Interface().(func(int, ...int) []int) 1822 1823 r = f(1, 2, 3) 1824 if r[0] != 2 || r[1] != 3 { 1825 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1826 } 1827 r = f(1, []int{2, 3}...) 1828 if r[0] != 2 || r[1] != 3 { 1829 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1]) 1830 } 1831} 1832 1833type Point struct { 1834 x, y int 1835} 1836 1837// This will be index 0. 1838func (p Point) AnotherMethod(scale int) int { 1839 return -1 1840} 1841 1842// This will be index 1. 1843func (p Point) Dist(scale int) int { 1844 //println("Point.Dist", p.x, p.y, scale) 1845 return p.x*p.x*scale + p.y*p.y*scale 1846} 1847 1848// This will be index 2. 1849func (p Point) GCMethod(k int) int { 1850 runtime.GC() 1851 return k + p.x 1852} 1853 1854// This will be index 3. 1855func (p Point) NoArgs() { 1856 // Exercise no-argument/no-result paths. 1857} 1858 1859// This will be index 4. 1860func (p Point) TotalDist(points ...Point) int { 1861 tot := 0 1862 for _, q := range points { 1863 dx := q.x - p.x 1864 dy := q.y - p.y 1865 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test. 1866 1867 } 1868 return tot 1869} 1870 1871func TestMethod(t *testing.T) { 1872 // Non-curried method of type. 1873 p := Point{3, 4} 1874 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int() 1875 if i != 250 { 1876 t.Errorf("Type Method returned %d; want 250", i) 1877 } 1878 1879 m, ok := TypeOf(p).MethodByName("Dist") 1880 if !ok { 1881 t.Fatalf("method by name failed") 1882 } 1883 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int() 1884 if i != 275 { 1885 t.Errorf("Type MethodByName returned %d; want 275", i) 1886 } 1887 1888 m, ok = TypeOf(p).MethodByName("NoArgs") 1889 if !ok { 1890 t.Fatalf("method by name failed") 1891 } 1892 n := len(m.Func.Call([]Value{ValueOf(p)})) 1893 if n != 0 { 1894 t.Errorf("NoArgs returned %d values; want 0", n) 1895 } 1896 1897 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int() 1898 if i != 300 { 1899 t.Errorf("Pointer Type Method returned %d; want 300", i) 1900 } 1901 1902 m, ok = TypeOf(&p).MethodByName("Dist") 1903 if !ok { 1904 t.Fatalf("ptr method by name failed") 1905 } 1906 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int() 1907 if i != 325 { 1908 t.Errorf("Pointer Type MethodByName returned %d; want 325", i) 1909 } 1910 1911 m, ok = TypeOf(&p).MethodByName("NoArgs") 1912 if !ok { 1913 t.Fatalf("method by name failed") 1914 } 1915 n = len(m.Func.Call([]Value{ValueOf(&p)})) 1916 if n != 0 { 1917 t.Errorf("NoArgs returned %d values; want 0", n) 1918 } 1919 1920 // Curried method of value. 1921 tfunc := TypeOf((func(int) int)(nil)) 1922 v := ValueOf(p).Method(1) 1923 if tt := v.Type(); tt != tfunc { 1924 t.Errorf("Value Method Type is %s; want %s", tt, tfunc) 1925 } 1926 i = v.Call([]Value{ValueOf(14)})[0].Int() 1927 if i != 350 { 1928 t.Errorf("Value Method returned %d; want 350", i) 1929 } 1930 v = ValueOf(p).MethodByName("Dist") 1931 if tt := v.Type(); tt != tfunc { 1932 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc) 1933 } 1934 i = v.Call([]Value{ValueOf(15)})[0].Int() 1935 if i != 375 { 1936 t.Errorf("Value MethodByName returned %d; want 375", i) 1937 } 1938 v = ValueOf(p).MethodByName("NoArgs") 1939 v.Call(nil) 1940 1941 // Curried method of pointer. 1942 v = ValueOf(&p).Method(1) 1943 if tt := v.Type(); tt != tfunc { 1944 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc) 1945 } 1946 i = v.Call([]Value{ValueOf(16)})[0].Int() 1947 if i != 400 { 1948 t.Errorf("Pointer Value Method returned %d; want 400", i) 1949 } 1950 v = ValueOf(&p).MethodByName("Dist") 1951 if tt := v.Type(); tt != tfunc { 1952 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc) 1953 } 1954 i = v.Call([]Value{ValueOf(17)})[0].Int() 1955 if i != 425 { 1956 t.Errorf("Pointer Value MethodByName returned %d; want 425", i) 1957 } 1958 v = ValueOf(&p).MethodByName("NoArgs") 1959 v.Call(nil) 1960 1961 // Curried method of interface value. 1962 // Have to wrap interface value in a struct to get at it. 1963 // Passing it to ValueOf directly would 1964 // access the underlying Point, not the interface. 1965 var x interface { 1966 Dist(int) int 1967 } = p 1968 pv := ValueOf(&x).Elem() 1969 v = pv.Method(0) 1970 if tt := v.Type(); tt != tfunc { 1971 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc) 1972 } 1973 i = v.Call([]Value{ValueOf(18)})[0].Int() 1974 if i != 450 { 1975 t.Errorf("Interface Method returned %d; want 450", i) 1976 } 1977 v = pv.MethodByName("Dist") 1978 if tt := v.Type(); tt != tfunc { 1979 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc) 1980 } 1981 i = v.Call([]Value{ValueOf(19)})[0].Int() 1982 if i != 475 { 1983 t.Errorf("Interface MethodByName returned %d; want 475", i) 1984 } 1985} 1986 1987func TestMethodValue(t *testing.T) { 1988 p := Point{3, 4} 1989 var i int64 1990 1991 // Curried method of value. 1992 tfunc := TypeOf((func(int) int)(nil)) 1993 v := ValueOf(p).Method(1) 1994 if tt := v.Type(); tt != tfunc { 1995 t.Errorf("Value Method Type is %s; want %s", tt, tfunc) 1996 } 1997 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int() 1998 if i != 250 { 1999 t.Errorf("Value Method returned %d; want 250", i) 2000 } 2001 v = ValueOf(p).MethodByName("Dist") 2002 if tt := v.Type(); tt != tfunc { 2003 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc) 2004 } 2005 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int() 2006 if i != 275 { 2007 t.Errorf("Value MethodByName returned %d; want 275", i) 2008 } 2009 v = ValueOf(p).MethodByName("NoArgs") 2010 ValueOf(v.Interface()).Call(nil) 2011 v.Interface().(func())() 2012 2013 // Curried method of pointer. 2014 v = ValueOf(&p).Method(1) 2015 if tt := v.Type(); tt != tfunc { 2016 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc) 2017 } 2018 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int() 2019 if i != 300 { 2020 t.Errorf("Pointer Value Method returned %d; want 300", i) 2021 } 2022 v = ValueOf(&p).MethodByName("Dist") 2023 if tt := v.Type(); tt != tfunc { 2024 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc) 2025 } 2026 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int() 2027 if i != 325 { 2028 t.Errorf("Pointer Value MethodByName returned %d; want 325", i) 2029 } 2030 v = ValueOf(&p).MethodByName("NoArgs") 2031 ValueOf(v.Interface()).Call(nil) 2032 v.Interface().(func())() 2033 2034 // Curried method of pointer to pointer. 2035 pp := &p 2036 v = ValueOf(&pp).Elem().Method(1) 2037 if tt := v.Type(); tt != tfunc { 2038 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc) 2039 } 2040 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int() 2041 if i != 350 { 2042 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i) 2043 } 2044 v = ValueOf(&pp).Elem().MethodByName("Dist") 2045 if tt := v.Type(); tt != tfunc { 2046 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc) 2047 } 2048 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int() 2049 if i != 375 { 2050 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i) 2051 } 2052 2053 // Curried method of interface value. 2054 // Have to wrap interface value in a struct to get at it. 2055 // Passing it to ValueOf directly would 2056 // access the underlying Point, not the interface. 2057 var s = struct { 2058 X interface { 2059 Dist(int) int 2060 } 2061 }{p} 2062 pv := ValueOf(s).Field(0) 2063 v = pv.Method(0) 2064 if tt := v.Type(); tt != tfunc { 2065 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc) 2066 } 2067 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int() 2068 if i != 400 { 2069 t.Errorf("Interface Method returned %d; want 400", i) 2070 } 2071 v = pv.MethodByName("Dist") 2072 if tt := v.Type(); tt != tfunc { 2073 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc) 2074 } 2075 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int() 2076 if i != 425 { 2077 t.Errorf("Interface MethodByName returned %d; want 425", i) 2078 } 2079} 2080 2081func TestVariadicMethodValue(t *testing.T) { 2082 p := Point{3, 4} 2083 points := []Point{{20, 21}, {22, 23}, {24, 25}} 2084 want := int64(p.TotalDist(points[0], points[1], points[2])) 2085 2086 // Curried method of value. 2087 tfunc := TypeOf((func(...Point) int)(nil)) 2088 v := ValueOf(p).Method(4) 2089 if tt := v.Type(); tt != tfunc { 2090 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc) 2091 } 2092 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int() 2093 if i != want { 2094 t.Errorf("Variadic Method returned %d; want %d", i, want) 2095 } 2096 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int() 2097 if i != want { 2098 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want) 2099 } 2100 2101 f := v.Interface().(func(...Point) int) 2102 i = int64(f(points[0], points[1], points[2])) 2103 if i != want { 2104 t.Errorf("Variadic Method Interface returned %d; want %d", i, want) 2105 } 2106 i = int64(f(points...)) 2107 if i != want { 2108 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want) 2109 } 2110} 2111 2112// Reflect version of $GOROOT/test/method5.go 2113 2114// Concrete types implementing M method. 2115// Smaller than a word, word-sized, larger than a word. 2116// Value and pointer receivers. 2117 2118type Tinter interface { 2119 M(int, byte) (byte, int) 2120} 2121 2122type Tsmallv byte 2123 2124func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) } 2125 2126type Tsmallp byte 2127 2128func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) } 2129 2130type Twordv uintptr 2131 2132func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) } 2133 2134type Twordp uintptr 2135 2136func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) } 2137 2138type Tbigv [2]uintptr 2139 2140func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) } 2141 2142type Tbigp [2]uintptr 2143 2144func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) } 2145 2146type tinter interface { 2147 m(int, byte) (byte, int) 2148} 2149 2150// Embedding via pointer. 2151 2152type Tm1 struct { 2153 Tm2 2154} 2155 2156type Tm2 struct { 2157 *Tm3 2158} 2159 2160type Tm3 struct { 2161 *Tm4 2162} 2163 2164type Tm4 struct { 2165} 2166 2167func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 } 2168 2169func TestMethod5(t *testing.T) { 2170 CheckF := func(name string, f func(int, byte) (byte, int), inc int) { 2171 b, x := f(1000, 99) 2172 if b != 99 || x != 1000+inc { 2173 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc) 2174 } 2175 } 2176 2177 CheckV := func(name string, i Value, inc int) { 2178 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))}) 2179 b := bx[0].Interface() 2180 x := bx[1].Interface() 2181 if b != byte(99) || x != 1000+inc { 2182 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc) 2183 } 2184 2185 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc) 2186 } 2187 2188 var TinterType = TypeOf(new(Tinter)).Elem() 2189 2190 CheckI := func(name string, i interface{}, inc int) { 2191 v := ValueOf(i) 2192 CheckV(name, v, inc) 2193 CheckV("(i="+name+")", v.Convert(TinterType), inc) 2194 } 2195 2196 sv := Tsmallv(1) 2197 CheckI("sv", sv, 1) 2198 CheckI("&sv", &sv, 1) 2199 2200 sp := Tsmallp(2) 2201 CheckI("&sp", &sp, 2) 2202 2203 wv := Twordv(3) 2204 CheckI("wv", wv, 3) 2205 CheckI("&wv", &wv, 3) 2206 2207 wp := Twordp(4) 2208 CheckI("&wp", &wp, 4) 2209 2210 bv := Tbigv([2]uintptr{5, 6}) 2211 CheckI("bv", bv, 11) 2212 CheckI("&bv", &bv, 11) 2213 2214 bp := Tbigp([2]uintptr{7, 8}) 2215 CheckI("&bp", &bp, 15) 2216 2217 t4 := Tm4{} 2218 t3 := Tm3{&t4} 2219 t2 := Tm2{&t3} 2220 t1 := Tm1{t2} 2221 CheckI("t4", t4, 40) 2222 CheckI("&t4", &t4, 40) 2223 CheckI("t3", t3, 40) 2224 CheckI("&t3", &t3, 40) 2225 CheckI("t2", t2, 40) 2226 CheckI("&t2", &t2, 40) 2227 CheckI("t1", t1, 40) 2228 CheckI("&t1", &t1, 40) 2229 2230 var tnil Tinter 2231 vnil := ValueOf(&tnil).Elem() 2232 shouldPanic(func() { vnil.Method(0) }) 2233} 2234 2235func TestInterfaceSet(t *testing.T) { 2236 p := &Point{3, 4} 2237 2238 var s struct { 2239 I interface{} 2240 P interface { 2241 Dist(int) int 2242 } 2243 } 2244 sv := ValueOf(&s).Elem() 2245 sv.Field(0).Set(ValueOf(p)) 2246 if q := s.I.(*Point); q != p { 2247 t.Errorf("i: have %p want %p", q, p) 2248 } 2249 2250 pv := sv.Field(1) 2251 pv.Set(ValueOf(p)) 2252 if q := s.P.(*Point); q != p { 2253 t.Errorf("i: have %p want %p", q, p) 2254 } 2255 2256 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int() 2257 if i != 250 { 2258 t.Errorf("Interface Method returned %d; want 250", i) 2259 } 2260} 2261 2262type T1 struct { 2263 a string 2264 int 2265} 2266 2267func TestAnonymousFields(t *testing.T) { 2268 var field StructField 2269 var ok bool 2270 var t1 T1 2271 type1 := TypeOf(t1) 2272 if field, ok = type1.FieldByName("int"); !ok { 2273 t.Fatal("no field 'int'") 2274 } 2275 if field.Index[0] != 1 { 2276 t.Error("field index should be 1; is", field.Index) 2277 } 2278} 2279 2280type FTest struct { 2281 s interface{} 2282 name string 2283 index []int 2284 value int 2285} 2286 2287type D1 struct { 2288 d int 2289} 2290type D2 struct { 2291 d int 2292} 2293 2294type S0 struct { 2295 A, B, C int 2296 D1 2297 D2 2298} 2299 2300type S1 struct { 2301 B int 2302 S0 2303} 2304 2305type S2 struct { 2306 A int 2307 *S1 2308} 2309 2310type S1x struct { 2311 S1 2312} 2313 2314type S1y struct { 2315 S1 2316} 2317 2318type S3 struct { 2319 S1x 2320 S2 2321 D, E int 2322 *S1y 2323} 2324 2325type S4 struct { 2326 *S4 2327 A int 2328} 2329 2330// The X in S6 and S7 annihilate, but they also block the X in S8.S9. 2331type S5 struct { 2332 S6 2333 S7 2334 S8 2335} 2336 2337type S6 struct { 2338 X int 2339} 2340 2341type S7 S6 2342 2343type S8 struct { 2344 S9 2345} 2346 2347type S9 struct { 2348 X int 2349 Y int 2350} 2351 2352// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. 2353type S10 struct { 2354 S11 2355 S12 2356 S13 2357} 2358 2359type S11 struct { 2360 S6 2361} 2362 2363type S12 struct { 2364 S6 2365} 2366 2367type S13 struct { 2368 S8 2369} 2370 2371// The X in S15.S11.S1 and S16.S11.S1 annihilate. 2372type S14 struct { 2373 S15 2374 S16 2375} 2376 2377type S15 struct { 2378 S11 2379} 2380 2381type S16 struct { 2382 S11 2383} 2384 2385var fieldTests = []FTest{ 2386 {struct{}{}, "", nil, 0}, 2387 {struct{}{}, "Foo", nil, 0}, 2388 {S0{A: 'a'}, "A", []int{0}, 'a'}, 2389 {S0{}, "D", nil, 0}, 2390 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'}, 2391 {S1{B: 'b'}, "B", []int{0}, 'b'}, 2392 {S1{}, "S0", []int{1}, 0}, 2393 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'}, 2394 {S2{A: 'a'}, "A", []int{0}, 'a'}, 2395 {S2{}, "S1", []int{1}, 0}, 2396 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'}, 2397 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'}, 2398 {S2{}, "D", nil, 0}, 2399 {S3{}, "S1", nil, 0}, 2400 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'}, 2401 {S3{}, "B", nil, 0}, 2402 {S3{D: 'd'}, "D", []int{2}, 0}, 2403 {S3{E: 'e'}, "E", []int{3}, 'e'}, 2404 {S4{A: 'a'}, "A", []int{1}, 'a'}, 2405 {S4{}, "B", nil, 0}, 2406 {S5{}, "X", nil, 0}, 2407 {S5{}, "Y", []int{2, 0, 1}, 0}, 2408 {S10{}, "X", nil, 0}, 2409 {S10{}, "Y", []int{2, 0, 0, 1}, 0}, 2410 {S14{}, "X", nil, 0}, 2411} 2412 2413func TestFieldByIndex(t *testing.T) { 2414 for _, test := range fieldTests { 2415 s := TypeOf(test.s) 2416 f := s.FieldByIndex(test.index) 2417 if f.Name != "" { 2418 if test.index != nil { 2419 if f.Name != test.name { 2420 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name) 2421 } 2422 } else { 2423 t.Errorf("%s.%s found", s.Name(), f.Name) 2424 } 2425 } else if len(test.index) > 0 { 2426 t.Errorf("%s.%s not found", s.Name(), test.name) 2427 } 2428 2429 if test.value != 0 { 2430 v := ValueOf(test.s).FieldByIndex(test.index) 2431 if v.IsValid() { 2432 if x, ok := v.Interface().(int); ok { 2433 if x != test.value { 2434 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value) 2435 } 2436 } else { 2437 t.Errorf("%s%v value not an int", s.Name(), test.index) 2438 } 2439 } else { 2440 t.Errorf("%s%v value not found", s.Name(), test.index) 2441 } 2442 } 2443 } 2444} 2445 2446func TestFieldByName(t *testing.T) { 2447 for _, test := range fieldTests { 2448 s := TypeOf(test.s) 2449 f, found := s.FieldByName(test.name) 2450 if found { 2451 if test.index != nil { 2452 // Verify field depth and index. 2453 if len(f.Index) != len(test.index) { 2454 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) 2455 } else { 2456 for i, x := range f.Index { 2457 if x != test.index[i] { 2458 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i]) 2459 } 2460 } 2461 } 2462 } else { 2463 t.Errorf("%s.%s found", s.Name(), f.Name) 2464 } 2465 } else if len(test.index) > 0 { 2466 t.Errorf("%s.%s not found", s.Name(), test.name) 2467 } 2468 2469 if test.value != 0 { 2470 v := ValueOf(test.s).FieldByName(test.name) 2471 if v.IsValid() { 2472 if x, ok := v.Interface().(int); ok { 2473 if x != test.value { 2474 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value) 2475 } 2476 } else { 2477 t.Errorf("%s.%s value not an int", s.Name(), test.name) 2478 } 2479 } else { 2480 t.Errorf("%s.%s value not found", s.Name(), test.name) 2481 } 2482 } 2483 } 2484} 2485 2486func TestImportPath(t *testing.T) { 2487 tests := []struct { 2488 t Type 2489 path string 2490 }{ 2491 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"}, 2492 {TypeOf(int(0)), ""}, 2493 {TypeOf(int8(0)), ""}, 2494 {TypeOf(int16(0)), ""}, 2495 {TypeOf(int32(0)), ""}, 2496 {TypeOf(int64(0)), ""}, 2497 {TypeOf(uint(0)), ""}, 2498 {TypeOf(uint8(0)), ""}, 2499 {TypeOf(uint16(0)), ""}, 2500 {TypeOf(uint32(0)), ""}, 2501 {TypeOf(uint64(0)), ""}, 2502 {TypeOf(uintptr(0)), ""}, 2503 {TypeOf(float32(0)), ""}, 2504 {TypeOf(float64(0)), ""}, 2505 {TypeOf(complex64(0)), ""}, 2506 {TypeOf(complex128(0)), ""}, 2507 {TypeOf(byte(0)), ""}, 2508 {TypeOf(rune(0)), ""}, 2509 {TypeOf([]byte(nil)), ""}, 2510 {TypeOf([]rune(nil)), ""}, 2511 {TypeOf(string("")), ""}, 2512 {TypeOf((*interface{})(nil)).Elem(), ""}, 2513 {TypeOf((*byte)(nil)), ""}, 2514 {TypeOf((*rune)(nil)), ""}, 2515 {TypeOf((*int64)(nil)), ""}, 2516 {TypeOf(map[string]int{}), ""}, 2517 {TypeOf((*error)(nil)).Elem(), ""}, 2518 {TypeOf((*Point)(nil)), ""}, 2519 {TypeOf((*Point)(nil)).Elem(), "reflect_test"}, 2520 } 2521 for _, test := range tests { 2522 if path := test.t.PkgPath(); path != test.path { 2523 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path) 2524 } 2525 } 2526} 2527 2528func TestFieldPkgPath(t *testing.T) { 2529 type x int 2530 typ := TypeOf(struct { 2531 Exported string 2532 unexported string 2533 OtherPkgFields 2534 int // issue 21702 2535 *x // issue 21122 2536 }{}) 2537 2538 type pkgpathTest struct { 2539 index []int 2540 pkgPath string 2541 anonymous bool 2542 } 2543 2544 checkPkgPath := func(name string, s []pkgpathTest) { 2545 for _, test := range s { 2546 f := typ.FieldByIndex(test.index) 2547 if got, want := f.PkgPath, test.pkgPath; got != want { 2548 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want) 2549 } 2550 if got, want := f.Anonymous, test.anonymous; got != want { 2551 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want) 2552 } 2553 } 2554 } 2555 2556 checkPkgPath("testStruct", []pkgpathTest{ 2557 {[]int{0}, "", false}, // Exported 2558 {[]int{1}, "reflect_test", false}, // unexported 2559 {[]int{2}, "", true}, // OtherPkgFields 2560 {[]int{2, 0}, "", false}, // OtherExported 2561 {[]int{2, 1}, "reflect", false}, // otherUnexported 2562 {[]int{3}, "reflect_test", true}, // int 2563 {[]int{4}, "reflect_test", true}, // *x 2564 }) 2565 2566 type localOtherPkgFields OtherPkgFields 2567 typ = TypeOf(localOtherPkgFields{}) 2568 checkPkgPath("localOtherPkgFields", []pkgpathTest{ 2569 {[]int{0}, "", false}, // OtherExported 2570 {[]int{1}, "reflect", false}, // otherUnexported 2571 }) 2572} 2573 2574func TestVariadicType(t *testing.T) { 2575 // Test example from Type documentation. 2576 var f func(x int, y ...float64) 2577 typ := TypeOf(f) 2578 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) { 2579 sl := typ.In(1) 2580 if sl.Kind() == Slice { 2581 if sl.Elem() == TypeOf(0.0) { 2582 // ok 2583 return 2584 } 2585 } 2586 } 2587 2588 // Failed 2589 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64") 2590 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn()) 2591 for i := 0; i < typ.NumIn(); i++ { 2592 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i)) 2593 } 2594 t.Error(s) 2595} 2596 2597type inner struct { 2598 x int 2599} 2600 2601type outer struct { 2602 y int 2603 inner 2604} 2605 2606func (*inner) M() {} 2607func (*outer) M() {} 2608 2609func TestNestedMethods(t *testing.T) { 2610 t.Skip("fails on gccgo due to function wrappers") 2611 typ := TypeOf((*outer)(nil)) 2612 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() { 2613 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M) 2614 for i := 0; i < typ.NumMethod(); i++ { 2615 m := typ.Method(i) 2616 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer()) 2617 } 2618 } 2619} 2620 2621type unexp struct{} 2622 2623func (*unexp) f() (int32, int8) { return 7, 7 } 2624func (*unexp) g() (int64, int8) { return 8, 8 } 2625 2626type unexpI interface { 2627 f() (int32, int8) 2628} 2629 2630var unexpi unexpI = new(unexp) 2631 2632func TestUnexportedMethods(t *testing.T) { 2633 typ := TypeOf(unexpi) 2634 2635 if got := typ.NumMethod(); got != 0 { 2636 t.Errorf("NumMethod=%d, want 0 satisfied methods", got) 2637 } 2638} 2639 2640type InnerInt struct { 2641 X int 2642} 2643 2644type OuterInt struct { 2645 Y int 2646 InnerInt 2647} 2648 2649func (i *InnerInt) M() int { 2650 return i.X 2651} 2652 2653func TestEmbeddedMethods(t *testing.T) { 2654 /* This part of the test fails on gccgo due to function wrappers. 2655 typ := TypeOf((*OuterInt)(nil)) 2656 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() { 2657 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M) 2658 for i := 0; i < typ.NumMethod(); i++ { 2659 m := typ.Method(i) 2660 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer()) 2661 } 2662 } 2663 */ 2664 2665 i := &InnerInt{3} 2666 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 { 2667 t.Errorf("i.M() = %d, want 3", v) 2668 } 2669 2670 o := &OuterInt{1, InnerInt{2}} 2671 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 { 2672 t.Errorf("i.M() = %d, want 2", v) 2673 } 2674 2675 f := (*OuterInt).M 2676 if v := f(o); v != 2 { 2677 t.Errorf("f(o) = %d, want 2", v) 2678 } 2679} 2680 2681type FuncDDD func(...interface{}) error 2682 2683func (f FuncDDD) M() {} 2684 2685func TestNumMethodOnDDD(t *testing.T) { 2686 rv := ValueOf((FuncDDD)(nil)) 2687 if n := rv.NumMethod(); n != 1 { 2688 t.Fatalf("NumMethod()=%d, want 1", n) 2689 } 2690} 2691 2692func TestPtrTo(t *testing.T) { 2693 // This block of code means that the ptrToThis field of the 2694 // reflect data for *unsafe.Pointer is non zero, see 2695 // https://golang.org/issue/19003 2696 var x unsafe.Pointer 2697 var y = &x 2698 var z = &y 2699 2700 var i int 2701 2702 typ := TypeOf(z) 2703 for i = 0; i < 100; i++ { 2704 typ = PtrTo(typ) 2705 } 2706 for i = 0; i < 100; i++ { 2707 typ = typ.Elem() 2708 } 2709 if typ != TypeOf(z) { 2710 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z)) 2711 } 2712} 2713 2714func TestPtrToGC(t *testing.T) { 2715 type T *uintptr 2716 tt := TypeOf(T(nil)) 2717 pt := PtrTo(tt) 2718 const n = 100 2719 var x []interface{} 2720 for i := 0; i < n; i++ { 2721 v := New(pt) 2722 p := new(*uintptr) 2723 *p = new(uintptr) 2724 **p = uintptr(i) 2725 v.Elem().Set(ValueOf(p).Convert(pt)) 2726 x = append(x, v.Interface()) 2727 } 2728 runtime.GC() 2729 2730 for i, xi := range x { 2731 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr) 2732 if k != uintptr(i) { 2733 t.Errorf("lost x[%d] = %d, want %d", i, k, i) 2734 } 2735 } 2736} 2737 2738func BenchmarkPtrTo(b *testing.B) { 2739 // Construct a type with a zero ptrToThis. 2740 type T struct{ int } 2741 t := SliceOf(TypeOf(T{})) 2742 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis") 2743 if !ptrToThis.IsValid() { 2744 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t) 2745 } 2746 if ptrToThis.Int() != 0 { 2747 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t) 2748 } 2749 b.ResetTimer() 2750 2751 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on 2752 // every call. 2753 b.RunParallel(func(pb *testing.PB) { 2754 for pb.Next() { 2755 PtrTo(t) 2756 } 2757 }) 2758} 2759 2760func TestAddr(t *testing.T) { 2761 var p struct { 2762 X, Y int 2763 } 2764 2765 v := ValueOf(&p) 2766 v = v.Elem() 2767 v = v.Addr() 2768 v = v.Elem() 2769 v = v.Field(0) 2770 v.SetInt(2) 2771 if p.X != 2 { 2772 t.Errorf("Addr.Elem.Set failed to set value") 2773 } 2774 2775 // Again but take address of the ValueOf value. 2776 // Exercises generation of PtrTypes not present in the binary. 2777 q := &p 2778 v = ValueOf(&q).Elem() 2779 v = v.Addr() 2780 v = v.Elem() 2781 v = v.Elem() 2782 v = v.Addr() 2783 v = v.Elem() 2784 v = v.Field(0) 2785 v.SetInt(3) 2786 if p.X != 3 { 2787 t.Errorf("Addr.Elem.Set failed to set value") 2788 } 2789 2790 // Starting without pointer we should get changed value 2791 // in interface. 2792 qq := p 2793 v = ValueOf(&qq).Elem() 2794 v0 := v 2795 v = v.Addr() 2796 v = v.Elem() 2797 v = v.Field(0) 2798 v.SetInt(4) 2799 if p.X != 3 { // should be unchanged from last time 2800 t.Errorf("somehow value Set changed original p") 2801 } 2802 p = v0.Interface().(struct { 2803 X, Y int 2804 }) 2805 if p.X != 4 { 2806 t.Errorf("Addr.Elem.Set valued to set value in top value") 2807 } 2808 2809 // Verify that taking the address of a type gives us a pointer 2810 // which we can convert back using the usual interface 2811 // notation. 2812 var s struct { 2813 B *bool 2814 } 2815 ps := ValueOf(&s).Elem().Field(0).Addr().Interface() 2816 *(ps.(**bool)) = new(bool) 2817 if s.B == nil { 2818 t.Errorf("Addr.Interface direct assignment failed") 2819 } 2820} 2821 2822/* gccgo does do allocations here. 2823 2824func noAlloc(t *testing.T, n int, f func(int)) { 2825 if testing.Short() { 2826 t.Skip("skipping malloc count in short mode") 2827 } 2828 if runtime.GOMAXPROCS(0) > 1 { 2829 t.Skip("skipping; GOMAXPROCS>1") 2830 } 2831 i := -1 2832 allocs := testing.AllocsPerRun(n, func() { 2833 f(i) 2834 i++ 2835 }) 2836 if allocs > 0 { 2837 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs) 2838 } 2839} 2840 2841func TestAllocations(t *testing.T) { 2842 noAlloc(t, 100, func(j int) { 2843 var i interface{} 2844 var v Value 2845 2846 // We can uncomment this when compiler escape analysis 2847 // is good enough to see that the integer assigned to i 2848 // does not escape and therefore need not be allocated. 2849 // 2850 // i = 42 + j 2851 // v = ValueOf(i) 2852 // if int(v.Int()) != 42+j { 2853 // panic("wrong int") 2854 // } 2855 2856 i = func(j int) int { return j } 2857 v = ValueOf(i) 2858 if v.Interface().(func(int) int)(j) != j { 2859 panic("wrong result") 2860 } 2861 }) 2862} 2863 2864*/ 2865 2866func TestSmallNegativeInt(t *testing.T) { 2867 i := int16(-1) 2868 v := ValueOf(i) 2869 if v.Int() != -1 { 2870 t.Errorf("int16(-1).Int() returned %v", v.Int()) 2871 } 2872} 2873 2874func TestIndex(t *testing.T) { 2875 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8} 2876 v := ValueOf(xs).Index(3).Interface().(byte) 2877 if v != xs[3] { 2878 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3]) 2879 } 2880 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80} 2881 v = ValueOf(xa).Index(2).Interface().(byte) 2882 if v != xa[2] { 2883 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2]) 2884 } 2885 s := "0123456789" 2886 v = ValueOf(s).Index(3).Interface().(byte) 2887 if v != s[3] { 2888 t.Errorf("s.Index(3) = %v; expected %v", v, s[3]) 2889 } 2890} 2891 2892func TestSlice(t *testing.T) { 2893 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2894 v := ValueOf(xs).Slice(3, 5).Interface().([]int) 2895 if len(v) != 2 { 2896 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v)) 2897 } 2898 if cap(v) != 5 { 2899 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v)) 2900 } 2901 if !DeepEqual(v[0:5], xs[3:]) { 2902 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5]) 2903 } 2904 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2905 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int) 2906 if len(v) != 3 { 2907 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v)) 2908 } 2909 if cap(v) != 6 { 2910 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v)) 2911 } 2912 if !DeepEqual(v[0:6], xa[2:]) { 2913 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6]) 2914 } 2915 s := "0123456789" 2916 vs := ValueOf(s).Slice(3, 5).Interface().(string) 2917 if vs != s[3:5] { 2918 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5]) 2919 } 2920 2921 rv := ValueOf(&xs).Elem() 2922 rv = rv.Slice(3, 4) 2923 ptr2 := rv.Pointer() 2924 rv = rv.Slice(5, 5) 2925 ptr3 := rv.Pointer() 2926 if ptr3 != ptr2 { 2927 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2) 2928 } 2929} 2930 2931func TestSlice3(t *testing.T) { 2932 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2933 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int) 2934 if len(v) != 2 { 2935 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v)) 2936 } 2937 if cap(v) != 4 { 2938 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v)) 2939 } 2940 if !DeepEqual(v[0:4], xs[3:7:7]) { 2941 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4]) 2942 } 2943 rv := ValueOf(&xs).Elem() 2944 shouldPanic(func() { rv.Slice3(1, 2, 1) }) 2945 shouldPanic(func() { rv.Slice3(1, 1, 11) }) 2946 shouldPanic(func() { rv.Slice3(2, 2, 1) }) 2947 2948 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2949 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int) 2950 if len(v) != 3 { 2951 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v)) 2952 } 2953 if cap(v) != 4 { 2954 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v)) 2955 } 2956 if !DeepEqual(v[0:4], xa[2:6:6]) { 2957 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4]) 2958 } 2959 rv = ValueOf(&xa).Elem() 2960 shouldPanic(func() { rv.Slice3(1, 2, 1) }) 2961 shouldPanic(func() { rv.Slice3(1, 1, 11) }) 2962 shouldPanic(func() { rv.Slice3(2, 2, 1) }) 2963 2964 s := "hello world" 2965 rv = ValueOf(&s).Elem() 2966 shouldPanic(func() { rv.Slice3(1, 2, 3) }) 2967 2968 rv = ValueOf(&xs).Elem() 2969 rv = rv.Slice3(3, 5, 7) 2970 ptr2 := rv.Pointer() 2971 rv = rv.Slice3(4, 4, 4) 2972 ptr3 := rv.Pointer() 2973 if ptr3 != ptr2 { 2974 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2) 2975 } 2976} 2977 2978func TestSetLenCap(t *testing.T) { 2979 xs := []int{1, 2, 3, 4, 5, 6, 7, 8} 2980 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80} 2981 2982 vs := ValueOf(&xs).Elem() 2983 shouldPanic(func() { vs.SetLen(10) }) 2984 shouldPanic(func() { vs.SetCap(10) }) 2985 shouldPanic(func() { vs.SetLen(-1) }) 2986 shouldPanic(func() { vs.SetCap(-1) }) 2987 shouldPanic(func() { vs.SetCap(6) }) // smaller than len 2988 vs.SetLen(5) 2989 if len(xs) != 5 || cap(xs) != 8 { 2990 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs)) 2991 } 2992 vs.SetCap(6) 2993 if len(xs) != 5 || cap(xs) != 6 { 2994 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs)) 2995 } 2996 vs.SetCap(5) 2997 if len(xs) != 5 || cap(xs) != 5 { 2998 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs)) 2999 } 3000 shouldPanic(func() { vs.SetCap(4) }) // smaller than len 3001 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap 3002 3003 va := ValueOf(&xa).Elem() 3004 shouldPanic(func() { va.SetLen(8) }) 3005 shouldPanic(func() { va.SetCap(8) }) 3006} 3007 3008func TestVariadic(t *testing.T) { 3009 var b bytes.Buffer 3010 V := ValueOf 3011 3012 b.Reset() 3013 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)}) 3014 if b.String() != "hello, 42 world" { 3015 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world") 3016 } 3017 3018 b.Reset() 3019 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})}) 3020 if b.String() != "hello, 42 world" { 3021 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world") 3022 } 3023} 3024 3025func TestFuncArg(t *testing.T) { 3026 f1 := func(i int, f func(int) int) int { return f(i) } 3027 f2 := func(i int) int { return i + 1 } 3028 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)}) 3029 if r[0].Int() != 101 { 3030 t.Errorf("function returned %d, want 101", r[0].Int()) 3031 } 3032} 3033 3034func TestStructArg(t *testing.T) { 3035 type padded struct { 3036 B string 3037 C int32 3038 } 3039 var ( 3040 gotA padded 3041 gotB uint32 3042 wantA = padded{"3", 4} 3043 wantB = uint32(5) 3044 ) 3045 f := func(a padded, b uint32) { 3046 gotA, gotB = a, b 3047 } 3048 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)}) 3049 if gotA != wantA || gotB != wantB { 3050 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB) 3051 } 3052} 3053 3054var tagGetTests = []struct { 3055 Tag StructTag 3056 Key string 3057 Value string 3058}{ 3059 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`}, 3060 {`protobuf:"PB(1,2)"`, `foo`, ``}, 3061 {`protobuf:"PB(1,2)"`, `rotobuf`, ``}, 3062 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`}, 3063 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`}, 3064 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"}, 3065 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"}, 3066} 3067 3068func TestTagGet(t *testing.T) { 3069 for _, tt := range tagGetTests { 3070 if v := tt.Tag.Get(tt.Key); v != tt.Value { 3071 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value) 3072 } 3073 } 3074} 3075 3076func TestBytes(t *testing.T) { 3077 type B []byte 3078 x := B{1, 2, 3, 4} 3079 y := ValueOf(x).Bytes() 3080 if !bytes.Equal(x, y) { 3081 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) 3082 } 3083 if &x[0] != &y[0] { 3084 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) 3085 } 3086} 3087 3088func TestSetBytes(t *testing.T) { 3089 type B []byte 3090 var x B 3091 y := []byte{1, 2, 3, 4} 3092 ValueOf(&x).Elem().SetBytes(y) 3093 if !bytes.Equal(x, y) { 3094 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y) 3095 } 3096 if &x[0] != &y[0] { 3097 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0]) 3098 } 3099} 3100 3101type Private struct { 3102 x int 3103 y **int 3104 Z int 3105} 3106 3107func (p *Private) m() { 3108} 3109 3110type private struct { 3111 Z int 3112 z int 3113 S string 3114 A [1]Private 3115 T []Private 3116} 3117 3118func (p *private) P() { 3119} 3120 3121type Public struct { 3122 X int 3123 Y **int 3124 private 3125} 3126 3127func (p *Public) M() { 3128} 3129 3130func TestUnexported(t *testing.T) { 3131 var pub Public 3132 pub.S = "S" 3133 pub.T = pub.A[:] 3134 v := ValueOf(&pub) 3135 isValid(v.Elem().Field(0)) 3136 isValid(v.Elem().Field(1)) 3137 isValid(v.Elem().Field(2)) 3138 isValid(v.Elem().FieldByName("X")) 3139 isValid(v.Elem().FieldByName("Y")) 3140 isValid(v.Elem().FieldByName("Z")) 3141 isValid(v.Type().Method(0).Func) 3142 m, _ := v.Type().MethodByName("M") 3143 isValid(m.Func) 3144 m, _ = v.Type().MethodByName("P") 3145 isValid(m.Func) 3146 isNonNil(v.Elem().Field(0).Interface()) 3147 isNonNil(v.Elem().Field(1).Interface()) 3148 isNonNil(v.Elem().Field(2).Field(2).Index(0)) 3149 isNonNil(v.Elem().FieldByName("X").Interface()) 3150 isNonNil(v.Elem().FieldByName("Y").Interface()) 3151 isNonNil(v.Elem().FieldByName("Z").Interface()) 3152 isNonNil(v.Elem().FieldByName("S").Index(0).Interface()) 3153 isNonNil(v.Type().Method(0).Func.Interface()) 3154 m, _ = v.Type().MethodByName("P") 3155 isNonNil(m.Func.Interface()) 3156 3157 var priv Private 3158 v = ValueOf(&priv) 3159 isValid(v.Elem().Field(0)) 3160 isValid(v.Elem().Field(1)) 3161 isValid(v.Elem().FieldByName("x")) 3162 isValid(v.Elem().FieldByName("y")) 3163 shouldPanic(func() { v.Elem().Field(0).Interface() }) 3164 shouldPanic(func() { v.Elem().Field(1).Interface() }) 3165 shouldPanic(func() { v.Elem().FieldByName("x").Interface() }) 3166 shouldPanic(func() { v.Elem().FieldByName("y").Interface() }) 3167 shouldPanic(func() { v.Type().Method(0) }) 3168} 3169 3170func TestSetPanic(t *testing.T) { 3171 ok := func(f func()) { f() } 3172 bad := shouldPanic 3173 clear := func(v Value) { v.Set(Zero(v.Type())) } 3174 3175 type t0 struct { 3176 W int 3177 } 3178 3179 type t1 struct { 3180 Y int 3181 t0 3182 } 3183 3184 type T2 struct { 3185 Z int 3186 namedT0 t0 3187 } 3188 3189 type T struct { 3190 X int 3191 t1 3192 T2 3193 NamedT1 t1 3194 NamedT2 T2 3195 namedT1 t1 3196 namedT2 T2 3197 } 3198 3199 // not addressable 3200 v := ValueOf(T{}) 3201 bad(func() { clear(v.Field(0)) }) // .X 3202 bad(func() { clear(v.Field(1)) }) // .t1 3203 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y 3204 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 3205 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W 3206 bad(func() { clear(v.Field(2)) }) // .T2 3207 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z 3208 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 3209 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W 3210 bad(func() { clear(v.Field(3)) }) // .NamedT1 3211 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y 3212 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 3213 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W 3214 bad(func() { clear(v.Field(4)) }) // .NamedT2 3215 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z 3216 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 3217 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W 3218 bad(func() { clear(v.Field(5)) }) // .namedT1 3219 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y 3220 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 3221 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W 3222 bad(func() { clear(v.Field(6)) }) // .namedT2 3223 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z 3224 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 3225 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W 3226 3227 // addressable 3228 v = ValueOf(&T{}).Elem() 3229 ok(func() { clear(v.Field(0)) }) // .X 3230 bad(func() { clear(v.Field(1)) }) // .t1 3231 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y 3232 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0 3233 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W 3234 ok(func() { clear(v.Field(2)) }) // .T2 3235 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z 3236 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0 3237 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W 3238 ok(func() { clear(v.Field(3)) }) // .NamedT1 3239 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y 3240 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0 3241 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W 3242 ok(func() { clear(v.Field(4)) }) // .NamedT2 3243 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z 3244 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0 3245 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W 3246 bad(func() { clear(v.Field(5)) }) // .namedT1 3247 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y 3248 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0 3249 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W 3250 bad(func() { clear(v.Field(6)) }) // .namedT2 3251 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z 3252 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0 3253 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W 3254} 3255 3256type timp int 3257 3258func (t timp) W() {} 3259func (t timp) Y() {} 3260func (t timp) w() {} 3261func (t timp) y() {} 3262 3263func TestCallPanic(t *testing.T) { 3264 type t0 interface { 3265 W() 3266 w() 3267 } 3268 type T1 interface { 3269 Y() 3270 y() 3271 } 3272 type T2 struct { 3273 T1 3274 t0 3275 } 3276 type T struct { 3277 t0 // 0 3278 T1 // 1 3279 3280 NamedT0 t0 // 2 3281 NamedT1 T1 // 3 3282 NamedT2 T2 // 4 3283 3284 namedT0 t0 // 5 3285 namedT1 T1 // 6 3286 namedT2 T2 // 7 3287 } 3288 ok := func(f func()) { f() } 3289 bad := shouldPanic 3290 call := func(v Value) { v.Call(nil) } 3291 3292 i := timp(0) 3293 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}}) 3294 ok(func() { call(v.Field(0).Method(0)) }) // .t0.W 3295 bad(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W 3296 bad(func() { call(v.Field(0).Method(1)) }) // .t0.w 3297 bad(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w 3298 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y 3299 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y 3300 bad(func() { call(v.Field(1).Method(1)) }) // .T1.y 3301 bad(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y 3302 3303 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W 3304 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W 3305 bad(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w 3306 bad(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w 3307 3308 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y 3309 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y 3310 bad(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y 3311 bad(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y 3312 3313 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y 3314 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W 3315 ok(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W 3316 bad(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W 3317 3318 bad(func() { call(v.Field(5).Method(0)) }) // .namedT0.W 3319 bad(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W 3320 bad(func() { call(v.Field(5).Method(1)) }) // .namedT0.w 3321 bad(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w 3322 3323 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y 3324 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y 3325 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.y 3326 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y 3327 3328 bad(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y 3329 bad(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W 3330 bad(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W 3331 bad(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W 3332} 3333 3334func shouldPanic(f func()) { 3335 defer func() { 3336 if recover() == nil { 3337 panic("did not panic") 3338 } 3339 }() 3340 f() 3341} 3342 3343func isNonNil(x interface{}) { 3344 if x == nil { 3345 panic("nil interface") 3346 } 3347} 3348 3349func isValid(v Value) { 3350 if !v.IsValid() { 3351 panic("zero Value") 3352 } 3353} 3354 3355func TestAlias(t *testing.T) { 3356 x := string("hello") 3357 v := ValueOf(&x).Elem() 3358 oldvalue := v.Interface() 3359 v.SetString("world") 3360 newvalue := v.Interface() 3361 3362 if oldvalue != "hello" || newvalue != "world" { 3363 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue) 3364 } 3365} 3366 3367var V = ValueOf 3368 3369func EmptyInterfaceV(x interface{}) Value { 3370 return ValueOf(&x).Elem() 3371} 3372 3373func ReaderV(x io.Reader) Value { 3374 return ValueOf(&x).Elem() 3375} 3376 3377func ReadWriterV(x io.ReadWriter) Value { 3378 return ValueOf(&x).Elem() 3379} 3380 3381type Empty struct{} 3382type MyStruct struct { 3383 x int `some:"tag"` 3384} 3385type MyString string 3386type MyBytes []byte 3387type MyRunes []int32 3388type MyFunc func() 3389type MyByte byte 3390 3391var convertTests = []struct { 3392 in Value 3393 out Value 3394}{ 3395 // numbers 3396 /* 3397 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go 3398 3399 package main 3400 3401 import "fmt" 3402 3403 var numbers = []string{ 3404 "int8", "uint8", "int16", "uint16", 3405 "int32", "uint32", "int64", "uint64", 3406 "int", "uint", "uintptr", 3407 "float32", "float64", 3408 } 3409 3410 func main() { 3411 // all pairs but in an unusual order, 3412 // to emit all the int8, uint8 cases 3413 // before n grows too big. 3414 n := 1 3415 for i, f := range numbers { 3416 for _, g := range numbers[i:] { 3417 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n) 3418 n++ 3419 if f != g { 3420 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n) 3421 n++ 3422 } 3423 } 3424 } 3425 } 3426 */ 3427 {V(int8(1)), V(int8(1))}, 3428 {V(int8(2)), V(uint8(2))}, 3429 {V(uint8(3)), V(int8(3))}, 3430 {V(int8(4)), V(int16(4))}, 3431 {V(int16(5)), V(int8(5))}, 3432 {V(int8(6)), V(uint16(6))}, 3433 {V(uint16(7)), V(int8(7))}, 3434 {V(int8(8)), V(int32(8))}, 3435 {V(int32(9)), V(int8(9))}, 3436 {V(int8(10)), V(uint32(10))}, 3437 {V(uint32(11)), V(int8(11))}, 3438 {V(int8(12)), V(int64(12))}, 3439 {V(int64(13)), V(int8(13))}, 3440 {V(int8(14)), V(uint64(14))}, 3441 {V(uint64(15)), V(int8(15))}, 3442 {V(int8(16)), V(int(16))}, 3443 {V(int(17)), V(int8(17))}, 3444 {V(int8(18)), V(uint(18))}, 3445 {V(uint(19)), V(int8(19))}, 3446 {V(int8(20)), V(uintptr(20))}, 3447 {V(uintptr(21)), V(int8(21))}, 3448 {V(int8(22)), V(float32(22))}, 3449 {V(float32(23)), V(int8(23))}, 3450 {V(int8(24)), V(float64(24))}, 3451 {V(float64(25)), V(int8(25))}, 3452 {V(uint8(26)), V(uint8(26))}, 3453 {V(uint8(27)), V(int16(27))}, 3454 {V(int16(28)), V(uint8(28))}, 3455 {V(uint8(29)), V(uint16(29))}, 3456 {V(uint16(30)), V(uint8(30))}, 3457 {V(uint8(31)), V(int32(31))}, 3458 {V(int32(32)), V(uint8(32))}, 3459 {V(uint8(33)), V(uint32(33))}, 3460 {V(uint32(34)), V(uint8(34))}, 3461 {V(uint8(35)), V(int64(35))}, 3462 {V(int64(36)), V(uint8(36))}, 3463 {V(uint8(37)), V(uint64(37))}, 3464 {V(uint64(38)), V(uint8(38))}, 3465 {V(uint8(39)), V(int(39))}, 3466 {V(int(40)), V(uint8(40))}, 3467 {V(uint8(41)), V(uint(41))}, 3468 {V(uint(42)), V(uint8(42))}, 3469 {V(uint8(43)), V(uintptr(43))}, 3470 {V(uintptr(44)), V(uint8(44))}, 3471 {V(uint8(45)), V(float32(45))}, 3472 {V(float32(46)), V(uint8(46))}, 3473 {V(uint8(47)), V(float64(47))}, 3474 {V(float64(48)), V(uint8(48))}, 3475 {V(int16(49)), V(int16(49))}, 3476 {V(int16(50)), V(uint16(50))}, 3477 {V(uint16(51)), V(int16(51))}, 3478 {V(int16(52)), V(int32(52))}, 3479 {V(int32(53)), V(int16(53))}, 3480 {V(int16(54)), V(uint32(54))}, 3481 {V(uint32(55)), V(int16(55))}, 3482 {V(int16(56)), V(int64(56))}, 3483 {V(int64(57)), V(int16(57))}, 3484 {V(int16(58)), V(uint64(58))}, 3485 {V(uint64(59)), V(int16(59))}, 3486 {V(int16(60)), V(int(60))}, 3487 {V(int(61)), V(int16(61))}, 3488 {V(int16(62)), V(uint(62))}, 3489 {V(uint(63)), V(int16(63))}, 3490 {V(int16(64)), V(uintptr(64))}, 3491 {V(uintptr(65)), V(int16(65))}, 3492 {V(int16(66)), V(float32(66))}, 3493 {V(float32(67)), V(int16(67))}, 3494 {V(int16(68)), V(float64(68))}, 3495 {V(float64(69)), V(int16(69))}, 3496 {V(uint16(70)), V(uint16(70))}, 3497 {V(uint16(71)), V(int32(71))}, 3498 {V(int32(72)), V(uint16(72))}, 3499 {V(uint16(73)), V(uint32(73))}, 3500 {V(uint32(74)), V(uint16(74))}, 3501 {V(uint16(75)), V(int64(75))}, 3502 {V(int64(76)), V(uint16(76))}, 3503 {V(uint16(77)), V(uint64(77))}, 3504 {V(uint64(78)), V(uint16(78))}, 3505 {V(uint16(79)), V(int(79))}, 3506 {V(int(80)), V(uint16(80))}, 3507 {V(uint16(81)), V(uint(81))}, 3508 {V(uint(82)), V(uint16(82))}, 3509 {V(uint16(83)), V(uintptr(83))}, 3510 {V(uintptr(84)), V(uint16(84))}, 3511 {V(uint16(85)), V(float32(85))}, 3512 {V(float32(86)), V(uint16(86))}, 3513 {V(uint16(87)), V(float64(87))}, 3514 {V(float64(88)), V(uint16(88))}, 3515 {V(int32(89)), V(int32(89))}, 3516 {V(int32(90)), V(uint32(90))}, 3517 {V(uint32(91)), V(int32(91))}, 3518 {V(int32(92)), V(int64(92))}, 3519 {V(int64(93)), V(int32(93))}, 3520 {V(int32(94)), V(uint64(94))}, 3521 {V(uint64(95)), V(int32(95))}, 3522 {V(int32(96)), V(int(96))}, 3523 {V(int(97)), V(int32(97))}, 3524 {V(int32(98)), V(uint(98))}, 3525 {V(uint(99)), V(int32(99))}, 3526 {V(int32(100)), V(uintptr(100))}, 3527 {V(uintptr(101)), V(int32(101))}, 3528 {V(int32(102)), V(float32(102))}, 3529 {V(float32(103)), V(int32(103))}, 3530 {V(int32(104)), V(float64(104))}, 3531 {V(float64(105)), V(int32(105))}, 3532 {V(uint32(106)), V(uint32(106))}, 3533 {V(uint32(107)), V(int64(107))}, 3534 {V(int64(108)), V(uint32(108))}, 3535 {V(uint32(109)), V(uint64(109))}, 3536 {V(uint64(110)), V(uint32(110))}, 3537 {V(uint32(111)), V(int(111))}, 3538 {V(int(112)), V(uint32(112))}, 3539 {V(uint32(113)), V(uint(113))}, 3540 {V(uint(114)), V(uint32(114))}, 3541 {V(uint32(115)), V(uintptr(115))}, 3542 {V(uintptr(116)), V(uint32(116))}, 3543 {V(uint32(117)), V(float32(117))}, 3544 {V(float32(118)), V(uint32(118))}, 3545 {V(uint32(119)), V(float64(119))}, 3546 {V(float64(120)), V(uint32(120))}, 3547 {V(int64(121)), V(int64(121))}, 3548 {V(int64(122)), V(uint64(122))}, 3549 {V(uint64(123)), V(int64(123))}, 3550 {V(int64(124)), V(int(124))}, 3551 {V(int(125)), V(int64(125))}, 3552 {V(int64(126)), V(uint(126))}, 3553 {V(uint(127)), V(int64(127))}, 3554 {V(int64(128)), V(uintptr(128))}, 3555 {V(uintptr(129)), V(int64(129))}, 3556 {V(int64(130)), V(float32(130))}, 3557 {V(float32(131)), V(int64(131))}, 3558 {V(int64(132)), V(float64(132))}, 3559 {V(float64(133)), V(int64(133))}, 3560 {V(uint64(134)), V(uint64(134))}, 3561 {V(uint64(135)), V(int(135))}, 3562 {V(int(136)), V(uint64(136))}, 3563 {V(uint64(137)), V(uint(137))}, 3564 {V(uint(138)), V(uint64(138))}, 3565 {V(uint64(139)), V(uintptr(139))}, 3566 {V(uintptr(140)), V(uint64(140))}, 3567 {V(uint64(141)), V(float32(141))}, 3568 {V(float32(142)), V(uint64(142))}, 3569 {V(uint64(143)), V(float64(143))}, 3570 {V(float64(144)), V(uint64(144))}, 3571 {V(int(145)), V(int(145))}, 3572 {V(int(146)), V(uint(146))}, 3573 {V(uint(147)), V(int(147))}, 3574 {V(int(148)), V(uintptr(148))}, 3575 {V(uintptr(149)), V(int(149))}, 3576 {V(int(150)), V(float32(150))}, 3577 {V(float32(151)), V(int(151))}, 3578 {V(int(152)), V(float64(152))}, 3579 {V(float64(153)), V(int(153))}, 3580 {V(uint(154)), V(uint(154))}, 3581 {V(uint(155)), V(uintptr(155))}, 3582 {V(uintptr(156)), V(uint(156))}, 3583 {V(uint(157)), V(float32(157))}, 3584 {V(float32(158)), V(uint(158))}, 3585 {V(uint(159)), V(float64(159))}, 3586 {V(float64(160)), V(uint(160))}, 3587 {V(uintptr(161)), V(uintptr(161))}, 3588 {V(uintptr(162)), V(float32(162))}, 3589 {V(float32(163)), V(uintptr(163))}, 3590 {V(uintptr(164)), V(float64(164))}, 3591 {V(float64(165)), V(uintptr(165))}, 3592 {V(float32(166)), V(float32(166))}, 3593 {V(float32(167)), V(float64(167))}, 3594 {V(float64(168)), V(float32(168))}, 3595 {V(float64(169)), V(float64(169))}, 3596 3597 // truncation 3598 {V(float64(1.5)), V(int(1))}, 3599 3600 // complex 3601 {V(complex64(1i)), V(complex64(1i))}, 3602 {V(complex64(2i)), V(complex128(2i))}, 3603 {V(complex128(3i)), V(complex64(3i))}, 3604 {V(complex128(4i)), V(complex128(4i))}, 3605 3606 // string 3607 {V(string("hello")), V(string("hello"))}, 3608 {V(string("bytes1")), V([]byte("bytes1"))}, 3609 {V([]byte("bytes2")), V(string("bytes2"))}, 3610 {V([]byte("bytes3")), V([]byte("bytes3"))}, 3611 {V(string("runes♝")), V([]rune("runes♝"))}, 3612 {V([]rune("runes♕")), V(string("runes♕"))}, 3613 {V([]rune("runes")), V([]rune("runes"))}, 3614 {V(int('a')), V(string("a"))}, 3615 {V(int8('a')), V(string("a"))}, 3616 {V(int16('a')), V(string("a"))}, 3617 {V(int32('a')), V(string("a"))}, 3618 {V(int64('a')), V(string("a"))}, 3619 {V(uint('a')), V(string("a"))}, 3620 {V(uint8('a')), V(string("a"))}, 3621 {V(uint16('a')), V(string("a"))}, 3622 {V(uint32('a')), V(string("a"))}, 3623 {V(uint64('a')), V(string("a"))}, 3624 {V(uintptr('a')), V(string("a"))}, 3625 {V(int(-1)), V(string("\uFFFD"))}, 3626 {V(int8(-2)), V(string("\uFFFD"))}, 3627 {V(int16(-3)), V(string("\uFFFD"))}, 3628 {V(int32(-4)), V(string("\uFFFD"))}, 3629 {V(int64(-5)), V(string("\uFFFD"))}, 3630 {V(uint(0x110001)), V(string("\uFFFD"))}, 3631 {V(uint32(0x110002)), V(string("\uFFFD"))}, 3632 {V(uint64(0x110003)), V(string("\uFFFD"))}, 3633 {V(uintptr(0x110004)), V(string("\uFFFD"))}, 3634 3635 // named string 3636 {V(MyString("hello")), V(string("hello"))}, 3637 {V(string("hello")), V(MyString("hello"))}, 3638 {V(string("hello")), V(string("hello"))}, 3639 {V(MyString("hello")), V(MyString("hello"))}, 3640 {V(MyString("bytes1")), V([]byte("bytes1"))}, 3641 {V([]byte("bytes2")), V(MyString("bytes2"))}, 3642 {V([]byte("bytes3")), V([]byte("bytes3"))}, 3643 {V(MyString("runes♝")), V([]rune("runes♝"))}, 3644 {V([]rune("runes♕")), V(MyString("runes♕"))}, 3645 {V([]rune("runes")), V([]rune("runes"))}, 3646 {V([]rune("runes")), V(MyRunes("runes"))}, 3647 {V(MyRunes("runes")), V([]rune("runes"))}, 3648 {V(int('a')), V(MyString("a"))}, 3649 {V(int8('a')), V(MyString("a"))}, 3650 {V(int16('a')), V(MyString("a"))}, 3651 {V(int32('a')), V(MyString("a"))}, 3652 {V(int64('a')), V(MyString("a"))}, 3653 {V(uint('a')), V(MyString("a"))}, 3654 {V(uint8('a')), V(MyString("a"))}, 3655 {V(uint16('a')), V(MyString("a"))}, 3656 {V(uint32('a')), V(MyString("a"))}, 3657 {V(uint64('a')), V(MyString("a"))}, 3658 {V(uintptr('a')), V(MyString("a"))}, 3659 {V(int(-1)), V(MyString("\uFFFD"))}, 3660 {V(int8(-2)), V(MyString("\uFFFD"))}, 3661 {V(int16(-3)), V(MyString("\uFFFD"))}, 3662 {V(int32(-4)), V(MyString("\uFFFD"))}, 3663 {V(int64(-5)), V(MyString("\uFFFD"))}, 3664 {V(uint(0x110001)), V(MyString("\uFFFD"))}, 3665 {V(uint32(0x110002)), V(MyString("\uFFFD"))}, 3666 {V(uint64(0x110003)), V(MyString("\uFFFD"))}, 3667 {V(uintptr(0x110004)), V(MyString("\uFFFD"))}, 3668 3669 // named []byte 3670 {V(string("bytes1")), V(MyBytes("bytes1"))}, 3671 {V(MyBytes("bytes2")), V(string("bytes2"))}, 3672 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))}, 3673 {V(MyString("bytes1")), V(MyBytes("bytes1"))}, 3674 {V(MyBytes("bytes2")), V(MyString("bytes2"))}, 3675 3676 // named []rune 3677 {V(string("runes♝")), V(MyRunes("runes♝"))}, 3678 {V(MyRunes("runes♕")), V(string("runes♕"))}, 3679 {V(MyRunes("runes")), V(MyRunes("runes"))}, 3680 {V(MyString("runes♝")), V(MyRunes("runes♝"))}, 3681 {V(MyRunes("runes♕")), V(MyString("runes♕"))}, 3682 3683 // named types and equal underlying types 3684 {V(new(int)), V(new(integer))}, 3685 {V(new(integer)), V(new(int))}, 3686 {V(Empty{}), V(struct{}{})}, 3687 {V(new(Empty)), V(new(struct{}))}, 3688 {V(struct{}{}), V(Empty{})}, 3689 {V(new(struct{})), V(new(Empty))}, 3690 {V(Empty{}), V(Empty{})}, 3691 {V(MyBytes{}), V([]byte{})}, 3692 {V([]byte{}), V(MyBytes{})}, 3693 {V((func())(nil)), V(MyFunc(nil))}, 3694 {V((MyFunc)(nil)), V((func())(nil))}, 3695 3696 // structs with different tags 3697 {V(struct { 3698 x int `some:"foo"` 3699 }{}), V(struct { 3700 x int `some:"bar"` 3701 }{})}, 3702 3703 {V(struct { 3704 x int `some:"bar"` 3705 }{}), V(struct { 3706 x int `some:"foo"` 3707 }{})}, 3708 3709 {V(MyStruct{}), V(struct { 3710 x int `some:"foo"` 3711 }{})}, 3712 3713 {V(struct { 3714 x int `some:"foo"` 3715 }{}), V(MyStruct{})}, 3716 3717 {V(MyStruct{}), V(struct { 3718 x int `some:"bar"` 3719 }{})}, 3720 3721 {V(struct { 3722 x int `some:"bar"` 3723 }{}), V(MyStruct{})}, 3724 3725 // can convert *byte and *MyByte 3726 {V((*byte)(nil)), V((*MyByte)(nil))}, 3727 {V((*MyByte)(nil)), V((*byte)(nil))}, 3728 3729 // cannot convert mismatched array sizes 3730 {V([2]byte{}), V([2]byte{})}, 3731 {V([3]byte{}), V([3]byte{})}, 3732 3733 // cannot convert other instances 3734 {V((**byte)(nil)), V((**byte)(nil))}, 3735 {V((**MyByte)(nil)), V((**MyByte)(nil))}, 3736 {V((chan byte)(nil)), V((chan byte)(nil))}, 3737 {V((chan MyByte)(nil)), V((chan MyByte)(nil))}, 3738 {V(([]byte)(nil)), V(([]byte)(nil))}, 3739 {V(([]MyByte)(nil)), V(([]MyByte)(nil))}, 3740 {V((map[int]byte)(nil)), V((map[int]byte)(nil))}, 3741 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))}, 3742 {V((map[byte]int)(nil)), V((map[byte]int)(nil))}, 3743 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))}, 3744 {V([2]byte{}), V([2]byte{})}, 3745 {V([2]MyByte{}), V([2]MyByte{})}, 3746 3747 // other 3748 {V((***int)(nil)), V((***int)(nil))}, 3749 {V((***byte)(nil)), V((***byte)(nil))}, 3750 {V((***int32)(nil)), V((***int32)(nil))}, 3751 {V((***int64)(nil)), V((***int64)(nil))}, 3752 {V((chan int)(nil)), V((<-chan int)(nil))}, 3753 {V((chan int)(nil)), V((chan<- int)(nil))}, 3754 {V((chan string)(nil)), V((<-chan string)(nil))}, 3755 {V((chan string)(nil)), V((chan<- string)(nil))}, 3756 {V((chan byte)(nil)), V((chan byte)(nil))}, 3757 {V((chan MyByte)(nil)), V((chan MyByte)(nil))}, 3758 {V((map[int]bool)(nil)), V((map[int]bool)(nil))}, 3759 {V((map[int]byte)(nil)), V((map[int]byte)(nil))}, 3760 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))}, 3761 {V([]uint(nil)), V([]uint(nil))}, 3762 {V([]int(nil)), V([]int(nil))}, 3763 {V(new(interface{})), V(new(interface{}))}, 3764 {V(new(io.Reader)), V(new(io.Reader))}, 3765 {V(new(io.Writer)), V(new(io.Writer))}, 3766 3767 // interfaces 3768 {V(int(1)), EmptyInterfaceV(int(1))}, 3769 {V(string("hello")), EmptyInterfaceV(string("hello"))}, 3770 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, 3771 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))}, 3772 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))}, 3773} 3774 3775func TestConvert(t *testing.T) { 3776 canConvert := map[[2]Type]bool{} 3777 all := map[Type]bool{} 3778 3779 for _, tt := range convertTests { 3780 t1 := tt.in.Type() 3781 if !t1.ConvertibleTo(t1) { 3782 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1) 3783 continue 3784 } 3785 3786 t2 := tt.out.Type() 3787 if !t1.ConvertibleTo(t2) { 3788 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2) 3789 continue 3790 } 3791 3792 all[t1] = true 3793 all[t2] = true 3794 canConvert[[2]Type{t1, t2}] = true 3795 3796 // vout1 represents the in value converted to the in type. 3797 v1 := tt.in 3798 vout1 := v1.Convert(t1) 3799 out1 := vout1.Interface() 3800 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) { 3801 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface()) 3802 } 3803 3804 // vout2 represents the in value converted to the out type. 3805 vout2 := v1.Convert(t2) 3806 out2 := vout2.Interface() 3807 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) { 3808 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface()) 3809 } 3810 3811 // vout3 represents a new value of the out type, set to vout2. This makes 3812 // sure the converted value vout2 is really usable as a regular value. 3813 vout3 := New(t2).Elem() 3814 vout3.Set(vout2) 3815 out3 := vout3.Interface() 3816 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) { 3817 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface()) 3818 } 3819 3820 if IsRO(v1) { 3821 t.Errorf("table entry %v is RO, should not be", v1) 3822 } 3823 if IsRO(vout1) { 3824 t.Errorf("self-conversion output %v is RO, should not be", vout1) 3825 } 3826 if IsRO(vout2) { 3827 t.Errorf("conversion output %v is RO, should not be", vout2) 3828 } 3829 if IsRO(vout3) { 3830 t.Errorf("set(conversion output) %v is RO, should not be", vout3) 3831 } 3832 if !IsRO(MakeRO(v1).Convert(t1)) { 3833 t.Errorf("RO self-conversion output %v is not RO, should be", v1) 3834 } 3835 if !IsRO(MakeRO(v1).Convert(t2)) { 3836 t.Errorf("RO conversion output %v is not RO, should be", v1) 3837 } 3838 } 3839 3840 // Assume that of all the types we saw during the tests, 3841 // if there wasn't an explicit entry for a conversion between 3842 // a pair of types, then it's not to be allowed. This checks for 3843 // things like 'int64' converting to '*int'. 3844 for t1 := range all { 3845 for t2 := range all { 3846 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0 3847 if ok := t1.ConvertibleTo(t2); ok != expectOK { 3848 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK) 3849 } 3850 } 3851 } 3852} 3853 3854type ComparableStruct struct { 3855 X int 3856} 3857 3858type NonComparableStruct struct { 3859 X int 3860 Y map[string]int 3861} 3862 3863var comparableTests = []struct { 3864 typ Type 3865 ok bool 3866}{ 3867 {TypeOf(1), true}, 3868 {TypeOf("hello"), true}, 3869 {TypeOf(new(byte)), true}, 3870 {TypeOf((func())(nil)), false}, 3871 {TypeOf([]byte{}), false}, 3872 {TypeOf(map[string]int{}), false}, 3873 {TypeOf(make(chan int)), true}, 3874 {TypeOf(1.5), true}, 3875 {TypeOf(false), true}, 3876 {TypeOf(1i), true}, 3877 {TypeOf(ComparableStruct{}), true}, 3878 {TypeOf(NonComparableStruct{}), false}, 3879 {TypeOf([10]map[string]int{}), false}, 3880 {TypeOf([10]string{}), true}, 3881 {TypeOf(new(interface{})).Elem(), true}, 3882} 3883 3884func TestComparable(t *testing.T) { 3885 for _, tt := range comparableTests { 3886 if ok := tt.typ.Comparable(); ok != tt.ok { 3887 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok) 3888 } 3889 } 3890} 3891 3892func TestOverflow(t *testing.T) { 3893 if ovf := V(float64(0)).OverflowFloat(1e300); ovf { 3894 t.Errorf("%v wrongly overflows float64", 1e300) 3895 } 3896 3897 maxFloat32 := float64((1<<24 - 1) << (127 - 23)) 3898 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf { 3899 t.Errorf("%v wrongly overflows float32", maxFloat32) 3900 } 3901 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52)) 3902 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf { 3903 t.Errorf("%v should overflow float32", ovfFloat32) 3904 } 3905 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf { 3906 t.Errorf("%v should overflow float32", -ovfFloat32) 3907 } 3908 3909 maxInt32 := int64(0x7fffffff) 3910 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf { 3911 t.Errorf("%v wrongly overflows int32", maxInt32) 3912 } 3913 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf { 3914 t.Errorf("%v wrongly overflows int32", -int64(1)<<31) 3915 } 3916 ovfInt32 := int64(1 << 31) 3917 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf { 3918 t.Errorf("%v should overflow int32", ovfInt32) 3919 } 3920 3921 maxUint32 := uint64(0xffffffff) 3922 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf { 3923 t.Errorf("%v wrongly overflows uint32", maxUint32) 3924 } 3925 ovfUint32 := uint64(1 << 32) 3926 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf { 3927 t.Errorf("%v should overflow uint32", ovfUint32) 3928 } 3929} 3930 3931func checkSameType(t *testing.T, x, y interface{}) { 3932 if TypeOf(x) != TypeOf(y) { 3933 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y)) 3934 } 3935} 3936 3937func TestArrayOf(t *testing.T) { 3938 // check construction and use of type not in binary 3939 tests := []struct { 3940 n int 3941 value func(i int) interface{} 3942 comparable bool 3943 want string 3944 }{ 3945 { 3946 n: 0, 3947 value: func(i int) interface{} { type Tint int; return Tint(i) }, 3948 comparable: true, 3949 want: "[]", 3950 }, 3951 { 3952 n: 10, 3953 value: func(i int) interface{} { type Tint int; return Tint(i) }, 3954 comparable: true, 3955 want: "[0 1 2 3 4 5 6 7 8 9]", 3956 }, 3957 { 3958 n: 10, 3959 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) }, 3960 comparable: true, 3961 want: "[0 1 2 3 4 5 6 7 8 9]", 3962 }, 3963 { 3964 n: 10, 3965 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) }, 3966 comparable: true, 3967 want: "[0 1 2 3 4 5 6 7 8 9]", 3968 }, 3969 { 3970 n: 10, 3971 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} }, 3972 comparable: true, 3973 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]", 3974 }, 3975 { 3976 n: 10, 3977 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} }, 3978 comparable: false, 3979 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", 3980 }, 3981 { 3982 n: 10, 3983 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} }, 3984 comparable: true, 3985 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", 3986 }, 3987 { 3988 n: 10, 3989 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} }, 3990 comparable: true, 3991 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", 3992 }, 3993 { 3994 n: 10, 3995 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} }, 3996 comparable: false, 3997 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", 3998 }, 3999 { 4000 n: 10, 4001 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} }, 4002 comparable: true, 4003 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", 4004 }, 4005 { 4006 n: 10, 4007 value: func(i int) interface{} { 4008 type TstructUV struct { 4009 U int 4010 V float64 4011 } 4012 return TstructUV{i, float64(i)} 4013 }, 4014 comparable: true, 4015 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", 4016 }, 4017 } 4018 4019 for _, table := range tests { 4020 at := ArrayOf(table.n, TypeOf(table.value(0))) 4021 v := New(at).Elem() 4022 vok := New(at).Elem() 4023 vnot := New(at).Elem() 4024 for i := 0; i < v.Len(); i++ { 4025 v.Index(i).Set(ValueOf(table.value(i))) 4026 vok.Index(i).Set(ValueOf(table.value(i))) 4027 j := i 4028 if i+1 == v.Len() { 4029 j = i + 1 4030 } 4031 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element 4032 } 4033 s := fmt.Sprint(v.Interface()) 4034 if s != table.want { 4035 t.Errorf("constructed array = %s, want %s", s, table.want) 4036 } 4037 4038 if table.comparable != at.Comparable() { 4039 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable) 4040 } 4041 if table.comparable { 4042 if table.n > 0 { 4043 if DeepEqual(vnot.Interface(), v.Interface()) { 4044 t.Errorf( 4045 "arrays (%#v) compare ok (but should not)", 4046 v.Interface(), 4047 ) 4048 } 4049 } 4050 if !DeepEqual(vok.Interface(), v.Interface()) { 4051 t.Errorf( 4052 "arrays (%#v) compare NOT-ok (but should)", 4053 v.Interface(), 4054 ) 4055 } 4056 } 4057 } 4058 4059 // check that type already in binary is found 4060 type T int 4061 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{}) 4062} 4063 4064func TestArrayOfGC(t *testing.T) { 4065 type T *uintptr 4066 tt := TypeOf(T(nil)) 4067 const n = 100 4068 var x []interface{} 4069 for i := 0; i < n; i++ { 4070 v := New(ArrayOf(n, tt)).Elem() 4071 for j := 0; j < v.Len(); j++ { 4072 p := new(uintptr) 4073 *p = uintptr(i*n + j) 4074 v.Index(j).Set(ValueOf(p).Convert(tt)) 4075 } 4076 x = append(x, v.Interface()) 4077 } 4078 runtime.GC() 4079 4080 for i, xi := range x { 4081 v := ValueOf(xi) 4082 for j := 0; j < v.Len(); j++ { 4083 k := v.Index(j).Elem().Interface() 4084 if k != uintptr(i*n+j) { 4085 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4086 } 4087 } 4088 } 4089} 4090 4091func TestArrayOfAlg(t *testing.T) { 4092 at := ArrayOf(6, TypeOf(byte(0))) 4093 v1 := New(at).Elem() 4094 v2 := New(at).Elem() 4095 if v1.Interface() != v1.Interface() { 4096 t.Errorf("constructed array %v not equal to itself", v1.Interface()) 4097 } 4098 v1.Index(5).Set(ValueOf(byte(1))) 4099 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { 4100 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) 4101 } 4102 4103 at = ArrayOf(6, TypeOf([]int(nil))) 4104 v1 = New(at).Elem() 4105 shouldPanic(func() { _ = v1.Interface() == v1.Interface() }) 4106} 4107 4108func TestArrayOfGenericAlg(t *testing.T) { 4109 at1 := ArrayOf(5, TypeOf(string(""))) 4110 at := ArrayOf(6, at1) 4111 v1 := New(at).Elem() 4112 v2 := New(at).Elem() 4113 if v1.Interface() != v1.Interface() { 4114 t.Errorf("constructed array %v not equal to itself", v1.Interface()) 4115 } 4116 4117 v1.Index(0).Index(0).Set(ValueOf("abc")) 4118 v2.Index(0).Index(0).Set(ValueOf("efg")) 4119 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 { 4120 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2) 4121 } 4122 4123 v1.Index(0).Index(0).Set(ValueOf("abc")) 4124 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3])) 4125 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 { 4126 t.Errorf("constructed arrays %v and %v should be equal", i1, i2) 4127 } 4128 4129 // Test hash 4130 m := MakeMap(MapOf(at, TypeOf(int(0)))) 4131 m.SetMapIndex(v1, ValueOf(1)) 4132 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4133 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2) 4134 } 4135} 4136 4137func TestArrayOfDirectIface(t *testing.T) { 4138 t.Skip("skipping test because gccgo uses a different directiface value") 4139 { 4140 type T [1]*byte 4141 i1 := Zero(TypeOf(T{})).Interface() 4142 v1 := ValueOf(&i1).Elem() 4143 p1 := v1.InterfaceData()[1] 4144 4145 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface() 4146 v2 := ValueOf(&i2).Elem() 4147 p2 := v2.InterfaceData()[1] 4148 4149 if p1 != 0 { 4150 t.Errorf("got p1=%v. want=%v", p1, nil) 4151 } 4152 4153 if p2 != 0 { 4154 t.Errorf("got p2=%v. want=%v", p2, nil) 4155 } 4156 } 4157 { 4158 type T [0]*byte 4159 i1 := Zero(TypeOf(T{})).Interface() 4160 v1 := ValueOf(&i1).Elem() 4161 p1 := v1.InterfaceData()[1] 4162 4163 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface() 4164 v2 := ValueOf(&i2).Elem() 4165 p2 := v2.InterfaceData()[1] 4166 4167 if p1 == 0 { 4168 t.Errorf("got p1=%v. want=not-%v", p1, nil) 4169 } 4170 4171 if p2 == 0 { 4172 t.Errorf("got p2=%v. want=not-%v", p2, nil) 4173 } 4174 } 4175} 4176 4177func TestSliceOf(t *testing.T) { 4178 // check construction and use of type not in binary 4179 type T int 4180 st := SliceOf(TypeOf(T(1))) 4181 if got, want := st.String(), "[]reflect_test.T"; got != want { 4182 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want) 4183 } 4184 v := MakeSlice(st, 10, 10) 4185 runtime.GC() 4186 for i := 0; i < v.Len(); i++ { 4187 v.Index(i).Set(ValueOf(T(i))) 4188 runtime.GC() 4189 } 4190 s := fmt.Sprint(v.Interface()) 4191 want := "[0 1 2 3 4 5 6 7 8 9]" 4192 if s != want { 4193 t.Errorf("constructed slice = %s, want %s", s, want) 4194 } 4195 4196 // check that type already in binary is found 4197 type T1 int 4198 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{}) 4199} 4200 4201func TestSliceOverflow(t *testing.T) { 4202 // check that MakeSlice panics when size of slice overflows uint 4203 const S = 1e6 4204 s := uint(S) 4205 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1 4206 if l*s >= s { 4207 t.Fatal("slice size does not overflow") 4208 } 4209 var x [S]byte 4210 st := SliceOf(TypeOf(x)) 4211 defer func() { 4212 err := recover() 4213 if err == nil { 4214 t.Fatal("slice overflow does not panic") 4215 } 4216 }() 4217 MakeSlice(st, int(l), int(l)) 4218} 4219 4220func TestSliceOfGC(t *testing.T) { 4221 type T *uintptr 4222 tt := TypeOf(T(nil)) 4223 st := SliceOf(tt) 4224 const n = 100 4225 var x []interface{} 4226 for i := 0; i < n; i++ { 4227 v := MakeSlice(st, n, n) 4228 for j := 0; j < v.Len(); j++ { 4229 p := new(uintptr) 4230 *p = uintptr(i*n + j) 4231 v.Index(j).Set(ValueOf(p).Convert(tt)) 4232 } 4233 x = append(x, v.Interface()) 4234 } 4235 runtime.GC() 4236 4237 for i, xi := range x { 4238 v := ValueOf(xi) 4239 for j := 0; j < v.Len(); j++ { 4240 k := v.Index(j).Elem().Interface() 4241 if k != uintptr(i*n+j) { 4242 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 4243 } 4244 } 4245 } 4246} 4247 4248func TestStructOfFieldName(t *testing.T) { 4249 // invalid field name "1nvalid" 4250 shouldPanic(func() { 4251 StructOf([]StructField{ 4252 StructField{Name: "valid", Type: TypeOf("")}, 4253 StructField{Name: "1nvalid", Type: TypeOf("")}, 4254 }) 4255 }) 4256 4257 // invalid field name "+" 4258 shouldPanic(func() { 4259 StructOf([]StructField{ 4260 StructField{Name: "val1d", Type: TypeOf("")}, 4261 StructField{Name: "+", Type: TypeOf("")}, 4262 }) 4263 }) 4264 4265 // no field name 4266 shouldPanic(func() { 4267 StructOf([]StructField{ 4268 StructField{Name: "", Type: TypeOf("")}, 4269 }) 4270 }) 4271 4272 // verify creation of a struct with valid struct fields 4273 validFields := []StructField{ 4274 StructField{ 4275 Name: "φ", 4276 Type: TypeOf(""), 4277 }, 4278 StructField{ 4279 Name: "ValidName", 4280 Type: TypeOf(""), 4281 }, 4282 StructField{ 4283 Name: "Val1dNam5", 4284 Type: TypeOf(""), 4285 }, 4286 } 4287 4288 validStruct := StructOf(validFields) 4289 4290 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }` 4291 if got, want := validStruct.String(), structStr; got != want { 4292 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want) 4293 } 4294} 4295 4296func TestStructOf(t *testing.T) { 4297 // check construction and use of type not in binary 4298 fields := []StructField{ 4299 StructField{ 4300 Name: "S", 4301 Tag: "s", 4302 Type: TypeOf(""), 4303 }, 4304 StructField{ 4305 Name: "X", 4306 Tag: "x", 4307 Type: TypeOf(byte(0)), 4308 }, 4309 StructField{ 4310 Name: "Y", 4311 Type: TypeOf(uint64(0)), 4312 }, 4313 StructField{ 4314 Name: "Z", 4315 Type: TypeOf([3]uint16{}), 4316 }, 4317 } 4318 4319 st := StructOf(fields) 4320 v := New(st).Elem() 4321 runtime.GC() 4322 v.FieldByName("X").Set(ValueOf(byte(2))) 4323 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1))) 4324 runtime.GC() 4325 4326 s := fmt.Sprint(v.Interface()) 4327 want := `{ 1 0 [0 0 0]}` 4328 if s != want { 4329 t.Errorf("constructed struct = %s, want %s", s, want) 4330 } 4331 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }` 4332 if got, want := st.String(), stStr; got != want { 4333 t.Errorf("StructOf(fields).String()=%q, want %q", got, want) 4334 } 4335 4336 // check the size, alignment and field offsets 4337 stt := TypeOf(struct { 4338 String string 4339 X byte 4340 Y uint64 4341 Z [3]uint16 4342 }{}) 4343 if st.Size() != stt.Size() { 4344 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size()) 4345 } 4346 if st.Align() != stt.Align() { 4347 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align()) 4348 } 4349 if st.FieldAlign() != stt.FieldAlign() { 4350 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) 4351 } 4352 for i := 0; i < st.NumField(); i++ { 4353 o1 := st.Field(i).Offset 4354 o2 := stt.Field(i).Offset 4355 if o1 != o2 { 4356 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2) 4357 } 4358 } 4359 4360 // Check size and alignment with a trailing zero-sized field. 4361 st = StructOf([]StructField{ 4362 { 4363 Name: "F1", 4364 Type: TypeOf(byte(0)), 4365 }, 4366 { 4367 Name: "F2", 4368 Type: TypeOf([0]*byte{}), 4369 }, 4370 }) 4371 stt = TypeOf(struct { 4372 G1 byte 4373 G2 [0]*byte 4374 }{}) 4375 // Broken with gccgo for now--gccgo does not pad structs yet. 4376 // if st.Size() != stt.Size() { 4377 // t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size()) 4378 // } 4379 if st.Align() != stt.Align() { 4380 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align()) 4381 } 4382 if st.FieldAlign() != stt.FieldAlign() { 4383 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign()) 4384 } 4385 for i := 0; i < st.NumField(); i++ { 4386 o1 := st.Field(i).Offset 4387 o2 := stt.Field(i).Offset 4388 if o1 != o2 { 4389 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2) 4390 } 4391 } 4392 4393 // check duplicate names 4394 shouldPanic(func() { 4395 StructOf([]StructField{ 4396 StructField{Name: "string", Type: TypeOf("")}, 4397 StructField{Name: "string", Type: TypeOf("")}, 4398 }) 4399 }) 4400 shouldPanic(func() { 4401 StructOf([]StructField{ 4402 StructField{Type: TypeOf("")}, 4403 StructField{Name: "string", Type: TypeOf("")}, 4404 }) 4405 }) 4406 shouldPanic(func() { 4407 StructOf([]StructField{ 4408 StructField{Type: TypeOf("")}, 4409 StructField{Type: TypeOf("")}, 4410 }) 4411 }) 4412 // check that type already in binary is found 4413 checkSameType(t, Zero(StructOf(fields[2:3])).Interface(), struct{ Y uint64 }{}) 4414} 4415 4416func TestStructOfExportRules(t *testing.T) { 4417 type S1 struct{} 4418 type s2 struct{} 4419 type ΦType struct{} 4420 type φType struct{} 4421 4422 testPanic := func(i int, mustPanic bool, f func()) { 4423 defer func() { 4424 err := recover() 4425 if err == nil && mustPanic { 4426 t.Errorf("test-%d did not panic", i) 4427 } 4428 if err != nil && !mustPanic { 4429 t.Errorf("test-%d panicked: %v\n", i, err) 4430 } 4431 }() 4432 f() 4433 } 4434 4435 tests := []struct { 4436 field StructField 4437 mustPanic bool 4438 exported bool 4439 }{ 4440 { 4441 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})}, 4442 exported: true, 4443 }, 4444 { 4445 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))}, 4446 exported: true, 4447 }, 4448 { 4449 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})}, 4450 mustPanic: true, 4451 }, 4452 { 4453 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))}, 4454 mustPanic: true, 4455 }, 4456 { 4457 field: StructField{Name: "Name", Type: nil, PkgPath: ""}, 4458 mustPanic: true, 4459 }, 4460 { 4461 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""}, 4462 mustPanic: true, 4463 }, 4464 { 4465 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"}, 4466 mustPanic: true, 4467 }, 4468 { 4469 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, 4470 mustPanic: true, 4471 }, 4472 { 4473 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"}, 4474 mustPanic: true, 4475 }, 4476 { 4477 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, 4478 mustPanic: true, 4479 }, 4480 { 4481 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"}, 4482 mustPanic: true, 4483 }, 4484 { 4485 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"}, 4486 mustPanic: true, 4487 }, 4488 { 4489 field: StructField{Name: "S", Type: TypeOf(S1{})}, 4490 mustPanic: false, 4491 exported: true, 4492 }, 4493 { 4494 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))}, 4495 exported: true, 4496 }, 4497 { 4498 field: StructField{Name: "S", Type: TypeOf(s2{})}, 4499 exported: true, 4500 }, 4501 { 4502 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))}, 4503 exported: true, 4504 }, 4505 { 4506 field: StructField{Name: "s", Type: TypeOf(S1{})}, 4507 mustPanic: true, 4508 }, 4509 { 4510 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))}, 4511 mustPanic: true, 4512 }, 4513 { 4514 field: StructField{Name: "s", Type: TypeOf(s2{})}, 4515 mustPanic: true, 4516 }, 4517 { 4518 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))}, 4519 mustPanic: true, 4520 }, 4521 { 4522 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"}, 4523 mustPanic: true, // TODO(sbinet): creating a name with a package path 4524 }, 4525 { 4526 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"}, 4527 mustPanic: true, // TODO(sbinet): creating a name with a package path 4528 }, 4529 { 4530 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"}, 4531 mustPanic: true, // TODO(sbinet): creating a name with a package path 4532 }, 4533 { 4534 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"}, 4535 mustPanic: true, // TODO(sbinet): creating a name with a package path 4536 }, 4537 { 4538 field: StructField{Name: "", Type: TypeOf(ΦType{})}, 4539 mustPanic: true, 4540 }, 4541 { 4542 field: StructField{Name: "", Type: TypeOf(φType{})}, 4543 mustPanic: true, 4544 }, 4545 { 4546 field: StructField{Name: "Φ", Type: TypeOf(0)}, 4547 exported: true, 4548 }, 4549 { 4550 field: StructField{Name: "φ", Type: TypeOf(0)}, 4551 exported: false, 4552 }, 4553 } 4554 4555 for i, test := range tests { 4556 testPanic(i, test.mustPanic, func() { 4557 typ := StructOf([]StructField{test.field}) 4558 if typ == nil { 4559 t.Errorf("test-%d: error creating struct type", i) 4560 return 4561 } 4562 field := typ.Field(0) 4563 n := field.Name 4564 if n == "" { 4565 panic("field.Name must not be empty") 4566 } 4567 exported := isExported(n) 4568 if exported != test.exported { 4569 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported) 4570 } 4571 }) 4572 } 4573} 4574 4575// isExported reports whether name is an exported Go symbol 4576// (that is, whether it begins with an upper-case letter). 4577// 4578func isExported(name string) bool { 4579 ch, _ := utf8.DecodeRuneInString(name) 4580 return unicode.IsUpper(ch) 4581} 4582 4583func TestStructOfGC(t *testing.T) { 4584 type T *uintptr 4585 tt := TypeOf(T(nil)) 4586 fields := []StructField{ 4587 {Name: "X", Type: tt}, 4588 {Name: "Y", Type: tt}, 4589 } 4590 st := StructOf(fields) 4591 4592 const n = 10000 4593 var x []interface{} 4594 for i := 0; i < n; i++ { 4595 v := New(st).Elem() 4596 for j := 0; j < v.NumField(); j++ { 4597 p := new(uintptr) 4598 *p = uintptr(i*n + j) 4599 v.Field(j).Set(ValueOf(p).Convert(tt)) 4600 } 4601 x = append(x, v.Interface()) 4602 } 4603 runtime.GC() 4604 4605 for i, xi := range x { 4606 v := ValueOf(xi) 4607 for j := 0; j < v.NumField(); j++ { 4608 k := v.Field(j).Elem().Interface() 4609 if k != uintptr(i*n+j) { 4610 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j) 4611 } 4612 } 4613 } 4614} 4615 4616func TestStructOfAlg(t *testing.T) { 4617 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}}) 4618 v1 := New(st).Elem() 4619 v2 := New(st).Elem() 4620 if !DeepEqual(v1.Interface(), v1.Interface()) { 4621 t.Errorf("constructed struct %v not equal to itself", v1.Interface()) 4622 } 4623 v1.FieldByName("X").Set(ValueOf(int(1))) 4624 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { 4625 t.Errorf("constructed structs %v and %v should not be equal", i1, i2) 4626 } 4627 4628 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}}) 4629 v1 = New(st).Elem() 4630 shouldPanic(func() { _ = v1.Interface() == v1.Interface() }) 4631} 4632 4633func TestStructOfGenericAlg(t *testing.T) { 4634 st1 := StructOf([]StructField{ 4635 {Name: "X", Tag: "x", Type: TypeOf(int64(0))}, 4636 {Name: "Y", Type: TypeOf(string(""))}, 4637 }) 4638 st := StructOf([]StructField{ 4639 {Name: "S0", Type: st1}, 4640 {Name: "S1", Type: st1}, 4641 }) 4642 4643 tests := []struct { 4644 rt Type 4645 idx []int 4646 }{ 4647 { 4648 rt: st, 4649 idx: []int{0, 1}, 4650 }, 4651 { 4652 rt: st1, 4653 idx: []int{1}, 4654 }, 4655 { 4656 rt: StructOf( 4657 []StructField{ 4658 {Name: "XX", Type: TypeOf([0]int{})}, 4659 {Name: "YY", Type: TypeOf("")}, 4660 }, 4661 ), 4662 idx: []int{1}, 4663 }, 4664 { 4665 rt: StructOf( 4666 []StructField{ 4667 {Name: "XX", Type: TypeOf([0]int{})}, 4668 {Name: "YY", Type: TypeOf("")}, 4669 {Name: "ZZ", Type: TypeOf([2]int{})}, 4670 }, 4671 ), 4672 idx: []int{1}, 4673 }, 4674 { 4675 rt: StructOf( 4676 []StructField{ 4677 {Name: "XX", Type: TypeOf([1]int{})}, 4678 {Name: "YY", Type: TypeOf("")}, 4679 }, 4680 ), 4681 idx: []int{1}, 4682 }, 4683 { 4684 rt: StructOf( 4685 []StructField{ 4686 {Name: "XX", Type: TypeOf([1]int{})}, 4687 {Name: "YY", Type: TypeOf("")}, 4688 {Name: "ZZ", Type: TypeOf([1]int{})}, 4689 }, 4690 ), 4691 idx: []int{1}, 4692 }, 4693 { 4694 rt: StructOf( 4695 []StructField{ 4696 {Name: "XX", Type: TypeOf([2]int{})}, 4697 {Name: "YY", Type: TypeOf("")}, 4698 {Name: "ZZ", Type: TypeOf([2]int{})}, 4699 }, 4700 ), 4701 idx: []int{1}, 4702 }, 4703 { 4704 rt: StructOf( 4705 []StructField{ 4706 {Name: "XX", Type: TypeOf(int64(0))}, 4707 {Name: "YY", Type: TypeOf(byte(0))}, 4708 {Name: "ZZ", Type: TypeOf("")}, 4709 }, 4710 ), 4711 idx: []int{2}, 4712 }, 4713 { 4714 rt: StructOf( 4715 []StructField{ 4716 {Name: "XX", Type: TypeOf(int64(0))}, 4717 {Name: "YY", Type: TypeOf(int64(0))}, 4718 {Name: "ZZ", Type: TypeOf("")}, 4719 {Name: "AA", Type: TypeOf([1]int64{})}, 4720 }, 4721 ), 4722 idx: []int{2}, 4723 }, 4724 } 4725 4726 for _, table := range tests { 4727 v1 := New(table.rt).Elem() 4728 v2 := New(table.rt).Elem() 4729 4730 if !DeepEqual(v1.Interface(), v1.Interface()) { 4731 t.Errorf("constructed struct %v not equal to itself", v1.Interface()) 4732 } 4733 4734 v1.FieldByIndex(table.idx).Set(ValueOf("abc")) 4735 v2.FieldByIndex(table.idx).Set(ValueOf("def")) 4736 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) { 4737 t.Errorf("constructed structs %v and %v should not be equal", i1, i2) 4738 } 4739 4740 abc := "abc" 4741 v1.FieldByIndex(table.idx).Set(ValueOf(abc)) 4742 val := "+" + abc + "-" 4743 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4])) 4744 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { 4745 t.Errorf("constructed structs %v and %v should be equal", i1, i2) 4746 } 4747 4748 // Test hash 4749 m := MakeMap(MapOf(table.rt, TypeOf(int(0)))) 4750 m.SetMapIndex(v1, ValueOf(1)) 4751 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4752 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2) 4753 } 4754 4755 v2.FieldByIndex(table.idx).Set(ValueOf("abc")) 4756 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) { 4757 t.Errorf("constructed structs %v and %v should be equal", i1, i2) 4758 } 4759 4760 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() { 4761 t.Errorf("constructed structs %v and %v have different hashes", i1, i2) 4762 } 4763 } 4764} 4765 4766/* 4767gccgo does not use the same directiface settings as gc. 4768 4769func TestStructOfDirectIface(t *testing.T) { 4770 { 4771 type T struct{ X [1]*byte } 4772 i1 := Zero(TypeOf(T{})).Interface() 4773 v1 := ValueOf(&i1).Elem() 4774 p1 := v1.InterfaceData()[1] 4775 4776 i2 := Zero(StructOf([]StructField{ 4777 { 4778 Name: "X", 4779 Type: ArrayOf(1, TypeOf((*int8)(nil))), 4780 }, 4781 })).Interface() 4782 v2 := ValueOf(&i2).Elem() 4783 p2 := v2.InterfaceData()[1] 4784 4785 if p1 != 0 { 4786 t.Errorf("got p1=%v. want=%v", p1, nil) 4787 } 4788 4789 if p2 != 0 { 4790 t.Errorf("got p2=%v. want=%v", p2, nil) 4791 } 4792 } 4793 { 4794 type T struct{ X [0]*byte } 4795 i1 := Zero(TypeOf(T{})).Interface() 4796 v1 := ValueOf(&i1).Elem() 4797 p1 := v1.InterfaceData()[1] 4798 4799 i2 := Zero(StructOf([]StructField{ 4800 { 4801 Name: "X", 4802 Type: ArrayOf(0, TypeOf((*int8)(nil))), 4803 }, 4804 })).Interface() 4805 v2 := ValueOf(&i2).Elem() 4806 p2 := v2.InterfaceData()[1] 4807 4808 if p1 == 0 { 4809 t.Errorf("got p1=%v. want=not-%v", p1, nil) 4810 } 4811 4812 if p2 == 0 { 4813 t.Errorf("got p2=%v. want=not-%v", p2, nil) 4814 } 4815 } 4816} 4817*/ 4818 4819type StructI int 4820 4821func (i StructI) Get() int { return int(i) } 4822 4823type StructIPtr int 4824 4825func (i *StructIPtr) Get() int { return int(*i) } 4826 4827/* 4828gccgo does not yet support StructOf with methods. 4829 4830func TestStructOfWithInterface(t *testing.T) { 4831 const want = 42 4832 type Iface interface { 4833 Get() int 4834 } 4835 tests := []struct { 4836 name string 4837 typ Type 4838 val Value 4839 impl bool 4840 }{ 4841 { 4842 name: "StructI", 4843 typ: TypeOf(StructI(want)), 4844 val: ValueOf(StructI(want)), 4845 impl: true, 4846 }, 4847 { 4848 name: "StructI", 4849 typ: PtrTo(TypeOf(StructI(want))), 4850 val: ValueOf(func() interface{} { 4851 v := StructI(want) 4852 return &v 4853 }()), 4854 impl: true, 4855 }, 4856 { 4857 name: "StructIPtr", 4858 typ: PtrTo(TypeOf(StructIPtr(want))), 4859 val: ValueOf(func() interface{} { 4860 v := StructIPtr(want) 4861 return &v 4862 }()), 4863 impl: true, 4864 }, 4865 { 4866 name: "StructIPtr", 4867 typ: TypeOf(StructIPtr(want)), 4868 val: ValueOf(StructIPtr(want)), 4869 impl: false, 4870 }, 4871 // { 4872 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn 4873 // val: ValueOf(StructI(want)), 4874 // impl: true, 4875 // }, 4876 } 4877 4878 for i, table := range tests { 4879 for j := 0; j < 2; j++ { 4880 var fields []StructField 4881 if j == 1 { 4882 fields = append(fields, StructField{ 4883 Name: "Dummy", 4884 PkgPath: "", 4885 Type: TypeOf(int(0)), 4886 }) 4887 } 4888 fields = append(fields, StructField{ 4889 Name: table.name, 4890 Anonymous: true, 4891 PkgPath: "", 4892 Type: table.typ, 4893 }) 4894 4895 // We currently do not correctly implement methods 4896 // for anonymous fields other than the first. 4897 // Therefore, for now, we expect those methods 4898 // to not exist. See issues 15924 and 20824. 4899 // When those issues are fixed, this test of panic 4900 // should be removed. 4901 if j == 1 && table.impl { 4902 func() { 4903 defer func() { 4904 if err := recover(); err == nil { 4905 t.Errorf("test-%d-%d did not panic", i, j) 4906 } 4907 }() 4908 _ = StructOf(fields) 4909 }() 4910 continue 4911 } 4912 4913 rt := StructOf(fields) 4914 rv := New(rt).Elem() 4915 rv.Field(j).Set(table.val) 4916 4917 if _, ok := rv.Interface().(Iface); ok != table.impl { 4918 if table.impl { 4919 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ) 4920 } else { 4921 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ) 4922 } 4923 continue 4924 } 4925 4926 if !table.impl { 4927 continue 4928 } 4929 4930 v := rv.Interface().(Iface).Get() 4931 if v != want { 4932 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want) 4933 } 4934 4935 fct := rv.MethodByName("Get") 4936 out := fct.Call(nil) 4937 if !DeepEqual(out[0].Interface(), want) { 4938 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want) 4939 } 4940 } 4941 } 4942} 4943*/ 4944 4945func TestChanOf(t *testing.T) { 4946 // check construction and use of type not in binary 4947 type T string 4948 ct := ChanOf(BothDir, TypeOf(T(""))) 4949 v := MakeChan(ct, 2) 4950 runtime.GC() 4951 v.Send(ValueOf(T("hello"))) 4952 runtime.GC() 4953 v.Send(ValueOf(T("world"))) 4954 runtime.GC() 4955 4956 sv1, _ := v.Recv() 4957 sv2, _ := v.Recv() 4958 s1 := sv1.String() 4959 s2 := sv2.String() 4960 if s1 != "hello" || s2 != "world" { 4961 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world") 4962 } 4963 4964 // check that type already in binary is found 4965 type T1 int 4966 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil)) 4967} 4968 4969func TestChanOfDir(t *testing.T) { 4970 // check construction and use of type not in binary 4971 type T string 4972 crt := ChanOf(RecvDir, TypeOf(T(""))) 4973 cst := ChanOf(SendDir, TypeOf(T(""))) 4974 4975 // check that type already in binary is found 4976 type T1 int 4977 checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil)) 4978 checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil)) 4979 4980 // check String form of ChanDir 4981 if crt.ChanDir().String() != "<-chan" { 4982 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan") 4983 } 4984 if cst.ChanDir().String() != "chan<-" { 4985 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-") 4986 } 4987} 4988 4989func TestChanOfGC(t *testing.T) { 4990 done := make(chan bool, 1) 4991 go func() { 4992 select { 4993 case <-done: 4994 case <-time.After(5 * time.Second): 4995 panic("deadlock in TestChanOfGC") 4996 } 4997 }() 4998 4999 defer func() { 5000 done <- true 5001 }() 5002 5003 type T *uintptr 5004 tt := TypeOf(T(nil)) 5005 ct := ChanOf(BothDir, tt) 5006 5007 // NOTE: The garbage collector handles allocated channels specially, 5008 // so we have to save pointers to channels in x; the pointer code will 5009 // use the gc info in the newly constructed chan type. 5010 const n = 100 5011 var x []interface{} 5012 for i := 0; i < n; i++ { 5013 v := MakeChan(ct, n) 5014 for j := 0; j < n; j++ { 5015 p := new(uintptr) 5016 *p = uintptr(i*n + j) 5017 v.Send(ValueOf(p).Convert(tt)) 5018 } 5019 pv := New(ct) 5020 pv.Elem().Set(v) 5021 x = append(x, pv.Interface()) 5022 } 5023 runtime.GC() 5024 5025 for i, xi := range x { 5026 v := ValueOf(xi).Elem() 5027 for j := 0; j < n; j++ { 5028 pv, _ := v.Recv() 5029 k := pv.Elem().Interface() 5030 if k != uintptr(i*n+j) { 5031 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 5032 } 5033 } 5034 } 5035} 5036 5037func TestMapOf(t *testing.T) { 5038 // check construction and use of type not in binary 5039 type K string 5040 type V float64 5041 5042 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0)))) 5043 runtime.GC() 5044 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1))) 5045 runtime.GC() 5046 5047 s := fmt.Sprint(v.Interface()) 5048 want := "map[a:1]" 5049 if s != want { 5050 t.Errorf("constructed map = %s, want %s", s, want) 5051 } 5052 5053 // check that type already in binary is found 5054 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil)) 5055 5056 // check that invalid key type panics 5057 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) }) 5058} 5059 5060func TestMapOfGCKeys(t *testing.T) { 5061 type T *uintptr 5062 tt := TypeOf(T(nil)) 5063 mt := MapOf(tt, TypeOf(false)) 5064 5065 // NOTE: The garbage collector handles allocated maps specially, 5066 // so we have to save pointers to maps in x; the pointer code will 5067 // use the gc info in the newly constructed map type. 5068 const n = 100 5069 var x []interface{} 5070 for i := 0; i < n; i++ { 5071 v := MakeMap(mt) 5072 for j := 0; j < n; j++ { 5073 p := new(uintptr) 5074 *p = uintptr(i*n + j) 5075 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true)) 5076 } 5077 pv := New(mt) 5078 pv.Elem().Set(v) 5079 x = append(x, pv.Interface()) 5080 } 5081 runtime.GC() 5082 5083 for i, xi := range x { 5084 v := ValueOf(xi).Elem() 5085 var out []int 5086 for _, kv := range v.MapKeys() { 5087 out = append(out, int(kv.Elem().Interface().(uintptr))) 5088 } 5089 sort.Ints(out) 5090 for j, k := range out { 5091 if k != i*n+j { 5092 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 5093 } 5094 } 5095 } 5096} 5097 5098func TestMapOfGCValues(t *testing.T) { 5099 type T *uintptr 5100 tt := TypeOf(T(nil)) 5101 mt := MapOf(TypeOf(1), tt) 5102 5103 // NOTE: The garbage collector handles allocated maps specially, 5104 // so we have to save pointers to maps in x; the pointer code will 5105 // use the gc info in the newly constructed map type. 5106 const n = 100 5107 var x []interface{} 5108 for i := 0; i < n; i++ { 5109 v := MakeMap(mt) 5110 for j := 0; j < n; j++ { 5111 p := new(uintptr) 5112 *p = uintptr(i*n + j) 5113 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt)) 5114 } 5115 pv := New(mt) 5116 pv.Elem().Set(v) 5117 x = append(x, pv.Interface()) 5118 } 5119 runtime.GC() 5120 5121 for i, xi := range x { 5122 v := ValueOf(xi).Elem() 5123 for j := 0; j < n; j++ { 5124 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr) 5125 if k != uintptr(i*n+j) { 5126 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j) 5127 } 5128 } 5129 } 5130} 5131 5132func TestTypelinksSorted(t *testing.T) { 5133 var last string 5134 for i, n := range TypeLinks() { 5135 if n < last { 5136 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i) 5137 } 5138 last = n 5139 } 5140} 5141 5142func TestFuncOf(t *testing.T) { 5143 // check construction and use of type not in binary 5144 type K string 5145 type V float64 5146 5147 fn := func(args []Value) []Value { 5148 if len(args) != 1 { 5149 t.Errorf("args == %v, want exactly one arg", args) 5150 } else if args[0].Type() != TypeOf(K("")) { 5151 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K(""))) 5152 } else if args[0].String() != "gopher" { 5153 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher") 5154 } 5155 return []Value{ValueOf(V(3.14))} 5156 } 5157 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn) 5158 5159 outs := v.Call([]Value{ValueOf(K("gopher"))}) 5160 if len(outs) != 1 { 5161 t.Fatalf("v.Call returned %v, want exactly one result", outs) 5162 } else if outs[0].Type() != TypeOf(V(0)) { 5163 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0))) 5164 } 5165 f := outs[0].Float() 5166 if f != 3.14 { 5167 t.Errorf("constructed func returned %f, want %f", f, 3.14) 5168 } 5169 5170 // check that types already in binary are found 5171 type T1 int 5172 testCases := []struct { 5173 in, out []Type 5174 variadic bool 5175 want interface{} 5176 }{ 5177 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)}, 5178 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)}, 5179 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)}, 5180 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)}, 5181 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)}, 5182 } 5183 for _, tt := range testCases { 5184 checkSameType(t, Zero(FuncOf(tt.in, tt.out, tt.variadic)).Interface(), tt.want) 5185 } 5186 5187 // check that variadic requires last element be a slice. 5188 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true) 5189 shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) }) 5190 shouldPanic(func() { FuncOf(nil, nil, true) }) 5191} 5192 5193type B1 struct { 5194 X int 5195 Y int 5196 Z int 5197} 5198 5199func BenchmarkFieldByName1(b *testing.B) { 5200 t := TypeOf(B1{}) 5201 b.RunParallel(func(pb *testing.PB) { 5202 for pb.Next() { 5203 t.FieldByName("Z") 5204 } 5205 }) 5206} 5207 5208func BenchmarkFieldByName2(b *testing.B) { 5209 t := TypeOf(S3{}) 5210 b.RunParallel(func(pb *testing.PB) { 5211 for pb.Next() { 5212 t.FieldByName("B") 5213 } 5214 }) 5215} 5216 5217type R0 struct { 5218 *R1 5219 *R2 5220 *R3 5221 *R4 5222} 5223 5224type R1 struct { 5225 *R5 5226 *R6 5227 *R7 5228 *R8 5229} 5230 5231type R2 R1 5232type R3 R1 5233type R4 R1 5234 5235type R5 struct { 5236 *R9 5237 *R10 5238 *R11 5239 *R12 5240} 5241 5242type R6 R5 5243type R7 R5 5244type R8 R5 5245 5246type R9 struct { 5247 *R13 5248 *R14 5249 *R15 5250 *R16 5251} 5252 5253type R10 R9 5254type R11 R9 5255type R12 R9 5256 5257type R13 struct { 5258 *R17 5259 *R18 5260 *R19 5261 *R20 5262} 5263 5264type R14 R13 5265type R15 R13 5266type R16 R13 5267 5268type R17 struct { 5269 *R21 5270 *R22 5271 *R23 5272 *R24 5273} 5274 5275type R18 R17 5276type R19 R17 5277type R20 R17 5278 5279type R21 struct { 5280 X int 5281} 5282 5283type R22 R21 5284type R23 R21 5285type R24 R21 5286 5287func TestEmbed(t *testing.T) { 5288 typ := TypeOf(R0{}) 5289 f, ok := typ.FieldByName("X") 5290 if ok { 5291 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index) 5292 } 5293} 5294 5295func BenchmarkFieldByName3(b *testing.B) { 5296 t := TypeOf(R0{}) 5297 b.RunParallel(func(pb *testing.PB) { 5298 for pb.Next() { 5299 t.FieldByName("X") 5300 } 5301 }) 5302} 5303 5304type S struct { 5305 i1 int64 5306 i2 int64 5307} 5308 5309func BenchmarkInterfaceBig(b *testing.B) { 5310 v := ValueOf(S{}) 5311 b.RunParallel(func(pb *testing.PB) { 5312 for pb.Next() { 5313 v.Interface() 5314 } 5315 }) 5316 b.StopTimer() 5317} 5318 5319func TestAllocsInterfaceBig(t *testing.T) { 5320 if testing.Short() { 5321 t.Skip("skipping malloc count in short mode") 5322 } 5323 v := ValueOf(S{}) 5324 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { 5325 t.Error("allocs:", allocs) 5326 } 5327} 5328 5329func BenchmarkInterfaceSmall(b *testing.B) { 5330 v := ValueOf(int64(0)) 5331 b.RunParallel(func(pb *testing.PB) { 5332 for pb.Next() { 5333 v.Interface() 5334 } 5335 }) 5336} 5337 5338func TestAllocsInterfaceSmall(t *testing.T) { 5339 if testing.Short() { 5340 t.Skip("skipping malloc count in short mode") 5341 } 5342 v := ValueOf(int64(0)) 5343 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 { 5344 t.Error("allocs:", allocs) 5345 } 5346} 5347 5348// An exhaustive is a mechanism for writing exhaustive or stochastic tests. 5349// The basic usage is: 5350// 5351// for x.Next() { 5352// ... code using x.Maybe() or x.Choice(n) to create test cases ... 5353// } 5354// 5355// Each iteration of the loop returns a different set of results, until all 5356// possible result sets have been explored. It is okay for different code paths 5357// to make different method call sequences on x, but there must be no 5358// other source of non-determinism in the call sequences. 5359// 5360// When faced with a new decision, x chooses randomly. Future explorations 5361// of that path will choose successive values for the result. Thus, stopping 5362// the loop after a fixed number of iterations gives somewhat stochastic 5363// testing. 5364// 5365// Example: 5366// 5367// for x.Next() { 5368// v := make([]bool, x.Choose(4)) 5369// for i := range v { 5370// v[i] = x.Maybe() 5371// } 5372// fmt.Println(v) 5373// } 5374// 5375// prints (in some order): 5376// 5377// [] 5378// [false] 5379// [true] 5380// [false false] 5381// [false true] 5382// ... 5383// [true true] 5384// [false false false] 5385// ... 5386// [true true true] 5387// [false false false false] 5388// ... 5389// [true true true true] 5390// 5391type exhaustive struct { 5392 r *rand.Rand 5393 pos int 5394 last []choice 5395} 5396 5397type choice struct { 5398 off int 5399 n int 5400 max int 5401} 5402 5403func (x *exhaustive) Next() bool { 5404 if x.r == nil { 5405 x.r = rand.New(rand.NewSource(time.Now().UnixNano())) 5406 } 5407 x.pos = 0 5408 if x.last == nil { 5409 x.last = []choice{} 5410 return true 5411 } 5412 for i := len(x.last) - 1; i >= 0; i-- { 5413 c := &x.last[i] 5414 if c.n+1 < c.max { 5415 c.n++ 5416 x.last = x.last[:i+1] 5417 return true 5418 } 5419 } 5420 return false 5421} 5422 5423func (x *exhaustive) Choose(max int) int { 5424 if x.pos >= len(x.last) { 5425 x.last = append(x.last, choice{x.r.Intn(max), 0, max}) 5426 } 5427 c := &x.last[x.pos] 5428 x.pos++ 5429 if c.max != max { 5430 panic("inconsistent use of exhaustive tester") 5431 } 5432 return (c.n + c.off) % max 5433} 5434 5435func (x *exhaustive) Maybe() bool { 5436 return x.Choose(2) == 1 5437} 5438 5439func GCFunc(args []Value) []Value { 5440 runtime.GC() 5441 return []Value{} 5442} 5443 5444func TestReflectFuncTraceback(t *testing.T) { 5445 f := MakeFunc(TypeOf(func() {}), GCFunc) 5446 f.Call([]Value{}) 5447} 5448 5449func TestReflectMethodTraceback(t *testing.T) { 5450 p := Point{3, 4} 5451 m := ValueOf(p).MethodByName("GCMethod") 5452 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int() 5453 if i != 8 { 5454 t.Errorf("Call returned %d; want 8", i) 5455 } 5456} 5457 5458func TestBigZero(t *testing.T) { 5459 const size = 1 << 10 5460 var v [size]byte 5461 z := Zero(ValueOf(v).Type()).Interface().([size]byte) 5462 for i := 0; i < size; i++ { 5463 if z[i] != 0 { 5464 t.Fatalf("Zero object not all zero, index %d", i) 5465 } 5466 } 5467} 5468 5469func TestFieldByIndexNil(t *testing.T) { 5470 type P struct { 5471 F int 5472 } 5473 type T struct { 5474 *P 5475 } 5476 v := ValueOf(T{}) 5477 5478 v.FieldByName("P") // should be fine 5479 5480 defer func() { 5481 if err := recover(); err == nil { 5482 t.Fatalf("no error") 5483 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") { 5484 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err) 5485 } 5486 }() 5487 v.FieldByName("F") // should panic 5488 5489 t.Fatalf("did not panic") 5490} 5491 5492// Given 5493// type Outer struct { 5494// *Inner 5495// ... 5496// } 5497// the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner. 5498// The implementation is logically: 5499// func (p *Outer) M() { 5500// (p.Inner).M() 5501// } 5502// but since the only change here is the replacement of one pointer receiver with another, 5503// the actual generated code overwrites the original receiver with the p.Inner pointer and 5504// then jumps to the M method expecting the *Inner receiver. 5505// 5506// During reflect.Value.Call, we create an argument frame and the associated data structures 5507// to describe it to the garbage collector, populate the frame, call reflect.call to 5508// run a function call using that frame, and then copy the results back out of the frame. 5509// The reflect.call function does a memmove of the frame structure onto the 5510// stack (to set up the inputs), runs the call, and the memmoves the stack back to 5511// the frame structure (to preserve the outputs). 5512// 5513// Originally reflect.call did not distinguish inputs from outputs: both memmoves 5514// were for the full stack frame. However, in the case where the called function was 5515// one of these wrappers, the rewritten receiver is almost certainly a different type 5516// than the original receiver. This is not a problem on the stack, where we use the 5517// program counter to determine the type information and understand that 5518// during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same 5519// memory word is now an *Inner. But in the statically typed argument frame created 5520// by reflect, the receiver is always an *Outer. Copying the modified receiver pointer 5521// off the stack into the frame will store an *Inner there, and then if a garbage collection 5522// happens to scan that argument frame before it is discarded, it will scan the *Inner 5523// memory as if it were an *Outer. If the two have different memory layouts, the 5524// collection will interpret the memory incorrectly. 5525// 5526// One such possible incorrect interpretation is to treat two arbitrary memory words 5527// (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting 5528// an interface requires dereferencing the itab word, the misinterpretation will try to 5529// deference Inner.P1, causing a crash during garbage collection. 5530// 5531// This came up in a real program in issue 7725. 5532 5533type Outer struct { 5534 *Inner 5535 R io.Reader 5536} 5537 5538type Inner struct { 5539 X *Outer 5540 P1 uintptr 5541 P2 uintptr 5542} 5543 5544func (pi *Inner) M() { 5545 // Clear references to pi so that the only way the 5546 // garbage collection will find the pointer is in the 5547 // argument frame, typed as a *Outer. 5548 pi.X.Inner = nil 5549 5550 // Set up an interface value that will cause a crash. 5551 // P1 = 1 is a non-zero, so the interface looks non-nil. 5552 // P2 = pi ensures that the data word points into the 5553 // allocated heap; if not the collection skips the interface 5554 // value as irrelevant, without dereferencing P1. 5555 pi.P1 = 1 5556 pi.P2 = uintptr(unsafe.Pointer(pi)) 5557} 5558 5559func TestCallMethodJump(t *testing.T) { 5560 // In reflect.Value.Call, trigger a garbage collection after reflect.call 5561 // returns but before the args frame has been discarded. 5562 // This is a little clumsy but makes the failure repeatable. 5563 *CallGC = true 5564 5565 p := &Outer{Inner: new(Inner)} 5566 p.Inner.X = p 5567 ValueOf(p).Method(0).Call(nil) 5568 5569 // Stop garbage collecting during reflect.call. 5570 *CallGC = false 5571} 5572 5573func TestMakeFuncStackCopy(t *testing.T) { 5574 target := func(in []Value) []Value { 5575 runtime.GC() 5576 useStack(16) 5577 return []Value{ValueOf(9)} 5578 } 5579 5580 var concrete func(*int, int) int 5581 fn := MakeFunc(ValueOf(concrete).Type(), target) 5582 ValueOf(&concrete).Elem().Set(fn) 5583 x := concrete(nil, 7) 5584 if x != 9 { 5585 t.Errorf("have %#q want 9", x) 5586 } 5587} 5588 5589// use about n KB of stack 5590func useStack(n int) { 5591 if n == 0 { 5592 return 5593 } 5594 var b [1024]byte // makes frame about 1KB 5595 useStack(n - 1 + int(b[99])) 5596} 5597 5598type Impl struct{} 5599 5600func (Impl) F() {} 5601 5602func TestValueString(t *testing.T) { 5603 rv := ValueOf(Impl{}) 5604 if rv.String() != "<reflect_test.Impl Value>" { 5605 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>") 5606 } 5607 5608 method := rv.Method(0) 5609 if method.String() != "<func() Value>" { 5610 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>") 5611 } 5612} 5613 5614func TestInvalid(t *testing.T) { 5615 // Used to have inconsistency between IsValid() and Kind() != Invalid. 5616 type T struct{ v interface{} } 5617 5618 v := ValueOf(T{}).Field(0) 5619 if v.IsValid() != true || v.Kind() != Interface { 5620 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind()) 5621 } 5622 v = v.Elem() 5623 if v.IsValid() != false || v.Kind() != Invalid { 5624 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind()) 5625 } 5626} 5627 5628// Issue 8917. 5629func TestLargeGCProg(t *testing.T) { 5630 fv := ValueOf(func([256]*byte) {}) 5631 fv.Call([]Value{ValueOf([256]*byte{})}) 5632} 5633 5634func fieldIndexRecover(t Type, i int) (recovered interface{}) { 5635 defer func() { 5636 recovered = recover() 5637 }() 5638 5639 t.Field(i) 5640 return 5641} 5642 5643// Issue 15046. 5644func TestTypeFieldOutOfRangePanic(t *testing.T) { 5645 typ := TypeOf(struct{ X int }{10}) 5646 testIndices := [...]struct { 5647 i int 5648 mustPanic bool 5649 }{ 5650 0: {-2, true}, 5651 1: {0, false}, 5652 2: {1, true}, 5653 3: {1 << 10, true}, 5654 } 5655 for i, tt := range testIndices { 5656 recoveredErr := fieldIndexRecover(typ, tt.i) 5657 if tt.mustPanic { 5658 if recoveredErr == nil { 5659 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i) 5660 } 5661 } else { 5662 if recoveredErr != nil { 5663 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr) 5664 } 5665 } 5666 } 5667} 5668 5669// Issue 9179. 5670func TestCallGC(t *testing.T) { 5671 f := func(a, b, c, d, e string) { 5672 } 5673 g := func(in []Value) []Value { 5674 runtime.GC() 5675 return nil 5676 } 5677 typ := ValueOf(f).Type() 5678 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string)) 5679 f2("four", "five5", "six666", "seven77", "eight888") 5680} 5681 5682// Issue 18635 (function version). 5683func TestKeepFuncLive(t *testing.T) { 5684 // Test that we keep makeFuncImpl live as long as it is 5685 // referenced on the stack. 5686 typ := TypeOf(func(i int) {}) 5687 var f, g func(in []Value) []Value 5688 f = func(in []Value) []Value { 5689 clobber() 5690 i := int(in[0].Int()) 5691 if i > 0 { 5692 // We can't use Value.Call here because 5693 // runtime.call* will keep the makeFuncImpl 5694 // alive. However, by converting it to an 5695 // interface value and calling that, 5696 // reflect.callReflect is the only thing that 5697 // can keep the makeFuncImpl live. 5698 // 5699 // Alternate between f and g so that if we do 5700 // reuse the memory prematurely it's more 5701 // likely to get obviously corrupted. 5702 MakeFunc(typ, g).Interface().(func(i int))(i - 1) 5703 } 5704 return nil 5705 } 5706 g = func(in []Value) []Value { 5707 clobber() 5708 i := int(in[0].Int()) 5709 MakeFunc(typ, f).Interface().(func(i int))(i) 5710 return nil 5711 } 5712 MakeFunc(typ, f).Call([]Value{ValueOf(10)}) 5713} 5714 5715type UnExportedFirst int 5716 5717func (i UnExportedFirst) ΦExported() {} 5718func (i UnExportedFirst) unexported() {} 5719 5720// Issue 21177 5721func TestMethodByNameUnExportedFirst(t *testing.T) { 5722 defer func() { 5723 if recover() != nil { 5724 t.Errorf("should not panic") 5725 } 5726 }() 5727 typ := TypeOf(UnExportedFirst(0)) 5728 m, _ := typ.MethodByName("ΦExported") 5729 if m.Name != "ΦExported" { 5730 t.Errorf("got %s, expected ΦExported", m.Name) 5731 } 5732} 5733 5734// Issue 18635 (method version). 5735type KeepMethodLive struct{} 5736 5737func (k KeepMethodLive) Method1(i int) { 5738 clobber() 5739 if i > 0 { 5740 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1) 5741 } 5742} 5743 5744func (k KeepMethodLive) Method2(i int) { 5745 clobber() 5746 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i) 5747} 5748 5749func TestKeepMethodLive(t *testing.T) { 5750 // Test that we keep methodValue live as long as it is 5751 // referenced on the stack. 5752 KeepMethodLive{}.Method1(10) 5753} 5754 5755// clobber tries to clobber unreachable memory. 5756func clobber() { 5757 runtime.GC() 5758 for i := 1; i < 32; i++ { 5759 for j := 0; j < 10; j++ { 5760 obj := make([]*byte, i) 5761 sink = obj 5762 } 5763 } 5764 runtime.GC() 5765} 5766 5767type funcLayoutTest struct { 5768 rcvr, t Type 5769 size, argsize, retOffset uintptr 5770 stack []byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized) 5771 gc []byte 5772} 5773 5774var funcLayoutTests []funcLayoutTest 5775 5776func init() { 5777 var argAlign uintptr = PtrSize 5778 if runtime.GOARCH == "amd64p32" { 5779 argAlign = 2 * PtrSize 5780 } 5781 roundup := func(x uintptr, a uintptr) uintptr { 5782 return (x + a - 1) / a * a 5783 } 5784 5785 funcLayoutTests = append(funcLayoutTests, 5786 funcLayoutTest{ 5787 nil, 5788 ValueOf(func(a, b string) string { return "" }).Type(), 5789 6 * PtrSize, 5790 4 * PtrSize, 5791 4 * PtrSize, 5792 []byte{1, 0, 1}, 5793 []byte{1, 0, 1, 0, 1}, 5794 }) 5795 5796 var r []byte 5797 if PtrSize == 4 { 5798 r = []byte{0, 0, 0, 1} 5799 } else { 5800 r = []byte{0, 0, 1} 5801 } 5802 funcLayoutTests = append(funcLayoutTests, 5803 funcLayoutTest{ 5804 nil, 5805 ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(), 5806 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign), 5807 roundup(3*4, PtrSize) + PtrSize + 2, 5808 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign), 5809 r, 5810 r, 5811 }) 5812 5813 funcLayoutTests = append(funcLayoutTests, 5814 funcLayoutTest{ 5815 nil, 5816 ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(), 5817 4 * PtrSize, 5818 4 * PtrSize, 5819 4 * PtrSize, 5820 []byte{1, 0, 1, 1}, 5821 []byte{1, 0, 1, 1}, 5822 }) 5823 5824 type S struct { 5825 a, b uintptr 5826 c, d *byte 5827 } 5828 funcLayoutTests = append(funcLayoutTests, 5829 funcLayoutTest{ 5830 nil, 5831 ValueOf(func(a S) {}).Type(), 5832 4 * PtrSize, 5833 4 * PtrSize, 5834 4 * PtrSize, 5835 []byte{0, 0, 1, 1}, 5836 []byte{0, 0, 1, 1}, 5837 }) 5838 5839 funcLayoutTests = append(funcLayoutTests, 5840 funcLayoutTest{ 5841 ValueOf((*byte)(nil)).Type(), 5842 ValueOf(func(a uintptr, b *int) {}).Type(), 5843 roundup(3*PtrSize, argAlign), 5844 3 * PtrSize, 5845 roundup(3*PtrSize, argAlign), 5846 []byte{1, 0, 1}, 5847 []byte{1, 0, 1}, 5848 }) 5849 5850 funcLayoutTests = append(funcLayoutTests, 5851 funcLayoutTest{ 5852 nil, 5853 ValueOf(func(a uintptr) {}).Type(), 5854 roundup(PtrSize, argAlign), 5855 PtrSize, 5856 roundup(PtrSize, argAlign), 5857 []byte{}, 5858 []byte{}, 5859 }) 5860 5861 funcLayoutTests = append(funcLayoutTests, 5862 funcLayoutTest{ 5863 nil, 5864 ValueOf(func() uintptr { return 0 }).Type(), 5865 PtrSize, 5866 0, 5867 0, 5868 []byte{}, 5869 []byte{}, 5870 }) 5871 5872 funcLayoutTests = append(funcLayoutTests, 5873 funcLayoutTest{ 5874 ValueOf(uintptr(0)).Type(), 5875 ValueOf(func(a uintptr) {}).Type(), 5876 2 * PtrSize, 5877 2 * PtrSize, 5878 2 * PtrSize, 5879 []byte{1}, 5880 []byte{1}, 5881 // Note: this one is tricky, as the receiver is not a pointer. But we 5882 // pass the receiver by reference to the autogenerated pointer-receiver 5883 // version of the function. 5884 }) 5885} 5886 5887func TestFuncLayout(t *testing.T) { 5888 t.Skip("gccgo does not use funcLayout") 5889 for _, lt := range funcLayoutTests { 5890 typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr) 5891 if typ.Size() != lt.size { 5892 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size) 5893 } 5894 if argsize != lt.argsize { 5895 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize) 5896 } 5897 if retOffset != lt.retOffset { 5898 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset) 5899 } 5900 if !bytes.Equal(stack, lt.stack) { 5901 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack) 5902 } 5903 if !bytes.Equal(gc, lt.gc) { 5904 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc) 5905 } 5906 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 { 5907 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs) 5908 } 5909 } 5910} 5911 5912func verifyGCBits(t *testing.T, typ Type, bits []byte) { 5913 heapBits := GCBits(New(typ).Interface()) 5914 if !bytes.Equal(heapBits, bits) { 5915 t.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ, heapBits, bits) 5916 } 5917} 5918 5919func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) { 5920 // Creating a slice causes the runtime to repeat a bitmap, 5921 // which exercises a different path from making the compiler 5922 // repeat a bitmap for a small array or executing a repeat in 5923 // a GC program. 5924 val := MakeSlice(typ, 0, cap) 5925 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer())) 5926 heapBits := GCBits(data.Interface()) 5927 // Repeat the bitmap for the slice size, trimming scalars in 5928 // the last element. 5929 bits = rep(cap, bits) 5930 for len(bits) > 2 && bits[len(bits)-1] == 0 { 5931 bits = bits[:len(bits)-1] 5932 } 5933 if len(bits) == 2 && bits[0] == 0 && bits[1] == 0 { 5934 bits = bits[:0] 5935 } 5936 if !bytes.Equal(heapBits, bits) { 5937 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits) 5938 } 5939} 5940 5941func TestGCBits(t *testing.T) { 5942 t.Skip("gccgo does not use gcbits yet") 5943 5944 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1}) 5945 5946 // Building blocks for types seen by the compiler (like [2]Xscalar). 5947 // The compiler will create the type structures for the derived types, 5948 // including their GC metadata. 5949 type Xscalar struct{ x uintptr } 5950 type Xptr struct{ x *byte } 5951 type Xptrscalar struct { 5952 *byte 5953 uintptr 5954 } 5955 type Xscalarptr struct { 5956 uintptr 5957 *byte 5958 } 5959 type Xbigptrscalar struct { 5960 _ [100]*byte 5961 _ [100]uintptr 5962 } 5963 5964 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type 5965 { 5966 // Building blocks for types constructed by reflect. 5967 // This code is in a separate block so that code below 5968 // cannot accidentally refer to these. 5969 // The compiler must NOT see types derived from these 5970 // (for example, [2]Scalar must NOT appear in the program), 5971 // or else reflect will use it instead of having to construct one. 5972 // The goal is to test the construction. 5973 type Scalar struct{ x uintptr } 5974 type Ptr struct{ x *byte } 5975 type Ptrscalar struct { 5976 *byte 5977 uintptr 5978 } 5979 type Scalarptr struct { 5980 uintptr 5981 *byte 5982 } 5983 type Bigptrscalar struct { 5984 _ [100]*byte 5985 _ [100]uintptr 5986 } 5987 type Int64 int64 5988 Tscalar = TypeOf(Scalar{}) 5989 Tint64 = TypeOf(Int64(0)) 5990 Tptr = TypeOf(Ptr{}) 5991 Tscalarptr = TypeOf(Scalarptr{}) 5992 Tptrscalar = TypeOf(Ptrscalar{}) 5993 Tbigptrscalar = TypeOf(Bigptrscalar{}) 5994 } 5995 5996 empty := []byte{} 5997 5998 verifyGCBits(t, TypeOf(Xscalar{}), empty) 5999 verifyGCBits(t, Tscalar, empty) 6000 verifyGCBits(t, TypeOf(Xptr{}), lit(1)) 6001 verifyGCBits(t, Tptr, lit(1)) 6002 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1)) 6003 verifyGCBits(t, Tscalarptr, lit(0, 1)) 6004 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1)) 6005 verifyGCBits(t, Tptrscalar, lit(1)) 6006 6007 verifyGCBits(t, TypeOf([0]Xptr{}), empty) 6008 verifyGCBits(t, ArrayOf(0, Tptr), empty) 6009 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1)) 6010 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1)) 6011 verifyGCBits(t, TypeOf([2]Xscalar{}), empty) 6012 verifyGCBits(t, ArrayOf(2, Tscalar), empty) 6013 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty) 6014 verifyGCBits(t, ArrayOf(10000, Tscalar), empty) 6015 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1)) 6016 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1)) 6017 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1))) 6018 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1))) 6019 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1)) 6020 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1)) 6021 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1))) 6022 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1))) 6023 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1)) 6024 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1)) 6025 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0))) 6026 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0))) 6027 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0))) 6028 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0))) 6029 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0))) 6030 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0))) 6031 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) 6032 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1)))) 6033 6034 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty) 6035 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty) 6036 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1)) 6037 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1)) 6038 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0)) 6039 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0)) 6040 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0)) 6041 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0)) 6042 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1)) 6043 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1)) 6044 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1)) 6045 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1)) 6046 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1)) 6047 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1)) 6048 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1)) 6049 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1)) 6050 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0)) 6051 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0)) 6052 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0)) 6053 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0)) 6054 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0))) 6055 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0))) 6056 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0))) 6057 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0))) 6058 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0)))) 6059 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0)))) 6060 6061 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1)) 6062 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1)) 6063 6064 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1)) 6065 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1)) 6066 6067 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1)) 6068 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1)) 6069 6070 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1)) 6071 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1)) 6072 6073 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1)) 6074 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1)) 6075 6076 hdr := make([]byte, 8/PtrSize) 6077 6078 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) { 6079 verifyGCBits(t, MapBucketOf(k, e), want) 6080 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want) 6081 } 6082 verifyMapBucket(t, 6083 Tscalar, Tptr, 6084 map[Xscalar]Xptr(nil), 6085 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1))) 6086 verifyMapBucket(t, 6087 Tscalarptr, Tptr, 6088 map[Xscalarptr]Xptr(nil), 6089 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1))) 6090 verifyMapBucket(t, Tint64, Tptr, 6091 map[int64]Xptr(nil), 6092 join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), naclpad(), lit(1))) 6093 verifyMapBucket(t, 6094 Tscalar, Tscalar, 6095 map[Xscalar]Xscalar(nil), 6096 empty) 6097 verifyMapBucket(t, 6098 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar), 6099 map[[2]Xscalarptr][3]Xptrscalar(nil), 6100 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1))) 6101 verifyMapBucket(t, 6102 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar), 6103 map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil), 6104 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1))) 6105 verifyMapBucket(t, 6106 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar), 6107 map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil), 6108 join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1))) 6109 verifyMapBucket(t, 6110 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar), 6111 map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil), 6112 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1))) 6113 verifyMapBucket(t, 6114 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar), 6115 map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil), 6116 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1))) 6117} 6118 6119func naclpad() []byte { 6120 if runtime.GOARCH == "amd64p32" { 6121 return lit(0) 6122 } 6123 return nil 6124} 6125 6126func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) } 6127func join(b ...[]byte) []byte { return bytes.Join(b, nil) } 6128func lit(x ...byte) []byte { return x } 6129 6130func TestTypeOfTypeOf(t *testing.T) { 6131 // Check that all the type constructors return concrete *rtype implementations. 6132 // It's difficult to test directly because the reflect package is only at arm's length. 6133 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype. 6134 check := func(name string, typ Type) { 6135 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" { 6136 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying) 6137 } 6138 } 6139 6140 type T struct{ int } 6141 check("TypeOf", TypeOf(T{})) 6142 6143 check("ArrayOf", ArrayOf(10, TypeOf(T{}))) 6144 check("ChanOf", ChanOf(BothDir, TypeOf(T{}))) 6145 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false)) 6146 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{}))) 6147 check("PtrTo", PtrTo(TypeOf(T{}))) 6148 check("SliceOf", SliceOf(TypeOf(T{}))) 6149} 6150 6151type XM struct{ _ bool } 6152 6153func (*XM) String() string { return "" } 6154 6155func TestPtrToMethods(t *testing.T) { 6156 var y struct{ XM } 6157 yp := New(TypeOf(y)).Interface() 6158 _, ok := yp.(fmt.Stringer) 6159 if !ok { 6160 t.Fatal("does not implement Stringer, but should") 6161 } 6162} 6163 6164func TestMapAlloc(t *testing.T) { 6165 m := ValueOf(make(map[int]int, 10)) 6166 k := ValueOf(5) 6167 v := ValueOf(7) 6168 allocs := testing.AllocsPerRun(100, func() { 6169 m.SetMapIndex(k, v) 6170 }) 6171 if allocs > 0.5 { 6172 t.Errorf("allocs per map assignment: want 0 got %f", allocs) 6173 } 6174 6175 const size = 1000 6176 tmp := 0 6177 val := ValueOf(&tmp).Elem() 6178 allocs = testing.AllocsPerRun(100, func() { 6179 mv := MakeMapWithSize(TypeOf(map[int]int{}), size) 6180 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets. 6181 for i := 0; i < size/2; i++ { 6182 val.SetInt(int64(i)) 6183 mv.SetMapIndex(val, val) 6184 } 6185 }) 6186 if allocs > 10 { 6187 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs) 6188 } 6189 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set 6190 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the 6191 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added. 6192} 6193 6194func TestChanAlloc(t *testing.T) { 6195 // Note: for a chan int, the return Value must be allocated, so we 6196 // use a chan *int instead. 6197 c := ValueOf(make(chan *int, 1)) 6198 v := ValueOf(new(int)) 6199 allocs := testing.AllocsPerRun(100, func() { 6200 c.Send(v) 6201 _, _ = c.Recv() 6202 }) 6203 if allocs < 0.5 || allocs > 1.5 { 6204 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs) 6205 } 6206 // Note: there is one allocation in reflect.recv which seems to be 6207 // a limitation of escape analysis. If that is ever fixed the 6208 // allocs < 0.5 condition will trigger and this test should be fixed. 6209} 6210 6211type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int 6212 6213type nameTest struct { 6214 v interface{} 6215 want string 6216} 6217 6218var nameTests = []nameTest{ 6219 {(*int32)(nil), "int32"}, 6220 {(*D1)(nil), "D1"}, 6221 {(*[]D1)(nil), ""}, 6222 {(*chan D1)(nil), ""}, 6223 {(*func() D1)(nil), ""}, 6224 {(*<-chan D1)(nil), ""}, 6225 {(*chan<- D1)(nil), ""}, 6226 {(*interface{})(nil), ""}, 6227 {(*interface { 6228 F() 6229 })(nil), ""}, 6230 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"}, 6231} 6232 6233func TestNames(t *testing.T) { 6234 for _, test := range nameTests { 6235 typ := TypeOf(test.v).Elem() 6236 if got := typ.Name(); got != test.want { 6237 t.Errorf("%v Name()=%q, want %q", typ, got, test.want) 6238 } 6239 } 6240} 6241 6242/* 6243gccgo doesn't really record whether a type is exported. 6244It's not in the reflect API anyhow. 6245 6246func TestExported(t *testing.T) { 6247 type ΦExported struct{} 6248 type φUnexported struct{} 6249 type BigP *big 6250 type P int 6251 type p *P 6252 type P2 p 6253 type p3 p 6254 6255 type exportTest struct { 6256 v interface{} 6257 want bool 6258 } 6259 exportTests := []exportTest{ 6260 {D1{}, true}, 6261 {(*D1)(nil), true}, 6262 {big{}, false}, 6263 {(*big)(nil), false}, 6264 {(BigP)(nil), true}, 6265 {(*BigP)(nil), true}, 6266 {ΦExported{}, true}, 6267 {φUnexported{}, false}, 6268 {P(0), true}, 6269 {(p)(nil), false}, 6270 {(P2)(nil), true}, 6271 {(p3)(nil), false}, 6272 } 6273 6274 for i, test := range exportTests { 6275 typ := TypeOf(test.v) 6276 if got := IsExported(typ); got != test.want { 6277 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want) 6278 } 6279 } 6280} 6281*/ 6282 6283type embed struct { 6284 EmbedWithUnexpMeth 6285} 6286 6287/* 6288func TestNameBytesAreAligned(t *testing.T) { 6289 typ := TypeOf(embed{}) 6290 b := FirstMethodNameBytes(typ) 6291 v := uintptr(unsafe.Pointer(b)) 6292 if v%unsafe.Alignof((*byte)(nil)) != 0 { 6293 t.Errorf("reflect.name.bytes pointer is not aligned: %x", v) 6294 } 6295} 6296*/ 6297 6298func TestTypeStrings(t *testing.T) { 6299 type stringTest struct { 6300 typ Type 6301 want string 6302 } 6303 stringTests := []stringTest{ 6304 {TypeOf(func(int) {}), "func(int)"}, 6305 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"}, 6306 {TypeOf(XM{}), "reflect_test.XM"}, 6307 {TypeOf(new(XM)), "*reflect_test.XM"}, 6308 {TypeOf(new(XM).String), "func() string"}, 6309 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"}, 6310 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"}, 6311 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"}, 6312 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"}, 6313 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"}, 6314 } 6315 6316 for i, test := range stringTests { 6317 if got, want := test.typ.String(), test.want; got != want { 6318 t.Errorf("type %d String()=%q, want %q", i, got, want) 6319 } 6320 } 6321} 6322 6323/* 6324gccgo does not have resolveReflectName. 6325 6326func TestOffsetLock(t *testing.T) { 6327 var wg sync.WaitGroup 6328 for i := 0; i < 4; i++ { 6329 i := i 6330 wg.Add(1) 6331 go func() { 6332 for j := 0; j < 50; j++ { 6333 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j)) 6334 } 6335 wg.Done() 6336 }() 6337 } 6338 wg.Wait() 6339} 6340*/ 6341 6342func BenchmarkNew(b *testing.B) { 6343 v := TypeOf(XM{}) 6344 b.RunParallel(func(pb *testing.PB) { 6345 for pb.Next() { 6346 New(v) 6347 } 6348 }) 6349} 6350 6351func TestSwapper(t *testing.T) { 6352 type I int 6353 var a, b, c I 6354 type pair struct { 6355 x, y int 6356 } 6357 type pairPtr struct { 6358 x, y int 6359 p *I 6360 } 6361 type S string 6362 6363 tests := []struct { 6364 in interface{} 6365 i, j int 6366 want interface{} 6367 }{ 6368 { 6369 in: []int{1, 20, 300}, 6370 i: 0, 6371 j: 2, 6372 want: []int{300, 20, 1}, 6373 }, 6374 { 6375 in: []uintptr{1, 20, 300}, 6376 i: 0, 6377 j: 2, 6378 want: []uintptr{300, 20, 1}, 6379 }, 6380 { 6381 in: []int16{1, 20, 300}, 6382 i: 0, 6383 j: 2, 6384 want: []int16{300, 20, 1}, 6385 }, 6386 { 6387 in: []int8{1, 20, 100}, 6388 i: 0, 6389 j: 2, 6390 want: []int8{100, 20, 1}, 6391 }, 6392 { 6393 in: []*I{&a, &b, &c}, 6394 i: 0, 6395 j: 2, 6396 want: []*I{&c, &b, &a}, 6397 }, 6398 { 6399 in: []string{"eric", "sergey", "larry"}, 6400 i: 0, 6401 j: 2, 6402 want: []string{"larry", "sergey", "eric"}, 6403 }, 6404 { 6405 in: []S{"eric", "sergey", "larry"}, 6406 i: 0, 6407 j: 2, 6408 want: []S{"larry", "sergey", "eric"}, 6409 }, 6410 { 6411 in: []pair{{1, 2}, {3, 4}, {5, 6}}, 6412 i: 0, 6413 j: 2, 6414 want: []pair{{5, 6}, {3, 4}, {1, 2}}, 6415 }, 6416 { 6417 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}}, 6418 i: 0, 6419 j: 2, 6420 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}}, 6421 }, 6422 } 6423 6424 for i, tt := range tests { 6425 inStr := fmt.Sprint(tt.in) 6426 Swapper(tt.in)(tt.i, tt.j) 6427 if !DeepEqual(tt.in, tt.want) { 6428 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want) 6429 } 6430 } 6431} 6432 6433// TestUnaddressableField tests that the reflect package will not allow 6434// a type from another package to be used as a named type with an 6435// unexported field. 6436// 6437// This ensures that unexported fields cannot be modified by other packages. 6438func TestUnaddressableField(t *testing.T) { 6439 var b Buffer // type defined in reflect, a different package 6440 var localBuffer struct { 6441 buf []byte 6442 } 6443 lv := ValueOf(&localBuffer).Elem() 6444 rv := ValueOf(b) 6445 shouldPanic(func() { 6446 lv.Set(rv) 6447 }) 6448} 6449 6450type Tint int 6451 6452type Tint2 = Tint 6453 6454type Talias1 struct { 6455 byte 6456 uint8 6457 int 6458 int32 6459 rune 6460} 6461 6462type Talias2 struct { 6463 Tint 6464 Tint2 6465} 6466 6467func TestAliasNames(t *testing.T) { 6468 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5} 6469 out := fmt.Sprintf("%#v", t1) 6470 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}" 6471 if out != want { 6472 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want) 6473 } 6474 6475 t2 := Talias2{Tint: 1, Tint2: 2} 6476 out = fmt.Sprintf("%#v", t2) 6477 want = "reflect_test.Talias2{Tint:1, Tint2:2}" 6478 if out != want { 6479 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want) 6480 } 6481} 6482 6483func TestIssue22031(t *testing.T) { 6484 type s []struct{ C int } 6485 6486 type t1 struct{ s } 6487 type t2 struct{ f s } 6488 6489 tests := []Value{ 6490 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0), 6491 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0), 6492 } 6493 6494 for i, test := range tests { 6495 if test.CanSet() { 6496 t.Errorf("%d: CanSet: got true, want false", i) 6497 } 6498 } 6499} 6500 6501type NonExportedFirst int 6502 6503func (i NonExportedFirst) ΦExported() {} 6504func (i NonExportedFirst) nonexported() int { panic("wrong") } 6505 6506func TestIssue22073(t *testing.T) { 6507 m := ValueOf(NonExportedFirst(0)).Method(0) 6508 6509 if got := m.Type().NumOut(); got != 0 { 6510 t.Errorf("NumOut: got %v, want 0", got) 6511 } 6512 6513 // Shouldn't panic. 6514 m.Call(nil) 6515} 6516