Rebase.
[official-gcc.git] / libgo / go / reflect / value.go
blobc390b8e2d6c1dc020aabca53c44ef0ad28a82ed4
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.
5 package reflect
7 import (
8 "math"
9 "runtime"
10 "strconv"
11 "unsafe"
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"
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))
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))
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))
44 // Value is the reflection interface to a Go value.
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.
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.
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
65 // Pointer-valued data or, if flagIndir is set, pointer to data.
66 // Valid when either flagIndir is set or typ.pointers() is true.
67 // Gccgo always uses this field.
68 ptr unsafe.Pointer
70 // Non-pointer-valued data. When the data is smaller
71 // than a word, it begins at the first byte (in the memory
72 // address sense) of this field.
73 // Valid when flagIndir is not set and typ.pointers() is false.
74 // Gccgo never uses this field.
75 // scalar uintptr
77 // flag holds metadata about the value.
78 // The lowest bits are flag bits:
79 // - flagRO: obtained via unexported field, so read-only
80 // - flagIndir: val holds a pointer to the data
81 // - flagAddr: v.CanAddr is true (implies flagIndir)
82 // - flagMethod: v is a method value.
83 // The next five bits give the Kind of the value.
84 // This repeats typ.Kind() except for method values.
85 // The remaining 23+ bits give a method number for method values.
86 // If flag.kind() != Func, code can assume that flagMethod is unset.
87 // If typ.size > ptrSize, code can assume that flagIndir is set.
88 flag
90 // A method value represents a curried method invocation
91 // like r.Read for some receiver r. The typ+val+flag bits describe
92 // the receiver r, but the flag's Kind bits say Func (methods are
93 // functions), and the top bits of the flag give the method number
94 // in r's type's method table.
97 type flag uintptr
99 const (
100 flagRO flag = 1 << iota
101 flagIndir
102 flagAddr
103 flagMethod
104 flagMethodFn // gccgo: first fn parameter is always pointer
105 flagKindShift = iota
106 flagKindWidth = 5 // there are 27 kinds
107 flagKindMask flag = 1<<flagKindWidth - 1
108 flagMethodShift = flagKindShift + flagKindWidth
111 func (f flag) kind() Kind {
112 return Kind((f >> flagKindShift) & flagKindMask)
115 // pointer returns the underlying pointer represented by v.
116 // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
117 func (v Value) pointer() unsafe.Pointer {
118 if v.typ.size != ptrSize || !v.typ.pointers() {
119 panic("can't call pointer on a non-pointer Value")
121 if v.flag&flagIndir != 0 {
122 return *(*unsafe.Pointer)(v.ptr)
124 return v.ptr
127 // packEface converts v to the empty interface.
128 func packEface(v Value) interface{} {
129 t := v.typ
130 var i interface{}
131 e := (*emptyInterface)(unsafe.Pointer(&i))
132 // First, fill in the data portion of the interface.
133 switch {
134 case v.Kind() != Ptr && v.Kind() != UnsafePointer:
135 // Value is indirect, and so is the interface we're making.
136 if v.flag&flagIndir == 0 {
137 panic("reflect: missing flagIndir")
139 ptr := v.ptr
140 if v.flag&flagAddr != 0 {
141 // TODO: pass safe boolean from valueInterface so
142 // we don't need to copy if safe==true?
143 c := unsafe_New(t)
144 memmove(c, ptr, t.size)
145 ptr = c
147 e.word = iword(ptr)
148 case v.flag&flagIndir != 0:
149 // Value is indirect, but interface is direct. We need
150 // to load the data at v.ptr into the interface data word.
151 if t.pointers() {
152 e.word = iword(*(*unsafe.Pointer)(v.ptr))
153 } else {
154 e.word = iword(loadScalar(v.ptr, t.size))
156 default:
157 // Value is direct, and so is the interface.
158 if t.pointers() {
159 e.word = iword(v.ptr)
160 } else {
161 // e.word = iword(v.scalar)
162 panic("reflect: missing flagIndir")
165 // Now, fill in the type portion. We're very careful here not
166 // to have any operation between the e.word and e.typ assignments
167 // that would let the garbage collector observe the partially-built
168 // interface value.
169 e.typ = t
170 return i
173 // unpackEface converts the empty interface i to a Value.
174 func unpackEface(i interface{}) Value {
175 e := (*emptyInterface)(unsafe.Pointer(&i))
176 // NOTE: don't read e.word until we know whether it is really a pointer or not.
177 t := e.typ
178 if t == nil {
179 return Value{}
181 f := flag(t.Kind()) << flagKindShift
182 if t.Kind() != Ptr && t.Kind() != UnsafePointer {
183 f |= flagIndir
185 return Value{t, unsafe.Pointer(e.word), f}
188 // A ValueError occurs when a Value method is invoked on
189 // a Value that does not support it. Such cases are documented
190 // in the description of each method.
191 type ValueError struct {
192 Method string
193 Kind Kind
196 func (e *ValueError) Error() string {
197 if e.Kind == 0 {
198 return "reflect: call of " + e.Method + " on zero Value"
200 return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
203 // methodName returns the name of the calling method,
204 // assumed to be two stack frames above.
205 func methodName() string {
206 pc, _, _, _ := runtime.Caller(2)
207 f := runtime.FuncForPC(pc)
208 if f == nil {
209 return "unknown method"
211 return f.Name()
214 // An iword is the word that would be stored in an
215 // interface to represent a given value v. Specifically, if v is
216 // bigger than a pointer, its word is a pointer to v's data.
217 // Otherwise, its word holds the data stored
218 // in its leading bytes (so is not a pointer).
219 // This type is very dangerous for the garbage collector because
220 // it must be treated conservatively. We try to never expose it
221 // to the GC here so that GC remains precise.
222 type iword unsafe.Pointer
224 // loadScalar loads n bytes at p from memory into a uintptr
225 // that forms the second word of an interface. The data
226 // must be non-pointer in nature.
227 func loadScalar(p unsafe.Pointer, n uintptr) uintptr {
228 // Run the copy ourselves instead of calling memmove
229 // to avoid moving w to the heap.
230 var w uintptr
231 switch n {
232 default:
233 panic("reflect: internal error: loadScalar of " + strconv.Itoa(int(n)) + "-byte value")
234 case 0:
235 case 1:
236 *(*uint8)(unsafe.Pointer(&w)) = *(*uint8)(p)
237 case 2:
238 *(*uint16)(unsafe.Pointer(&w)) = *(*uint16)(p)
239 case 3:
240 *(*[3]byte)(unsafe.Pointer(&w)) = *(*[3]byte)(p)
241 case 4:
242 *(*uint32)(unsafe.Pointer(&w)) = *(*uint32)(p)
243 case 5:
244 *(*[5]byte)(unsafe.Pointer(&w)) = *(*[5]byte)(p)
245 case 6:
246 *(*[6]byte)(unsafe.Pointer(&w)) = *(*[6]byte)(p)
247 case 7:
248 *(*[7]byte)(unsafe.Pointer(&w)) = *(*[7]byte)(p)
249 case 8:
250 *(*uint64)(unsafe.Pointer(&w)) = *(*uint64)(p)
252 return w
255 // storeScalar stores n bytes from w into p.
256 func storeScalar(p unsafe.Pointer, w uintptr, n uintptr) {
257 // Run the copy ourselves instead of calling memmove
258 // to avoid moving w to the heap.
259 switch n {
260 default:
261 panic("reflect: internal error: storeScalar of " + strconv.Itoa(int(n)) + "-byte value")
262 case 0:
263 case 1:
264 *(*uint8)(p) = *(*uint8)(unsafe.Pointer(&w))
265 case 2:
266 *(*uint16)(p) = *(*uint16)(unsafe.Pointer(&w))
267 case 3:
268 *(*[3]byte)(p) = *(*[3]byte)(unsafe.Pointer(&w))
269 case 4:
270 *(*uint32)(p) = *(*uint32)(unsafe.Pointer(&w))
271 case 5:
272 *(*[5]byte)(p) = *(*[5]byte)(unsafe.Pointer(&w))
273 case 6:
274 *(*[6]byte)(p) = *(*[6]byte)(unsafe.Pointer(&w))
275 case 7:
276 *(*[7]byte)(p) = *(*[7]byte)(unsafe.Pointer(&w))
277 case 8:
278 *(*uint64)(p) = *(*uint64)(unsafe.Pointer(&w))
282 // emptyInterface is the header for an interface{} value.
283 type emptyInterface struct {
284 typ *rtype
285 word iword
288 // nonEmptyInterface is the header for a interface value with methods.
289 type nonEmptyInterface struct {
290 // see ../runtime/iface.c:/Itab
291 itab *struct {
292 typ *rtype // dynamic concrete type
293 fun [100000]unsafe.Pointer // method table
295 word iword
298 // mustBe panics if f's kind is not expected.
299 // Making this a method on flag instead of on Value
300 // (and embedding flag in Value) means that we can write
301 // the very clear v.mustBe(Bool) and have it compile into
302 // v.flag.mustBe(Bool), which will only bother to copy the
303 // single important word for the receiver.
304 func (f flag) mustBe(expected Kind) {
305 k := f.kind()
306 if k != expected {
307 panic(&ValueError{methodName(), k})
311 // mustBeExported panics if f records that the value was obtained using
312 // an unexported field.
313 func (f flag) mustBeExported() {
314 if f == 0 {
315 panic(&ValueError{methodName(), 0})
317 if f&flagRO != 0 {
318 panic("reflect: " + methodName() + " using value obtained using unexported field")
322 // mustBeAssignable panics if f records that the value is not assignable,
323 // which is to say that either it was obtained using an unexported field
324 // or it is not addressable.
325 func (f flag) mustBeAssignable() {
326 if f == 0 {
327 panic(&ValueError{methodName(), Invalid})
329 // Assignable if addressable and not read-only.
330 if f&flagRO != 0 {
331 panic("reflect: " + methodName() + " using value obtained using unexported field")
333 if f&flagAddr == 0 {
334 panic("reflect: " + methodName() + " using unaddressable value")
338 // Addr returns a pointer value representing the address of v.
339 // It panics if CanAddr() returns false.
340 // Addr is typically used to obtain a pointer to a struct field
341 // or slice element in order to call a method that requires a
342 // pointer receiver.
343 func (v Value) Addr() Value {
344 if v.flag&flagAddr == 0 {
345 panic("reflect.Value.Addr of unaddressable value")
347 return Value{v.typ.ptrTo(), v.ptr /* 0, */, (v.flag & flagRO) | flag(Ptr)<<flagKindShift}
350 // Bool returns v's underlying value.
351 // It panics if v's kind is not Bool.
352 func (v Value) Bool() bool {
353 v.mustBe(Bool)
354 if v.flag&flagIndir != 0 {
355 return *(*bool)(v.ptr)
357 // return *(*bool)(unsafe.Pointer(&v.scalar))
358 panic("reflect: missing flagIndir")
361 // Bytes returns v's underlying value.
362 // It panics if v's underlying value is not a slice of bytes.
363 func (v Value) Bytes() []byte {
364 v.mustBe(Slice)
365 if v.typ.Elem().Kind() != Uint8 {
366 panic("reflect.Value.Bytes of non-byte slice")
368 // Slice is always bigger than a word; assume flagIndir.
369 return *(*[]byte)(v.ptr)
372 // runes returns v's underlying value.
373 // It panics if v's underlying value is not a slice of runes (int32s).
374 func (v Value) runes() []rune {
375 v.mustBe(Slice)
376 if v.typ.Elem().Kind() != Int32 {
377 panic("reflect.Value.Bytes of non-rune slice")
379 // Slice is always bigger than a word; assume flagIndir.
380 return *(*[]rune)(v.ptr)
383 // CanAddr returns true if the value's address can be obtained with Addr.
384 // Such values are called addressable. A value is addressable if it is
385 // an element of a slice, an element of an addressable array,
386 // a field of an addressable struct, or the result of dereferencing a pointer.
387 // If CanAddr returns false, calling Addr will panic.
388 func (v Value) CanAddr() bool {
389 return v.flag&flagAddr != 0
392 // CanSet returns true if the value of v can be changed.
393 // A Value can be changed only if it is addressable and was not
394 // obtained by the use of unexported struct fields.
395 // If CanSet returns false, calling Set or any type-specific
396 // setter (e.g., SetBool, SetInt64) will panic.
397 func (v Value) CanSet() bool {
398 return v.flag&(flagAddr|flagRO) == flagAddr
401 // Call calls the function v with the input arguments in.
402 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
403 // Call panics if v's Kind is not Func.
404 // It returns the output results as Values.
405 // As in Go, each input argument must be assignable to the
406 // type of the function's corresponding input parameter.
407 // If v is a variadic function, Call creates the variadic slice parameter
408 // itself, copying in the corresponding values.
409 func (v Value) Call(in []Value) []Value {
410 v.mustBe(Func)
411 v.mustBeExported()
412 return v.call("Call", in)
415 // CallSlice calls the variadic function v with the input arguments in,
416 // assigning the slice in[len(in)-1] to v's final variadic argument.
417 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]...).
418 // Call panics if v's Kind is not Func or if v is not variadic.
419 // It returns the output results as Values.
420 // As in Go, each input argument must be assignable to the
421 // type of the function's corresponding input parameter.
422 func (v Value) CallSlice(in []Value) []Value {
423 v.mustBe(Func)
424 v.mustBeExported()
425 return v.call("CallSlice", in)
428 var callGC bool // for testing; see TestCallMethodJump
430 var makeFuncStubFn = makeFuncStub
431 var makeFuncStubCode = **(**uintptr)(unsafe.Pointer(&makeFuncStubFn))
433 func (v Value) call(op string, in []Value) []Value {
434 // Get function pointer, type.
435 t := v.typ
436 var (
437 fn unsafe.Pointer
438 rcvr Value
440 if v.flag&flagMethod != 0 {
441 rcvr = v
442 _, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
443 } else if v.flag&flagIndir != 0 {
444 fn = *(*unsafe.Pointer)(v.ptr)
445 } else {
446 fn = v.ptr
449 if fn == nil {
450 panic("reflect.Value.Call: call of nil function")
453 isSlice := op == "CallSlice"
454 n := t.NumIn()
455 if isSlice {
456 if !t.IsVariadic() {
457 panic("reflect: CallSlice of non-variadic function")
459 if len(in) < n {
460 panic("reflect: CallSlice with too few input arguments")
462 if len(in) > n {
463 panic("reflect: CallSlice with too many input arguments")
465 } else {
466 if t.IsVariadic() {
469 if len(in) < n {
470 panic("reflect: Call with too few input arguments")
472 if !t.IsVariadic() && len(in) > n {
473 panic("reflect: Call with too many input arguments")
476 for _, x := range in {
477 if x.Kind() == Invalid {
478 panic("reflect: " + op + " using zero Value argument")
481 for i := 0; i < n; i++ {
482 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
483 panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
486 if !isSlice && t.IsVariadic() {
487 // prepare slice for remaining values
488 m := len(in) - n
489 slice := MakeSlice(t.In(n), m, m)
490 elem := t.In(n).Elem()
491 for i := 0; i < m; i++ {
492 x := in[n+i]
493 if xt := x.Type(); !xt.AssignableTo(elem) {
494 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
496 slice.Index(i).Set(x)
498 origIn := in
499 in = make([]Value, n+1)
500 copy(in[:n], origIn)
501 in[n] = slice
504 nin := len(in)
505 if nin != t.NumIn() {
506 panic("reflect.Value.Call: wrong argument count")
508 nout := t.NumOut()
510 // If target is makeFuncStub, short circuit the unpack onto stack /
511 // pack back into []Value for the args and return values. Just do the
512 // call directly.
513 // We need to do this here because otherwise we have a situation where
514 // reflect.callXX calls makeFuncStub, neither of which knows the
515 // layout of the args. That's bad for precise gc & stack copying.
516 x := (*makeFuncImpl)(fn)
517 if x.code == makeFuncStubCode {
518 return x.call(in)
521 if v.flag&flagMethod != 0 {
522 nin++
524 firstPointer := len(in) > 0 && t.In(0).Kind() != Ptr && v.flag&flagMethodFn != 0
525 params := make([]unsafe.Pointer, nin)
526 off := 0
527 if v.flag&flagMethod != 0 {
528 // Hard-wired first argument.
529 p := new(unsafe.Pointer)
530 if rcvr.typ.Kind() == Interface {
531 *p = unsafe.Pointer((*nonEmptyInterface)(v.ptr).word)
532 } else if rcvr.typ.Kind() == Ptr || rcvr.typ.Kind() == UnsafePointer {
533 *p = rcvr.pointer()
534 } else {
535 *p = rcvr.ptr
537 params[0] = unsafe.Pointer(p)
538 off = 1
540 for i, pv := range in {
541 pv.mustBeExported()
542 targ := t.In(i).(*rtype)
543 pv = pv.assignTo("reflect.Value.Call", targ, nil)
544 if pv.flag&flagIndir == 0 {
545 p := new(unsafe.Pointer)
546 *p = pv.ptr
547 params[off] = unsafe.Pointer(p)
548 } else {
549 params[off] = pv.ptr
551 if i == 0 && firstPointer {
552 p := new(unsafe.Pointer)
553 *p = params[off]
554 params[off] = unsafe.Pointer(p)
556 off++
559 ret := make([]Value, nout)
560 results := make([]unsafe.Pointer, nout)
561 for i := 0; i < nout; i++ {
562 v := New(t.Out(i))
563 results[i] = unsafe.Pointer(v.Pointer())
564 ret[i] = Indirect(v)
567 var pp *unsafe.Pointer
568 if len(params) > 0 {
569 pp = &params[0]
571 var pr *unsafe.Pointer
572 if len(results) > 0 {
573 pr = &results[0]
576 call(t, fn, v.flag&flagMethod != 0, firstPointer, pp, pr)
578 // For testing; see TestCallMethodJump.
579 if callGC {
580 runtime.GC()
583 return ret
586 // methodReceiver returns information about the receiver
587 // described by v. The Value v may or may not have the
588 // flagMethod bit set, so the kind cached in v.flag should
589 // not be used.
590 // The return value rcvrtype gives the method's actual receiver type.
591 // The return value t gives the method type signature (without the receiver).
592 // The return value fn is a pointer to the method code.
593 func methodReceiver(op string, v Value, methodIndex int) (rcvrtype, t *rtype, fn unsafe.Pointer) {
594 i := methodIndex
595 if v.typ.Kind() == Interface {
596 tt := (*interfaceType)(unsafe.Pointer(v.typ))
597 if i < 0 || i >= len(tt.methods) {
598 panic("reflect: internal error: invalid method index")
600 m := &tt.methods[i]
601 if m.pkgPath != nil {
602 panic("reflect: " + op + " of unexported method")
604 iface := (*nonEmptyInterface)(v.ptr)
605 if iface.itab == nil {
606 panic("reflect: " + op + " of method on nil interface value")
608 rcvrtype = iface.itab.typ
609 fn = unsafe.Pointer(&iface.itab.fun[i])
610 t = m.typ
611 } else {
612 rcvrtype = v.typ
613 ut := v.typ.uncommon()
614 if ut == nil || i < 0 || i >= len(ut.methods) {
615 panic("reflect: internal error: invalid method index")
617 m := &ut.methods[i]
618 if m.pkgPath != nil {
619 panic("reflect: " + op + " of unexported method")
621 fn = unsafe.Pointer(&m.tfn)
622 t = m.mtyp
624 return
627 // v is a method receiver. Store at p the word which is used to
628 // encode that receiver at the start of the argument list.
629 // Reflect uses the "interface" calling convention for
630 // methods, which always uses one word to record the receiver.
631 func storeRcvr(v Value, p unsafe.Pointer) {
632 t := v.typ
633 if t.Kind() == Interface {
634 // the interface data word becomes the receiver word
635 iface := (*nonEmptyInterface)(v.ptr)
636 *(*unsafe.Pointer)(p) = unsafe.Pointer(iface.word)
637 } else if v.flag&flagIndir != 0 {
638 if t.size > ptrSize {
639 *(*unsafe.Pointer)(p) = v.ptr
640 } else if t.pointers() {
641 *(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
642 } else {
643 *(*uintptr)(p) = loadScalar(v.ptr, t.size)
645 } else if t.pointers() {
646 *(*unsafe.Pointer)(p) = v.ptr
647 } else {
648 // *(*uintptr)(p) = v.scalar
649 panic("reflect: missing flagIndir")
653 // align returns the result of rounding x up to a multiple of n.
654 // n must be a power of two.
655 func align(x, n uintptr) uintptr {
656 return (x + n - 1) &^ (n - 1)
659 // funcName returns the name of f, for use in error messages.
660 func funcName(f func([]Value) []Value) string {
661 pc := *(*uintptr)(unsafe.Pointer(&f))
662 rf := runtime.FuncForPC(pc)
663 if rf != nil {
664 return rf.Name()
666 return "closure"
669 // Cap returns v's capacity.
670 // It panics if v's Kind is not Array, Chan, or Slice.
671 func (v Value) Cap() int {
672 k := v.kind()
673 switch k {
674 case Array:
675 return v.typ.Len()
676 case Chan:
677 return int(chancap(v.pointer()))
678 case Slice:
679 // Slice is always bigger than a word; assume flagIndir.
680 return (*sliceHeader)(v.ptr).Cap
682 panic(&ValueError{"reflect.Value.Cap", k})
685 // Close closes the channel v.
686 // It panics if v's Kind is not Chan.
687 func (v Value) Close() {
688 v.mustBe(Chan)
689 v.mustBeExported()
690 chanclose(v.pointer())
693 // Complex returns v's underlying value, as a complex128.
694 // It panics if v's Kind is not Complex64 or Complex128
695 func (v Value) Complex() complex128 {
696 k := v.kind()
697 switch k {
698 case Complex64:
699 if v.flag&flagIndir != 0 {
700 return complex128(*(*complex64)(v.ptr))
702 // return complex128(*(*complex64)(unsafe.Pointer(&v.scalar)))
703 panic("reflect: missing flagIndir")
704 case Complex128:
705 // complex128 is always bigger than a word; assume flagIndir.
706 return *(*complex128)(v.ptr)
708 panic(&ValueError{"reflect.Value.Complex", k})
711 // Elem returns the value that the interface v contains
712 // or that the pointer v points to.
713 // It panics if v's Kind is not Interface or Ptr.
714 // It returns the zero Value if v is nil.
715 func (v Value) Elem() Value {
716 k := v.kind()
717 switch k {
718 case Interface:
719 var eface interface{}
720 if v.typ.NumMethod() == 0 {
721 eface = *(*interface{})(v.ptr)
722 } else {
723 eface = (interface{})(*(*interface {
725 })(v.ptr))
727 x := unpackEface(eface)
728 x.flag |= v.flag & flagRO
729 return x
730 case Ptr:
731 ptr := v.ptr
732 if v.flag&flagIndir != 0 {
733 ptr = *(*unsafe.Pointer)(ptr)
735 // The returned value's address is v's value.
736 if ptr == nil {
737 return Value{}
739 tt := (*ptrType)(unsafe.Pointer(v.typ))
740 typ := tt.elem
741 fl := v.flag&flagRO | flagIndir | flagAddr
742 fl |= flag(typ.Kind() << flagKindShift)
743 return Value{typ, ptr /* 0, */, fl}
745 panic(&ValueError{"reflect.Value.Elem", k})
748 // Field returns the i'th field of the struct v.
749 // It panics if v's Kind is not Struct or i is out of range.
750 func (v Value) Field(i int) Value {
751 v.mustBe(Struct)
752 tt := (*structType)(unsafe.Pointer(v.typ))
753 if i < 0 || i >= len(tt.fields) {
754 panic("reflect: Field index out of range")
756 field := &tt.fields[i]
757 typ := field.typ
759 // Inherit permission bits from v.
760 fl := v.flag & (flagRO | flagIndir | flagAddr)
761 // Using an unexported field forces flagRO.
762 if field.pkgPath != nil {
763 fl |= flagRO
765 fl |= flag(typ.Kind()) << flagKindShift
767 var ptr unsafe.Pointer
768 // var scalar uintptr
769 switch {
770 case fl&flagIndir != 0:
771 // Indirect. Just bump pointer.
772 ptr = unsafe.Pointer(uintptr(v.ptr) + field.offset)
773 case typ.pointers():
774 if field.offset != 0 {
775 panic("field access of ptr value isn't at offset 0")
777 ptr = v.ptr
778 case bigEndian:
779 // Must be scalar. Discard leading bytes.
780 // scalar = v.scalar << (field.offset * 8)
781 panic("reflect: missing flagIndir")
782 default:
783 // Must be scalar. Discard leading bytes.
784 // scalar = v.scalar >> (field.offset * 8)
785 panic("reflect: missing flagIndir")
788 return Value{typ, ptr /* scalar, */, fl}
791 // FieldByIndex returns the nested field corresponding to index.
792 // It panics if v's Kind is not struct.
793 func (v Value) FieldByIndex(index []int) Value {
794 v.mustBe(Struct)
795 for i, x := range index {
796 if i > 0 {
797 if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
798 if v.IsNil() {
799 panic("reflect: indirection through nil pointer to embedded struct")
801 v = v.Elem()
804 v = v.Field(x)
806 return v
809 // FieldByName returns the struct field with the given name.
810 // It returns the zero Value if no field was found.
811 // It panics if v's Kind is not struct.
812 func (v Value) FieldByName(name string) Value {
813 v.mustBe(Struct)
814 if f, ok := v.typ.FieldByName(name); ok {
815 return v.FieldByIndex(f.Index)
817 return Value{}
820 // FieldByNameFunc returns the struct field with a name
821 // that satisfies the match function.
822 // It panics if v's Kind is not struct.
823 // It returns the zero Value if no field was found.
824 func (v Value) FieldByNameFunc(match func(string) bool) Value {
825 v.mustBe(Struct)
826 if f, ok := v.typ.FieldByNameFunc(match); ok {
827 return v.FieldByIndex(f.Index)
829 return Value{}
832 // Float returns v's underlying value, as a float64.
833 // It panics if v's Kind is not Float32 or Float64
834 func (v Value) Float() float64 {
835 k := v.kind()
836 switch k {
837 case Float32:
838 if v.flag&flagIndir != 0 {
839 return float64(*(*float32)(v.ptr))
841 // return float64(*(*float32)(unsafe.Pointer(&v.scalar)))
842 panic("reflect: missing flagIndir")
843 case Float64:
844 if v.flag&flagIndir != 0 {
845 return *(*float64)(v.ptr)
847 // return *(*float64)(unsafe.Pointer(&v.scalar))
848 panic("reflect: missing flagIndir")
850 panic(&ValueError{"reflect.Value.Float", k})
853 var uint8Type = TypeOf(uint8(0)).(*rtype)
855 // Index returns v's i'th element.
856 // It panics if v's Kind is not Array, Slice, or String or i is out of range.
857 func (v Value) Index(i int) Value {
858 k := v.kind()
859 switch k {
860 case Array:
861 tt := (*arrayType)(unsafe.Pointer(v.typ))
862 if i < 0 || i > int(tt.len) {
863 panic("reflect: array index out of range")
865 typ := tt.elem
866 fl := v.flag & (flagRO | flagIndir | flagAddr) // bits same as overall array
867 fl |= flag(typ.Kind()) << flagKindShift
868 offset := uintptr(i) * typ.size
870 var val unsafe.Pointer
871 switch {
872 case fl&flagIndir != 0:
873 // Indirect. Just bump pointer.
874 val = unsafe.Pointer(uintptr(v.ptr) + offset)
875 case typ.pointers():
876 if offset != 0 {
877 panic("can't Index(i) with i!=0 on ptrLike value")
879 val = v.ptr
880 case bigEndian:
881 // Direct. Discard leading bytes.
882 // scalar = v.scalar << (offset * 8)
883 panic("reflect: missing flagIndir")
884 default:
885 // Direct. Discard leading bytes.
886 // scalar = v.scalar >> (offset * 8)
887 panic("reflect: missing flagIndir")
889 return Value{typ, val /* scalar, */, fl}
891 case Slice:
892 // Element flag same as Elem of Ptr.
893 // Addressable, indirect, possibly read-only.
894 fl := flagAddr | flagIndir | v.flag&flagRO
895 s := (*sliceHeader)(v.ptr)
896 if i < 0 || i >= s.Len {
897 panic("reflect: slice index out of range")
899 tt := (*sliceType)(unsafe.Pointer(v.typ))
900 typ := tt.elem
901 fl |= flag(typ.Kind()) << flagKindShift
902 val := unsafe.Pointer(uintptr(s.Data) + uintptr(i)*typ.size)
903 return Value{typ, val /* 0, */, fl}
905 case String:
906 fl := v.flag&flagRO | flag(Uint8<<flagKindShift) | flagIndir
907 s := (*StringHeader)(v.ptr)
908 if i < 0 || i >= s.Len {
909 panic("reflect: string index out of range")
911 b := uintptr(0)
912 *(*byte)(unsafe.Pointer(&b)) = *(*byte)(unsafe.Pointer(uintptr(s.Data) + uintptr(i)))
913 return Value{uint8Type, unsafe.Pointer(&b) /* 0, */, fl | flagIndir}
915 panic(&ValueError{"reflect.Value.Index", k})
918 // Int returns v's underlying value, as an int64.
919 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
920 func (v Value) Int() int64 {
921 k := v.kind()
922 var p unsafe.Pointer
923 if v.flag&flagIndir != 0 {
924 p = v.ptr
925 } else {
926 // The escape analysis is good enough that &v.scalar
927 // does not trigger a heap allocation.
928 // p = unsafe.Pointer(&v.scalar)
929 switch k {
930 case Int, Int8, Int16, Int32, Int64:
931 panic("reflect: missing flagIndir")
934 switch k {
935 case Int:
936 return int64(*(*int)(p))
937 case Int8:
938 return int64(*(*int8)(p))
939 case Int16:
940 return int64(*(*int16)(p))
941 case Int32:
942 return int64(*(*int32)(p))
943 case Int64:
944 return int64(*(*int64)(p))
946 panic(&ValueError{"reflect.Value.Int", k})
949 // CanInterface returns true if Interface can be used without panicking.
950 func (v Value) CanInterface() bool {
951 if v.flag == 0 {
952 panic(&ValueError{"reflect.Value.CanInterface", Invalid})
954 return v.flag&flagRO == 0
957 // Interface returns v's current value as an interface{}.
958 // It is equivalent to:
959 // var i interface{} = (v's underlying value)
960 // It panics if the Value was obtained by accessing
961 // unexported struct fields.
962 func (v Value) Interface() (i interface{}) {
963 return valueInterface(v, true)
966 func valueInterface(v Value, safe bool) interface{} {
967 if v.flag == 0 {
968 panic(&ValueError{"reflect.Value.Interface", 0})
970 if safe && v.flag&flagRO != 0 {
971 // Do not allow access to unexported values via Interface,
972 // because they might be pointers that should not be
973 // writable or methods or function that should not be callable.
974 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
976 if v.flag&flagMethod != 0 {
977 v = makeMethodValue("Interface", v)
980 if v.flag&flagMethodFn != 0 {
981 if v.typ.Kind() != Func {
982 panic("reflect: MethodFn of non-Func")
984 ft := (*funcType)(unsafe.Pointer(v.typ))
985 if ft.in[0].Kind() != Ptr {
986 v = makeValueMethod(v)
990 if v.kind() == Interface {
991 // Special case: return the element inside the interface.
992 // Empty interface has one layout, all interfaces with
993 // methods have a second layout.
994 if v.NumMethod() == 0 {
995 return *(*interface{})(v.ptr)
997 return *(*interface {
999 })(v.ptr)
1002 // TODO: pass safe to packEface so we don't need to copy if safe==true?
1003 return packEface(v)
1006 // InterfaceData returns the interface v's value as a uintptr pair.
1007 // It panics if v's Kind is not Interface.
1008 func (v Value) InterfaceData() [2]uintptr {
1009 // TODO: deprecate this
1010 v.mustBe(Interface)
1011 // We treat this as a read operation, so we allow
1012 // it even for unexported data, because the caller
1013 // has to import "unsafe" to turn it into something
1014 // that can be abused.
1015 // Interface value is always bigger than a word; assume flagIndir.
1016 return *(*[2]uintptr)(v.ptr)
1019 // IsNil reports whether its argument v is nil. The argument must be
1020 // a chan, func, interface, map, pointer, or slice value; if it is
1021 // not, IsNil panics. Note that IsNil is not always equivalent to a
1022 // regular comparison with nil in Go. For example, if v was created
1023 // by calling ValueOf with an uninitialized interface variable i,
1024 // i==nil will be true but v.IsNil will panic as v will be the zero
1025 // Value.
1026 func (v Value) IsNil() bool {
1027 k := v.kind()
1028 switch k {
1029 case Chan, Func, Map, Ptr:
1030 if v.flag&flagMethod != 0 {
1031 return false
1033 ptr := v.ptr
1034 if v.flag&flagIndir != 0 {
1035 ptr = *(*unsafe.Pointer)(ptr)
1037 return ptr == nil
1038 case Interface, Slice:
1039 // Both interface and slice are nil if first word is 0.
1040 // Both are always bigger than a word; assume flagIndir.
1041 return *(*unsafe.Pointer)(v.ptr) == nil
1043 panic(&ValueError{"reflect.Value.IsNil", k})
1046 // IsValid returns true if v represents a value.
1047 // It returns false if v is the zero Value.
1048 // If IsValid returns false, all other methods except String panic.
1049 // Most functions and methods never return an invalid value.
1050 // If one does, its documentation states the conditions explicitly.
1051 func (v Value) IsValid() bool {
1052 return v.flag != 0
1055 // Kind returns v's Kind.
1056 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
1057 func (v Value) Kind() Kind {
1058 return v.kind()
1061 // Len returns v's length.
1062 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
1063 func (v Value) Len() int {
1064 k := v.kind()
1065 switch k {
1066 case Array:
1067 tt := (*arrayType)(unsafe.Pointer(v.typ))
1068 return int(tt.len)
1069 case Chan:
1070 return chanlen(v.pointer())
1071 case Map:
1072 return maplen(v.pointer())
1073 case Slice:
1074 // Slice is bigger than a word; assume flagIndir.
1075 return (*sliceHeader)(v.ptr).Len
1076 case String:
1077 // String is bigger than a word; assume flagIndir.
1078 return (*stringHeader)(v.ptr).Len
1080 panic(&ValueError{"reflect.Value.Len", k})
1083 // MapIndex returns the value associated with key in the map v.
1084 // It panics if v's Kind is not Map.
1085 // It returns the zero Value if key is not found in the map or if v represents a nil map.
1086 // As in Go, the key's value must be assignable to the map's key type.
1087 func (v Value) MapIndex(key Value) Value {
1088 v.mustBe(Map)
1089 tt := (*mapType)(unsafe.Pointer(v.typ))
1091 // Do not require key to be exported, so that DeepEqual
1092 // and other programs can use all the keys returned by
1093 // MapKeys as arguments to MapIndex. If either the map
1094 // or the key is unexported, though, the result will be
1095 // considered unexported. This is consistent with the
1096 // behavior for structs, which allow read but not write
1097 // of unexported fields.
1098 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
1100 var k unsafe.Pointer
1101 if key.flag&flagIndir != 0 {
1102 k = key.ptr
1103 } else if key.typ.pointers() {
1104 k = unsafe.Pointer(&key.ptr)
1105 } else {
1106 // k = unsafe.Pointer(&key.scalar)
1107 panic("reflect: missing flagIndir")
1109 e := mapaccess(v.typ, v.pointer(), k)
1110 if e == nil {
1111 return Value{}
1113 typ := tt.elem
1114 fl := (v.flag | key.flag) & flagRO
1115 fl |= flag(typ.Kind()) << flagKindShift
1116 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
1117 // Copy result so future changes to the map
1118 // won't change the underlying value.
1119 c := unsafe_New(typ)
1120 memmove(c, e, typ.size)
1121 return Value{typ, c /* 0, */, fl | flagIndir}
1122 } else if typ.pointers() {
1123 return Value{typ, *(*unsafe.Pointer)(e) /* 0, */, fl}
1124 } else {
1125 panic("reflect: can't happen")
1129 // MapKeys returns a slice containing all the keys present in the map,
1130 // in unspecified order.
1131 // It panics if v's Kind is not Map.
1132 // It returns an empty slice if v represents a nil map.
1133 func (v Value) MapKeys() []Value {
1134 v.mustBe(Map)
1135 tt := (*mapType)(unsafe.Pointer(v.typ))
1136 keyType := tt.key
1138 fl := v.flag&flagRO | flag(keyType.Kind())<<flagKindShift
1139 if keyType.Kind() != Ptr && keyType.Kind() != UnsafePointer {
1140 fl |= flagIndir
1143 m := v.pointer()
1144 mlen := int(0)
1145 if m != nil {
1146 mlen = maplen(m)
1148 it := mapiterinit(v.typ, m)
1149 a := make([]Value, mlen)
1150 var i int
1151 for i = 0; i < len(a); i++ {
1152 key := mapiterkey(it)
1153 if key == nil {
1154 // Someone deleted an entry from the map since we
1155 // called maplen above. It's a data race, but nothing
1156 // we can do about it.
1157 break
1159 if keyType.Kind() != Ptr && keyType.Kind() != UnsafePointer {
1160 // Copy result so future changes to the map
1161 // won't change the underlying value.
1162 c := unsafe_New(keyType)
1163 memmove(c, key, keyType.size)
1164 a[i] = Value{keyType, c /* 0, */, fl | flagIndir}
1165 } else if keyType.pointers() {
1166 a[i] = Value{keyType, *(*unsafe.Pointer)(key) /* 0, */, fl}
1167 } else {
1168 panic("reflect: can't happen")
1170 mapiternext(it)
1172 return a[:i]
1175 // Method returns a function value corresponding to v's i'th method.
1176 // The arguments to a Call on the returned function should not include
1177 // a receiver; the returned function will always use v as the receiver.
1178 // Method panics if i is out of range or if v is a nil interface value.
1179 func (v Value) Method(i int) Value {
1180 if v.typ == nil {
1181 panic(&ValueError{"reflect.Value.Method", Invalid})
1183 if v.flag&flagMethod != 0 || i < 0 || i >= v.typ.NumMethod() {
1184 panic("reflect: Method index out of range")
1186 if v.typ.Kind() == Interface && v.IsNil() {
1187 panic("reflect: Method on nil interface value")
1189 fl := v.flag & (flagRO | flagIndir)
1190 fl |= flag(Func) << flagKindShift
1191 fl |= flag(i)<<flagMethodShift | flagMethod
1192 return Value{v.typ, v.ptr /* v.scalar, */, fl}
1195 // NumMethod returns the number of methods in the value's method set.
1196 func (v Value) NumMethod() int {
1197 if v.typ == nil {
1198 panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1200 if v.flag&flagMethod != 0 {
1201 return 0
1203 return v.typ.NumMethod()
1206 // MethodByName returns a function value corresponding to the method
1207 // of v with the given name.
1208 // The arguments to a Call on the returned function should not include
1209 // a receiver; the returned function will always use v as the receiver.
1210 // It returns the zero Value if no method was found.
1211 func (v Value) MethodByName(name string) Value {
1212 if v.typ == nil {
1213 panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1215 if v.flag&flagMethod != 0 {
1216 return Value{}
1218 m, ok := v.typ.MethodByName(name)
1219 if !ok {
1220 return Value{}
1222 return v.Method(m.Index)
1225 // NumField returns the number of fields in the struct v.
1226 // It panics if v's Kind is not Struct.
1227 func (v Value) NumField() int {
1228 v.mustBe(Struct)
1229 tt := (*structType)(unsafe.Pointer(v.typ))
1230 return len(tt.fields)
1233 // OverflowComplex returns true if the complex128 x cannot be represented by v's type.
1234 // It panics if v's Kind is not Complex64 or Complex128.
1235 func (v Value) OverflowComplex(x complex128) bool {
1236 k := v.kind()
1237 switch k {
1238 case Complex64:
1239 return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1240 case Complex128:
1241 return false
1243 panic(&ValueError{"reflect.Value.OverflowComplex", k})
1246 // OverflowFloat returns true if the float64 x cannot be represented by v's type.
1247 // It panics if v's Kind is not Float32 or Float64.
1248 func (v Value) OverflowFloat(x float64) bool {
1249 k := v.kind()
1250 switch k {
1251 case Float32:
1252 return overflowFloat32(x)
1253 case Float64:
1254 return false
1256 panic(&ValueError{"reflect.Value.OverflowFloat", k})
1259 func overflowFloat32(x float64) bool {
1260 if x < 0 {
1261 x = -x
1263 return math.MaxFloat32 < x && x <= math.MaxFloat64
1266 // OverflowInt returns true if the int64 x cannot be represented by v's type.
1267 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1268 func (v Value) OverflowInt(x int64) bool {
1269 k := v.kind()
1270 switch k {
1271 case Int, Int8, Int16, Int32, Int64:
1272 bitSize := v.typ.size * 8
1273 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1274 return x != trunc
1276 panic(&ValueError{"reflect.Value.OverflowInt", k})
1279 // OverflowUint returns true if the uint64 x cannot be represented by v's type.
1280 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1281 func (v Value) OverflowUint(x uint64) bool {
1282 k := v.kind()
1283 switch k {
1284 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1285 bitSize := v.typ.size * 8
1286 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1287 return x != trunc
1289 panic(&ValueError{"reflect.Value.OverflowUint", k})
1292 // Pointer returns v's value as a uintptr.
1293 // It returns uintptr instead of unsafe.Pointer so that
1294 // code using reflect cannot obtain unsafe.Pointers
1295 // without importing the unsafe package explicitly.
1296 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1298 // If v's Kind is Func, the returned pointer is an underlying
1299 // code pointer, but not necessarily enough to identify a
1300 // single function uniquely. The only guarantee is that the
1301 // result is zero if and only if v is a nil func Value.
1303 // If v's Kind is Slice, the returned pointer is to the first
1304 // element of the slice. If the slice is nil the returned value
1305 // is 0. If the slice is empty but non-nil the return value is non-zero.
1306 func (v Value) Pointer() uintptr {
1307 // TODO: deprecate
1308 k := v.kind()
1309 switch k {
1310 case Chan, Map, Ptr, UnsafePointer:
1311 return uintptr(v.pointer())
1312 case Func:
1313 if v.flag&flagMethod != 0 {
1314 // As the doc comment says, the returned pointer is an
1315 // underlying code pointer but not necessarily enough to
1316 // identify a single function uniquely. All method expressions
1317 // created via reflect have the same underlying code pointer,
1318 // so their Pointers are equal. The function used here must
1319 // match the one used in makeMethodValue.
1320 f := makeFuncStub
1321 return **(**uintptr)(unsafe.Pointer(&f))
1323 p := v.pointer()
1324 // Non-nil func value points at data block.
1325 // First word of data block is actual code.
1326 if p != nil {
1327 p = *(*unsafe.Pointer)(p)
1329 return uintptr(p)
1331 case Slice:
1332 return (*SliceHeader)(v.ptr).Data
1334 panic(&ValueError{"reflect.Value.Pointer", k})
1337 // Recv receives and returns a value from the channel v.
1338 // It panics if v's Kind is not Chan.
1339 // The receive blocks until a value is ready.
1340 // The boolean value ok is true if the value x corresponds to a send
1341 // on the channel, false if it is a zero value received because the channel is closed.
1342 func (v Value) Recv() (x Value, ok bool) {
1343 v.mustBe(Chan)
1344 v.mustBeExported()
1345 return v.recv(false)
1348 // internal recv, possibly non-blocking (nb).
1349 // v is known to be a channel.
1350 func (v Value) recv(nb bool) (val Value, ok bool) {
1351 tt := (*chanType)(unsafe.Pointer(v.typ))
1352 if ChanDir(tt.dir)&RecvDir == 0 {
1353 panic("reflect: recv on send-only channel")
1355 t := tt.elem
1356 val = Value{t, nil /* 0, */, flag(t.Kind()) << flagKindShift}
1357 var p unsafe.Pointer
1358 if t.Kind() != Ptr && t.Kind() != UnsafePointer {
1359 p = unsafe_New(t)
1360 val.ptr = p
1361 val.flag |= flagIndir
1362 } else {
1363 p = unsafe.Pointer(&val.ptr)
1365 selected, ok := chanrecv(v.typ, v.pointer(), nb, p)
1366 if !selected {
1367 val = Value{}
1369 return
1372 // Send sends x on the channel v.
1373 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1374 // As in Go, x's value must be assignable to the channel's element type.
1375 func (v Value) Send(x Value) {
1376 v.mustBe(Chan)
1377 v.mustBeExported()
1378 v.send(x, false)
1381 // internal send, possibly non-blocking.
1382 // v is known to be a channel.
1383 func (v Value) send(x Value, nb bool) (selected bool) {
1384 tt := (*chanType)(unsafe.Pointer(v.typ))
1385 if ChanDir(tt.dir)&SendDir == 0 {
1386 panic("reflect: send on recv-only channel")
1388 x.mustBeExported()
1389 x = x.assignTo("reflect.Value.Send", tt.elem, nil)
1390 var p unsafe.Pointer
1391 if x.flag&flagIndir != 0 {
1392 p = x.ptr
1393 } else if x.typ.pointers() {
1394 p = unsafe.Pointer(&x.ptr)
1395 } else {
1396 // p = unsafe.Pointer(&x.scalar)
1397 panic("reflect: missing flagIndir")
1399 return chansend(v.typ, v.pointer(), p, nb)
1402 // Set assigns x to the value v.
1403 // It panics if CanSet returns false.
1404 // As in Go, x's value must be assignable to v's type.
1405 func (v Value) Set(x Value) {
1406 v.mustBeAssignable()
1407 x.mustBeExported() // do not let unexported x leak
1408 var target *interface{}
1409 if v.kind() == Interface {
1410 target = (*interface{})(v.ptr)
1412 x = x.assignTo("reflect.Set", v.typ, target)
1413 if x.flag&flagIndir != 0 {
1414 memmove(v.ptr, x.ptr, v.typ.size)
1415 } else if x.typ.pointers() {
1416 *(*unsafe.Pointer)(v.ptr) = x.ptr
1417 } else {
1418 // memmove(v.ptr, unsafe.Pointer(&x.scalar), v.typ.size)
1419 panic("reflect: missing flagIndir")
1423 // SetBool sets v's underlying value.
1424 // It panics if v's Kind is not Bool or if CanSet() is false.
1425 func (v Value) SetBool(x bool) {
1426 v.mustBeAssignable()
1427 v.mustBe(Bool)
1428 *(*bool)(v.ptr) = x
1431 // SetBytes sets v's underlying value.
1432 // It panics if v's underlying value is not a slice of bytes.
1433 func (v Value) SetBytes(x []byte) {
1434 v.mustBeAssignable()
1435 v.mustBe(Slice)
1436 if v.typ.Elem().Kind() != Uint8 {
1437 panic("reflect.Value.SetBytes of non-byte slice")
1439 *(*[]byte)(v.ptr) = x
1442 // setRunes sets v's underlying value.
1443 // It panics if v's underlying value is not a slice of runes (int32s).
1444 func (v Value) setRunes(x []rune) {
1445 v.mustBeAssignable()
1446 v.mustBe(Slice)
1447 if v.typ.Elem().Kind() != Int32 {
1448 panic("reflect.Value.setRunes of non-rune slice")
1450 *(*[]rune)(v.ptr) = x
1453 // SetComplex sets v's underlying value to x.
1454 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1455 func (v Value) SetComplex(x complex128) {
1456 v.mustBeAssignable()
1457 switch k := v.kind(); k {
1458 default:
1459 panic(&ValueError{"reflect.Value.SetComplex", k})
1460 case Complex64:
1461 *(*complex64)(v.ptr) = complex64(x)
1462 case Complex128:
1463 *(*complex128)(v.ptr) = x
1467 // SetFloat sets v's underlying value to x.
1468 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1469 func (v Value) SetFloat(x float64) {
1470 v.mustBeAssignable()
1471 switch k := v.kind(); k {
1472 default:
1473 panic(&ValueError{"reflect.Value.SetFloat", k})
1474 case Float32:
1475 *(*float32)(v.ptr) = float32(x)
1476 case Float64:
1477 *(*float64)(v.ptr) = x
1481 // SetInt sets v's underlying value to x.
1482 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1483 func (v Value) SetInt(x int64) {
1484 v.mustBeAssignable()
1485 switch k := v.kind(); k {
1486 default:
1487 panic(&ValueError{"reflect.Value.SetInt", k})
1488 case Int:
1489 *(*int)(v.ptr) = int(x)
1490 case Int8:
1491 *(*int8)(v.ptr) = int8(x)
1492 case Int16:
1493 *(*int16)(v.ptr) = int16(x)
1494 case Int32:
1495 *(*int32)(v.ptr) = int32(x)
1496 case Int64:
1497 *(*int64)(v.ptr) = x
1501 // SetLen sets v's length to n.
1502 // It panics if v's Kind is not Slice or if n is negative or
1503 // greater than the capacity of the slice.
1504 func (v Value) SetLen(n int) {
1505 v.mustBeAssignable()
1506 v.mustBe(Slice)
1507 s := (*sliceHeader)(v.ptr)
1508 if n < 0 || n > int(s.Cap) {
1509 panic("reflect: slice length out of range in SetLen")
1511 s.Len = n
1514 // SetCap sets v's capacity to n.
1515 // It panics if v's Kind is not Slice or if n is smaller than the length or
1516 // greater than the capacity of the slice.
1517 func (v Value) SetCap(n int) {
1518 v.mustBeAssignable()
1519 v.mustBe(Slice)
1520 s := (*sliceHeader)(v.ptr)
1521 if n < int(s.Len) || n > int(s.Cap) {
1522 panic("reflect: slice capacity out of range in SetCap")
1524 s.Cap = n
1527 // SetMapIndex sets the value associated with key in the map v to val.
1528 // It panics if v's Kind is not Map.
1529 // If val is the zero Value, SetMapIndex deletes the key from the map.
1530 // Otherwise if v holds a nil map, SetMapIndex will panic.
1531 // As in Go, key's value must be assignable to the map's key type,
1532 // and val's value must be assignable to the map's value type.
1533 func (v Value) SetMapIndex(key, val Value) {
1534 v.mustBe(Map)
1535 v.mustBeExported()
1536 key.mustBeExported()
1537 tt := (*mapType)(unsafe.Pointer(v.typ))
1538 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
1539 var k unsafe.Pointer
1540 if key.flag&flagIndir != 0 {
1541 k = key.ptr
1542 } else if key.typ.pointers() {
1543 k = unsafe.Pointer(&key.ptr)
1544 } else {
1545 // k = unsafe.Pointer(&key.scalar)
1546 panic("reflect: missing flagIndir")
1548 if val.typ == nil {
1549 mapdelete(v.typ, v.pointer(), k)
1550 return
1552 val.mustBeExported()
1553 val = val.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
1554 var e unsafe.Pointer
1555 if val.flag&flagIndir != 0 {
1556 e = val.ptr
1557 } else if val.typ.pointers() {
1558 e = unsafe.Pointer(&val.ptr)
1559 } else {
1560 // e = unsafe.Pointer(&val.scalar)
1561 panic("reflect: missing flagIndir")
1563 mapassign(v.typ, v.pointer(), k, e)
1566 // SetUint sets v's underlying value to x.
1567 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1568 func (v Value) SetUint(x uint64) {
1569 v.mustBeAssignable()
1570 switch k := v.kind(); k {
1571 default:
1572 panic(&ValueError{"reflect.Value.SetUint", k})
1573 case Uint:
1574 *(*uint)(v.ptr) = uint(x)
1575 case Uint8:
1576 *(*uint8)(v.ptr) = uint8(x)
1577 case Uint16:
1578 *(*uint16)(v.ptr) = uint16(x)
1579 case Uint32:
1580 *(*uint32)(v.ptr) = uint32(x)
1581 case Uint64:
1582 *(*uint64)(v.ptr) = x
1583 case Uintptr:
1584 *(*uintptr)(v.ptr) = uintptr(x)
1588 // SetPointer sets the unsafe.Pointer value v to x.
1589 // It panics if v's Kind is not UnsafePointer.
1590 func (v Value) SetPointer(x unsafe.Pointer) {
1591 v.mustBeAssignable()
1592 v.mustBe(UnsafePointer)
1593 *(*unsafe.Pointer)(v.ptr) = x
1596 // SetString sets v's underlying value to x.
1597 // It panics if v's Kind is not String or if CanSet() is false.
1598 func (v Value) SetString(x string) {
1599 v.mustBeAssignable()
1600 v.mustBe(String)
1601 *(*string)(v.ptr) = x
1604 // Slice returns v[i:j].
1605 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1606 // or if the indexes are out of bounds.
1607 func (v Value) Slice(i, j int) Value {
1608 var (
1609 cap int
1610 typ *sliceType
1611 base unsafe.Pointer
1613 switch kind := v.kind(); kind {
1614 default:
1615 panic(&ValueError{"reflect.Value.Slice", kind})
1617 case Array:
1618 if v.flag&flagAddr == 0 {
1619 panic("reflect.Value.Slice: slice of unaddressable array")
1621 tt := (*arrayType)(unsafe.Pointer(v.typ))
1622 cap = int(tt.len)
1623 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1624 base = v.ptr
1626 case Slice:
1627 typ = (*sliceType)(unsafe.Pointer(v.typ))
1628 s := (*sliceHeader)(v.ptr)
1629 base = unsafe.Pointer(s.Data)
1630 cap = s.Cap
1632 case String:
1633 s := (*stringHeader)(v.ptr)
1634 if i < 0 || j < i || j > s.Len {
1635 panic("reflect.Value.Slice: string slice index out of bounds")
1637 t := stringHeader{unsafe.Pointer(uintptr(s.Data) + uintptr(i)), j - i}
1638 return Value{v.typ, unsafe.Pointer(&t) /* 0, */, v.flag}
1641 if i < 0 || j < i || j > cap {
1642 panic("reflect.Value.Slice: slice index out of bounds")
1645 // Declare slice so that gc can see the base pointer in it.
1646 var x []unsafe.Pointer
1648 // Reinterpret as *sliceHeader to edit.
1649 s := (*sliceHeader)(unsafe.Pointer(&x))
1650 s.Data = unsafe.Pointer(uintptr(base) + uintptr(i)*typ.elem.Size())
1651 s.Len = j - i
1652 s.Cap = cap - i
1654 fl := v.flag&flagRO | flagIndir | flag(Slice)<<flagKindShift
1655 return Value{typ.common(), unsafe.Pointer(&x) /* 0, */, fl}
1658 // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1659 // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1660 // or if the indexes are out of bounds.
1661 func (v Value) Slice3(i, j, k int) Value {
1662 var (
1663 cap int
1664 typ *sliceType
1665 base unsafe.Pointer
1667 switch kind := v.kind(); kind {
1668 default:
1669 panic(&ValueError{"reflect.Value.Slice3", kind})
1671 case Array:
1672 if v.flag&flagAddr == 0 {
1673 panic("reflect.Value.Slice3: slice of unaddressable array")
1675 tt := (*arrayType)(unsafe.Pointer(v.typ))
1676 cap = int(tt.len)
1677 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1678 base = v.ptr
1680 case Slice:
1681 typ = (*sliceType)(unsafe.Pointer(v.typ))
1682 s := (*sliceHeader)(v.ptr)
1683 base = s.Data
1684 cap = s.Cap
1687 if i < 0 || j < i || k < j || k > cap {
1688 panic("reflect.Value.Slice3: slice index out of bounds")
1691 // Declare slice so that the garbage collector
1692 // can see the base pointer in it.
1693 var x []unsafe.Pointer
1695 // Reinterpret as *sliceHeader to edit.
1696 s := (*sliceHeader)(unsafe.Pointer(&x))
1697 s.Data = unsafe.Pointer(uintptr(base) + uintptr(i)*typ.elem.Size())
1698 s.Len = j - i
1699 s.Cap = k - i
1701 fl := v.flag&flagRO | flagIndir | flag(Slice)<<flagKindShift
1702 return Value{typ.common(), unsafe.Pointer(&x) /* 0, */, fl}
1705 // String returns the string v's underlying value, as a string.
1706 // String is a special case because of Go's String method convention.
1707 // Unlike the other getters, it does not panic if v's Kind is not String.
1708 // Instead, it returns a string of the form "<T value>" where T is v's type.
1709 func (v Value) String() string {
1710 switch k := v.kind(); k {
1711 case Invalid:
1712 return "<invalid Value>"
1713 case String:
1714 return *(*string)(v.ptr)
1716 // If you call String on a reflect.Value of other type, it's better to
1717 // print something than to panic. Useful in debugging.
1718 return "<" + v.typ.String() + " Value>"
1721 // TryRecv attempts to receive a value from the channel v but will not block.
1722 // It panics if v's Kind is not Chan.
1723 // If the receive delivers a value, x is the transferred value and ok is true.
1724 // If the receive cannot finish without blocking, x is the zero Value and ok is false.
1725 // If the channel is closed, x is the zero value for the channel's element type and ok is false.
1726 func (v Value) TryRecv() (x Value, ok bool) {
1727 v.mustBe(Chan)
1728 v.mustBeExported()
1729 return v.recv(true)
1732 // TrySend attempts to send x on the channel v but will not block.
1733 // It panics if v's Kind is not Chan.
1734 // It returns true if the value was sent, false otherwise.
1735 // As in Go, x's value must be assignable to the channel's element type.
1736 func (v Value) TrySend(x Value) bool {
1737 v.mustBe(Chan)
1738 v.mustBeExported()
1739 return v.send(x, true)
1742 // Type returns v's type.
1743 func (v Value) Type() Type {
1744 f := v.flag
1745 if f == 0 {
1746 panic(&ValueError{"reflect.Value.Type", Invalid})
1748 if f&flagMethod == 0 {
1749 // Easy case
1750 return toType(v.typ)
1753 // Method value.
1754 // v.typ describes the receiver, not the method type.
1755 i := int(v.flag) >> flagMethodShift
1756 if v.typ.Kind() == Interface {
1757 // Method on interface.
1758 tt := (*interfaceType)(unsafe.Pointer(v.typ))
1759 if i < 0 || i >= len(tt.methods) {
1760 panic("reflect: internal error: invalid method index")
1762 m := &tt.methods[i]
1763 return toType(m.typ)
1765 // Method on concrete type.
1766 ut := v.typ.uncommon()
1767 if ut == nil || i < 0 || i >= len(ut.methods) {
1768 panic("reflect: internal error: invalid method index")
1770 m := &ut.methods[i]
1771 return toType(m.mtyp)
1774 // Uint returns v's underlying value, as a uint64.
1775 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1776 func (v Value) Uint() uint64 {
1777 k := v.kind()
1778 var p unsafe.Pointer
1779 if v.flag&flagIndir != 0 {
1780 p = v.ptr
1781 } else {
1782 // The escape analysis is good enough that &v.scalar
1783 // does not trigger a heap allocation.
1784 // p = unsafe.Pointer(&v.scalar)
1785 switch k {
1786 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
1787 panic("reflect: missing flagIndir")
1790 switch k {
1791 case Uint:
1792 return uint64(*(*uint)(p))
1793 case Uint8:
1794 return uint64(*(*uint8)(p))
1795 case Uint16:
1796 return uint64(*(*uint16)(p))
1797 case Uint32:
1798 return uint64(*(*uint32)(p))
1799 case Uint64:
1800 return uint64(*(*uint64)(p))
1801 case Uintptr:
1802 return uint64(*(*uintptr)(p))
1804 panic(&ValueError{"reflect.Value.Uint", k})
1807 // UnsafeAddr returns a pointer to v's data.
1808 // It is for advanced clients that also import the "unsafe" package.
1809 // It panics if v is not addressable.
1810 func (v Value) UnsafeAddr() uintptr {
1811 // TODO: deprecate
1812 if v.typ == nil {
1813 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1815 if v.flag&flagAddr == 0 {
1816 panic("reflect.Value.UnsafeAddr of unaddressable value")
1818 return uintptr(v.ptr)
1821 // StringHeader is the runtime representation of a string.
1822 // It cannot be used safely or portably and its representation may
1823 // change in a later release.
1824 // Moreover, the Data field is not sufficient to guarantee the data
1825 // it references will not be garbage collected, so programs must keep
1826 // a separate, correctly typed pointer to the underlying data.
1827 type StringHeader struct {
1828 Data uintptr
1829 Len int
1832 // stringHeader is a safe version of StringHeader used within this package.
1833 type stringHeader struct {
1834 Data unsafe.Pointer
1835 Len int
1838 // SliceHeader is the runtime representation of a slice.
1839 // It cannot be used safely or portably and its representation may
1840 // change in a later release.
1841 // Moreover, the Data field is not sufficient to guarantee the data
1842 // it references will not be garbage collected, so programs must keep
1843 // a separate, correctly typed pointer to the underlying data.
1844 type SliceHeader struct {
1845 Data uintptr
1846 Len int
1847 Cap int
1850 // sliceHeader is a safe version of SliceHeader used within this package.
1851 type sliceHeader struct {
1852 Data unsafe.Pointer
1853 Len int
1854 Cap int
1857 func typesMustMatch(what string, t1, t2 Type) {
1858 if t1 != t2 {
1859 panic(what + ": " + t1.String() + " != " + t2.String())
1863 // grow grows the slice s so that it can hold extra more values, allocating
1864 // more capacity if needed. It also returns the old and new slice lengths.
1865 func grow(s Value, extra int) (Value, int, int) {
1866 i0 := s.Len()
1867 i1 := i0 + extra
1868 if i1 < i0 {
1869 panic("reflect.Append: slice overflow")
1871 m := s.Cap()
1872 if i1 <= m {
1873 return s.Slice(0, i1), i0, i1
1875 if m == 0 {
1876 m = extra
1877 } else {
1878 for m < i1 {
1879 if i0 < 1024 {
1880 m += m
1881 } else {
1882 m += m / 4
1886 t := MakeSlice(s.Type(), i1, m)
1887 Copy(t, s)
1888 return t, i0, i1
1891 // Append appends the values x to a slice s and returns the resulting slice.
1892 // As in Go, each x's value must be assignable to the slice's element type.
1893 func Append(s Value, x ...Value) Value {
1894 s.mustBe(Slice)
1895 s, i0, i1 := grow(s, len(x))
1896 for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1897 s.Index(i).Set(x[j])
1899 return s
1902 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1903 // The slices s and t must have the same element type.
1904 func AppendSlice(s, t Value) Value {
1905 s.mustBe(Slice)
1906 t.mustBe(Slice)
1907 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1908 s, i0, i1 := grow(s, t.Len())
1909 Copy(s.Slice(i0, i1), t)
1910 return s
1913 // Copy copies the contents of src into dst until either
1914 // dst has been filled or src has been exhausted.
1915 // It returns the number of elements copied.
1916 // Dst and src each must have kind Slice or Array, and
1917 // dst and src must have the same element type.
1918 func Copy(dst, src Value) int {
1919 dk := dst.kind()
1920 if dk != Array && dk != Slice {
1921 panic(&ValueError{"reflect.Copy", dk})
1923 if dk == Array {
1924 dst.mustBeAssignable()
1926 dst.mustBeExported()
1928 sk := src.kind()
1929 if sk != Array && sk != Slice {
1930 panic(&ValueError{"reflect.Copy", sk})
1932 src.mustBeExported()
1934 de := dst.typ.Elem()
1935 se := src.typ.Elem()
1936 typesMustMatch("reflect.Copy", de, se)
1938 n := dst.Len()
1939 if sn := src.Len(); n > sn {
1940 n = sn
1943 // If sk is an in-line array, cannot take its address.
1944 // Instead, copy element by element.
1945 // TODO: memmove would be ok for this (sa = unsafe.Pointer(&v.scalar))
1946 // if we teach the compiler that ptrs don't escape from memmove.
1947 if src.flag&flagIndir == 0 {
1948 for i := 0; i < n; i++ {
1949 dst.Index(i).Set(src.Index(i))
1951 return n
1954 // Copy via memmove.
1955 var da, sa unsafe.Pointer
1956 if dk == Array {
1957 da = dst.ptr
1958 } else {
1959 da = (*sliceHeader)(dst.ptr).Data
1961 if sk == Array {
1962 sa = src.ptr
1963 } else {
1964 sa = (*sliceHeader)(src.ptr).Data
1966 memmove(da, sa, uintptr(n)*de.Size())
1967 return n
1970 // A runtimeSelect is a single case passed to rselect.
1971 // This must match ../runtime/chan.c:/runtimeSelect
1972 type runtimeSelect struct {
1973 dir uintptr // 0, SendDir, or RecvDir
1974 typ *rtype // channel type
1975 ch unsafe.Pointer // channel
1976 val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
1979 // rselect runs a select. It returns the index of the chosen case.
1980 // If the case was a receive, val is filled in with the received value.
1981 // The conventional OK bool indicates whether the receive corresponds
1982 // to a sent value.
1983 //go:noescape
1984 func rselect([]runtimeSelect) (chosen int, recvOK bool)
1986 // A SelectDir describes the communication direction of a select case.
1987 type SelectDir int
1989 // NOTE: These values must match ../runtime/chan.c:/SelectDir.
1991 const (
1992 _ SelectDir = iota
1993 SelectSend // case Chan <- Send
1994 SelectRecv // case <-Chan:
1995 SelectDefault // default
1998 // A SelectCase describes a single case in a select operation.
1999 // The kind of case depends on Dir, the communication direction.
2001 // If Dir is SelectDefault, the case represents a default case.
2002 // Chan and Send must be zero Values.
2004 // If Dir is SelectSend, the case represents a send operation.
2005 // Normally Chan's underlying value must be a channel, and Send's underlying value must be
2006 // assignable to the channel's element type. As a special case, if Chan is a zero Value,
2007 // then the case is ignored, and the field Send will also be ignored and may be either zero
2008 // or non-zero.
2010 // If Dir is SelectRecv, the case represents a receive operation.
2011 // Normally Chan's underlying value must be a channel and Send must be a zero Value.
2012 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
2013 // When a receive operation is selected, the received Value is returned by Select.
2015 type SelectCase struct {
2016 Dir SelectDir // direction of case
2017 Chan Value // channel to use (for send or receive)
2018 Send Value // value to send (for send)
2021 // Select executes a select operation described by the list of cases.
2022 // Like the Go select statement, it blocks until at least one of the cases
2023 // can proceed, makes a uniform pseudo-random choice,
2024 // and then executes that case. It returns the index of the chosen case
2025 // and, if that case was a receive operation, the value received and a
2026 // boolean indicating whether the value corresponds to a send on the channel
2027 // (as opposed to a zero value received because the channel is closed).
2028 func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
2029 // NOTE: Do not trust that caller is not modifying cases data underfoot.
2030 // The range is safe because the caller cannot modify our copy of the len
2031 // and each iteration makes its own copy of the value c.
2032 runcases := make([]runtimeSelect, len(cases))
2033 haveDefault := false
2034 for i, c := range cases {
2035 rc := &runcases[i]
2036 rc.dir = uintptr(c.Dir)
2037 switch c.Dir {
2038 default:
2039 panic("reflect.Select: invalid Dir")
2041 case SelectDefault: // default
2042 if haveDefault {
2043 panic("reflect.Select: multiple default cases")
2045 haveDefault = true
2046 if c.Chan.IsValid() {
2047 panic("reflect.Select: default case has Chan value")
2049 if c.Send.IsValid() {
2050 panic("reflect.Select: default case has Send value")
2053 case SelectSend:
2054 ch := c.Chan
2055 if !ch.IsValid() {
2056 break
2058 ch.mustBe(Chan)
2059 ch.mustBeExported()
2060 tt := (*chanType)(unsafe.Pointer(ch.typ))
2061 if ChanDir(tt.dir)&SendDir == 0 {
2062 panic("reflect.Select: SendDir case using recv-only channel")
2064 rc.ch = ch.pointer()
2065 rc.typ = &tt.rtype
2066 v := c.Send
2067 if !v.IsValid() {
2068 panic("reflect.Select: SendDir case missing Send value")
2070 v.mustBeExported()
2071 v = v.assignTo("reflect.Select", tt.elem, nil)
2072 if v.flag&flagIndir != 0 {
2073 rc.val = v.ptr
2074 } else if v.typ.pointers() {
2075 rc.val = unsafe.Pointer(&v.ptr)
2076 } else {
2077 // rc.val = unsafe.Pointer(&v.scalar)
2078 panic("reflect: missing flagIndir")
2081 case SelectRecv:
2082 if c.Send.IsValid() {
2083 panic("reflect.Select: RecvDir case has Send value")
2085 ch := c.Chan
2086 if !ch.IsValid() {
2087 break
2089 ch.mustBe(Chan)
2090 ch.mustBeExported()
2091 tt := (*chanType)(unsafe.Pointer(ch.typ))
2092 if ChanDir(tt.dir)&RecvDir == 0 {
2093 panic("reflect.Select: RecvDir case using send-only channel")
2095 rc.ch = ch.pointer()
2096 rc.typ = &tt.rtype
2097 rc.val = unsafe_New(tt.elem)
2101 chosen, recvOK = rselect(runcases)
2102 if runcases[chosen].dir == uintptr(SelectRecv) {
2103 tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
2104 t := tt.elem
2105 p := runcases[chosen].val
2106 fl := flag(t.Kind()) << flagKindShift
2107 if t.Kind() != Ptr && t.Kind() != UnsafePointer {
2108 recv = Value{t, p /* 0, */, fl | flagIndir}
2109 } else {
2110 recv = Value{t, *(*unsafe.Pointer)(p) /* 0, */, fl}
2113 return chosen, recv, recvOK
2117 * constructors
2120 // implemented in package runtime
2121 func unsafe_New(*rtype) unsafe.Pointer
2122 func unsafe_NewArray(*rtype, int) unsafe.Pointer
2124 // MakeSlice creates a new zero-initialized slice value
2125 // for the specified slice type, length, and capacity.
2126 func MakeSlice(typ Type, len, cap int) Value {
2127 if typ.Kind() != Slice {
2128 panic("reflect.MakeSlice of non-slice type")
2130 if len < 0 {
2131 panic("reflect.MakeSlice: negative len")
2133 if cap < 0 {
2134 panic("reflect.MakeSlice: negative cap")
2136 if len > cap {
2137 panic("reflect.MakeSlice: len > cap")
2140 s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap}
2141 return Value{typ.common(), unsafe.Pointer(&s) /* 0, */, flagIndir | flag(Slice)<<flagKindShift}
2144 // MakeChan creates a new channel with the specified type and buffer size.
2145 func MakeChan(typ Type, buffer int) Value {
2146 if typ.Kind() != Chan {
2147 panic("reflect.MakeChan of non-chan type")
2149 if buffer < 0 {
2150 panic("reflect.MakeChan: negative buffer size")
2152 if typ.ChanDir() != BothDir {
2153 panic("reflect.MakeChan: unidirectional channel type")
2155 ch := makechan(typ.(*rtype), uint64(buffer))
2156 return Value{typ.common(), unsafe.Pointer(&ch) /* 0, */, flagIndir | (flag(Chan) << flagKindShift)}
2159 // MakeMap creates a new map of the specified type.
2160 func MakeMap(typ Type) Value {
2161 if typ.Kind() != Map {
2162 panic("reflect.MakeMap of non-map type")
2164 m := makemap(typ.(*rtype))
2165 return Value{typ.common(), unsafe.Pointer(&m) /* 0, */, flagIndir | (flag(Map) << flagKindShift)}
2168 // Indirect returns the value that v points to.
2169 // If v is a nil pointer, Indirect returns a zero Value.
2170 // If v is not a pointer, Indirect returns v.
2171 func Indirect(v Value) Value {
2172 if v.Kind() != Ptr {
2173 return v
2175 return v.Elem()
2178 // ValueOf returns a new Value initialized to the concrete value
2179 // stored in the interface i. ValueOf(nil) returns the zero Value.
2180 func ValueOf(i interface{}) Value {
2181 if i == nil {
2182 return Value{}
2185 // TODO(rsc): Eliminate this terrible hack.
2186 // In the call to unpackEface, i.typ doesn't escape,
2187 // and i.word is an integer. So it looks like
2188 // i doesn't escape. But really it does,
2189 // because i.word is actually a pointer.
2190 escapes(i)
2192 return unpackEface(i)
2195 // Zero returns a Value representing the zero value for the specified type.
2196 // The result is different from the zero value of the Value struct,
2197 // which represents no value at all.
2198 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
2199 // The returned value is neither addressable nor settable.
2200 func Zero(typ Type) Value {
2201 if typ == nil {
2202 panic("reflect: Zero(nil)")
2204 t := typ.common()
2205 fl := flag(t.Kind()) << flagKindShift
2206 if t.Kind() == Ptr || t.Kind() == UnsafePointer {
2207 return Value{t, nil /* 0, */, fl}
2209 return Value{t, unsafe_New(typ.(*rtype)) /* 0, */, fl | flagIndir}
2212 // New returns a Value representing a pointer to a new zero value
2213 // for the specified type. That is, the returned Value's Type is PtrTo(typ).
2214 func New(typ Type) Value {
2215 if typ == nil {
2216 panic("reflect: New(nil)")
2218 ptr := unsafe_New(typ.(*rtype))
2219 fl := flag(Ptr) << flagKindShift
2220 return Value{typ.common().ptrTo(), ptr /* 0, */, fl}
2223 // NewAt returns a Value representing a pointer to a value of the
2224 // specified type, using p as that pointer.
2225 func NewAt(typ Type, p unsafe.Pointer) Value {
2226 fl := flag(Ptr) << flagKindShift
2227 return Value{typ.common().ptrTo(), p /* 0, */, fl}
2230 // assignTo returns a value v that can be assigned directly to typ.
2231 // It panics if v is not assignable to typ.
2232 // For a conversion to an interface type, target is a suggested scratch space to use.
2233 func (v Value) assignTo(context string, dst *rtype, target *interface{}) Value {
2234 if v.flag&flagMethod != 0 {
2235 v = makeMethodValue(context, v)
2238 switch {
2239 case directlyAssignable(dst, v.typ):
2240 // Overwrite type so that they match.
2241 // Same memory layout, so no harm done.
2242 v.typ = dst
2243 fl := v.flag & (flagRO | flagAddr | flagIndir)
2244 fl |= flag(dst.Kind()) << flagKindShift
2245 return Value{dst, v.ptr /* v.scalar, */, fl}
2247 case implements(dst, v.typ):
2248 if target == nil {
2249 target = new(interface{})
2251 x := valueInterface(v, false)
2252 if dst.NumMethod() == 0 {
2253 *target = x
2254 } else {
2255 ifaceE2I(dst, x, unsafe.Pointer(target))
2257 return Value{dst, unsafe.Pointer(target) /* 0, */, flagIndir | flag(Interface)<<flagKindShift}
2260 // Failed.
2261 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2264 // Convert returns the value v converted to type t.
2265 // If the usual Go conversion rules do not allow conversion
2266 // of the value v to type t, Convert panics.
2267 func (v Value) Convert(t Type) Value {
2268 if v.flag&flagMethod != 0 {
2269 v = makeMethodValue("Convert", v)
2271 op := convertOp(t.common(), v.typ)
2272 if op == nil {
2273 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2275 return op(v, t)
2278 // convertOp returns the function to convert a value of type src
2279 // to a value of type dst. If the conversion is illegal, convertOp returns nil.
2280 func convertOp(dst, src *rtype) func(Value, Type) Value {
2281 switch src.Kind() {
2282 case Int, Int8, Int16, Int32, Int64:
2283 switch dst.Kind() {
2284 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2285 return cvtInt
2286 case Float32, Float64:
2287 return cvtIntFloat
2288 case String:
2289 return cvtIntString
2292 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2293 switch dst.Kind() {
2294 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2295 return cvtUint
2296 case Float32, Float64:
2297 return cvtUintFloat
2298 case String:
2299 return cvtUintString
2302 case Float32, Float64:
2303 switch dst.Kind() {
2304 case Int, Int8, Int16, Int32, Int64:
2305 return cvtFloatInt
2306 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2307 return cvtFloatUint
2308 case Float32, Float64:
2309 return cvtFloat
2312 case Complex64, Complex128:
2313 switch dst.Kind() {
2314 case Complex64, Complex128:
2315 return cvtComplex
2318 case String:
2319 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2320 switch dst.Elem().Kind() {
2321 case Uint8:
2322 return cvtStringBytes
2323 case Int32:
2324 return cvtStringRunes
2328 case Slice:
2329 if dst.Kind() == String && src.Elem().PkgPath() == "" {
2330 switch src.Elem().Kind() {
2331 case Uint8:
2332 return cvtBytesString
2333 case Int32:
2334 return cvtRunesString
2339 // dst and src have same underlying type.
2340 if haveIdenticalUnderlyingType(dst, src) {
2341 return cvtDirect
2344 // dst and src are unnamed pointer types with same underlying base type.
2345 if dst.Kind() == Ptr && dst.Name() == "" &&
2346 src.Kind() == Ptr && src.Name() == "" &&
2347 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common()) {
2348 return cvtDirect
2351 if implements(dst, src) {
2352 if src.Kind() == Interface {
2353 return cvtI2I
2355 return cvtT2I
2358 return nil
2361 // makeInt returns a Value of type t equal to bits (possibly truncated),
2362 // where t is a signed or unsigned int type.
2363 func makeInt(f flag, bits uint64, t Type) Value {
2364 typ := t.common()
2365 if typ.size > ptrSize {
2366 // Assume ptrSize >= 4, so this must be uint64.
2367 ptr := unsafe_New(typ)
2368 *(*uint64)(unsafe.Pointer(ptr)) = bits
2369 return Value{typ, ptr /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2371 var s uintptr
2372 switch typ.size {
2373 case 1:
2374 *(*uint8)(unsafe.Pointer(&s)) = uint8(bits)
2375 case 2:
2376 *(*uint16)(unsafe.Pointer(&s)) = uint16(bits)
2377 case 4:
2378 *(*uint32)(unsafe.Pointer(&s)) = uint32(bits)
2379 case 8:
2380 *(*uint64)(unsafe.Pointer(&s)) = uint64(bits)
2382 return Value{typ, unsafe.Pointer(&s) /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2385 // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2386 // where t is a float32 or float64 type.
2387 func makeFloat(f flag, v float64, t Type) Value {
2388 typ := t.common()
2389 if typ.size > ptrSize {
2390 // Assume ptrSize >= 4, so this must be float64.
2391 ptr := unsafe_New(typ)
2392 *(*float64)(unsafe.Pointer(ptr)) = v
2393 return Value{typ, ptr /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2396 var s uintptr
2397 switch typ.size {
2398 case 4:
2399 *(*float32)(unsafe.Pointer(&s)) = float32(v)
2400 case 8:
2401 *(*float64)(unsafe.Pointer(&s)) = v
2403 return Value{typ, unsafe.Pointer(&s) /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2406 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2407 // where t is a complex64 or complex128 type.
2408 func makeComplex(f flag, v complex128, t Type) Value {
2409 typ := t.common()
2410 if typ.size > ptrSize {
2411 ptr := unsafe_New(typ)
2412 switch typ.size {
2413 case 8:
2414 *(*complex64)(unsafe.Pointer(ptr)) = complex64(v)
2415 case 16:
2416 *(*complex128)(unsafe.Pointer(ptr)) = v
2418 return Value{typ, ptr /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2421 // Assume ptrSize <= 8 so this must be complex64.
2422 var s uintptr
2423 *(*complex64)(unsafe.Pointer(&s)) = complex64(v)
2424 return Value{typ, unsafe.Pointer(&s) /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2427 func makeString(f flag, v string, t Type) Value {
2428 ret := New(t).Elem()
2429 ret.SetString(v)
2430 ret.flag = ret.flag&^flagAddr | f | flagIndir
2431 return ret
2434 func makeBytes(f flag, v []byte, t Type) Value {
2435 ret := New(t).Elem()
2436 ret.SetBytes(v)
2437 ret.flag = ret.flag&^flagAddr | f | flagIndir
2438 return ret
2441 func makeRunes(f flag, v []rune, t Type) Value {
2442 ret := New(t).Elem()
2443 ret.setRunes(v)
2444 ret.flag = ret.flag&^flagAddr | f | flagIndir
2445 return ret
2448 // These conversion functions are returned by convertOp
2449 // for classes of conversions. For example, the first function, cvtInt,
2450 // takes any value v of signed int type and returns the value converted
2451 // to type t, where t is any signed or unsigned int type.
2453 // convertOp: intXX -> [u]intXX
2454 func cvtInt(v Value, t Type) Value {
2455 return makeInt(v.flag&flagRO, uint64(v.Int()), t)
2458 // convertOp: uintXX -> [u]intXX
2459 func cvtUint(v Value, t Type) Value {
2460 return makeInt(v.flag&flagRO, v.Uint(), t)
2463 // convertOp: floatXX -> intXX
2464 func cvtFloatInt(v Value, t Type) Value {
2465 return makeInt(v.flag&flagRO, uint64(int64(v.Float())), t)
2468 // convertOp: floatXX -> uintXX
2469 func cvtFloatUint(v Value, t Type) Value {
2470 return makeInt(v.flag&flagRO, uint64(v.Float()), t)
2473 // convertOp: intXX -> floatXX
2474 func cvtIntFloat(v Value, t Type) Value {
2475 return makeFloat(v.flag&flagRO, float64(v.Int()), t)
2478 // convertOp: uintXX -> floatXX
2479 func cvtUintFloat(v Value, t Type) Value {
2480 return makeFloat(v.flag&flagRO, float64(v.Uint()), t)
2483 // convertOp: floatXX -> floatXX
2484 func cvtFloat(v Value, t Type) Value {
2485 return makeFloat(v.flag&flagRO, v.Float(), t)
2488 // convertOp: complexXX -> complexXX
2489 func cvtComplex(v Value, t Type) Value {
2490 return makeComplex(v.flag&flagRO, v.Complex(), t)
2493 // convertOp: intXX -> string
2494 func cvtIntString(v Value, t Type) Value {
2495 return makeString(v.flag&flagRO, string(v.Int()), t)
2498 // convertOp: uintXX -> string
2499 func cvtUintString(v Value, t Type) Value {
2500 return makeString(v.flag&flagRO, string(v.Uint()), t)
2503 // convertOp: []byte -> string
2504 func cvtBytesString(v Value, t Type) Value {
2505 return makeString(v.flag&flagRO, string(v.Bytes()), t)
2508 // convertOp: string -> []byte
2509 func cvtStringBytes(v Value, t Type) Value {
2510 return makeBytes(v.flag&flagRO, []byte(v.String()), t)
2513 // convertOp: []rune -> string
2514 func cvtRunesString(v Value, t Type) Value {
2515 return makeString(v.flag&flagRO, string(v.runes()), t)
2518 // convertOp: string -> []rune
2519 func cvtStringRunes(v Value, t Type) Value {
2520 return makeRunes(v.flag&flagRO, []rune(v.String()), t)
2523 // convertOp: direct copy
2524 func cvtDirect(v Value, typ Type) Value {
2525 f := v.flag
2526 t := typ.common()
2527 ptr := v.ptr
2528 if f&flagAddr != 0 {
2529 // indirect, mutable word - make a copy
2530 c := unsafe_New(t)
2531 memmove(c, ptr, t.size)
2532 ptr = c
2533 f &^= flagAddr
2535 return Value{t, ptr /* v.scalar, */, v.flag&flagRO | f} // v.flag&flagRO|f == f?
2538 // convertOp: concrete -> interface
2539 func cvtT2I(v Value, typ Type) Value {
2540 target := new(interface{})
2541 x := valueInterface(v, false)
2542 if typ.NumMethod() == 0 {
2543 *target = x
2544 } else {
2545 ifaceE2I(typ.(*rtype), x, unsafe.Pointer(target))
2547 return Value{typ.common(), unsafe.Pointer(target) /* 0, */, v.flag&flagRO | flagIndir | flag(Interface)<<flagKindShift}
2550 // convertOp: interface -> interface
2551 func cvtI2I(v Value, typ Type) Value {
2552 if v.IsNil() {
2553 ret := Zero(typ)
2554 ret.flag |= v.flag & flagRO
2555 return ret
2557 return cvtT2I(v.Elem(), typ)
2560 // implemented in ../pkg/runtime
2561 func chancap(ch unsafe.Pointer) int
2562 func chanclose(ch unsafe.Pointer)
2563 func chanlen(ch unsafe.Pointer) int
2565 //go:noescape
2566 func chanrecv(t *rtype, ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
2568 //go:noescape
2569 func chansend(t *rtype, ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
2571 func makechan(typ *rtype, size uint64) (ch unsafe.Pointer)
2572 func makemap(t *rtype) (m unsafe.Pointer)
2573 func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
2574 func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
2575 func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
2576 func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
2577 func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
2578 func mapiternext(it unsafe.Pointer)
2579 func maplen(m unsafe.Pointer) int
2581 func call(typ *rtype, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
2582 func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
2584 // Dummy annotation marking that the value x escapes,
2585 // for use in cases where the reflect code is so clever that
2586 // the compiler cannot follow.
2587 func escapes(x interface{}) {
2588 if dummy.b {
2589 dummy.x = x
2593 var dummy struct {
2594 b bool
2595 x interface{}