1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package reflect 6 7import ( 8 "math" 9 "runtime" 10 "unsafe" 11) 12 13const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const 14 15// Value is the reflection interface to a Go value. 16// 17// Not all methods apply to all kinds of values. Restrictions, 18// if any, are noted in the documentation for each method. 19// Use the Kind method to find out the kind of value before 20// calling kind-specific methods. Calling a method 21// inappropriate to the kind of type causes a run time panic. 22// 23// The zero Value represents no value. 24// Its IsValid method returns false, its Kind method returns Invalid, 25// its String method returns "<invalid Value>", and all other methods panic. 26// Most functions and methods never return an invalid value. 27// If one does, its documentation states the conditions explicitly. 28// 29// A Value can be used concurrently by multiple goroutines provided that 30// the underlying Go value can be used concurrently for the equivalent 31// direct operations. 32// 33// To compare two Values, compare the results of the Interface method. 34// Using == on two Values does not compare the underlying values 35// they represent. 36type Value struct { 37 // typ holds the type of the value represented by a Value. 38 typ *rtype 39 40 // Pointer-valued data or, if flagIndir is set, pointer to data. 41 // Valid when either flagIndir is set or typ.pointers() is true. 42 ptr unsafe.Pointer 43 44 // flag holds metadata about the value. 45 // The lowest bits are flag bits: 46 // - flagStickyRO: obtained via unexported not embedded field, so read-only 47 // - flagEmbedRO: obtained via unexported embedded field, so read-only 48 // - flagIndir: val holds a pointer to the data 49 // - flagAddr: v.CanAddr is true (implies flagIndir) 50 // - flagMethod: v is a method value. 51 // The next five bits give the Kind of the value. 52 // This repeats typ.Kind() except for method values. 53 // The remaining 23+ bits give a method number for method values. 54 // If flag.kind() != Func, code can assume that flagMethod is unset. 55 // If ifaceIndir(typ), code can assume that flagIndir is set. 56 flag 57 58 // A method value represents a curried method invocation 59 // like r.Read for some receiver r. The typ+val+flag bits describe 60 // the receiver r, but the flag's Kind bits say Func (methods are 61 // functions), and the top bits of the flag give the method number 62 // in r's type's method table. 63} 64 65type flag uintptr 66 67const ( 68 flagKindWidth = 5 // there are 27 kinds 69 flagKindMask flag = 1<<flagKindWidth - 1 70 flagStickyRO flag = 1 << 5 71 flagEmbedRO flag = 1 << 6 72 flagIndir flag = 1 << 7 73 flagAddr flag = 1 << 8 74 flagMethod flag = 1 << 9 75 flagMethodFn flag = 1 << 10 // gccgo: first fn parameter is always pointer 76 flagMethodShift = 11 77 flagRO flag = flagStickyRO | flagEmbedRO 78) 79 80func (f flag) kind() Kind { 81 return Kind(f & flagKindMask) 82} 83 84func (f flag) ro() flag { 85 if f&flagRO != 0 { 86 return flagStickyRO 87 } 88 return 0 89} 90 91// pointer returns the underlying pointer represented by v. 92// v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer 93func (v Value) pointer() unsafe.Pointer { 94 if v.typ.size != ptrSize || !v.typ.pointers() { 95 panic("can't call pointer on a non-pointer Value") 96 } 97 if v.flag&flagIndir != 0 { 98 return *(*unsafe.Pointer)(v.ptr) 99 } 100 return v.ptr 101} 102 103// packEface converts v to the empty interface. 104func packEface(v Value) interface{} { 105 t := v.typ 106 var i interface{} 107 e := (*emptyInterface)(unsafe.Pointer(&i)) 108 // First, fill in the data portion of the interface. 109 switch { 110 case ifaceIndir(t): 111 if v.flag&flagIndir == 0 { 112 panic("bad indir") 113 } 114 // Value is indirect, and so is the interface we're making. 115 ptr := v.ptr 116 if v.flag&flagAddr != 0 { 117 // TODO: pass safe boolean from valueInterface so 118 // we don't need to copy if safe==true? 119 c := unsafe_New(t) 120 typedmemmove(t, c, ptr) 121 ptr = c 122 } 123 e.word = ptr 124 case v.flag&flagIndir != 0: 125 // Value is indirect, but interface is direct. We need 126 // to load the data at v.ptr into the interface data word. 127 e.word = *(*unsafe.Pointer)(v.ptr) 128 default: 129 // Value is direct, and so is the interface. 130 e.word = v.ptr 131 } 132 // Now, fill in the type portion. We're very careful here not 133 // to have any operation between the e.word and e.typ assignments 134 // that would let the garbage collector observe the partially-built 135 // interface value. 136 e.typ = t 137 return i 138} 139 140// unpackEface converts the empty interface i to a Value. 141func unpackEface(i interface{}) Value { 142 e := (*emptyInterface)(unsafe.Pointer(&i)) 143 // NOTE: don't read e.word until we know whether it is really a pointer or not. 144 t := e.typ 145 if t == nil { 146 return Value{} 147 } 148 f := flag(t.Kind()) 149 if ifaceIndir(t) { 150 f |= flagIndir 151 } 152 return Value{t, e.word, f} 153} 154 155// A ValueError occurs when a Value method is invoked on 156// a Value that does not support it. Such cases are documented 157// in the description of each method. 158type ValueError struct { 159 Method string 160 Kind Kind 161} 162 163func (e *ValueError) Error() string { 164 if e.Kind == 0 { 165 return "reflect: call of " + e.Method + " on zero Value" 166 } 167 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value" 168} 169 170// methodName returns the name of the calling method, 171// assumed to be two stack frames above. 172func methodName() string { 173 pc, _, _, _ := runtime.Caller(2) 174 f := runtime.FuncForPC(pc) 175 if f == nil { 176 return "unknown method" 177 } 178 return f.Name() 179} 180 181// emptyInterface is the header for an interface{} value. 182type emptyInterface struct { 183 typ *rtype 184 word unsafe.Pointer 185} 186 187// nonEmptyInterface is the header for an interface value with methods. 188type nonEmptyInterface struct { 189 // see ../runtime/iface.go:/Itab 190 itab *struct { 191 typ *rtype // dynamic concrete type 192 fun [100000]unsafe.Pointer // method table 193 } 194 word unsafe.Pointer 195} 196 197// mustBe panics if f's kind is not expected. 198// Making this a method on flag instead of on Value 199// (and embedding flag in Value) means that we can write 200// the very clear v.mustBe(Bool) and have it compile into 201// v.flag.mustBe(Bool), which will only bother to copy the 202// single important word for the receiver. 203func (f flag) mustBe(expected Kind) { 204 // TODO(mvdan): use f.kind() again once mid-stack inlining gets better 205 if Kind(f&flagKindMask) != expected { 206 panic(&ValueError{methodName(), f.kind()}) 207 } 208} 209 210// mustBeExported panics if f records that the value was obtained using 211// an unexported field. 212func (f flag) mustBeExported() { 213 if f == 0 || f&flagRO != 0 { 214 f.mustBeExportedSlow() 215 } 216} 217 218func (f flag) mustBeExportedSlow() { 219 if f == 0 { 220 panic(&ValueError{methodName(), Invalid}) 221 } 222 if f&flagRO != 0 { 223 panic("reflect: " + methodName() + " using value obtained using unexported field") 224 } 225} 226 227// mustBeAssignable panics if f records that the value is not assignable, 228// which is to say that either it was obtained using an unexported field 229// or it is not addressable. 230func (f flag) mustBeAssignable() { 231 if f&flagRO != 0 || f&flagAddr == 0 { 232 f.mustBeAssignableSlow() 233 } 234} 235 236func (f flag) mustBeAssignableSlow() { 237 if f == 0 { 238 panic(&ValueError{methodName(), Invalid}) 239 } 240 // Assignable if addressable and not read-only. 241 if f&flagRO != 0 { 242 panic("reflect: " + methodName() + " using value obtained using unexported field") 243 } 244 if f&flagAddr == 0 { 245 panic("reflect: " + methodName() + " using unaddressable value") 246 } 247} 248 249// Addr returns a pointer value representing the address of v. 250// It panics if CanAddr() returns false. 251// Addr is typically used to obtain a pointer to a struct field 252// or slice element in order to call a method that requires a 253// pointer receiver. 254func (v Value) Addr() Value { 255 if v.flag&flagAddr == 0 { 256 panic("reflect.Value.Addr of unaddressable value") 257 } 258 return Value{v.typ.ptrTo(), v.ptr, v.flag.ro() | flag(Ptr)} 259} 260 261// Bool returns v's underlying value. 262// It panics if v's kind is not Bool. 263func (v Value) Bool() bool { 264 v.mustBe(Bool) 265 return *(*bool)(v.ptr) 266} 267 268// Bytes returns v's underlying value. 269// It panics if v's underlying value is not a slice of bytes. 270func (v Value) Bytes() []byte { 271 v.mustBe(Slice) 272 if v.typ.Elem().Kind() != Uint8 { 273 panic("reflect.Value.Bytes of non-byte slice") 274 } 275 // Slice is always bigger than a word; assume flagIndir. 276 return *(*[]byte)(v.ptr) 277} 278 279// runes returns v's underlying value. 280// It panics if v's underlying value is not a slice of runes (int32s). 281func (v Value) runes() []rune { 282 v.mustBe(Slice) 283 if v.typ.Elem().Kind() != Int32 { 284 panic("reflect.Value.Bytes of non-rune slice") 285 } 286 // Slice is always bigger than a word; assume flagIndir. 287 return *(*[]rune)(v.ptr) 288} 289 290// CanAddr reports whether the value's address can be obtained with Addr. 291// Such values are called addressable. A value is addressable if it is 292// an element of a slice, an element of an addressable array, 293// a field of an addressable struct, or the result of dereferencing a pointer. 294// If CanAddr returns false, calling Addr will panic. 295func (v Value) CanAddr() bool { 296 return v.flag&flagAddr != 0 297} 298 299// CanSet reports whether the value of v can be changed. 300// A Value can be changed only if it is addressable and was not 301// obtained by the use of unexported struct fields. 302// If CanSet returns false, calling Set or any type-specific 303// setter (e.g., SetBool, SetInt) will panic. 304func (v Value) CanSet() bool { 305 return v.flag&(flagAddr|flagRO) == flagAddr 306} 307 308// Call calls the function v with the input arguments in. 309// For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). 310// Call panics if v's Kind is not Func. 311// It returns the output results as Values. 312// As in Go, each input argument must be assignable to the 313// type of the function's corresponding input parameter. 314// If v is a variadic function, Call creates the variadic slice parameter 315// itself, copying in the corresponding values. 316func (v Value) Call(in []Value) []Value { 317 v.mustBe(Func) 318 v.mustBeExported() 319 return v.call("Call", in) 320} 321 322// CallSlice calls the variadic function v with the input arguments in, 323// assigning the slice in[len(in)-1] to v's final variadic argument. 324// For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...). 325// CallSlice panics if v's Kind is not Func or if v is not variadic. 326// It returns the output results as Values. 327// As in Go, each input argument must be assignable to the 328// type of the function's corresponding input parameter. 329func (v Value) CallSlice(in []Value) []Value { 330 v.mustBe(Func) 331 v.mustBeExported() 332 return v.call("CallSlice", in) 333} 334 335var callGC bool // for testing; see TestCallMethodJump 336 337func (v Value) call(op string, in []Value) []Value { 338 // Get function pointer, type. 339 t := (*funcType)(unsafe.Pointer(v.typ)) 340 var ( 341 fn unsafe.Pointer 342 rcvr Value 343 ) 344 if v.flag&flagMethod != 0 { 345 rcvr = v 346 _, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift) 347 } else if v.flag&flagIndir != 0 { 348 fn = *(*unsafe.Pointer)(v.ptr) 349 } else { 350 fn = v.ptr 351 } 352 353 if fn == nil { 354 panic("reflect.Value.Call: call of nil function") 355 } 356 357 isSlice := op == "CallSlice" 358 n := t.NumIn() 359 if isSlice { 360 if !t.IsVariadic() { 361 panic("reflect: CallSlice of non-variadic function") 362 } 363 if len(in) < n { 364 panic("reflect: CallSlice with too few input arguments") 365 } 366 if len(in) > n { 367 panic("reflect: CallSlice with too many input arguments") 368 } 369 } else { 370 if t.IsVariadic() { 371 n-- 372 } 373 if len(in) < n { 374 panic("reflect: Call with too few input arguments") 375 } 376 if !t.IsVariadic() && len(in) > n { 377 panic("reflect: Call with too many input arguments") 378 } 379 } 380 for _, x := range in { 381 if x.Kind() == Invalid { 382 panic("reflect: " + op + " using zero Value argument") 383 } 384 } 385 for i := 0; i < n; i++ { 386 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) { 387 panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String()) 388 } 389 } 390 if !isSlice && t.IsVariadic() { 391 // prepare slice for remaining values 392 m := len(in) - n 393 slice := MakeSlice(t.In(n), m, m) 394 elem := t.In(n).Elem() 395 for i := 0; i < m; i++ { 396 x := in[n+i] 397 if xt := x.Type(); !xt.AssignableTo(elem) { 398 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op) 399 } 400 slice.Index(i).Set(x) 401 } 402 origIn := in 403 in = make([]Value, n+1) 404 copy(in[:n], origIn) 405 in[n] = slice 406 } 407 408 nin := len(in) 409 if nin != t.NumIn() { 410 panic("reflect.Value.Call: wrong argument count") 411 } 412 nout := t.NumOut() 413 414 if v.flag&flagMethod != 0 { 415 nin++ 416 } 417 firstPointer := len(in) > 0 && ifaceIndir(t.In(0).common()) && v.flag&flagMethodFn != 0 418 params := make([]unsafe.Pointer, nin) 419 off := 0 420 if v.flag&flagMethod != 0 { 421 // Hard-wired first argument. 422 p := new(unsafe.Pointer) 423 if rcvr.typ.Kind() == Interface { 424 *p = unsafe.Pointer((*nonEmptyInterface)(v.ptr).word) 425 } else if rcvr.typ.Kind() == Ptr || rcvr.typ.Kind() == UnsafePointer { 426 *p = rcvr.pointer() 427 } else { 428 *p = rcvr.ptr 429 } 430 params[0] = unsafe.Pointer(p) 431 off = 1 432 } 433 for i, pv := range in { 434 pv.mustBeExported() 435 targ := t.In(i).(*rtype) 436 pv = pv.assignTo("reflect.Value.Call", targ, nil) 437 if pv.flag&flagIndir == 0 { 438 p := new(unsafe.Pointer) 439 *p = pv.ptr 440 params[off] = unsafe.Pointer(p) 441 } else { 442 params[off] = pv.ptr 443 } 444 if i == 0 && firstPointer { 445 p := new(unsafe.Pointer) 446 *p = params[off] 447 params[off] = unsafe.Pointer(p) 448 } 449 off++ 450 } 451 452 ret := make([]Value, nout) 453 results := make([]unsafe.Pointer, nout) 454 for i := 0; i < nout; i++ { 455 tv := t.Out(i) 456 v := New(tv) 457 results[i] = v.pointer() 458 fl := flagIndir | flag(tv.Kind()) 459 ret[i] = Value{tv.common(), v.pointer(), fl} 460 } 461 462 var pp *unsafe.Pointer 463 if len(params) > 0 { 464 pp = ¶ms[0] 465 } 466 var pr *unsafe.Pointer 467 if len(results) > 0 { 468 pr = &results[0] 469 } 470 471 call(t, fn, v.flag&flagMethod != 0, firstPointer, pp, pr) 472 473 // For testing; see TestCallMethodJump. 474 if callGC { 475 runtime.GC() 476 } 477 478 return ret 479} 480 481// methodReceiver returns information about the receiver 482// described by v. The Value v may or may not have the 483// flagMethod bit set, so the kind cached in v.flag should 484// not be used. 485// The return value rcvrtype gives the method's actual receiver type. 486// The return value t gives the method type signature (without the receiver). 487// The return value fn is a pointer to the method code. 488func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *rtype, t *funcType, fn unsafe.Pointer) { 489 i := methodIndex 490 if v.typ.Kind() == Interface { 491 tt := (*interfaceType)(unsafe.Pointer(v.typ)) 492 if uint(i) >= uint(len(tt.methods)) { 493 panic("reflect: internal error: invalid method index") 494 } 495 m := &tt.methods[i] 496 if m.pkgPath != nil { 497 panic("reflect: " + op + " of unexported method") 498 } 499 iface := (*nonEmptyInterface)(v.ptr) 500 if iface.itab == nil { 501 panic("reflect: " + op + " of method on nil interface value") 502 } 503 rcvrtype = iface.itab.typ 504 fn = unsafe.Pointer(&iface.itab.fun[i]) 505 t = (*funcType)(unsafe.Pointer(m.typ)) 506 } else { 507 rcvrtype = v.typ 508 ms := v.typ.exportedMethods() 509 if uint(i) >= uint(len(ms)) { 510 panic("reflect: internal error: invalid method index") 511 } 512 m := ms[i] 513 if m.pkgPath != nil { 514 panic("reflect: " + op + " of unexported method") 515 } 516 fn = unsafe.Pointer(&m.tfn) 517 t = (*funcType)(unsafe.Pointer(m.mtyp)) 518 } 519 return 520} 521 522// v is a method receiver. Store at p the word which is used to 523// encode that receiver at the start of the argument list. 524// Reflect uses the "interface" calling convention for 525// methods, which always uses one word to record the receiver. 526func storeRcvr(v Value, p unsafe.Pointer) { 527 t := v.typ 528 if t.Kind() == Interface { 529 // the interface data word becomes the receiver word 530 iface := (*nonEmptyInterface)(v.ptr) 531 *(*unsafe.Pointer)(p) = iface.word 532 } else if v.flag&flagIndir != 0 && !ifaceIndir(t) { 533 *(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr) 534 } else { 535 *(*unsafe.Pointer)(p) = v.ptr 536 } 537} 538 539// align returns the result of rounding x up to a multiple of n. 540// n must be a power of two. 541func align(x, n uintptr) uintptr { 542 return (x + n - 1) &^ (n - 1) 543} 544 545// funcName returns the name of f, for use in error messages. 546func funcName(f func([]Value) []Value) string { 547 pc := *(*uintptr)(unsafe.Pointer(&f)) 548 rf := runtime.FuncForPC(pc) 549 if rf != nil { 550 return rf.Name() 551 } 552 return "closure" 553} 554 555// Cap returns v's capacity. 556// It panics if v's Kind is not Array, Chan, or Slice. 557func (v Value) Cap() int { 558 k := v.kind() 559 switch k { 560 case Array: 561 return v.typ.Len() 562 case Chan: 563 return chancap(v.pointer()) 564 case Slice: 565 // Slice is always bigger than a word; assume flagIndir. 566 return (*sliceHeader)(v.ptr).Cap 567 } 568 panic(&ValueError{"reflect.Value.Cap", v.kind()}) 569} 570 571// Close closes the channel v. 572// It panics if v's Kind is not Chan. 573func (v Value) Close() { 574 v.mustBe(Chan) 575 v.mustBeExported() 576 chanclose(v.pointer()) 577} 578 579// Complex returns v's underlying value, as a complex128. 580// It panics if v's Kind is not Complex64 or Complex128 581func (v Value) Complex() complex128 { 582 k := v.kind() 583 switch k { 584 case Complex64: 585 return complex128(*(*complex64)(v.ptr)) 586 case Complex128: 587 return *(*complex128)(v.ptr) 588 } 589 panic(&ValueError{"reflect.Value.Complex", v.kind()}) 590} 591 592// Elem returns the value that the interface v contains 593// or that the pointer v points to. 594// It panics if v's Kind is not Interface or Ptr. 595// It returns the zero Value if v is nil. 596func (v Value) Elem() Value { 597 k := v.kind() 598 switch k { 599 case Interface: 600 var eface interface{} 601 if v.typ.NumMethod() == 0 { 602 eface = *(*interface{})(v.ptr) 603 } else { 604 eface = (interface{})(*(*interface { 605 M() 606 })(v.ptr)) 607 } 608 x := unpackEface(eface) 609 if x.flag != 0 { 610 x.flag |= v.flag.ro() 611 } 612 return x 613 case Ptr: 614 ptr := v.ptr 615 if v.flag&flagIndir != 0 { 616 ptr = *(*unsafe.Pointer)(ptr) 617 } 618 // The returned value's address is v's value. 619 if ptr == nil { 620 return Value{} 621 } 622 tt := (*ptrType)(unsafe.Pointer(v.typ)) 623 typ := tt.elem 624 fl := v.flag&flagRO | flagIndir | flagAddr 625 fl |= flag(typ.Kind()) 626 return Value{typ, ptr, fl} 627 } 628 panic(&ValueError{"reflect.Value.Elem", v.kind()}) 629} 630 631// Field returns the i'th field of the struct v. 632// It panics if v's Kind is not Struct or i is out of range. 633func (v Value) Field(i int) Value { 634 if v.kind() != Struct { 635 panic(&ValueError{"reflect.Value.Field", v.kind()}) 636 } 637 tt := (*structType)(unsafe.Pointer(v.typ)) 638 if uint(i) >= uint(len(tt.fields)) { 639 panic("reflect: Field index out of range") 640 } 641 field := &tt.fields[i] 642 typ := field.typ 643 644 // Inherit permission bits from v, but clear flagEmbedRO. 645 fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind()) 646 // Using an unexported field forces flagRO. 647 if field.pkgPath != nil { 648 if field.embedded() { 649 fl |= flagEmbedRO 650 } else { 651 fl |= flagStickyRO 652 } 653 } 654 // Either flagIndir is set and v.ptr points at struct, 655 // or flagIndir is not set and v.ptr is the actual struct data. 656 // In the former case, we want v.ptr + offset. 657 // In the latter case, we must have field.offset = 0, 658 // so v.ptr + field.offset is still the correct address. 659 ptr := add(v.ptr, field.offset(), "same as non-reflect &v.field") 660 return Value{typ, ptr, fl} 661} 662 663// FieldByIndex returns the nested field corresponding to index. 664// It panics if v's Kind is not struct. 665func (v Value) FieldByIndex(index []int) Value { 666 if len(index) == 1 { 667 return v.Field(index[0]) 668 } 669 v.mustBe(Struct) 670 for i, x := range index { 671 if i > 0 { 672 if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct { 673 if v.IsNil() { 674 panic("reflect: indirection through nil pointer to embedded struct") 675 } 676 v = v.Elem() 677 } 678 } 679 v = v.Field(x) 680 } 681 return v 682} 683 684// FieldByName returns the struct field with the given name. 685// It returns the zero Value if no field was found. 686// It panics if v's Kind is not struct. 687func (v Value) FieldByName(name string) Value { 688 v.mustBe(Struct) 689 if f, ok := v.typ.FieldByName(name); ok { 690 return v.FieldByIndex(f.Index) 691 } 692 return Value{} 693} 694 695// FieldByNameFunc returns the struct field with a name 696// that satisfies the match function. 697// It panics if v's Kind is not struct. 698// It returns the zero Value if no field was found. 699func (v Value) FieldByNameFunc(match func(string) bool) Value { 700 if f, ok := v.typ.FieldByNameFunc(match); ok { 701 return v.FieldByIndex(f.Index) 702 } 703 return Value{} 704} 705 706// Float returns v's underlying value, as a float64. 707// It panics if v's Kind is not Float32 or Float64 708func (v Value) Float() float64 { 709 k := v.kind() 710 switch k { 711 case Float32: 712 return float64(*(*float32)(v.ptr)) 713 case Float64: 714 return *(*float64)(v.ptr) 715 } 716 panic(&ValueError{"reflect.Value.Float", v.kind()}) 717} 718 719var uint8Type = TypeOf(uint8(0)).(*rtype) 720 721// Index returns v's i'th element. 722// It panics if v's Kind is not Array, Slice, or String or i is out of range. 723func (v Value) Index(i int) Value { 724 switch v.kind() { 725 case Array: 726 tt := (*arrayType)(unsafe.Pointer(v.typ)) 727 if uint(i) >= uint(tt.len) { 728 panic("reflect: array index out of range") 729 } 730 typ := tt.elem 731 offset := uintptr(i) * typ.size 732 733 // Either flagIndir is set and v.ptr points at array, 734 // or flagIndir is not set and v.ptr is the actual array data. 735 // In the former case, we want v.ptr + offset. 736 // In the latter case, we must be doing Index(0), so offset = 0, 737 // so v.ptr + offset is still the correct address. 738 val := add(v.ptr, offset, "same as &v[i], i < tt.len") 739 fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array 740 return Value{typ, val, fl} 741 742 case Slice: 743 // Element flag same as Elem of Ptr. 744 // Addressable, indirect, possibly read-only. 745 s := (*sliceHeader)(v.ptr) 746 if uint(i) >= uint(s.Len) { 747 panic("reflect: slice index out of range") 748 } 749 tt := (*sliceType)(unsafe.Pointer(v.typ)) 750 typ := tt.elem 751 val := arrayAt(s.Data, i, typ.size, "i < s.Len") 752 fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind()) 753 return Value{typ, val, fl} 754 755 case String: 756 s := (*stringHeader)(v.ptr) 757 if uint(i) >= uint(s.Len) { 758 panic("reflect: string index out of range") 759 } 760 p := arrayAt(s.Data, i, 1, "i < s.Len") 761 fl := v.flag.ro() | flag(Uint8) | flagIndir 762 return Value{uint8Type, p, fl} 763 } 764 panic(&ValueError{"reflect.Value.Index", v.kind()}) 765} 766 767// Int returns v's underlying value, as an int64. 768// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64. 769func (v Value) Int() int64 { 770 k := v.kind() 771 p := v.ptr 772 switch k { 773 case Int: 774 return int64(*(*int)(p)) 775 case Int8: 776 return int64(*(*int8)(p)) 777 case Int16: 778 return int64(*(*int16)(p)) 779 case Int32: 780 return int64(*(*int32)(p)) 781 case Int64: 782 return *(*int64)(p) 783 } 784 panic(&ValueError{"reflect.Value.Int", v.kind()}) 785} 786 787// CanInterface reports whether Interface can be used without panicking. 788func (v Value) CanInterface() bool { 789 if v.flag == 0 { 790 panic(&ValueError{"reflect.Value.CanInterface", Invalid}) 791 } 792 return v.flag&flagRO == 0 793} 794 795// Interface returns v's current value as an interface{}. 796// It is equivalent to: 797// var i interface{} = (v's underlying value) 798// It panics if the Value was obtained by accessing 799// unexported struct fields. 800func (v Value) Interface() (i interface{}) { 801 return valueInterface(v, true) 802} 803 804func valueInterface(v Value, safe bool) interface{} { 805 if v.flag == 0 { 806 panic(&ValueError{"reflect.Value.Interface", Invalid}) 807 } 808 if safe && v.flag&flagRO != 0 { 809 // Do not allow access to unexported values via Interface, 810 // because they might be pointers that should not be 811 // writable or methods or function that should not be callable. 812 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method") 813 } 814 if v.flag&flagMethod != 0 { 815 v = makeMethodValue("Interface", v) 816 } 817 818 if v.flag&flagMethodFn != 0 { 819 if v.typ.Kind() != Func { 820 panic("reflect: MethodFn of non-Func") 821 } 822 ft := (*funcType)(unsafe.Pointer(v.typ)) 823 if ft.in[0].Kind() != Ptr { 824 v = makeValueMethod(v) 825 } 826 } 827 828 if v.kind() == Interface { 829 // Special case: return the element inside the interface. 830 // Empty interface has one layout, all interfaces with 831 // methods have a second layout. 832 if v.NumMethod() == 0 { 833 return *(*interface{})(v.ptr) 834 } 835 return *(*interface { 836 M() 837 })(v.ptr) 838 } 839 840 // TODO: pass safe to packEface so we don't need to copy if safe==true? 841 return packEface(v) 842} 843 844// InterfaceData returns the interface v's value as a uintptr pair. 845// It panics if v's Kind is not Interface. 846func (v Value) InterfaceData() [2]uintptr { 847 // TODO: deprecate this 848 v.mustBe(Interface) 849 // We treat this as a read operation, so we allow 850 // it even for unexported data, because the caller 851 // has to import "unsafe" to turn it into something 852 // that can be abused. 853 // Interface value is always bigger than a word; assume flagIndir. 854 return *(*[2]uintptr)(v.ptr) 855} 856 857// IsNil reports whether its argument v is nil. The argument must be 858// a chan, func, interface, map, pointer, or slice value; if it is 859// not, IsNil panics. Note that IsNil is not always equivalent to a 860// regular comparison with nil in Go. For example, if v was created 861// by calling ValueOf with an uninitialized interface variable i, 862// i==nil will be true but v.IsNil will panic as v will be the zero 863// Value. 864func (v Value) IsNil() bool { 865 k := v.kind() 866 switch k { 867 case Chan, Func, Map, Ptr, UnsafePointer: 868 if v.flag&flagMethod != 0 { 869 return false 870 } 871 ptr := v.ptr 872 if v.flag&flagIndir != 0 { 873 ptr = *(*unsafe.Pointer)(ptr) 874 } 875 return ptr == nil 876 case Interface, Slice: 877 // Both interface and slice are nil if first word is 0. 878 // Both are always bigger than a word; assume flagIndir. 879 return *(*unsafe.Pointer)(v.ptr) == nil 880 } 881 panic(&ValueError{"reflect.Value.IsNil", v.kind()}) 882} 883 884// IsValid reports whether v represents a value. 885// It returns false if v is the zero Value. 886// If IsValid returns false, all other methods except String panic. 887// Most functions and methods never return an invalid Value. 888// If one does, its documentation states the conditions explicitly. 889func (v Value) IsValid() bool { 890 return v.flag != 0 891} 892 893// IsZero reports whether v is the zero value for its type. 894// It panics if the argument is invalid. 895func (v Value) IsZero() bool { 896 switch v.kind() { 897 case Bool: 898 return !v.Bool() 899 case Int, Int8, Int16, Int32, Int64: 900 return v.Int() == 0 901 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 902 return v.Uint() == 0 903 case Float32, Float64: 904 return math.Float64bits(v.Float()) == 0 905 case Complex64, Complex128: 906 c := v.Complex() 907 return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0 908 case Array: 909 for i := 0; i < v.Len(); i++ { 910 if !v.Index(i).IsZero() { 911 return false 912 } 913 } 914 return true 915 case Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer: 916 return v.IsNil() 917 case String: 918 return v.Len() == 0 919 case Struct: 920 for i := 0; i < v.NumField(); i++ { 921 if !v.Field(i).IsZero() { 922 return false 923 } 924 } 925 return true 926 default: 927 // This should never happens, but will act as a safeguard for 928 // later, as a default value doesn't makes sense here. 929 panic(&ValueError{"reflect.Value.IsZero", v.Kind()}) 930 } 931} 932 933// Kind returns v's Kind. 934// If v is the zero Value (IsValid returns false), Kind returns Invalid. 935func (v Value) Kind() Kind { 936 return v.kind() 937} 938 939// Len returns v's length. 940// It panics if v's Kind is not Array, Chan, Map, Slice, or String. 941func (v Value) Len() int { 942 k := v.kind() 943 switch k { 944 case Array: 945 tt := (*arrayType)(unsafe.Pointer(v.typ)) 946 return int(tt.len) 947 case Chan: 948 return chanlen(v.pointer()) 949 case Map: 950 return maplen(v.pointer()) 951 case Slice: 952 // Slice is bigger than a word; assume flagIndir. 953 return (*sliceHeader)(v.ptr).Len 954 case String: 955 // String is bigger than a word; assume flagIndir. 956 return (*stringHeader)(v.ptr).Len 957 } 958 panic(&ValueError{"reflect.Value.Len", v.kind()}) 959} 960 961// MapIndex returns the value associated with key in the map v. 962// It panics if v's Kind is not Map. 963// It returns the zero Value if key is not found in the map or if v represents a nil map. 964// As in Go, the key's value must be assignable to the map's key type. 965func (v Value) MapIndex(key Value) Value { 966 v.mustBe(Map) 967 tt := (*mapType)(unsafe.Pointer(v.typ)) 968 969 // Do not require key to be exported, so that DeepEqual 970 // and other programs can use all the keys returned by 971 // MapKeys as arguments to MapIndex. If either the map 972 // or the key is unexported, though, the result will be 973 // considered unexported. This is consistent with the 974 // behavior for structs, which allow read but not write 975 // of unexported fields. 976 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil) 977 978 var k unsafe.Pointer 979 if key.flag&flagIndir != 0 { 980 k = key.ptr 981 } else { 982 k = unsafe.Pointer(&key.ptr) 983 } 984 e := mapaccess(v.typ, v.pointer(), k) 985 if e == nil { 986 return Value{} 987 } 988 typ := tt.elem 989 fl := (v.flag | key.flag).ro() 990 fl |= flag(typ.Kind()) 991 return copyVal(typ, fl, e) 992} 993 994// MapKeys returns a slice containing all the keys present in the map, 995// in unspecified order. 996// It panics if v's Kind is not Map. 997// It returns an empty slice if v represents a nil map. 998func (v Value) MapKeys() []Value { 999 v.mustBe(Map) 1000 tt := (*mapType)(unsafe.Pointer(v.typ)) 1001 keyType := tt.key 1002 1003 fl := v.flag.ro() | flag(keyType.Kind()) 1004 1005 m := v.pointer() 1006 mlen := int(0) 1007 if m != nil { 1008 mlen = maplen(m) 1009 } 1010 it := mapiterinit(v.typ, m) 1011 a := make([]Value, mlen) 1012 var i int 1013 for i = 0; i < len(a); i++ { 1014 key := mapiterkey(it) 1015 if key == nil { 1016 // Someone deleted an entry from the map since we 1017 // called maplen above. It's a data race, but nothing 1018 // we can do about it. 1019 break 1020 } 1021 a[i] = copyVal(keyType, fl, key) 1022 mapiternext(it) 1023 } 1024 return a[:i] 1025} 1026 1027// A MapIter is an iterator for ranging over a map. 1028// See Value.MapRange. 1029type MapIter struct { 1030 m Value 1031 it unsafe.Pointer 1032} 1033 1034// Key returns the key of the iterator's current map entry. 1035func (it *MapIter) Key() Value { 1036 if it.it == nil { 1037 panic("MapIter.Key called before Next") 1038 } 1039 if mapiterkey(it.it) == nil { 1040 panic("MapIter.Key called on exhausted iterator") 1041 } 1042 1043 t := (*mapType)(unsafe.Pointer(it.m.typ)) 1044 ktype := t.key 1045 return copyVal(ktype, it.m.flag.ro()|flag(ktype.Kind()), mapiterkey(it.it)) 1046} 1047 1048// Value returns the value of the iterator's current map entry. 1049func (it *MapIter) Value() Value { 1050 if it.it == nil { 1051 panic("MapIter.Value called before Next") 1052 } 1053 if mapiterkey(it.it) == nil { 1054 panic("MapIter.Value called on exhausted iterator") 1055 } 1056 1057 t := (*mapType)(unsafe.Pointer(it.m.typ)) 1058 vtype := t.elem 1059 return copyVal(vtype, it.m.flag.ro()|flag(vtype.Kind()), mapiterelem(it.it)) 1060} 1061 1062// Next advances the map iterator and reports whether there is another 1063// entry. It returns false when the iterator is exhausted; subsequent 1064// calls to Key, Value, or Next will panic. 1065func (it *MapIter) Next() bool { 1066 if it.it == nil { 1067 it.it = mapiterinit(it.m.typ, it.m.pointer()) 1068 } else { 1069 if mapiterkey(it.it) == nil { 1070 panic("MapIter.Next called on exhausted iterator") 1071 } 1072 mapiternext(it.it) 1073 } 1074 return mapiterkey(it.it) != nil 1075} 1076 1077// MapRange returns a range iterator for a map. 1078// It panics if v's Kind is not Map. 1079// 1080// Call Next to advance the iterator, and Key/Value to access each entry. 1081// Next returns false when the iterator is exhausted. 1082// MapRange follows the same iteration semantics as a range statement. 1083// 1084// Example: 1085// 1086// iter := reflect.ValueOf(m).MapRange() 1087// for iter.Next() { 1088// k := iter.Key() 1089// v := iter.Value() 1090// ... 1091// } 1092// 1093func (v Value) MapRange() *MapIter { 1094 v.mustBe(Map) 1095 return &MapIter{m: v} 1096} 1097 1098// copyVal returns a Value containing the map key or value at ptr, 1099// allocating a new variable as needed. 1100func copyVal(typ *rtype, fl flag, ptr unsafe.Pointer) Value { 1101 if ifaceIndir(typ) { 1102 // Copy result so future changes to the map 1103 // won't change the underlying value. 1104 c := unsafe_New(typ) 1105 typedmemmove(typ, c, ptr) 1106 return Value{typ, c, fl | flagIndir} 1107 } 1108 return Value{typ, *(*unsafe.Pointer)(ptr), fl} 1109} 1110 1111// Method returns a function value corresponding to v's i'th method. 1112// The arguments to a Call on the returned function should not include 1113// a receiver; the returned function will always use v as the receiver. 1114// Method panics if i is out of range or if v is a nil interface value. 1115func (v Value) Method(i int) Value { 1116 if v.typ == nil { 1117 panic(&ValueError{"reflect.Value.Method", Invalid}) 1118 } 1119 if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) { 1120 panic("reflect: Method index out of range") 1121 } 1122 if v.typ.Kind() == Interface && v.IsNil() { 1123 panic("reflect: Method on nil interface value") 1124 } 1125 fl := v.flag & (flagStickyRO | flagIndir) // Clear flagEmbedRO 1126 fl |= flag(Func) 1127 fl |= flag(i)<<flagMethodShift | flagMethod 1128 return Value{v.typ, v.ptr, fl} 1129} 1130 1131// NumMethod returns the number of exported methods in the value's method set. 1132func (v Value) NumMethod() int { 1133 if v.typ == nil { 1134 panic(&ValueError{"reflect.Value.NumMethod", Invalid}) 1135 } 1136 if v.flag&flagMethod != 0 { 1137 return 0 1138 } 1139 return v.typ.NumMethod() 1140} 1141 1142// MethodByName returns a function value corresponding to the method 1143// of v with the given name. 1144// The arguments to a Call on the returned function should not include 1145// a receiver; the returned function will always use v as the receiver. 1146// It returns the zero Value if no method was found. 1147func (v Value) MethodByName(name string) Value { 1148 if v.typ == nil { 1149 panic(&ValueError{"reflect.Value.MethodByName", Invalid}) 1150 } 1151 if v.flag&flagMethod != 0 { 1152 return Value{} 1153 } 1154 m, ok := v.typ.MethodByName(name) 1155 if !ok { 1156 return Value{} 1157 } 1158 return v.Method(m.Index) 1159} 1160 1161// NumField returns the number of fields in the struct v. 1162// It panics if v's Kind is not Struct. 1163func (v Value) NumField() int { 1164 v.mustBe(Struct) 1165 tt := (*structType)(unsafe.Pointer(v.typ)) 1166 return len(tt.fields) 1167} 1168 1169// OverflowComplex reports whether the complex128 x cannot be represented by v's type. 1170// It panics if v's Kind is not Complex64 or Complex128. 1171func (v Value) OverflowComplex(x complex128) bool { 1172 k := v.kind() 1173 switch k { 1174 case Complex64: 1175 return overflowFloat32(real(x)) || overflowFloat32(imag(x)) 1176 case Complex128: 1177 return false 1178 } 1179 panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()}) 1180} 1181 1182// OverflowFloat reports whether the float64 x cannot be represented by v's type. 1183// It panics if v's Kind is not Float32 or Float64. 1184func (v Value) OverflowFloat(x float64) bool { 1185 k := v.kind() 1186 switch k { 1187 case Float32: 1188 return overflowFloat32(x) 1189 case Float64: 1190 return false 1191 } 1192 panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()}) 1193} 1194 1195func overflowFloat32(x float64) bool { 1196 if x < 0 { 1197 x = -x 1198 } 1199 return math.MaxFloat32 < x && x <= math.MaxFloat64 1200} 1201 1202// OverflowInt reports whether the int64 x cannot be represented by v's type. 1203// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64. 1204func (v Value) OverflowInt(x int64) bool { 1205 k := v.kind() 1206 switch k { 1207 case Int, Int8, Int16, Int32, Int64: 1208 bitSize := v.typ.size * 8 1209 trunc := (x << (64 - bitSize)) >> (64 - bitSize) 1210 return x != trunc 1211 } 1212 panic(&ValueError{"reflect.Value.OverflowInt", v.kind()}) 1213} 1214 1215// OverflowUint reports whether the uint64 x cannot be represented by v's type. 1216// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. 1217func (v Value) OverflowUint(x uint64) bool { 1218 k := v.kind() 1219 switch k { 1220 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64: 1221 bitSize := v.typ.size * 8 1222 trunc := (x << (64 - bitSize)) >> (64 - bitSize) 1223 return x != trunc 1224 } 1225 panic(&ValueError{"reflect.Value.OverflowUint", v.kind()}) 1226} 1227 1228//go:nocheckptr 1229// This prevents inlining Value.Pointer when -d=checkptr is enabled, 1230// which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer()) 1231// and make an exception. 1232 1233// Pointer returns v's value as a uintptr. 1234// It returns uintptr instead of unsafe.Pointer so that 1235// code using reflect cannot obtain unsafe.Pointers 1236// without importing the unsafe package explicitly. 1237// It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer. 1238// 1239// If v's Kind is Func, the returned pointer is an underlying 1240// code pointer, but not necessarily enough to identify a 1241// single function uniquely. The only guarantee is that the 1242// result is zero if and only if v is a nil func Value. 1243// 1244// If v's Kind is Slice, the returned pointer is to the first 1245// element of the slice. If the slice is nil the returned value 1246// is 0. If the slice is empty but non-nil the return value is non-zero. 1247func (v Value) Pointer() uintptr { 1248 // TODO: deprecate 1249 k := v.kind() 1250 switch k { 1251 case Chan, Map, Ptr, UnsafePointer: 1252 return uintptr(v.pointer()) 1253 case Func: 1254 p := v.pointer() 1255 // Non-nil func value points at data block. 1256 // First word of data block is actual code. 1257 if p != nil { 1258 p = *(*unsafe.Pointer)(p) 1259 } 1260 return uintptr(p) 1261 1262 case Slice: 1263 return (*SliceHeader)(v.ptr).Data 1264 } 1265 panic(&ValueError{"reflect.Value.Pointer", v.kind()}) 1266} 1267 1268// Recv receives and returns a value from the channel v. 1269// It panics if v's Kind is not Chan. 1270// The receive blocks until a value is ready. 1271// The boolean value ok is true if the value x corresponds to a send 1272// on the channel, false if it is a zero value received because the channel is closed. 1273func (v Value) Recv() (x Value, ok bool) { 1274 v.mustBe(Chan) 1275 v.mustBeExported() 1276 return v.recv(false) 1277} 1278 1279// internal recv, possibly non-blocking (nb). 1280// v is known to be a channel. 1281func (v Value) recv(nb bool) (val Value, ok bool) { 1282 tt := (*chanType)(unsafe.Pointer(v.typ)) 1283 if ChanDir(tt.dir)&RecvDir == 0 { 1284 panic("reflect: recv on send-only channel") 1285 } 1286 t := tt.elem 1287 val = Value{t, nil, flag(t.Kind())} 1288 var p unsafe.Pointer 1289 if ifaceIndir(t) { 1290 p = unsafe_New(t) 1291 val.ptr = p 1292 val.flag |= flagIndir 1293 } else { 1294 p = unsafe.Pointer(&val.ptr) 1295 } 1296 selected, ok := chanrecv(v.pointer(), nb, p) 1297 if !selected { 1298 val = Value{} 1299 } 1300 return 1301} 1302 1303// Send sends x on the channel v. 1304// It panics if v's kind is not Chan or if x's type is not the same type as v's element type. 1305// As in Go, x's value must be assignable to the channel's element type. 1306func (v Value) Send(x Value) { 1307 v.mustBe(Chan) 1308 v.mustBeExported() 1309 v.send(x, false) 1310} 1311 1312// internal send, possibly non-blocking. 1313// v is known to be a channel. 1314func (v Value) send(x Value, nb bool) (selected bool) { 1315 tt := (*chanType)(unsafe.Pointer(v.typ)) 1316 if ChanDir(tt.dir)&SendDir == 0 { 1317 panic("reflect: send on recv-only channel") 1318 } 1319 x.mustBeExported() 1320 x = x.assignTo("reflect.Value.Send", tt.elem, nil) 1321 var p unsafe.Pointer 1322 if x.flag&flagIndir != 0 { 1323 p = x.ptr 1324 } else { 1325 p = unsafe.Pointer(&x.ptr) 1326 } 1327 return chansend(v.pointer(), p, nb) 1328} 1329 1330// Set assigns x to the value v. 1331// It panics if CanSet returns false. 1332// As in Go, x's value must be assignable to v's type. 1333func (v Value) Set(x Value) { 1334 v.mustBeAssignable() 1335 x.mustBeExported() // do not let unexported x leak 1336 var target unsafe.Pointer 1337 if v.kind() == Interface { 1338 target = v.ptr 1339 } 1340 x = x.assignTo("reflect.Set", v.typ, target) 1341 if x.flag&flagIndir != 0 { 1342 typedmemmove(v.typ, v.ptr, x.ptr) 1343 } else { 1344 *(*unsafe.Pointer)(v.ptr) = x.ptr 1345 } 1346} 1347 1348// SetBool sets v's underlying value. 1349// It panics if v's Kind is not Bool or if CanSet() is false. 1350func (v Value) SetBool(x bool) { 1351 v.mustBeAssignable() 1352 v.mustBe(Bool) 1353 *(*bool)(v.ptr) = x 1354} 1355 1356// SetBytes sets v's underlying value. 1357// It panics if v's underlying value is not a slice of bytes. 1358func (v Value) SetBytes(x []byte) { 1359 v.mustBeAssignable() 1360 v.mustBe(Slice) 1361 if v.typ.Elem().Kind() != Uint8 { 1362 panic("reflect.Value.SetBytes of non-byte slice") 1363 } 1364 *(*[]byte)(v.ptr) = x 1365} 1366 1367// setRunes sets v's underlying value. 1368// It panics if v's underlying value is not a slice of runes (int32s). 1369func (v Value) setRunes(x []rune) { 1370 v.mustBeAssignable() 1371 v.mustBe(Slice) 1372 if v.typ.Elem().Kind() != Int32 { 1373 panic("reflect.Value.setRunes of non-rune slice") 1374 } 1375 *(*[]rune)(v.ptr) = x 1376} 1377 1378// SetComplex sets v's underlying value to x. 1379// It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false. 1380func (v Value) SetComplex(x complex128) { 1381 v.mustBeAssignable() 1382 switch k := v.kind(); k { 1383 default: 1384 panic(&ValueError{"reflect.Value.SetComplex", v.kind()}) 1385 case Complex64: 1386 *(*complex64)(v.ptr) = complex64(x) 1387 case Complex128: 1388 *(*complex128)(v.ptr) = x 1389 } 1390} 1391 1392// SetFloat sets v's underlying value to x. 1393// It panics if v's Kind is not Float32 or Float64, or if CanSet() is false. 1394func (v Value) SetFloat(x float64) { 1395 v.mustBeAssignable() 1396 switch k := v.kind(); k { 1397 default: 1398 panic(&ValueError{"reflect.Value.SetFloat", v.kind()}) 1399 case Float32: 1400 *(*float32)(v.ptr) = float32(x) 1401 case Float64: 1402 *(*float64)(v.ptr) = x 1403 } 1404} 1405 1406// SetInt sets v's underlying value to x. 1407// It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false. 1408func (v Value) SetInt(x int64) { 1409 v.mustBeAssignable() 1410 switch k := v.kind(); k { 1411 default: 1412 panic(&ValueError{"reflect.Value.SetInt", v.kind()}) 1413 case Int: 1414 *(*int)(v.ptr) = int(x) 1415 case Int8: 1416 *(*int8)(v.ptr) = int8(x) 1417 case Int16: 1418 *(*int16)(v.ptr) = int16(x) 1419 case Int32: 1420 *(*int32)(v.ptr) = int32(x) 1421 case Int64: 1422 *(*int64)(v.ptr) = x 1423 } 1424} 1425 1426// SetLen sets v's length to n. 1427// It panics if v's Kind is not Slice or if n is negative or 1428// greater than the capacity of the slice. 1429func (v Value) SetLen(n int) { 1430 v.mustBeAssignable() 1431 v.mustBe(Slice) 1432 s := (*sliceHeader)(v.ptr) 1433 if uint(n) > uint(s.Cap) { 1434 panic("reflect: slice length out of range in SetLen") 1435 } 1436 s.Len = n 1437} 1438 1439// SetCap sets v's capacity to n. 1440// It panics if v's Kind is not Slice or if n is smaller than the length or 1441// greater than the capacity of the slice. 1442func (v Value) SetCap(n int) { 1443 v.mustBeAssignable() 1444 v.mustBe(Slice) 1445 s := (*sliceHeader)(v.ptr) 1446 if n < s.Len || n > s.Cap { 1447 panic("reflect: slice capacity out of range in SetCap") 1448 } 1449 s.Cap = n 1450} 1451 1452// SetMapIndex sets the element associated with key in the map v to elem. 1453// It panics if v's Kind is not Map. 1454// If elem is the zero Value, SetMapIndex deletes the key from the map. 1455// Otherwise if v holds a nil map, SetMapIndex will panic. 1456// As in Go, key's elem must be assignable to the map's key type, 1457// and elem's value must be assignable to the map's elem type. 1458func (v Value) SetMapIndex(key, elem Value) { 1459 v.mustBe(Map) 1460 v.mustBeExported() 1461 key.mustBeExported() 1462 tt := (*mapType)(unsafe.Pointer(v.typ)) 1463 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil) 1464 var k unsafe.Pointer 1465 if key.flag&flagIndir != 0 { 1466 k = key.ptr 1467 } else { 1468 k = unsafe.Pointer(&key.ptr) 1469 } 1470 if elem.typ == nil { 1471 mapdelete(v.typ, v.pointer(), k) 1472 return 1473 } 1474 elem.mustBeExported() 1475 elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil) 1476 var e unsafe.Pointer 1477 if elem.flag&flagIndir != 0 { 1478 e = elem.ptr 1479 } else { 1480 e = unsafe.Pointer(&elem.ptr) 1481 } 1482 mapassign(v.typ, v.pointer(), k, e) 1483} 1484 1485// SetUint sets v's underlying value to x. 1486// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false. 1487func (v Value) SetUint(x uint64) { 1488 v.mustBeAssignable() 1489 switch k := v.kind(); k { 1490 default: 1491 panic(&ValueError{"reflect.Value.SetUint", v.kind()}) 1492 case Uint: 1493 *(*uint)(v.ptr) = uint(x) 1494 case Uint8: 1495 *(*uint8)(v.ptr) = uint8(x) 1496 case Uint16: 1497 *(*uint16)(v.ptr) = uint16(x) 1498 case Uint32: 1499 *(*uint32)(v.ptr) = uint32(x) 1500 case Uint64: 1501 *(*uint64)(v.ptr) = x 1502 case Uintptr: 1503 *(*uintptr)(v.ptr) = uintptr(x) 1504 } 1505} 1506 1507// SetPointer sets the unsafe.Pointer value v to x. 1508// It panics if v's Kind is not UnsafePointer. 1509func (v Value) SetPointer(x unsafe.Pointer) { 1510 v.mustBeAssignable() 1511 v.mustBe(UnsafePointer) 1512 *(*unsafe.Pointer)(v.ptr) = x 1513} 1514 1515// SetString sets v's underlying value to x. 1516// It panics if v's Kind is not String or if CanSet() is false. 1517func (v Value) SetString(x string) { 1518 v.mustBeAssignable() 1519 v.mustBe(String) 1520 *(*string)(v.ptr) = x 1521} 1522 1523// Slice returns v[i:j]. 1524// It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, 1525// or if the indexes are out of bounds. 1526func (v Value) Slice(i, j int) Value { 1527 var ( 1528 cap int 1529 typ *sliceType 1530 base unsafe.Pointer 1531 ) 1532 switch kind := v.kind(); kind { 1533 default: 1534 panic(&ValueError{"reflect.Value.Slice", v.kind()}) 1535 1536 case Array: 1537 if v.flag&flagAddr == 0 { 1538 panic("reflect.Value.Slice: slice of unaddressable array") 1539 } 1540 tt := (*arrayType)(unsafe.Pointer(v.typ)) 1541 cap = int(tt.len) 1542 typ = (*sliceType)(unsafe.Pointer(tt.slice)) 1543 base = v.ptr 1544 1545 case Slice: 1546 typ = (*sliceType)(unsafe.Pointer(v.typ)) 1547 s := (*sliceHeader)(v.ptr) 1548 base = s.Data 1549 cap = s.Cap 1550 1551 case String: 1552 s := (*stringHeader)(v.ptr) 1553 if i < 0 || j < i || j > s.Len { 1554 panic("reflect.Value.Slice: string slice index out of bounds") 1555 } 1556 var t stringHeader 1557 if i < s.Len { 1558 t = stringHeader{arrayAt(s.Data, i, 1, "i < s.Len"), j - i} 1559 } 1560 return Value{v.typ, unsafe.Pointer(&t), v.flag} 1561 } 1562 1563 if i < 0 || j < i || j > cap { 1564 panic("reflect.Value.Slice: slice index out of bounds") 1565 } 1566 1567 // Declare slice so that gc can see the base pointer in it. 1568 var x []unsafe.Pointer 1569 1570 // Reinterpret as *sliceHeader to edit. 1571 s := (*sliceHeader)(unsafe.Pointer(&x)) 1572 s.Len = j - i 1573 s.Cap = cap - i 1574 if cap-i > 0 { 1575 s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap") 1576 } else { 1577 // do not advance pointer, to avoid pointing beyond end of slice 1578 s.Data = base 1579 } 1580 1581 fl := v.flag.ro() | flagIndir | flag(Slice) 1582 return Value{typ.common(), unsafe.Pointer(&x), fl} 1583} 1584 1585// Slice3 is the 3-index form of the slice operation: it returns v[i:j:k]. 1586// It panics if v's Kind is not Array or Slice, or if v is an unaddressable array, 1587// or if the indexes are out of bounds. 1588func (v Value) Slice3(i, j, k int) Value { 1589 var ( 1590 cap int 1591 typ *sliceType 1592 base unsafe.Pointer 1593 ) 1594 switch kind := v.kind(); kind { 1595 default: 1596 panic(&ValueError{"reflect.Value.Slice3", v.kind()}) 1597 1598 case Array: 1599 if v.flag&flagAddr == 0 { 1600 panic("reflect.Value.Slice3: slice of unaddressable array") 1601 } 1602 tt := (*arrayType)(unsafe.Pointer(v.typ)) 1603 cap = int(tt.len) 1604 typ = (*sliceType)(unsafe.Pointer(tt.slice)) 1605 base = v.ptr 1606 1607 case Slice: 1608 typ = (*sliceType)(unsafe.Pointer(v.typ)) 1609 s := (*sliceHeader)(v.ptr) 1610 base = s.Data 1611 cap = s.Cap 1612 } 1613 1614 if i < 0 || j < i || k < j || k > cap { 1615 panic("reflect.Value.Slice3: slice index out of bounds") 1616 } 1617 1618 // Declare slice so that the garbage collector 1619 // can see the base pointer in it. 1620 var x []unsafe.Pointer 1621 1622 // Reinterpret as *sliceHeader to edit. 1623 s := (*sliceHeader)(unsafe.Pointer(&x)) 1624 s.Len = j - i 1625 s.Cap = k - i 1626 if k-i > 0 { 1627 s.Data = arrayAt(base, i, typ.elem.Size(), "i < k <= cap") 1628 } else { 1629 // do not advance pointer, to avoid pointing beyond end of slice 1630 s.Data = base 1631 } 1632 1633 fl := v.flag.ro() | flagIndir | flag(Slice) 1634 return Value{typ.common(), unsafe.Pointer(&x), fl} 1635} 1636 1637// String returns the string v's underlying value, as a string. 1638// String is a special case because of Go's String method convention. 1639// Unlike the other getters, it does not panic if v's Kind is not String. 1640// Instead, it returns a string of the form "<T value>" where T is v's type. 1641// The fmt package treats Values specially. It does not call their String 1642// method implicitly but instead prints the concrete values they hold. 1643func (v Value) String() string { 1644 switch k := v.kind(); k { 1645 case Invalid: 1646 return "<invalid Value>" 1647 case String: 1648 return *(*string)(v.ptr) 1649 } 1650 // If you call String on a reflect.Value of other type, it's better to 1651 // print something than to panic. Useful in debugging. 1652 return "<" + v.Type().String() + " Value>" 1653} 1654 1655// TryRecv attempts to receive a value from the channel v but will not block. 1656// It panics if v's Kind is not Chan. 1657// If the receive delivers a value, x is the transferred value and ok is true. 1658// If the receive cannot finish without blocking, x is the zero Value and ok is false. 1659// If the channel is closed, x is the zero value for the channel's element type and ok is false. 1660func (v Value) TryRecv() (x Value, ok bool) { 1661 v.mustBe(Chan) 1662 v.mustBeExported() 1663 return v.recv(true) 1664} 1665 1666// TrySend attempts to send x on the channel v but will not block. 1667// It panics if v's Kind is not Chan. 1668// It reports whether the value was sent. 1669// As in Go, x's value must be assignable to the channel's element type. 1670func (v Value) TrySend(x Value) bool { 1671 v.mustBe(Chan) 1672 v.mustBeExported() 1673 return v.send(x, true) 1674} 1675 1676// Type returns v's type. 1677func (v Value) Type() Type { 1678 f := v.flag 1679 if f == 0 { 1680 panic(&ValueError{"reflect.Value.Type", Invalid}) 1681 } 1682 if f&flagMethod == 0 { 1683 // Easy case 1684 return toType(v.typ) 1685 } 1686 1687 // Method value. 1688 // v.typ describes the receiver, not the method type. 1689 i := int(v.flag) >> flagMethodShift 1690 if v.typ.Kind() == Interface { 1691 // Method on interface. 1692 tt := (*interfaceType)(unsafe.Pointer(v.typ)) 1693 if uint(i) >= uint(len(tt.methods)) { 1694 panic("reflect: internal error: invalid method index") 1695 } 1696 m := &tt.methods[i] 1697 return toType(m.typ) 1698 } 1699 // Method on concrete type. 1700 ms := v.typ.exportedMethods() 1701 if uint(i) >= uint(len(ms)) { 1702 panic("reflect: internal error: invalid method index") 1703 } 1704 m := ms[i] 1705 return toType(m.mtyp) 1706} 1707 1708// Uint returns v's underlying value, as a uint64. 1709// It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. 1710func (v Value) Uint() uint64 { 1711 k := v.kind() 1712 p := v.ptr 1713 switch k { 1714 case Uint: 1715 return uint64(*(*uint)(p)) 1716 case Uint8: 1717 return uint64(*(*uint8)(p)) 1718 case Uint16: 1719 return uint64(*(*uint16)(p)) 1720 case Uint32: 1721 return uint64(*(*uint32)(p)) 1722 case Uint64: 1723 return *(*uint64)(p) 1724 case Uintptr: 1725 return uint64(*(*uintptr)(p)) 1726 } 1727 panic(&ValueError{"reflect.Value.Uint", v.kind()}) 1728} 1729 1730//go:nocheckptr 1731// This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled, 1732// which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr()) 1733// and make an exception. 1734 1735// UnsafeAddr returns a pointer to v's data. 1736// It is for advanced clients that also import the "unsafe" package. 1737// It panics if v is not addressable. 1738func (v Value) UnsafeAddr() uintptr { 1739 // TODO: deprecate 1740 if v.typ == nil { 1741 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid}) 1742 } 1743 if v.flag&flagAddr == 0 { 1744 panic("reflect.Value.UnsafeAddr of unaddressable value") 1745 } 1746 return uintptr(v.ptr) 1747} 1748 1749// StringHeader is the runtime representation of a string. 1750// It cannot be used safely or portably and its representation may 1751// change in a later release. 1752// Moreover, the Data field is not sufficient to guarantee the data 1753// it references will not be garbage collected, so programs must keep 1754// a separate, correctly typed pointer to the underlying data. 1755type StringHeader struct { 1756 Data uintptr 1757 Len int 1758} 1759 1760// stringHeader is a safe version of StringHeader used within this package. 1761type stringHeader struct { 1762 Data unsafe.Pointer 1763 Len int 1764} 1765 1766// SliceHeader is the runtime representation of a slice. 1767// It cannot be used safely or portably and its representation may 1768// change in a later release. 1769// Moreover, the Data field is not sufficient to guarantee the data 1770// it references will not be garbage collected, so programs must keep 1771// a separate, correctly typed pointer to the underlying data. 1772type SliceHeader struct { 1773 Data uintptr 1774 Len int 1775 Cap int 1776} 1777 1778// sliceHeader is a safe version of SliceHeader used within this package. 1779type sliceHeader struct { 1780 Data unsafe.Pointer 1781 Len int 1782 Cap int 1783} 1784 1785func typesMustMatch(what string, t1, t2 Type) { 1786 if t1 != t2 { 1787 panic(what + ": " + t1.String() + " != " + t2.String()) 1788 } 1789} 1790 1791// arrayAt returns the i-th element of p, 1792// an array whose elements are eltSize bytes wide. 1793// The array pointed at by p must have at least i+1 elements: 1794// it is invalid (but impossible to check here) to pass i >= len, 1795// because then the result will point outside the array. 1796// whySafe must explain why i < len. (Passing "i < len" is fine; 1797// the benefit is to surface this assumption at the call site.) 1798func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer { 1799 return add(p, uintptr(i)*eltSize, "i < len") 1800} 1801 1802// grow grows the slice s so that it can hold extra more values, allocating 1803// more capacity if needed. It also returns the old and new slice lengths. 1804func grow(s Value, extra int) (Value, int, int) { 1805 i0 := s.Len() 1806 i1 := i0 + extra 1807 if i1 < i0 { 1808 panic("reflect.Append: slice overflow") 1809 } 1810 m := s.Cap() 1811 if i1 <= m { 1812 return s.Slice(0, i1), i0, i1 1813 } 1814 if m == 0 { 1815 m = extra 1816 } else { 1817 for m < i1 { 1818 if i0 < 1024 { 1819 m += m 1820 } else { 1821 m += m / 4 1822 } 1823 } 1824 } 1825 t := MakeSlice(s.Type(), i1, m) 1826 Copy(t, s) 1827 return t, i0, i1 1828} 1829 1830// Append appends the values x to a slice s and returns the resulting slice. 1831// As in Go, each x's value must be assignable to the slice's element type. 1832func Append(s Value, x ...Value) Value { 1833 s.mustBe(Slice) 1834 s, i0, i1 := grow(s, len(x)) 1835 for i, j := i0, 0; i < i1; i, j = i+1, j+1 { 1836 s.Index(i).Set(x[j]) 1837 } 1838 return s 1839} 1840 1841// AppendSlice appends a slice t to a slice s and returns the resulting slice. 1842// The slices s and t must have the same element type. 1843func AppendSlice(s, t Value) Value { 1844 s.mustBe(Slice) 1845 t.mustBe(Slice) 1846 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem()) 1847 s, i0, i1 := grow(s, t.Len()) 1848 Copy(s.Slice(i0, i1), t) 1849 return s 1850} 1851 1852// Copy copies the contents of src into dst until either 1853// dst has been filled or src has been exhausted. 1854// It returns the number of elements copied. 1855// Dst and src each must have kind Slice or Array, and 1856// dst and src must have the same element type. 1857// 1858// As a special case, src can have kind String if the element type of dst is kind Uint8. 1859func Copy(dst, src Value) int { 1860 dk := dst.kind() 1861 if dk != Array && dk != Slice { 1862 panic(&ValueError{"reflect.Copy", dk}) 1863 } 1864 if dk == Array { 1865 dst.mustBeAssignable() 1866 } 1867 dst.mustBeExported() 1868 1869 sk := src.kind() 1870 var stringCopy bool 1871 if sk != Array && sk != Slice { 1872 stringCopy = sk == String && dst.typ.Elem().Kind() == Uint8 1873 if !stringCopy { 1874 panic(&ValueError{"reflect.Copy", sk}) 1875 } 1876 } 1877 src.mustBeExported() 1878 1879 de := dst.typ.Elem() 1880 if !stringCopy { 1881 se := src.typ.Elem() 1882 typesMustMatch("reflect.Copy", de, se) 1883 } 1884 1885 var ds, ss sliceHeader 1886 if dk == Array { 1887 ds.Data = dst.ptr 1888 ds.Len = dst.Len() 1889 ds.Cap = ds.Len 1890 } else { 1891 ds = *(*sliceHeader)(dst.ptr) 1892 } 1893 if sk == Array { 1894 ss.Data = src.ptr 1895 ss.Len = src.Len() 1896 ss.Cap = ss.Len 1897 } else if sk == Slice { 1898 ss = *(*sliceHeader)(src.ptr) 1899 } else { 1900 sh := *(*stringHeader)(src.ptr) 1901 ss.Data = sh.Data 1902 ss.Len = sh.Len 1903 ss.Cap = sh.Len 1904 } 1905 1906 return typedslicecopy(de.common(), ds, ss) 1907} 1908 1909// A runtimeSelect is a single case passed to rselect. 1910// This must match ../runtime/select.go:/runtimeSelect 1911type runtimeSelect struct { 1912 dir SelectDir // SelectSend, SelectRecv or SelectDefault 1913 typ *rtype // channel type 1914 ch unsafe.Pointer // channel 1915 val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir) 1916} 1917 1918// rselect runs a select. It returns the index of the chosen case. 1919// If the case was a receive, val is filled in with the received value. 1920// The conventional OK bool indicates whether the receive corresponds 1921// to a sent value. 1922//go:noescape 1923func rselect([]runtimeSelect) (chosen int, recvOK bool) 1924 1925// A SelectDir describes the communication direction of a select case. 1926type SelectDir int 1927 1928// NOTE: These values must match ../runtime/select.go:/selectDir. 1929 1930const ( 1931 _ SelectDir = iota 1932 SelectSend // case Chan <- Send 1933 SelectRecv // case <-Chan: 1934 SelectDefault // default 1935) 1936 1937// A SelectCase describes a single case in a select operation. 1938// The kind of case depends on Dir, the communication direction. 1939// 1940// If Dir is SelectDefault, the case represents a default case. 1941// Chan and Send must be zero Values. 1942// 1943// If Dir is SelectSend, the case represents a send operation. 1944// Normally Chan's underlying value must be a channel, and Send's underlying value must be 1945// assignable to the channel's element type. As a special case, if Chan is a zero Value, 1946// then the case is ignored, and the field Send will also be ignored and may be either zero 1947// or non-zero. 1948// 1949// If Dir is SelectRecv, the case represents a receive operation. 1950// Normally Chan's underlying value must be a channel and Send must be a zero Value. 1951// If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value. 1952// When a receive operation is selected, the received Value is returned by Select. 1953// 1954type SelectCase struct { 1955 Dir SelectDir // direction of case 1956 Chan Value // channel to use (for send or receive) 1957 Send Value // value to send (for send) 1958} 1959 1960// Select executes a select operation described by the list of cases. 1961// Like the Go select statement, it blocks until at least one of the cases 1962// can proceed, makes a uniform pseudo-random choice, 1963// and then executes that case. It returns the index of the chosen case 1964// and, if that case was a receive operation, the value received and a 1965// boolean indicating whether the value corresponds to a send on the channel 1966// (as opposed to a zero value received because the channel is closed). 1967func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) { 1968 // NOTE: Do not trust that caller is not modifying cases data underfoot. 1969 // The range is safe because the caller cannot modify our copy of the len 1970 // and each iteration makes its own copy of the value c. 1971 runcases := make([]runtimeSelect, len(cases)) 1972 haveDefault := false 1973 for i, c := range cases { 1974 rc := &runcases[i] 1975 rc.dir = c.Dir 1976 switch c.Dir { 1977 default: 1978 panic("reflect.Select: invalid Dir") 1979 1980 case SelectDefault: // default 1981 if haveDefault { 1982 panic("reflect.Select: multiple default cases") 1983 } 1984 haveDefault = true 1985 if c.Chan.IsValid() { 1986 panic("reflect.Select: default case has Chan value") 1987 } 1988 if c.Send.IsValid() { 1989 panic("reflect.Select: default case has Send value") 1990 } 1991 1992 case SelectSend: 1993 ch := c.Chan 1994 if !ch.IsValid() { 1995 break 1996 } 1997 ch.mustBe(Chan) 1998 ch.mustBeExported() 1999 tt := (*chanType)(unsafe.Pointer(ch.typ)) 2000 if ChanDir(tt.dir)&SendDir == 0 { 2001 panic("reflect.Select: SendDir case using recv-only channel") 2002 } 2003 rc.ch = ch.pointer() 2004 rc.typ = &tt.rtype 2005 v := c.Send 2006 if !v.IsValid() { 2007 panic("reflect.Select: SendDir case missing Send value") 2008 } 2009 v.mustBeExported() 2010 v = v.assignTo("reflect.Select", tt.elem, nil) 2011 if v.flag&flagIndir != 0 { 2012 rc.val = v.ptr 2013 } else { 2014 rc.val = unsafe.Pointer(&v.ptr) 2015 } 2016 2017 case SelectRecv: 2018 if c.Send.IsValid() { 2019 panic("reflect.Select: RecvDir case has Send value") 2020 } 2021 ch := c.Chan 2022 if !ch.IsValid() { 2023 break 2024 } 2025 ch.mustBe(Chan) 2026 ch.mustBeExported() 2027 tt := (*chanType)(unsafe.Pointer(ch.typ)) 2028 if ChanDir(tt.dir)&RecvDir == 0 { 2029 panic("reflect.Select: RecvDir case using send-only channel") 2030 } 2031 rc.ch = ch.pointer() 2032 rc.typ = &tt.rtype 2033 rc.val = unsafe_New(tt.elem) 2034 } 2035 } 2036 2037 chosen, recvOK = rselect(runcases) 2038 if runcases[chosen].dir == SelectRecv { 2039 tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ)) 2040 t := tt.elem 2041 p := runcases[chosen].val 2042 fl := flag(t.Kind()) 2043 if ifaceIndir(t) { 2044 recv = Value{t, p, fl | flagIndir} 2045 } else { 2046 recv = Value{t, *(*unsafe.Pointer)(p), fl} 2047 } 2048 } 2049 return chosen, recv, recvOK 2050} 2051 2052/* 2053 * constructors 2054 */ 2055 2056// implemented in package runtime 2057func unsafe_New(*rtype) unsafe.Pointer 2058func unsafe_NewArray(*rtype, int) unsafe.Pointer 2059 2060// MakeSlice creates a new zero-initialized slice value 2061// for the specified slice type, length, and capacity. 2062func MakeSlice(typ Type, len, cap int) Value { 2063 if typ.Kind() != Slice { 2064 panic("reflect.MakeSlice of non-slice type") 2065 } 2066 if len < 0 { 2067 panic("reflect.MakeSlice: negative len") 2068 } 2069 if cap < 0 { 2070 panic("reflect.MakeSlice: negative cap") 2071 } 2072 if len > cap { 2073 panic("reflect.MakeSlice: len > cap") 2074 } 2075 2076 s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap} 2077 return Value{typ.(*rtype), unsafe.Pointer(&s), flagIndir | flag(Slice)} 2078} 2079 2080// MakeChan creates a new channel with the specified type and buffer size. 2081func MakeChan(typ Type, buffer int) Value { 2082 if typ.Kind() != Chan { 2083 panic("reflect.MakeChan of non-chan type") 2084 } 2085 if buffer < 0 { 2086 panic("reflect.MakeChan: negative buffer size") 2087 } 2088 if typ.ChanDir() != BothDir { 2089 panic("reflect.MakeChan: unidirectional channel type") 2090 } 2091 t := typ.(*rtype) 2092 ch := makechan(t, buffer) 2093 return Value{t, unsafe.Pointer(&ch), flag(Chan) | flagIndir} 2094} 2095 2096// MakeMap creates a new map with the specified type. 2097func MakeMap(typ Type) Value { 2098 return MakeMapWithSize(typ, 0) 2099} 2100 2101// MakeMapWithSize creates a new map with the specified type 2102// and initial space for approximately n elements. 2103func MakeMapWithSize(typ Type, n int) Value { 2104 if typ.Kind() != Map { 2105 panic("reflect.MakeMapWithSize of non-map type") 2106 } 2107 t := typ.(*rtype) 2108 m := makemap(t, n) 2109 return Value{t, unsafe.Pointer(&m), flag(Map) | flagIndir} 2110} 2111 2112// Indirect returns the value that v points to. 2113// If v is a nil pointer, Indirect returns a zero Value. 2114// If v is not a pointer, Indirect returns v. 2115func Indirect(v Value) Value { 2116 if v.Kind() != Ptr { 2117 return v 2118 } 2119 return v.Elem() 2120} 2121 2122// ValueOf returns a new Value initialized to the concrete value 2123// stored in the interface i. ValueOf(nil) returns the zero Value. 2124func ValueOf(i interface{}) Value { 2125 if i == nil { 2126 return Value{} 2127 } 2128 2129 // TODO: Maybe allow contents of a Value to live on the stack. 2130 // For now we make the contents always escape to the heap. It 2131 // makes life easier in a few places (see chanrecv/mapassign 2132 // comment below). 2133 escapes(i) 2134 2135 return unpackEface(i) 2136} 2137 2138// Zero returns a Value representing the zero value for the specified type. 2139// The result is different from the zero value of the Value struct, 2140// which represents no value at all. 2141// For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. 2142// The returned value is neither addressable nor settable. 2143func Zero(typ Type) Value { 2144 if typ == nil { 2145 panic("reflect: Zero(nil)") 2146 } 2147 t := typ.(*rtype) 2148 fl := flag(t.Kind()) 2149 if ifaceIndir(t) { 2150 return Value{t, unsafe_New(t), fl | flagIndir} 2151 } 2152 return Value{t, nil, fl} 2153} 2154 2155// New returns a Value representing a pointer to a new zero value 2156// for the specified type. That is, the returned Value's Type is PtrTo(typ). 2157func New(typ Type) Value { 2158 if typ == nil { 2159 panic("reflect: New(nil)") 2160 } 2161 t := typ.(*rtype) 2162 ptr := unsafe_New(t) 2163 fl := flag(Ptr) 2164 return Value{t.ptrTo(), ptr, fl} 2165} 2166 2167// NewAt returns a Value representing a pointer to a value of the 2168// specified type, using p as that pointer. 2169func NewAt(typ Type, p unsafe.Pointer) Value { 2170 fl := flag(Ptr) 2171 t := typ.(*rtype) 2172 return Value{t.ptrTo(), p, fl} 2173} 2174 2175// assignTo returns a value v that can be assigned directly to typ. 2176// It panics if v is not assignable to typ. 2177// For a conversion to an interface type, target is a suggested scratch space to use. 2178// target must be initialized memory (or nil). 2179func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value { 2180 if v.flag&flagMethod != 0 { 2181 v = makeMethodValue(context, v) 2182 } 2183 2184 switch { 2185 case directlyAssignable(dst, v.typ): 2186 // Overwrite type so that they match. 2187 // Same memory layout, so no harm done. 2188 fl := v.flag&(flagAddr|flagIndir) | v.flag.ro() 2189 fl |= flag(dst.Kind()) 2190 return Value{dst, v.ptr, fl} 2191 2192 case implements(dst, v.typ): 2193 if target == nil { 2194 target = unsafe_New(dst) 2195 } 2196 if v.Kind() == Interface && v.IsNil() { 2197 // A nil ReadWriter passed to nil Reader is OK, 2198 // but using ifaceE2I below will panic. 2199 // Avoid the panic by returning a nil dst (e.g., Reader) explicitly. 2200 return Value{dst, nil, flag(Interface)} 2201 } 2202 x := valueInterface(v, false) 2203 if dst.NumMethod() == 0 { 2204 *(*interface{})(target) = x 2205 } else { 2206 ifaceE2I(dst, x, target) 2207 } 2208 return Value{dst, target, flagIndir | flag(Interface)} 2209 } 2210 2211 // Failed. 2212 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String()) 2213} 2214 2215// Convert returns the value v converted to type t. 2216// If the usual Go conversion rules do not allow conversion 2217// of the value v to type t, Convert panics. 2218func (v Value) Convert(t Type) Value { 2219 if v.flag&flagMethod != 0 { 2220 v = makeMethodValue("Convert", v) 2221 } 2222 op := convertOp(t.common(), v.typ) 2223 if op == nil { 2224 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String()) 2225 } 2226 return op(v, t) 2227} 2228 2229// convertOp returns the function to convert a value of type src 2230// to a value of type dst. If the conversion is illegal, convertOp returns nil. 2231func convertOp(dst, src *rtype) func(Value, Type) Value { 2232 switch src.Kind() { 2233 case Int, Int8, Int16, Int32, Int64: 2234 switch dst.Kind() { 2235 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2236 return cvtInt 2237 case Float32, Float64: 2238 return cvtIntFloat 2239 case String: 2240 return cvtIntString 2241 } 2242 2243 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2244 switch dst.Kind() { 2245 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2246 return cvtUint 2247 case Float32, Float64: 2248 return cvtUintFloat 2249 case String: 2250 return cvtUintString 2251 } 2252 2253 case Float32, Float64: 2254 switch dst.Kind() { 2255 case Int, Int8, Int16, Int32, Int64: 2256 return cvtFloatInt 2257 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: 2258 return cvtFloatUint 2259 case Float32, Float64: 2260 return cvtFloat 2261 } 2262 2263 case Complex64, Complex128: 2264 switch dst.Kind() { 2265 case Complex64, Complex128: 2266 return cvtComplex 2267 } 2268 2269 case String: 2270 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" { 2271 switch dst.Elem().Kind() { 2272 case Uint8: 2273 return cvtStringBytes 2274 case Int32: 2275 return cvtStringRunes 2276 } 2277 } 2278 2279 case Slice: 2280 if dst.Kind() == String && src.Elem().PkgPath() == "" { 2281 switch src.Elem().Kind() { 2282 case Uint8: 2283 return cvtBytesString 2284 case Int32: 2285 return cvtRunesString 2286 } 2287 } 2288 2289 case Chan: 2290 if dst.Kind() == Chan && specialChannelAssignability(dst, src) { 2291 return cvtDirect 2292 } 2293 } 2294 2295 // dst and src have same underlying type. 2296 if haveIdenticalUnderlyingType(dst, src, false) { 2297 return cvtDirect 2298 } 2299 2300 // dst and src are non-defined pointer types with same underlying base type. 2301 if dst.Kind() == Ptr && dst.Name() == "" && 2302 src.Kind() == Ptr && src.Name() == "" && 2303 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) { 2304 return cvtDirect 2305 } 2306 2307 if implements(dst, src) { 2308 if src.Kind() == Interface { 2309 return cvtI2I 2310 } 2311 return cvtT2I 2312 } 2313 2314 return nil 2315} 2316 2317// makeInt returns a Value of type t equal to bits (possibly truncated), 2318// where t is a signed or unsigned int type. 2319func makeInt(f flag, bits uint64, t Type) Value { 2320 typ := t.common() 2321 ptr := unsafe_New(typ) 2322 switch typ.size { 2323 case 1: 2324 *(*uint8)(ptr) = uint8(bits) 2325 case 2: 2326 *(*uint16)(ptr) = uint16(bits) 2327 case 4: 2328 *(*uint32)(ptr) = uint32(bits) 2329 case 8: 2330 *(*uint64)(ptr) = bits 2331 } 2332 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2333} 2334 2335// makeFloat returns a Value of type t equal to v (possibly truncated to float32), 2336// where t is a float32 or float64 type. 2337func makeFloat(f flag, v float64, t Type) Value { 2338 typ := t.common() 2339 ptr := unsafe_New(typ) 2340 switch typ.size { 2341 case 4: 2342 *(*float32)(ptr) = float32(v) 2343 case 8: 2344 *(*float64)(ptr) = v 2345 } 2346 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2347} 2348 2349// makeComplex returns a Value of type t equal to v (possibly truncated to complex64), 2350// where t is a complex64 or complex128 type. 2351func makeComplex(f flag, v complex128, t Type) Value { 2352 typ := t.common() 2353 ptr := unsafe_New(typ) 2354 switch typ.size { 2355 case 8: 2356 *(*complex64)(ptr) = complex64(v) 2357 case 16: 2358 *(*complex128)(ptr) = v 2359 } 2360 return Value{typ, ptr, f | flagIndir | flag(typ.Kind())} 2361} 2362 2363func makeString(f flag, v string, t Type) Value { 2364 ret := New(t).Elem() 2365 ret.SetString(v) 2366 ret.flag = ret.flag&^flagAddr | f 2367 return ret 2368} 2369 2370func makeBytes(f flag, v []byte, t Type) Value { 2371 ret := New(t).Elem() 2372 ret.SetBytes(v) 2373 ret.flag = ret.flag&^flagAddr | f 2374 return ret 2375} 2376 2377func makeRunes(f flag, v []rune, t Type) Value { 2378 ret := New(t).Elem() 2379 ret.setRunes(v) 2380 ret.flag = ret.flag&^flagAddr | f 2381 return ret 2382} 2383 2384// These conversion functions are returned by convertOp 2385// for classes of conversions. For example, the first function, cvtInt, 2386// takes any value v of signed int type and returns the value converted 2387// to type t, where t is any signed or unsigned int type. 2388 2389// convertOp: intXX -> [u]intXX 2390func cvtInt(v Value, t Type) Value { 2391 return makeInt(v.flag.ro(), uint64(v.Int()), t) 2392} 2393 2394// convertOp: uintXX -> [u]intXX 2395func cvtUint(v Value, t Type) Value { 2396 return makeInt(v.flag.ro(), v.Uint(), t) 2397} 2398 2399// convertOp: floatXX -> intXX 2400func cvtFloatInt(v Value, t Type) Value { 2401 return makeInt(v.flag.ro(), uint64(int64(v.Float())), t) 2402} 2403 2404// convertOp: floatXX -> uintXX 2405func cvtFloatUint(v Value, t Type) Value { 2406 return makeInt(v.flag.ro(), uint64(v.Float()), t) 2407} 2408 2409// convertOp: intXX -> floatXX 2410func cvtIntFloat(v Value, t Type) Value { 2411 return makeFloat(v.flag.ro(), float64(v.Int()), t) 2412} 2413 2414// convertOp: uintXX -> floatXX 2415func cvtUintFloat(v Value, t Type) Value { 2416 return makeFloat(v.flag.ro(), float64(v.Uint()), t) 2417} 2418 2419// convertOp: floatXX -> floatXX 2420func cvtFloat(v Value, t Type) Value { 2421 return makeFloat(v.flag.ro(), v.Float(), t) 2422} 2423 2424// convertOp: complexXX -> complexXX 2425func cvtComplex(v Value, t Type) Value { 2426 return makeComplex(v.flag.ro(), v.Complex(), t) 2427} 2428 2429// convertOp: intXX -> string 2430func cvtIntString(v Value, t Type) Value { 2431 return makeString(v.flag.ro(), string(v.Int()), t) 2432} 2433 2434// convertOp: uintXX -> string 2435func cvtUintString(v Value, t Type) Value { 2436 return makeString(v.flag.ro(), string(v.Uint()), t) 2437} 2438 2439// convertOp: []byte -> string 2440func cvtBytesString(v Value, t Type) Value { 2441 return makeString(v.flag.ro(), string(v.Bytes()), t) 2442} 2443 2444// convertOp: string -> []byte 2445func cvtStringBytes(v Value, t Type) Value { 2446 return makeBytes(v.flag.ro(), []byte(v.String()), t) 2447} 2448 2449// convertOp: []rune -> string 2450func cvtRunesString(v Value, t Type) Value { 2451 return makeString(v.flag.ro(), string(v.runes()), t) 2452} 2453 2454// convertOp: string -> []rune 2455func cvtStringRunes(v Value, t Type) Value { 2456 return makeRunes(v.flag.ro(), []rune(v.String()), t) 2457} 2458 2459// convertOp: direct copy 2460func cvtDirect(v Value, typ Type) Value { 2461 f := v.flag 2462 t := typ.common() 2463 ptr := v.ptr 2464 if f&flagAddr != 0 { 2465 // indirect, mutable word - make a copy 2466 c := unsafe_New(t) 2467 typedmemmove(t, c, ptr) 2468 ptr = c 2469 f &^= flagAddr 2470 } 2471 return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f? 2472} 2473 2474// convertOp: concrete -> interface 2475func cvtT2I(v Value, typ Type) Value { 2476 target := unsafe_New(typ.common()) 2477 x := valueInterface(v, false) 2478 if typ.NumMethod() == 0 { 2479 *(*interface{})(target) = x 2480 } else { 2481 ifaceE2I(typ.(*rtype), x, target) 2482 } 2483 return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)} 2484} 2485 2486// convertOp: interface -> interface 2487func cvtI2I(v Value, typ Type) Value { 2488 if v.IsNil() { 2489 ret := Zero(typ) 2490 ret.flag |= v.flag.ro() 2491 return ret 2492 } 2493 return cvtT2I(v.Elem(), typ) 2494} 2495 2496// implemented in ../runtime 2497func chancap(ch unsafe.Pointer) int 2498func chanclose(ch unsafe.Pointer) 2499func chanlen(ch unsafe.Pointer) int 2500 2501// Note: some of the noescape annotations below are technically a lie, 2502// but safe in the context of this package. Functions like chansend 2503// and mapassign don't escape the referent, but may escape anything 2504// the referent points to (they do shallow copies of the referent). 2505// It is safe in this package because the referent may only point 2506// to something a Value may point to, and that is always in the heap 2507// (due to the escapes() call in ValueOf). 2508 2509//go:noescape 2510func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool) 2511 2512//go:noescape 2513func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool 2514 2515func makechan(typ *rtype, size int) (ch unsafe.Pointer) 2516func makemap(t *rtype, cap int) (m unsafe.Pointer) 2517 2518//go:noescape 2519func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer) 2520 2521//go:noescape 2522func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer) 2523 2524//go:noescape 2525func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer) 2526 2527// m escapes into the return value, but the caller of mapiterinit 2528// doesn't let the return value escape. 2529//go:noescape 2530func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer 2531 2532//go:noescape 2533func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer) 2534 2535//go:noescape 2536func mapiterelem(it unsafe.Pointer) (elem unsafe.Pointer) 2537 2538//go:noescape 2539func mapiternext(it unsafe.Pointer) 2540 2541//go:noescape 2542func maplen(m unsafe.Pointer) int 2543 2544//go:linkname call runtime.reflectcall 2545func call(typ *funcType, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer) 2546 2547func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer) 2548 2549// memmove copies size bytes to dst from src. No write barriers are used. 2550//go:noescape 2551func memmove(dst, src unsafe.Pointer, size uintptr) 2552 2553// typedmemmove copies a value of type t to dst from src. 2554//go:noescape 2555func typedmemmove(t *rtype, dst, src unsafe.Pointer) 2556 2557// typedslicecopy copies a slice of elemType values from src to dst, 2558// returning the number of elements copied. 2559//go:noescape 2560func typedslicecopy(elemType *rtype, dst, src sliceHeader) int 2561 2562//go:noescape 2563func typehash(t *rtype, p unsafe.Pointer, h uintptr) uintptr 2564 2565// Dummy annotation marking that the value x escapes, 2566// for use in cases where the reflect code is so clever that 2567// the compiler cannot follow. 2568func escapes(x interface{}) { 2569 if dummy.b { 2570 dummy.x = x 2571 } 2572} 2573 2574var dummy struct { 2575 b bool 2576 x interface{} 2577} 2578