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