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