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