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