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