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