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