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