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