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