libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / reflect / value.go
blob877bfac6d245a32548e356df70aea165311792f1
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 // Because the value sometimes holds a pointer, we use
220 // unsafe.Pointer to represent it, so that if iword appears
221 // in a struct, the garbage collector knows that might be
222 // a pointer.
223 // TODO: get rid of all occurrences of iword (except in the interface decls below?)
224 // We want to get rid of the "feature" that an unsafe.Pointer is sometimes a pointer
225 // and sometimes a uintptr.
226 type iword unsafe.Pointer
228 // Get an iword that represents this value.
229 // TODO: this function goes away at some point
230 func (v Value) iword() iword {
231 t := v.typ
232 if t == nil {
233 return iword(nil)
235 if v.flag&flagIndir != 0 {
236 if v.kind() != Ptr && v.kind() != UnsafePointer {
237 return iword(v.ptr)
239 // Have indirect but want direct word.
240 if t.pointers() {
241 return iword(*(*unsafe.Pointer)(v.ptr))
243 return iword(loadScalar(v.ptr, v.typ.size))
245 if t.pointers() {
246 return iword(v.ptr)
248 // return iword(v.scalar)
249 panic("reflect: missing flagIndir")
252 // Build a Value from a type/iword pair, plus any extra flags.
253 // TODO: this function goes away at some point
254 func fromIword(t *rtype, w iword, fl flag) Value {
255 fl |= flag(t.Kind()) << flagKindShift
256 if t.Kind() != Ptr && t.Kind() != UnsafePointer {
257 return Value{t, unsafe.Pointer(w) /* 0, */, fl | flagIndir}
258 } else if t.pointers() {
259 return Value{t, unsafe.Pointer(w) /* 0, */, fl}
260 } else {
261 panic("reflect: can't reach")
265 // loadScalar loads n bytes at p from memory into a uintptr
266 // that forms the second word of an interface. The data
267 // must be non-pointer in nature.
268 func loadScalar(p unsafe.Pointer, n uintptr) uintptr {
269 // Run the copy ourselves instead of calling memmove
270 // to avoid moving w to the heap.
271 var w uintptr
272 switch n {
273 default:
274 panic("reflect: internal error: loadScalar of " + strconv.Itoa(int(n)) + "-byte value")
275 case 0:
276 case 1:
277 *(*uint8)(unsafe.Pointer(&w)) = *(*uint8)(p)
278 case 2:
279 *(*uint16)(unsafe.Pointer(&w)) = *(*uint16)(p)
280 case 3:
281 *(*[3]byte)(unsafe.Pointer(&w)) = *(*[3]byte)(p)
282 case 4:
283 *(*uint32)(unsafe.Pointer(&w)) = *(*uint32)(p)
284 case 5:
285 *(*[5]byte)(unsafe.Pointer(&w)) = *(*[5]byte)(p)
286 case 6:
287 *(*[6]byte)(unsafe.Pointer(&w)) = *(*[6]byte)(p)
288 case 7:
289 *(*[7]byte)(unsafe.Pointer(&w)) = *(*[7]byte)(p)
290 case 8:
291 *(*uint64)(unsafe.Pointer(&w)) = *(*uint64)(p)
293 return w
296 // storeScalar stores n bytes from w into p.
297 func storeScalar(p unsafe.Pointer, w uintptr, n uintptr) {
298 // Run the copy ourselves instead of calling memmove
299 // to avoid moving w to the heap.
300 switch n {
301 default:
302 panic("reflect: internal error: storeScalar of " + strconv.Itoa(int(n)) + "-byte value")
303 case 0:
304 case 1:
305 *(*uint8)(p) = *(*uint8)(unsafe.Pointer(&w))
306 case 2:
307 *(*uint16)(p) = *(*uint16)(unsafe.Pointer(&w))
308 case 3:
309 *(*[3]byte)(p) = *(*[3]byte)(unsafe.Pointer(&w))
310 case 4:
311 *(*uint32)(p) = *(*uint32)(unsafe.Pointer(&w))
312 case 5:
313 *(*[5]byte)(p) = *(*[5]byte)(unsafe.Pointer(&w))
314 case 6:
315 *(*[6]byte)(p) = *(*[6]byte)(unsafe.Pointer(&w))
316 case 7:
317 *(*[7]byte)(p) = *(*[7]byte)(unsafe.Pointer(&w))
318 case 8:
319 *(*uint64)(p) = *(*uint64)(unsafe.Pointer(&w))
323 // emptyInterface is the header for an interface{} value.
324 type emptyInterface struct {
325 typ *rtype
326 word iword
329 // nonEmptyInterface is the header for a interface value with methods.
330 type nonEmptyInterface struct {
331 // see ../runtime/iface.c:/Itab
332 itab *struct {
333 typ *rtype // dynamic concrete type
334 fun [100000]unsafe.Pointer // method table
336 word iword
339 // mustBe panics if f's kind is not expected.
340 // Making this a method on flag instead of on Value
341 // (and embedding flag in Value) means that we can write
342 // the very clear v.mustBe(Bool) and have it compile into
343 // v.flag.mustBe(Bool), which will only bother to copy the
344 // single important word for the receiver.
345 func (f flag) mustBe(expected Kind) {
346 k := f.kind()
347 if k != expected {
348 panic(&ValueError{methodName(), k})
352 // mustBeExported panics if f records that the value was obtained using
353 // an unexported field.
354 func (f flag) mustBeExported() {
355 if f == 0 {
356 panic(&ValueError{methodName(), 0})
358 if f&flagRO != 0 {
359 panic("reflect: " + methodName() + " using value obtained using unexported field")
363 // mustBeAssignable panics if f records that the value is not assignable,
364 // which is to say that either it was obtained using an unexported field
365 // or it is not addressable.
366 func (f flag) mustBeAssignable() {
367 if f == 0 {
368 panic(&ValueError{methodName(), Invalid})
370 // Assignable if addressable and not read-only.
371 if f&flagRO != 0 {
372 panic("reflect: " + methodName() + " using value obtained using unexported field")
374 if f&flagAddr == 0 {
375 panic("reflect: " + methodName() + " using unaddressable value")
379 // Addr returns a pointer value representing the address of v.
380 // It panics if CanAddr() returns false.
381 // Addr is typically used to obtain a pointer to a struct field
382 // or slice element in order to call a method that requires a
383 // pointer receiver.
384 func (v Value) Addr() Value {
385 if v.flag&flagAddr == 0 {
386 panic("reflect.Value.Addr of unaddressable value")
388 return Value{v.typ.ptrTo(), v.ptr /* 0, */, (v.flag & flagRO) | flag(Ptr)<<flagKindShift}
391 // Bool returns v's underlying value.
392 // It panics if v's kind is not Bool.
393 func (v Value) Bool() bool {
394 v.mustBe(Bool)
395 if v.flag&flagIndir != 0 {
396 return *(*bool)(v.ptr)
398 // return *(*bool)(unsafe.Pointer(&v.scalar))
399 panic("reflect: missing flagIndir")
402 // Bytes returns v's underlying value.
403 // It panics if v's underlying value is not a slice of bytes.
404 func (v Value) Bytes() []byte {
405 v.mustBe(Slice)
406 if v.typ.Elem().Kind() != Uint8 {
407 panic("reflect.Value.Bytes of non-byte slice")
409 // Slice is always bigger than a word; assume flagIndir.
410 return *(*[]byte)(v.ptr)
413 // runes returns v's underlying value.
414 // It panics if v's underlying value is not a slice of runes (int32s).
415 func (v Value) runes() []rune {
416 v.mustBe(Slice)
417 if v.typ.Elem().Kind() != Int32 {
418 panic("reflect.Value.Bytes of non-rune slice")
420 // Slice is always bigger than a word; assume flagIndir.
421 return *(*[]rune)(v.ptr)
424 // CanAddr returns true if the value's address can be obtained with Addr.
425 // Such values are called addressable. A value is addressable if it is
426 // an element of a slice, an element of an addressable array,
427 // a field of an addressable struct, or the result of dereferencing a pointer.
428 // If CanAddr returns false, calling Addr will panic.
429 func (v Value) CanAddr() bool {
430 return v.flag&flagAddr != 0
433 // CanSet returns true if the value of v can be changed.
434 // A Value can be changed only if it is addressable and was not
435 // obtained by the use of unexported struct fields.
436 // If CanSet returns false, calling Set or any type-specific
437 // setter (e.g., SetBool, SetInt64) will panic.
438 func (v Value) CanSet() bool {
439 return v.flag&(flagAddr|flagRO) == flagAddr
442 // Call calls the function v with the input arguments in.
443 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
444 // Call panics if v's Kind is not Func.
445 // It returns the output results as Values.
446 // As in Go, each input argument must be assignable to the
447 // type of the function's corresponding input parameter.
448 // If v is a variadic function, Call creates the variadic slice parameter
449 // itself, copying in the corresponding values.
450 func (v Value) Call(in []Value) []Value {
451 v.mustBe(Func)
452 v.mustBeExported()
453 return v.call("Call", in)
456 // CallSlice calls the variadic function v with the input arguments in,
457 // assigning the slice in[len(in)-1] to v's final variadic argument.
458 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]...).
459 // Call panics if v's Kind is not Func or if v is not variadic.
460 // It returns the output results as Values.
461 // As in Go, each input argument must be assignable to the
462 // type of the function's corresponding input parameter.
463 func (v Value) CallSlice(in []Value) []Value {
464 v.mustBe(Func)
465 v.mustBeExported()
466 return v.call("CallSlice", in)
469 var makeFuncStubFn = makeFuncStub
470 var makeFuncStubCode = **(**uintptr)(unsafe.Pointer(&makeFuncStubFn))
472 func (v Value) call(op string, in []Value) []Value {
473 // Get function pointer, type.
474 t := v.typ
475 var (
476 fn unsafe.Pointer
477 rcvr iword
479 if v.flag&flagMethod != 0 {
480 t, fn, rcvr = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
481 } else if v.flag&flagIndir != 0 {
482 fn = *(*unsafe.Pointer)(v.ptr)
483 } else {
484 fn = v.ptr
487 if fn == nil {
488 panic("reflect.Value.Call: call of nil function")
491 // If target is makeFuncStub, short circuit the unpack onto stack /
492 // pack back into []Value for the args and return values. Just do the
493 // call directly.
494 // We need to do this here because otherwise we have a situation where
495 // reflect.callXX calls makeFuncStub, neither of which knows the
496 // layout of the args. That's bad for precise gc & stack copying.
497 x := (*makeFuncImpl)(fn)
498 if x.code == makeFuncStubCode {
499 return x.call(in)
502 isSlice := op == "CallSlice"
503 n := t.NumIn()
504 if isSlice {
505 if !t.IsVariadic() {
506 panic("reflect: CallSlice of non-variadic function")
508 if len(in) < n {
509 panic("reflect: CallSlice with too few input arguments")
511 if len(in) > n {
512 panic("reflect: CallSlice with too many input arguments")
514 } else {
515 if t.IsVariadic() {
518 if len(in) < n {
519 panic("reflect: Call with too few input arguments")
521 if !t.IsVariadic() && len(in) > n {
522 panic("reflect: Call with too many input arguments")
525 for _, x := range in {
526 if x.Kind() == Invalid {
527 panic("reflect: " + op + " using zero Value argument")
530 for i := 0; i < n; i++ {
531 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
532 panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
535 if !isSlice && t.IsVariadic() {
536 // prepare slice for remaining values
537 m := len(in) - n
538 slice := MakeSlice(t.In(n), m, m)
539 elem := t.In(n).Elem()
540 for i := 0; i < m; i++ {
541 x := in[n+i]
542 if xt := x.Type(); !xt.AssignableTo(elem) {
543 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
545 slice.Index(i).Set(x)
547 origIn := in
548 in = make([]Value, n+1)
549 copy(in[:n], origIn)
550 in[n] = slice
553 nin := len(in)
554 if nin != t.NumIn() {
555 panic("reflect.Value.Call: wrong argument count")
557 nout := t.NumOut()
559 if v.flag&flagMethod != 0 {
560 nin++
562 firstPointer := len(in) > 0 && t.In(0).Kind() != Ptr && v.flag&flagMethodFn != 0
563 params := make([]unsafe.Pointer, nin)
564 off := 0
565 if v.flag&flagMethod != 0 {
566 // Hard-wired first argument.
567 p := new(iword)
568 *p = rcvr
569 params[0] = unsafe.Pointer(p)
570 off = 1
572 for i, pv := range in {
573 pv.mustBeExported()
574 targ := t.In(i).(*rtype)
575 pv = pv.assignTo("reflect.Value.Call", targ, nil)
576 if pv.flag&flagIndir == 0 {
577 p := new(unsafe.Pointer)
578 *p = pv.ptr
579 params[off] = unsafe.Pointer(p)
580 } else {
581 params[off] = pv.ptr
583 if i == 0 && firstPointer {
584 p := new(unsafe.Pointer)
585 *p = params[off]
586 params[off] = unsafe.Pointer(p)
588 off++
591 ret := make([]Value, nout)
592 results := make([]unsafe.Pointer, nout)
593 for i := 0; i < nout; i++ {
594 v := New(t.Out(i))
595 results[i] = unsafe.Pointer(v.Pointer())
596 ret[i] = Indirect(v)
599 var pp *unsafe.Pointer
600 if len(params) > 0 {
601 pp = &params[0]
603 var pr *unsafe.Pointer
604 if len(results) > 0 {
605 pr = &results[0]
608 call(t, fn, v.flag&flagMethod != 0, firstPointer, pp, pr)
610 return ret
613 // methodReceiver returns information about the receiver
614 // described by v. The Value v may or may not have the
615 // flagMethod bit set, so the kind cached in v.flag should
616 // not be used.
617 func methodReceiver(op string, v Value, methodIndex int) (t *rtype, fn unsafe.Pointer, rcvr iword) {
618 i := methodIndex
619 if v.typ.Kind() == Interface {
620 tt := (*interfaceType)(unsafe.Pointer(v.typ))
621 if i < 0 || i >= len(tt.methods) {
622 panic("reflect: internal error: invalid method index")
624 m := &tt.methods[i]
625 if m.pkgPath != nil {
626 panic("reflect: " + op + " of unexported method")
628 t = m.typ
629 iface := (*nonEmptyInterface)(v.ptr)
630 if iface.itab == nil {
631 panic("reflect: " + op + " of method on nil interface value")
633 fn = unsafe.Pointer(&iface.itab.fun[i])
634 rcvr = iface.word
635 } else {
636 ut := v.typ.uncommon()
637 if ut == nil || i < 0 || i >= len(ut.methods) {
638 panic("reflect: internal error: invalid method index")
640 m := &ut.methods[i]
641 if m.pkgPath != nil {
642 panic("reflect: " + op + " of unexported method")
644 fn = unsafe.Pointer(&m.tfn)
645 t = m.mtyp
646 // Can't call iword here, because it checks v.kind,
647 // and that is always Func.
648 if v.flag&flagIndir != 0 && (v.typ.Kind() == Ptr || v.typ.Kind() == UnsafePointer) {
649 rcvr = iword(loadScalar(v.ptr, v.typ.size))
650 } else {
651 rcvr = iword(v.ptr)
654 return
657 // align returns the result of rounding x up to a multiple of n.
658 // n must be a power of two.
659 func align(x, n uintptr) uintptr {
660 return (x + n - 1) &^ (n - 1)
663 // funcName returns the name of f, for use in error messages.
664 func funcName(f func([]Value) []Value) string {
665 pc := *(*uintptr)(unsafe.Pointer(&f))
666 rf := runtime.FuncForPC(pc)
667 if rf != nil {
668 return rf.Name()
670 return "closure"
673 // Cap returns v's capacity.
674 // It panics if v's Kind is not Array, Chan, or Slice.
675 func (v Value) Cap() int {
676 k := v.kind()
677 switch k {
678 case Array:
679 return v.typ.Len()
680 case Chan:
681 return int(chancap(v.pointer()))
682 case Slice:
683 // Slice is always bigger than a word; assume flagIndir.
684 return (*sliceHeader)(v.ptr).Cap
686 panic(&ValueError{"reflect.Value.Cap", k})
689 // Close closes the channel v.
690 // It panics if v's Kind is not Chan.
691 func (v Value) Close() {
692 v.mustBe(Chan)
693 v.mustBeExported()
694 chanclose(v.pointer())
697 // Complex returns v's underlying value, as a complex128.
698 // It panics if v's Kind is not Complex64 or Complex128
699 func (v Value) Complex() complex128 {
700 k := v.kind()
701 switch k {
702 case Complex64:
703 if v.flag&flagIndir != 0 {
704 return complex128(*(*complex64)(v.ptr))
706 // return complex128(*(*complex64)(unsafe.Pointer(&v.scalar)))
707 panic("reflect: missing flagIndir")
708 case Complex128:
709 // complex128 is always bigger than a word; assume flagIndir.
710 return *(*complex128)(v.ptr)
712 panic(&ValueError{"reflect.Value.Complex", k})
715 // Elem returns the value that the interface v contains
716 // or that the pointer v points to.
717 // It panics if v's Kind is not Interface or Ptr.
718 // It returns the zero Value if v is nil.
719 func (v Value) Elem() Value {
720 k := v.kind()
721 switch k {
722 case Interface:
723 var eface interface{}
724 if v.typ.NumMethod() == 0 {
725 eface = *(*interface{})(v.ptr)
726 } else {
727 eface = (interface{})(*(*interface {
729 })(v.ptr))
731 x := unpackEface(eface)
732 x.flag |= v.flag & flagRO
733 return x
734 case Ptr:
735 ptr := v.ptr
736 if v.flag&flagIndir != 0 {
737 ptr = *(*unsafe.Pointer)(ptr)
739 // The returned value's address is v's value.
740 if ptr == nil {
741 return Value{}
743 tt := (*ptrType)(unsafe.Pointer(v.typ))
744 typ := tt.elem
745 fl := v.flag&flagRO | flagIndir | flagAddr
746 fl |= flag(typ.Kind() << flagKindShift)
747 return Value{typ, ptr /* 0, */, fl}
749 panic(&ValueError{"reflect.Value.Elem", k})
752 // Field returns the i'th field of the struct v.
753 // It panics if v's Kind is not Struct or i is out of range.
754 func (v Value) Field(i int) Value {
755 v.mustBe(Struct)
756 tt := (*structType)(unsafe.Pointer(v.typ))
757 if i < 0 || i >= len(tt.fields) {
758 panic("reflect: Field index out of range")
760 field := &tt.fields[i]
761 typ := field.typ
763 // Inherit permission bits from v.
764 fl := v.flag & (flagRO | flagIndir | flagAddr)
765 // Using an unexported field forces flagRO.
766 if field.pkgPath != nil {
767 fl |= flagRO
769 fl |= flag(typ.Kind()) << flagKindShift
771 var ptr unsafe.Pointer
772 // var scalar uintptr
773 switch {
774 case fl&flagIndir != 0:
775 // Indirect. Just bump pointer.
776 ptr = unsafe.Pointer(uintptr(v.ptr) + field.offset)
777 case typ.pointers():
778 if field.offset != 0 {
779 panic("field access of ptr value isn't at offset 0")
781 ptr = v.ptr
782 case bigEndian:
783 // Must be scalar. Discard leading bytes.
784 // scalar = v.scalar << (field.offset * 8)
785 panic("reflect: missing flagIndir")
786 default:
787 // Must be scalar. Discard leading bytes.
788 // scalar = v.scalar >> (field.offset * 8)
789 panic("reflect: missing flagIndir")
792 return Value{typ, ptr /* scalar, */, fl}
795 // FieldByIndex returns the nested field corresponding to index.
796 // It panics if v's Kind is not struct.
797 func (v Value) FieldByIndex(index []int) Value {
798 v.mustBe(Struct)
799 for i, x := range index {
800 if i > 0 {
801 if v.Kind() == Ptr && v.Elem().Kind() == Struct {
802 v = v.Elem()
805 v = v.Field(x)
807 return v
810 // FieldByName returns the struct field with the given name.
811 // It returns the zero Value if no field was found.
812 // It panics if v's Kind is not struct.
813 func (v Value) FieldByName(name string) Value {
814 v.mustBe(Struct)
815 if f, ok := v.typ.FieldByName(name); ok {
816 return v.FieldByIndex(f.Index)
818 return Value{}
821 // FieldByNameFunc returns the struct field with a name
822 // that satisfies the match function.
823 // It panics if v's Kind is not struct.
824 // It returns the zero Value if no field was found.
825 func (v Value) FieldByNameFunc(match func(string) bool) Value {
826 v.mustBe(Struct)
827 if f, ok := v.typ.FieldByNameFunc(match); ok {
828 return v.FieldByIndex(f.Index)
830 return Value{}
833 // Float returns v's underlying value, as a float64.
834 // It panics if v's Kind is not Float32 or Float64
835 func (v Value) Float() float64 {
836 k := v.kind()
837 switch k {
838 case Float32:
839 if v.flag&flagIndir != 0 {
840 return float64(*(*float32)(v.ptr))
842 // return float64(*(*float32)(unsafe.Pointer(&v.scalar)))
843 panic("reflect: missing flagIndir")
844 case Float64:
845 if v.flag&flagIndir != 0 {
846 return *(*float64)(v.ptr)
848 // return *(*float64)(unsafe.Pointer(&v.scalar))
849 panic("reflect: missing flagIndir")
851 panic(&ValueError{"reflect.Value.Float", k})
854 var uint8Type = TypeOf(uint8(0)).(*rtype)
856 // Index returns v's i'th element.
857 // It panics if v's Kind is not Array, Slice, or String or i is out of range.
858 func (v Value) Index(i int) Value {
859 k := v.kind()
860 switch k {
861 case Array:
862 tt := (*arrayType)(unsafe.Pointer(v.typ))
863 if i < 0 || i > int(tt.len) {
864 panic("reflect: array index out of range")
866 typ := tt.elem
867 fl := v.flag & (flagRO | flagIndir | flagAddr) // bits same as overall array
868 fl |= flag(typ.Kind()) << flagKindShift
869 offset := uintptr(i) * typ.size
871 var val unsafe.Pointer
872 switch {
873 case fl&flagIndir != 0:
874 // Indirect. Just bump pointer.
875 val = unsafe.Pointer(uintptr(v.ptr) + offset)
876 case typ.pointers():
877 if offset != 0 {
878 panic("can't Index(i) with i!=0 on ptrLike value")
880 val = v.ptr
881 case bigEndian:
882 // Direct. Discard leading bytes.
883 // scalar = v.scalar << (offset * 8)
884 panic("reflect: missing flagIndir")
885 default:
886 // Direct. Discard leading bytes.
887 // scalar = v.scalar >> (offset * 8)
888 panic("reflect: missing flagIndir")
890 return Value{typ, val /* scalar, */, fl}
892 case Slice:
893 // Element flag same as Elem of Ptr.
894 // Addressable, indirect, possibly read-only.
895 fl := flagAddr | flagIndir | v.flag&flagRO
896 s := (*sliceHeader)(v.ptr)
897 if i < 0 || i >= s.Len {
898 panic("reflect: slice index out of range")
900 tt := (*sliceType)(unsafe.Pointer(v.typ))
901 typ := tt.elem
902 fl |= flag(typ.Kind()) << flagKindShift
903 val := unsafe.Pointer(uintptr(s.Data) + uintptr(i)*typ.size)
904 return Value{typ, val /* 0, */, fl}
906 case String:
907 fl := v.flag&flagRO | flag(Uint8<<flagKindShift) | flagIndir
908 s := (*StringHeader)(v.ptr)
909 if i < 0 || i >= s.Len {
910 panic("reflect: string index out of range")
912 b := uintptr(0)
913 *(*byte)(unsafe.Pointer(&b)) = *(*byte)(unsafe.Pointer(uintptr(s.Data) + uintptr(i)))
914 return Value{uint8Type, unsafe.Pointer(&b) /* 0, */, fl | flagIndir}
916 panic(&ValueError{"reflect.Value.Index", k})
919 // Int returns v's underlying value, as an int64.
920 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
921 func (v Value) Int() int64 {
922 k := v.kind()
923 var p unsafe.Pointer
924 if v.flag&flagIndir != 0 {
925 p = v.ptr
926 } else {
927 // The escape analysis is good enough that &v.scalar
928 // does not trigger a heap allocation.
929 // p = unsafe.Pointer(&v.scalar)
930 switch k {
931 case Int, Int8, Int16, Int32, Int64:
932 panic("reflect: missing flagIndir")
935 switch k {
936 case Int:
937 return int64(*(*int)(p))
938 case Int8:
939 return int64(*(*int8)(p))
940 case Int16:
941 return int64(*(*int16)(p))
942 case Int32:
943 return int64(*(*int32)(p))
944 case Int64:
945 return int64(*(*int64)(p))
947 panic(&ValueError{"reflect.Value.Int", k})
950 // CanInterface returns true if Interface can be used without panicking.
951 func (v Value) CanInterface() bool {
952 if v.flag == 0 {
953 panic(&ValueError{"reflect.Value.CanInterface", Invalid})
955 return v.flag&flagRO == 0
958 // Interface returns v's current value as an interface{}.
959 // It is equivalent to:
960 // var i interface{} = (v's underlying value)
961 // It panics if the Value was obtained by accessing
962 // unexported struct fields.
963 func (v Value) Interface() (i interface{}) {
964 return valueInterface(v, true)
967 func valueInterface(v Value, safe bool) interface{} {
968 if v.flag == 0 {
969 panic(&ValueError{"reflect.Value.Interface", 0})
971 if safe && v.flag&flagRO != 0 {
972 // Do not allow access to unexported values via Interface,
973 // because they might be pointers that should not be
974 // writable or methods or function that should not be callable.
975 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
977 if v.flag&flagMethod != 0 {
978 v = makeMethodValue("Interface", v)
981 if v.flag&flagMethodFn != 0 {
982 if v.typ.Kind() != Func {
983 panic("reflect: MethodFn of non-Func")
985 ft := (*funcType)(unsafe.Pointer(v.typ))
986 if ft.in[0].Kind() != Ptr {
987 v = makeValueMethod(v)
991 if v.kind() == Interface {
992 // Special case: return the element inside the interface.
993 // Empty interface has one layout, all interfaces with
994 // methods have a second layout.
995 if v.NumMethod() == 0 {
996 return *(*interface{})(v.ptr)
998 return *(*interface {
1000 })(v.ptr)
1003 // Non-interface value.
1004 var eface emptyInterface
1005 eface.typ = toType(v.typ).common()
1006 eface.word = v.iword()
1008 // Don't need to allocate if v is not addressable or fits in one word.
1009 if v.flag&flagAddr != 0 && v.kind() != Ptr && v.kind() != UnsafePointer {
1010 // eface.word is a pointer to the actual data,
1011 // which might be changed. We need to return
1012 // a pointer to unchanging data, so make a copy.
1013 ptr := unsafe_New(v.typ)
1014 memmove(ptr, unsafe.Pointer(eface.word), v.typ.size)
1015 eface.word = iword(ptr)
1018 if v.flag&flagIndir == 0 && v.kind() != Ptr && v.kind() != UnsafePointer {
1019 panic("missing flagIndir")
1021 // TODO: pass safe to packEface so we don't need to copy if safe==true?
1022 return packEface(v)
1025 // InterfaceData returns the interface v's value as a uintptr pair.
1026 // It panics if v's Kind is not Interface.
1027 func (v Value) InterfaceData() [2]uintptr {
1028 // TODO: deprecate this
1029 v.mustBe(Interface)
1030 // We treat this as a read operation, so we allow
1031 // it even for unexported data, because the caller
1032 // has to import "unsafe" to turn it into something
1033 // that can be abused.
1034 // Interface value is always bigger than a word; assume flagIndir.
1035 return *(*[2]uintptr)(v.ptr)
1038 // IsNil returns true if v is a nil value.
1039 // It panics if v's Kind is not Chan, Func, Interface, Map, Ptr, or Slice.
1040 func (v Value) IsNil() bool {
1041 k := v.kind()
1042 switch k {
1043 case Chan, Func, Map, Ptr:
1044 if v.flag&flagMethod != 0 {
1045 return false
1047 ptr := v.ptr
1048 if v.flag&flagIndir != 0 {
1049 ptr = *(*unsafe.Pointer)(ptr)
1051 return ptr == nil
1052 case Interface, Slice:
1053 // Both interface and slice are nil if first word is 0.
1054 // Both are always bigger than a word; assume flagIndir.
1055 return *(*unsafe.Pointer)(v.ptr) == nil
1057 panic(&ValueError{"reflect.Value.IsNil", k})
1060 // IsValid returns true if v represents a value.
1061 // It returns false if v is the zero Value.
1062 // If IsValid returns false, all other methods except String panic.
1063 // Most functions and methods never return an invalid value.
1064 // If one does, its documentation states the conditions explicitly.
1065 func (v Value) IsValid() bool {
1066 return v.flag != 0
1069 // Kind returns v's Kind.
1070 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
1071 func (v Value) Kind() Kind {
1072 return v.kind()
1075 // Len returns v's length.
1076 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
1077 func (v Value) Len() int {
1078 k := v.kind()
1079 switch k {
1080 case Array:
1081 tt := (*arrayType)(unsafe.Pointer(v.typ))
1082 return int(tt.len)
1083 case Chan:
1084 return chanlen(v.pointer())
1085 case Map:
1086 return maplen(v.pointer())
1087 case Slice:
1088 // Slice is bigger than a word; assume flagIndir.
1089 return (*sliceHeader)(v.ptr).Len
1090 case String:
1091 // String is bigger than a word; assume flagIndir.
1092 return (*stringHeader)(v.ptr).Len
1094 panic(&ValueError{"reflect.Value.Len", k})
1097 // MapIndex returns the value associated with key in the map v.
1098 // It panics if v's Kind is not Map.
1099 // It returns the zero Value if key is not found in the map or if v represents a nil map.
1100 // As in Go, the key's value must be assignable to the map's key type.
1101 func (v Value) MapIndex(key Value) Value {
1102 v.mustBe(Map)
1103 tt := (*mapType)(unsafe.Pointer(v.typ))
1105 // Do not require key to be exported, so that DeepEqual
1106 // and other programs can use all the keys returned by
1107 // MapKeys as arguments to MapIndex. If either the map
1108 // or the key is unexported, though, the result will be
1109 // considered unexported. This is consistent with the
1110 // behavior for structs, which allow read but not write
1111 // of unexported fields.
1112 key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
1114 var k unsafe.Pointer
1115 if key.flag&flagIndir != 0 {
1116 k = key.ptr
1117 } else if key.typ.pointers() {
1118 k = unsafe.Pointer(&key.ptr)
1119 } else {
1120 // k = unsafe.Pointer(&key.scalar)
1121 panic("reflect: missing flagIndir")
1123 e := mapaccess(v.typ, v.pointer(), k)
1124 if e == nil {
1125 return Value{}
1127 typ := tt.elem
1128 fl := (v.flag | key.flag) & flagRO
1129 fl |= flag(typ.Kind()) << flagKindShift
1130 if typ.Kind() != Ptr && typ.Kind() != UnsafePointer {
1131 // Copy result so future changes to the map
1132 // won't change the underlying value.
1133 c := unsafe_New(typ)
1134 memmove(c, e, typ.size)
1135 return Value{typ, c /* 0, */, fl | flagIndir}
1136 } else if typ.pointers() {
1137 return Value{typ, *(*unsafe.Pointer)(e) /* 0, */, fl}
1138 } else {
1139 panic("reflect: can't happen")
1143 // MapKeys returns a slice containing all the keys present in the map,
1144 // in unspecified order.
1145 // It panics if v's Kind is not Map.
1146 // It returns an empty slice if v represents a nil map.
1147 func (v Value) MapKeys() []Value {
1148 v.mustBe(Map)
1149 tt := (*mapType)(unsafe.Pointer(v.typ))
1150 keyType := tt.key
1152 fl := v.flag&flagRO | flag(keyType.Kind())<<flagKindShift
1153 if keyType.Kind() != Ptr && keyType.Kind() != UnsafePointer {
1154 fl |= flagIndir
1157 m := v.pointer()
1158 mlen := int(0)
1159 if m != nil {
1160 mlen = maplen(m)
1162 it := mapiterinit(v.typ, m)
1163 a := make([]Value, mlen)
1164 var i int
1165 for i = 0; i < len(a); i++ {
1166 key := mapiterkey(it)
1167 if key == nil {
1168 // Someone deleted an entry from the map since we
1169 // called maplen above. It's a data race, but nothing
1170 // we can do about it.
1171 break
1173 if keyType.Kind() != Ptr && keyType.Kind() != UnsafePointer {
1174 // Copy result so future changes to the map
1175 // won't change the underlying value.
1176 c := unsafe_New(keyType)
1177 memmove(c, key, keyType.size)
1178 a[i] = Value{keyType, c /* 0, */, fl | flagIndir}
1179 } else if keyType.pointers() {
1180 a[i] = Value{keyType, *(*unsafe.Pointer)(key) /* 0, */, fl}
1181 } else {
1182 panic("reflect: can't happen")
1184 mapiternext(it)
1186 return a[:i]
1189 // Method returns a function value corresponding to v's i'th method.
1190 // The arguments to a Call on the returned function should not include
1191 // a receiver; the returned function will always use v as the receiver.
1192 // Method panics if i is out of range or if v is a nil interface value.
1193 func (v Value) Method(i int) Value {
1194 if v.typ == nil {
1195 panic(&ValueError{"reflect.Value.Method", Invalid})
1197 if v.flag&flagMethod != 0 || i < 0 || i >= v.typ.NumMethod() {
1198 panic("reflect: Method index out of range")
1200 if v.typ.Kind() == Interface && v.IsNil() {
1201 panic("reflect: Method on nil interface value")
1203 fl := v.flag & (flagRO | flagIndir)
1204 fl |= flag(Func) << flagKindShift
1205 fl |= flag(i)<<flagMethodShift | flagMethod
1206 return Value{v.typ, v.ptr /* v.scalar, */, fl}
1209 // NumMethod returns the number of methods in the value's method set.
1210 func (v Value) NumMethod() int {
1211 if v.typ == nil {
1212 panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1214 if v.flag&flagMethod != 0 {
1215 return 0
1217 return v.typ.NumMethod()
1220 // MethodByName returns a function value corresponding to the method
1221 // of v with the given name.
1222 // The arguments to a Call on the returned function should not include
1223 // a receiver; the returned function will always use v as the receiver.
1224 // It returns the zero Value if no method was found.
1225 func (v Value) MethodByName(name string) Value {
1226 if v.typ == nil {
1227 panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1229 if v.flag&flagMethod != 0 {
1230 return Value{}
1232 m, ok := v.typ.MethodByName(name)
1233 if !ok {
1234 return Value{}
1236 return v.Method(m.Index)
1239 // NumField returns the number of fields in the struct v.
1240 // It panics if v's Kind is not Struct.
1241 func (v Value) NumField() int {
1242 v.mustBe(Struct)
1243 tt := (*structType)(unsafe.Pointer(v.typ))
1244 return len(tt.fields)
1247 // OverflowComplex returns true if the complex128 x cannot be represented by v's type.
1248 // It panics if v's Kind is not Complex64 or Complex128.
1249 func (v Value) OverflowComplex(x complex128) bool {
1250 k := v.kind()
1251 switch k {
1252 case Complex64:
1253 return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1254 case Complex128:
1255 return false
1257 panic(&ValueError{"reflect.Value.OverflowComplex", k})
1260 // OverflowFloat returns true if the float64 x cannot be represented by v's type.
1261 // It panics if v's Kind is not Float32 or Float64.
1262 func (v Value) OverflowFloat(x float64) bool {
1263 k := v.kind()
1264 switch k {
1265 case Float32:
1266 return overflowFloat32(x)
1267 case Float64:
1268 return false
1270 panic(&ValueError{"reflect.Value.OverflowFloat", k})
1273 func overflowFloat32(x float64) bool {
1274 if x < 0 {
1275 x = -x
1277 return math.MaxFloat32 < x && x <= math.MaxFloat64
1280 // OverflowInt returns true if the int64 x cannot be represented by v's type.
1281 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1282 func (v Value) OverflowInt(x int64) bool {
1283 k := v.kind()
1284 switch k {
1285 case Int, Int8, Int16, Int32, Int64:
1286 bitSize := v.typ.size * 8
1287 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1288 return x != trunc
1290 panic(&ValueError{"reflect.Value.OverflowInt", k})
1293 // OverflowUint returns true if the uint64 x cannot be represented by v's type.
1294 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1295 func (v Value) OverflowUint(x uint64) bool {
1296 k := v.kind()
1297 switch k {
1298 case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1299 bitSize := v.typ.size * 8
1300 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1301 return x != trunc
1303 panic(&ValueError{"reflect.Value.OverflowUint", k})
1306 // Pointer returns v's value as a uintptr.
1307 // It returns uintptr instead of unsafe.Pointer so that
1308 // code using reflect cannot obtain unsafe.Pointers
1309 // without importing the unsafe package explicitly.
1310 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1312 // If v's Kind is Func, the returned pointer is an underlying
1313 // code pointer, but not necessarily enough to identify a
1314 // single function uniquely. The only guarantee is that the
1315 // result is zero if and only if v is a nil func Value.
1317 // If v's Kind is Slice, the returned pointer is to the first
1318 // element of the slice. If the slice is nil the returned value
1319 // is 0. If the slice is empty but non-nil the return value is non-zero.
1320 func (v Value) Pointer() uintptr {
1321 // TODO: deprecate
1322 k := v.kind()
1323 switch k {
1324 case Chan, Map, Ptr, UnsafePointer:
1325 return uintptr(v.pointer())
1326 case Func:
1327 if v.flag&flagMethod != 0 {
1328 // As the doc comment says, the returned pointer is an
1329 // underlying code pointer but not necessarily enough to
1330 // identify a single function uniquely. All method expressions
1331 // created via reflect have the same underlying code pointer,
1332 // so their Pointers are equal. The function used here must
1333 // match the one used in makeMethodValue.
1334 f := makeFuncStub
1335 return **(**uintptr)(unsafe.Pointer(&f))
1337 p := v.pointer()
1338 // Non-nil func value points at data block.
1339 // First word of data block is actual code.
1340 if p != nil {
1341 p = *(*unsafe.Pointer)(p)
1343 return uintptr(p)
1345 case Slice:
1346 return (*SliceHeader)(v.ptr).Data
1348 panic(&ValueError{"reflect.Value.Pointer", k})
1351 // Recv receives and returns a value from the channel v.
1352 // It panics if v's Kind is not Chan.
1353 // The receive blocks until a value is ready.
1354 // The boolean value ok is true if the value x corresponds to a send
1355 // on the channel, false if it is a zero value received because the channel is closed.
1356 func (v Value) Recv() (x Value, ok bool) {
1357 v.mustBe(Chan)
1358 v.mustBeExported()
1359 return v.recv(false)
1362 // internal recv, possibly non-blocking (nb).
1363 // v is known to be a channel.
1364 func (v Value) recv(nb bool) (val Value, ok bool) {
1365 tt := (*chanType)(unsafe.Pointer(v.typ))
1366 if ChanDir(tt.dir)&RecvDir == 0 {
1367 panic("reflect: recv on send-only channel")
1369 word, selected, ok := chanrecv(v.typ, v.pointer(), nb)
1370 if selected {
1371 val = fromIword(tt.elem, word, 0)
1373 return
1376 // Send sends x on the channel v.
1377 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1378 // As in Go, x's value must be assignable to the channel's element type.
1379 func (v Value) Send(x Value) {
1380 v.mustBe(Chan)
1381 v.mustBeExported()
1382 v.send(x, false)
1385 // internal send, possibly non-blocking.
1386 // v is known to be a channel.
1387 func (v Value) send(x Value, nb bool) (selected bool) {
1388 tt := (*chanType)(unsafe.Pointer(v.typ))
1389 if ChanDir(tt.dir)&SendDir == 0 {
1390 panic("reflect: send on recv-only channel")
1392 x.mustBeExported()
1393 x = x.assignTo("reflect.Value.Send", tt.elem, nil)
1394 return chansend(v.typ, v.pointer(), x.iword(), nb)
1397 // Set assigns x to the value v.
1398 // It panics if CanSet returns false.
1399 // As in Go, x's value must be assignable to v's type.
1400 func (v Value) Set(x Value) {
1401 v.mustBeAssignable()
1402 x.mustBeExported() // do not let unexported x leak
1403 var target *interface{}
1404 if v.kind() == Interface {
1405 target = (*interface{})(v.ptr)
1407 x = x.assignTo("reflect.Set", v.typ, target)
1408 if x.flag&flagIndir != 0 {
1409 memmove(v.ptr, x.ptr, v.typ.size)
1410 } else if x.typ.pointers() {
1411 *(*unsafe.Pointer)(v.ptr) = x.ptr
1412 } else {
1413 // memmove(v.ptr, unsafe.Pointer(&x.scalar), v.typ.size)
1414 panic("reflect: missing flagIndir")
1418 // SetBool sets v's underlying value.
1419 // It panics if v's Kind is not Bool or if CanSet() is false.
1420 func (v Value) SetBool(x bool) {
1421 v.mustBeAssignable()
1422 v.mustBe(Bool)
1423 *(*bool)(v.ptr) = x
1426 // SetBytes sets v's underlying value.
1427 // It panics if v's underlying value is not a slice of bytes.
1428 func (v Value) SetBytes(x []byte) {
1429 v.mustBeAssignable()
1430 v.mustBe(Slice)
1431 if v.typ.Elem().Kind() != Uint8 {
1432 panic("reflect.Value.SetBytes of non-byte slice")
1434 *(*[]byte)(v.ptr) = x
1437 // setRunes sets v's underlying value.
1438 // It panics if v's underlying value is not a slice of runes (int32s).
1439 func (v Value) setRunes(x []rune) {
1440 v.mustBeAssignable()
1441 v.mustBe(Slice)
1442 if v.typ.Elem().Kind() != Int32 {
1443 panic("reflect.Value.setRunes of non-rune slice")
1445 *(*[]rune)(v.ptr) = x
1448 // SetComplex sets v's underlying value to x.
1449 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1450 func (v Value) SetComplex(x complex128) {
1451 v.mustBeAssignable()
1452 switch k := v.kind(); k {
1453 default:
1454 panic(&ValueError{"reflect.Value.SetComplex", k})
1455 case Complex64:
1456 *(*complex64)(v.ptr) = complex64(x)
1457 case Complex128:
1458 *(*complex128)(v.ptr) = x
1462 // SetFloat sets v's underlying value to x.
1463 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1464 func (v Value) SetFloat(x float64) {
1465 v.mustBeAssignable()
1466 switch k := v.kind(); k {
1467 default:
1468 panic(&ValueError{"reflect.Value.SetFloat", k})
1469 case Float32:
1470 *(*float32)(v.ptr) = float32(x)
1471 case Float64:
1472 *(*float64)(v.ptr) = x
1476 // SetInt sets v's underlying value to x.
1477 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1478 func (v Value) SetInt(x int64) {
1479 v.mustBeAssignable()
1480 switch k := v.kind(); k {
1481 default:
1482 panic(&ValueError{"reflect.Value.SetInt", k})
1483 case Int:
1484 *(*int)(v.ptr) = int(x)
1485 case Int8:
1486 *(*int8)(v.ptr) = int8(x)
1487 case Int16:
1488 *(*int16)(v.ptr) = int16(x)
1489 case Int32:
1490 *(*int32)(v.ptr) = int32(x)
1491 case Int64:
1492 *(*int64)(v.ptr) = x
1496 // SetLen sets v's length to n.
1497 // It panics if v's Kind is not Slice or if n is negative or
1498 // greater than the capacity of the slice.
1499 func (v Value) SetLen(n int) {
1500 v.mustBeAssignable()
1501 v.mustBe(Slice)
1502 s := (*sliceHeader)(v.ptr)
1503 if n < 0 || n > int(s.Cap) {
1504 panic("reflect: slice length out of range in SetLen")
1506 s.Len = n
1509 // SetCap sets v's capacity to n.
1510 // It panics if v's Kind is not Slice or if n is smaller than the length or
1511 // greater than the capacity of the slice.
1512 func (v Value) SetCap(n int) {
1513 v.mustBeAssignable()
1514 v.mustBe(Slice)
1515 s := (*sliceHeader)(v.ptr)
1516 if n < int(s.Len) || n > int(s.Cap) {
1517 panic("reflect: slice capacity out of range in SetCap")
1519 s.Cap = n
1522 // SetMapIndex sets the value associated with key in the map v to val.
1523 // It panics if v's Kind is not Map.
1524 // If val is the zero Value, SetMapIndex deletes the key from the map.
1525 // As in Go, key's value must be assignable to the map's key type,
1526 // and val's value must be assignable to the map's value type.
1527 func (v Value) SetMapIndex(key, val Value) {
1528 v.mustBe(Map)
1529 v.mustBeExported()
1530 key.mustBeExported()
1531 tt := (*mapType)(unsafe.Pointer(v.typ))
1532 key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
1533 var k unsafe.Pointer
1534 if key.flag&flagIndir != 0 {
1535 k = key.ptr
1536 } else if key.typ.pointers() {
1537 k = unsafe.Pointer(&key.ptr)
1538 } else {
1539 // k = unsafe.Pointer(&key.scalar)
1540 panic("reflect: missing flagIndir")
1542 if val.typ == nil {
1543 mapdelete(v.typ, v.pointer(), k)
1544 return
1546 val.mustBeExported()
1547 val = val.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
1548 var e unsafe.Pointer
1549 if val.flag&flagIndir != 0 {
1550 e = val.ptr
1551 } else if val.typ.pointers() {
1552 e = unsafe.Pointer(&val.ptr)
1553 } else {
1554 // e = unsafe.Pointer(&val.scalar)
1555 panic("reflect: missing flagIndir")
1557 mapassign(v.typ, v.pointer(), k, e)
1560 // SetUint sets v's underlying value to x.
1561 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1562 func (v Value) SetUint(x uint64) {
1563 v.mustBeAssignable()
1564 switch k := v.kind(); k {
1565 default:
1566 panic(&ValueError{"reflect.Value.SetUint", k})
1567 case Uint:
1568 *(*uint)(v.ptr) = uint(x)
1569 case Uint8:
1570 *(*uint8)(v.ptr) = uint8(x)
1571 case Uint16:
1572 *(*uint16)(v.ptr) = uint16(x)
1573 case Uint32:
1574 *(*uint32)(v.ptr) = uint32(x)
1575 case Uint64:
1576 *(*uint64)(v.ptr) = x
1577 case Uintptr:
1578 *(*uintptr)(v.ptr) = uintptr(x)
1582 // SetPointer sets the unsafe.Pointer value v to x.
1583 // It panics if v's Kind is not UnsafePointer.
1584 func (v Value) SetPointer(x unsafe.Pointer) {
1585 v.mustBeAssignable()
1586 v.mustBe(UnsafePointer)
1587 *(*unsafe.Pointer)(v.ptr) = x
1590 // SetString sets v's underlying value to x.
1591 // It panics if v's Kind is not String or if CanSet() is false.
1592 func (v Value) SetString(x string) {
1593 v.mustBeAssignable()
1594 v.mustBe(String)
1595 *(*string)(v.ptr) = x
1598 // Slice returns v[i:j].
1599 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1600 // or if the indexes are out of bounds.
1601 func (v Value) Slice(i, j int) Value {
1602 var (
1603 cap int
1604 typ *sliceType
1605 base unsafe.Pointer
1607 switch kind := v.kind(); kind {
1608 default:
1609 panic(&ValueError{"reflect.Value.Slice", kind})
1611 case Array:
1612 if v.flag&flagAddr == 0 {
1613 panic("reflect.Value.Slice: slice of unaddressable array")
1615 tt := (*arrayType)(unsafe.Pointer(v.typ))
1616 cap = int(tt.len)
1617 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1618 base = v.ptr
1620 case Slice:
1621 typ = (*sliceType)(unsafe.Pointer(v.typ))
1622 s := (*sliceHeader)(v.ptr)
1623 base = unsafe.Pointer(s.Data)
1624 cap = s.Cap
1626 case String:
1627 s := (*stringHeader)(v.ptr)
1628 if i < 0 || j < i || j > s.Len {
1629 panic("reflect.Value.Slice: string slice index out of bounds")
1631 t := stringHeader{unsafe.Pointer(uintptr(s.Data) + uintptr(i)), j - i}
1632 return Value{v.typ, unsafe.Pointer(&t) /* 0, */, v.flag}
1635 if i < 0 || j < i || j > cap {
1636 panic("reflect.Value.Slice: slice index out of bounds")
1639 // Declare slice so that gc can see the base pointer in it.
1640 var x []unsafe.Pointer
1642 // Reinterpret as *sliceHeader to edit.
1643 s := (*sliceHeader)(unsafe.Pointer(&x))
1644 s.Data = unsafe.Pointer(uintptr(base) + uintptr(i)*typ.elem.Size())
1645 s.Len = j - i
1646 s.Cap = cap - i
1648 fl := v.flag&flagRO | flagIndir | flag(Slice)<<flagKindShift
1649 return Value{typ.common(), unsafe.Pointer(&x) /* 0, */, fl}
1652 // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1653 // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1654 // or if the indexes are out of bounds.
1655 func (v Value) Slice3(i, j, k int) Value {
1656 var (
1657 cap int
1658 typ *sliceType
1659 base unsafe.Pointer
1661 switch kind := v.kind(); kind {
1662 default:
1663 panic(&ValueError{"reflect.Value.Slice3", kind})
1665 case Array:
1666 if v.flag&flagAddr == 0 {
1667 panic("reflect.Value.Slice3: slice of unaddressable array")
1669 tt := (*arrayType)(unsafe.Pointer(v.typ))
1670 cap = int(tt.len)
1671 typ = (*sliceType)(unsafe.Pointer(tt.slice))
1672 base = v.ptr
1674 case Slice:
1675 typ = (*sliceType)(unsafe.Pointer(v.typ))
1676 s := (*sliceHeader)(v.ptr)
1677 base = s.Data
1678 cap = s.Cap
1681 if i < 0 || j < i || k < j || k > cap {
1682 panic("reflect.Value.Slice3: slice index out of bounds")
1685 // Declare slice so that the garbage collector
1686 // can see the base pointer in it.
1687 var x []unsafe.Pointer
1689 // Reinterpret as *sliceHeader to edit.
1690 s := (*sliceHeader)(unsafe.Pointer(&x))
1691 s.Data = unsafe.Pointer(uintptr(base) + uintptr(i)*typ.elem.Size())
1692 s.Len = j - i
1693 s.Cap = k - i
1695 fl := v.flag&flagRO | flagIndir | flag(Slice)<<flagKindShift
1696 return Value{typ.common(), unsafe.Pointer(&x) /* 0, */, fl}
1699 // String returns the string v's underlying value, as a string.
1700 // String is a special case because of Go's String method convention.
1701 // Unlike the other getters, it does not panic if v's Kind is not String.
1702 // Instead, it returns a string of the form "<T value>" where T is v's type.
1703 func (v Value) String() string {
1704 switch k := v.kind(); k {
1705 case Invalid:
1706 return "<invalid Value>"
1707 case String:
1708 return *(*string)(v.ptr)
1710 // If you call String on a reflect.Value of other type, it's better to
1711 // print something than to panic. Useful in debugging.
1712 return "<" + v.typ.String() + " Value>"
1715 // TryRecv attempts to receive a value from the channel v but will not block.
1716 // It panics if v's Kind is not Chan.
1717 // If the receive cannot finish without blocking, x is the zero Value.
1718 // The boolean ok is true if the value x corresponds to a send
1719 // on the channel, false if it is a zero value received because the channel is closed.
1720 func (v Value) TryRecv() (x Value, ok bool) {
1721 v.mustBe(Chan)
1722 v.mustBeExported()
1723 return v.recv(true)
1726 // TrySend attempts to send x on the channel v but will not block.
1727 // It panics if v's Kind is not Chan.
1728 // It returns true if the value was sent, false otherwise.
1729 // As in Go, x's value must be assignable to the channel's element type.
1730 func (v Value) TrySend(x Value) bool {
1731 v.mustBe(Chan)
1732 v.mustBeExported()
1733 return v.send(x, true)
1736 // Type returns v's type.
1737 func (v Value) Type() Type {
1738 f := v.flag
1739 if f == 0 {
1740 panic(&ValueError{"reflect.Value.Type", Invalid})
1742 if f&flagMethod == 0 {
1743 // Easy case
1744 return toType(v.typ)
1747 // Method value.
1748 // v.typ describes the receiver, not the method type.
1749 i := int(v.flag) >> flagMethodShift
1750 if v.typ.Kind() == Interface {
1751 // Method on interface.
1752 tt := (*interfaceType)(unsafe.Pointer(v.typ))
1753 if i < 0 || i >= len(tt.methods) {
1754 panic("reflect: internal error: invalid method index")
1756 m := &tt.methods[i]
1757 return toType(m.typ)
1759 // Method on concrete type.
1760 ut := v.typ.uncommon()
1761 if ut == nil || i < 0 || i >= len(ut.methods) {
1762 panic("reflect: internal error: invalid method index")
1764 m := &ut.methods[i]
1765 return toType(m.mtyp)
1768 // Uint returns v's underlying value, as a uint64.
1769 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1770 func (v Value) Uint() uint64 {
1771 k := v.kind()
1772 var p unsafe.Pointer
1773 if v.flag&flagIndir != 0 {
1774 p = v.ptr
1775 } else {
1776 // The escape analysis is good enough that &v.scalar
1777 // does not trigger a heap allocation.
1778 // p = unsafe.Pointer(&v.scalar)
1779 switch k {
1780 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
1781 panic("reflect: missing flagIndir")
1784 switch k {
1785 case Uint:
1786 return uint64(*(*uint)(p))
1787 case Uint8:
1788 return uint64(*(*uint8)(p))
1789 case Uint16:
1790 return uint64(*(*uint16)(p))
1791 case Uint32:
1792 return uint64(*(*uint32)(p))
1793 case Uint64:
1794 return uint64(*(*uint64)(p))
1795 case Uintptr:
1796 return uint64(*(*uintptr)(p))
1798 panic(&ValueError{"reflect.Value.Uint", k})
1801 // UnsafeAddr returns a pointer to v's data.
1802 // It is for advanced clients that also import the "unsafe" package.
1803 // It panics if v is not addressable.
1804 func (v Value) UnsafeAddr() uintptr {
1805 // TODO: deprecate
1806 if v.typ == nil {
1807 panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
1809 if v.flag&flagAddr == 0 {
1810 panic("reflect.Value.UnsafeAddr of unaddressable value")
1812 return uintptr(v.ptr)
1815 // StringHeader is the runtime representation of a string.
1816 // It cannot be used safely or portably and its representation may
1817 // change in a later release.
1818 // Moreover, the Data field is not sufficient to guarantee the data
1819 // it references will not be garbage collected, so programs must keep
1820 // a separate, correctly typed pointer to the underlying data.
1821 type StringHeader struct {
1822 Data uintptr
1823 Len int
1826 // stringHeader is a safe version of StringHeader used within this package.
1827 type stringHeader struct {
1828 Data unsafe.Pointer
1829 Len int
1832 // SliceHeader is the runtime representation of a slice.
1833 // It cannot be used safely or portably and its representation may
1834 // change in a later release.
1835 // Moreover, the Data field is not sufficient to guarantee the data
1836 // it references will not be garbage collected, so programs must keep
1837 // a separate, correctly typed pointer to the underlying data.
1838 type SliceHeader struct {
1839 Data uintptr
1840 Len int
1841 Cap int
1844 // sliceHeader is a safe version of SliceHeader used within this package.
1845 type sliceHeader struct {
1846 Data unsafe.Pointer
1847 Len int
1848 Cap int
1851 func typesMustMatch(what string, t1, t2 Type) {
1852 if t1 != t2 {
1853 panic(what + ": " + t1.String() + " != " + t2.String())
1857 // grow grows the slice s so that it can hold extra more values, allocating
1858 // more capacity if needed. It also returns the old and new slice lengths.
1859 func grow(s Value, extra int) (Value, int, int) {
1860 i0 := s.Len()
1861 i1 := i0 + extra
1862 if i1 < i0 {
1863 panic("reflect.Append: slice overflow")
1865 m := s.Cap()
1866 if i1 <= m {
1867 return s.Slice(0, i1), i0, i1
1869 if m == 0 {
1870 m = extra
1871 } else {
1872 for m < i1 {
1873 if i0 < 1024 {
1874 m += m
1875 } else {
1876 m += m / 4
1880 t := MakeSlice(s.Type(), i1, m)
1881 Copy(t, s)
1882 return t, i0, i1
1885 // Append appends the values x to a slice s and returns the resulting slice.
1886 // As in Go, each x's value must be assignable to the slice's element type.
1887 func Append(s Value, x ...Value) Value {
1888 s.mustBe(Slice)
1889 s, i0, i1 := grow(s, len(x))
1890 for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1891 s.Index(i).Set(x[j])
1893 return s
1896 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1897 // The slices s and t must have the same element type.
1898 func AppendSlice(s, t Value) Value {
1899 s.mustBe(Slice)
1900 t.mustBe(Slice)
1901 typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1902 s, i0, i1 := grow(s, t.Len())
1903 Copy(s.Slice(i0, i1), t)
1904 return s
1907 // Copy copies the contents of src into dst until either
1908 // dst has been filled or src has been exhausted.
1909 // It returns the number of elements copied.
1910 // Dst and src each must have kind Slice or Array, and
1911 // dst and src must have the same element type.
1912 func Copy(dst, src Value) int {
1913 dk := dst.kind()
1914 if dk != Array && dk != Slice {
1915 panic(&ValueError{"reflect.Copy", dk})
1917 if dk == Array {
1918 dst.mustBeAssignable()
1920 dst.mustBeExported()
1922 sk := src.kind()
1923 if sk != Array && sk != Slice {
1924 panic(&ValueError{"reflect.Copy", sk})
1926 src.mustBeExported()
1928 de := dst.typ.Elem()
1929 se := src.typ.Elem()
1930 typesMustMatch("reflect.Copy", de, se)
1932 n := dst.Len()
1933 if sn := src.Len(); n > sn {
1934 n = sn
1937 // If sk is an in-line array, cannot take its address.
1938 // Instead, copy element by element.
1939 // TODO: memmove would be ok for this (sa = unsafe.Pointer(&v.scalar))
1940 // if we teach the compiler that ptrs don't escape from memmove.
1941 if src.flag&flagIndir == 0 {
1942 for i := 0; i < n; i++ {
1943 dst.Index(i).Set(src.Index(i))
1945 return n
1948 // Copy via memmove.
1949 var da, sa unsafe.Pointer
1950 if dk == Array {
1951 da = dst.ptr
1952 } else {
1953 da = (*sliceHeader)(dst.ptr).Data
1955 if sk == Array {
1956 sa = src.ptr
1957 } else {
1958 sa = (*sliceHeader)(src.ptr).Data
1960 memmove(da, sa, uintptr(n)*de.Size())
1961 return n
1964 // A runtimeSelect is a single case passed to rselect.
1965 // This must match ../runtime/chan.c:/runtimeSelect
1966 type runtimeSelect struct {
1967 dir uintptr // 0, SendDir, or RecvDir
1968 typ *rtype // channel type
1969 ch iword // interface word for channel
1970 val iword // interface word for value (for SendDir)
1973 // rselect runs a select. It returns the index of the chosen case,
1974 // and if the case was a receive, the interface word of the received
1975 // value and the conventional OK bool to indicate whether the receive
1976 // corresponds to a sent value.
1977 func rselect([]runtimeSelect) (chosen int, recv iword, recvOK bool)
1979 // A SelectDir describes the communication direction of a select case.
1980 type SelectDir int
1982 // NOTE: These values must match ../runtime/chan.c:/SelectDir.
1984 const (
1985 _ SelectDir = iota
1986 SelectSend // case Chan <- Send
1987 SelectRecv // case <-Chan:
1988 SelectDefault // default
1991 // A SelectCase describes a single case in a select operation.
1992 // The kind of case depends on Dir, the communication direction.
1994 // If Dir is SelectDefault, the case represents a default case.
1995 // Chan and Send must be zero Values.
1997 // If Dir is SelectSend, the case represents a send operation.
1998 // Normally Chan's underlying value must be a channel, and Send's underlying value must be
1999 // assignable to the channel's element type. As a special case, if Chan is a zero Value,
2000 // then the case is ignored, and the field Send will also be ignored and may be either zero
2001 // or non-zero.
2003 // If Dir is SelectRecv, the case represents a receive operation.
2004 // Normally Chan's underlying value must be a channel and Send must be a zero Value.
2005 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
2006 // When a receive operation is selected, the received Value is returned by Select.
2008 type SelectCase struct {
2009 Dir SelectDir // direction of case
2010 Chan Value // channel to use (for send or receive)
2011 Send Value // value to send (for send)
2014 // Select executes a select operation described by the list of cases.
2015 // Like the Go select statement, it blocks until at least one of the cases
2016 // can proceed, makes a uniform pseudo-random choice,
2017 // and then executes that case. It returns the index of the chosen case
2018 // and, if that case was a receive operation, the value received and a
2019 // boolean indicating whether the value corresponds to a send on the channel
2020 // (as opposed to a zero value received because the channel is closed).
2021 func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
2022 // NOTE: Do not trust that caller is not modifying cases data underfoot.
2023 // The range is safe because the caller cannot modify our copy of the len
2024 // and each iteration makes its own copy of the value c.
2025 runcases := make([]runtimeSelect, len(cases))
2026 haveDefault := false
2027 for i, c := range cases {
2028 rc := &runcases[i]
2029 rc.dir = uintptr(c.Dir)
2030 switch c.Dir {
2031 default:
2032 panic("reflect.Select: invalid Dir")
2034 case SelectDefault: // default
2035 if haveDefault {
2036 panic("reflect.Select: multiple default cases")
2038 haveDefault = true
2039 if c.Chan.IsValid() {
2040 panic("reflect.Select: default case has Chan value")
2042 if c.Send.IsValid() {
2043 panic("reflect.Select: default case has Send value")
2046 case SelectSend:
2047 ch := c.Chan
2048 if !ch.IsValid() {
2049 break
2051 ch.mustBe(Chan)
2052 ch.mustBeExported()
2053 tt := (*chanType)(unsafe.Pointer(ch.typ))
2054 if ChanDir(tt.dir)&SendDir == 0 {
2055 panic("reflect.Select: SendDir case using recv-only channel")
2057 rc.ch = *(*iword)(ch.iword())
2058 rc.typ = &tt.rtype
2059 v := c.Send
2060 if !v.IsValid() {
2061 panic("reflect.Select: SendDir case missing Send value")
2063 v.mustBeExported()
2064 v = v.assignTo("reflect.Select", tt.elem, nil)
2065 rc.val = v.iword()
2067 case SelectRecv:
2068 if c.Send.IsValid() {
2069 panic("reflect.Select: RecvDir case has Send value")
2071 ch := c.Chan
2072 if !ch.IsValid() {
2073 break
2075 ch.mustBe(Chan)
2076 ch.mustBeExported()
2077 tt := (*chanType)(unsafe.Pointer(ch.typ))
2078 rc.typ = &tt.rtype
2079 if ChanDir(tt.dir)&RecvDir == 0 {
2080 panic("reflect.Select: RecvDir case using send-only channel")
2082 rc.ch = *(*iword)(ch.iword())
2086 chosen, word, recvOK := rselect(runcases)
2087 if runcases[chosen].dir == uintptr(SelectRecv) {
2088 tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
2089 recv = fromIword(tt.elem, word, 0)
2091 return chosen, recv, recvOK
2095 * constructors
2098 // implemented in package runtime
2099 func unsafe_New(*rtype) unsafe.Pointer
2100 func unsafe_NewArray(*rtype, int) unsafe.Pointer
2102 // MakeSlice creates a new zero-initialized slice value
2103 // for the specified slice type, length, and capacity.
2104 func MakeSlice(typ Type, len, cap int) Value {
2105 if typ.Kind() != Slice {
2106 panic("reflect.MakeSlice of non-slice type")
2108 if len < 0 {
2109 panic("reflect.MakeSlice: negative len")
2111 if cap < 0 {
2112 panic("reflect.MakeSlice: negative cap")
2114 if len > cap {
2115 panic("reflect.MakeSlice: len > cap")
2118 s := sliceHeader{unsafe_NewArray(typ.Elem().(*rtype), cap), len, cap}
2119 return Value{typ.common(), unsafe.Pointer(&s) /* 0, */, flagIndir | flag(Slice)<<flagKindShift}
2122 // MakeChan creates a new channel with the specified type and buffer size.
2123 func MakeChan(typ Type, buffer int) Value {
2124 if typ.Kind() != Chan {
2125 panic("reflect.MakeChan of non-chan type")
2127 if buffer < 0 {
2128 panic("reflect.MakeChan: negative buffer size")
2130 if typ.ChanDir() != BothDir {
2131 panic("reflect.MakeChan: unidirectional channel type")
2133 ch := makechan(typ.(*rtype), uint64(buffer))
2134 return Value{typ.common(), unsafe.Pointer(&ch) /* 0, */, flagIndir | (flag(Chan) << flagKindShift)}
2137 // MakeMap creates a new map of the specified type.
2138 func MakeMap(typ Type) Value {
2139 if typ.Kind() != Map {
2140 panic("reflect.MakeMap of non-map type")
2142 m := makemap(typ.(*rtype))
2143 return Value{typ.common(), unsafe.Pointer(&m) /* 0, */, flagIndir | (flag(Map) << flagKindShift)}
2146 // Indirect returns the value that v points to.
2147 // If v is a nil pointer, Indirect returns a zero Value.
2148 // If v is not a pointer, Indirect returns v.
2149 func Indirect(v Value) Value {
2150 if v.Kind() != Ptr {
2151 return v
2153 return v.Elem()
2156 // ValueOf returns a new Value initialized to the concrete value
2157 // stored in the interface i. ValueOf(nil) returns the zero Value.
2158 func ValueOf(i interface{}) Value {
2159 if i == nil {
2160 return Value{}
2163 // TODO(rsc): Eliminate this terrible hack.
2164 // In the call to unpackEface, i.typ doesn't escape,
2165 // and i.word is an integer. So it looks like
2166 // i doesn't escape. But really it does,
2167 // because i.word is actually a pointer.
2168 escapes(i)
2170 return unpackEface(i)
2173 // Zero returns a Value representing the zero value for the specified type.
2174 // The result is different from the zero value of the Value struct,
2175 // which represents no value at all.
2176 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
2177 // The returned value is neither addressable nor settable.
2178 func Zero(typ Type) Value {
2179 if typ == nil {
2180 panic("reflect: Zero(nil)")
2182 t := typ.common()
2183 fl := flag(t.Kind()) << flagKindShift
2184 if t.Kind() == Ptr || t.Kind() == UnsafePointer {
2185 return Value{t, nil /* 0, */, fl}
2187 return Value{t, unsafe_New(typ.(*rtype)) /* 0, */, fl | flagIndir}
2190 // New returns a Value representing a pointer to a new zero value
2191 // for the specified type. That is, the returned Value's Type is PtrTo(t).
2192 func New(typ Type) Value {
2193 if typ == nil {
2194 panic("reflect: New(nil)")
2196 ptr := unsafe_New(typ.(*rtype))
2197 fl := flag(Ptr) << flagKindShift
2198 return Value{typ.common().ptrTo(), ptr /* 0, */, fl}
2201 // NewAt returns a Value representing a pointer to a value of the
2202 // specified type, using p as that pointer.
2203 func NewAt(typ Type, p unsafe.Pointer) Value {
2204 fl := flag(Ptr) << flagKindShift
2205 return Value{typ.common().ptrTo(), p /* 0, */, fl}
2208 // assignTo returns a value v that can be assigned directly to typ.
2209 // It panics if v is not assignable to typ.
2210 // For a conversion to an interface type, target is a suggested scratch space to use.
2211 func (v Value) assignTo(context string, dst *rtype, target *interface{}) Value {
2212 if v.flag&flagMethod != 0 {
2213 v = makeMethodValue(context, v)
2216 switch {
2217 case directlyAssignable(dst, v.typ):
2218 // Overwrite type so that they match.
2219 // Same memory layout, so no harm done.
2220 v.typ = dst
2221 fl := v.flag & (flagRO | flagAddr | flagIndir)
2222 fl |= flag(dst.Kind()) << flagKindShift
2223 return Value{dst, v.ptr /* v.scalar, */, fl}
2225 case implements(dst, v.typ):
2226 if target == nil {
2227 target = new(interface{})
2229 x := valueInterface(v, false)
2230 if dst.NumMethod() == 0 {
2231 *target = x
2232 } else {
2233 ifaceE2I(dst, x, unsafe.Pointer(target))
2235 return Value{dst, unsafe.Pointer(target) /* 0, */, flagIndir | flag(Interface)<<flagKindShift}
2238 // Failed.
2239 panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
2242 // Convert returns the value v converted to type t.
2243 // If the usual Go conversion rules do not allow conversion
2244 // of the value v to type t, Convert panics.
2245 func (v Value) Convert(t Type) Value {
2246 if v.flag&flagMethod != 0 {
2247 v = makeMethodValue("Convert", v)
2249 op := convertOp(t.common(), v.typ)
2250 if op == nil {
2251 panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
2253 return op(v, t)
2256 // convertOp returns the function to convert a value of type src
2257 // to a value of type dst. If the conversion is illegal, convertOp returns nil.
2258 func convertOp(dst, src *rtype) func(Value, Type) Value {
2259 switch src.Kind() {
2260 case Int, Int8, Int16, Int32, Int64:
2261 switch dst.Kind() {
2262 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2263 return cvtInt
2264 case Float32, Float64:
2265 return cvtIntFloat
2266 case String:
2267 return cvtIntString
2270 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2271 switch dst.Kind() {
2272 case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2273 return cvtUint
2274 case Float32, Float64:
2275 return cvtUintFloat
2276 case String:
2277 return cvtUintString
2280 case Float32, Float64:
2281 switch dst.Kind() {
2282 case Int, Int8, Int16, Int32, Int64:
2283 return cvtFloatInt
2284 case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
2285 return cvtFloatUint
2286 case Float32, Float64:
2287 return cvtFloat
2290 case Complex64, Complex128:
2291 switch dst.Kind() {
2292 case Complex64, Complex128:
2293 return cvtComplex
2296 case String:
2297 if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
2298 switch dst.Elem().Kind() {
2299 case Uint8:
2300 return cvtStringBytes
2301 case Int32:
2302 return cvtStringRunes
2306 case Slice:
2307 if dst.Kind() == String && src.Elem().PkgPath() == "" {
2308 switch src.Elem().Kind() {
2309 case Uint8:
2310 return cvtBytesString
2311 case Int32:
2312 return cvtRunesString
2317 // dst and src have same underlying type.
2318 if haveIdenticalUnderlyingType(dst, src) {
2319 return cvtDirect
2322 // dst and src are unnamed pointer types with same underlying base type.
2323 if dst.Kind() == Ptr && dst.Name() == "" &&
2324 src.Kind() == Ptr && src.Name() == "" &&
2325 haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common()) {
2326 return cvtDirect
2329 if implements(dst, src) {
2330 if src.Kind() == Interface {
2331 return cvtI2I
2333 return cvtT2I
2336 return nil
2339 // makeInt returns a Value of type t equal to bits (possibly truncated),
2340 // where t is a signed or unsigned int type.
2341 func makeInt(f flag, bits uint64, t Type) Value {
2342 typ := t.common()
2343 if typ.size > ptrSize {
2344 // Assume ptrSize >= 4, so this must be uint64.
2345 ptr := unsafe_New(typ)
2346 *(*uint64)(unsafe.Pointer(ptr)) = bits
2347 return Value{typ, ptr /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2349 var s uintptr
2350 switch typ.size {
2351 case 1:
2352 *(*uint8)(unsafe.Pointer(&s)) = uint8(bits)
2353 case 2:
2354 *(*uint16)(unsafe.Pointer(&s)) = uint16(bits)
2355 case 4:
2356 *(*uint32)(unsafe.Pointer(&s)) = uint32(bits)
2357 case 8:
2358 *(*uint64)(unsafe.Pointer(&s)) = uint64(bits)
2360 return Value{typ, unsafe.Pointer(&s) /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2363 // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2364 // where t is a float32 or float64 type.
2365 func makeFloat(f flag, v float64, t Type) Value {
2366 typ := t.common()
2367 if typ.size > ptrSize {
2368 // Assume ptrSize >= 4, so this must be float64.
2369 ptr := unsafe_New(typ)
2370 *(*float64)(unsafe.Pointer(ptr)) = v
2371 return Value{typ, ptr /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2374 var s uintptr
2375 switch typ.size {
2376 case 4:
2377 *(*float32)(unsafe.Pointer(&s)) = float32(v)
2378 case 8:
2379 *(*float64)(unsafe.Pointer(&s)) = v
2381 return Value{typ, unsafe.Pointer(&s) /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2384 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2385 // where t is a complex64 or complex128 type.
2386 func makeComplex(f flag, v complex128, t Type) Value {
2387 typ := t.common()
2388 if typ.size > ptrSize {
2389 ptr := unsafe_New(typ)
2390 switch typ.size {
2391 case 8:
2392 *(*complex64)(unsafe.Pointer(ptr)) = complex64(v)
2393 case 16:
2394 *(*complex128)(unsafe.Pointer(ptr)) = v
2396 return Value{typ, ptr /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2399 // Assume ptrSize <= 8 so this must be complex64.
2400 var s uintptr
2401 *(*complex64)(unsafe.Pointer(&s)) = complex64(v)
2402 return Value{typ, unsafe.Pointer(&s) /* 0, */, f | flagIndir | flag(typ.Kind())<<flagKindShift}
2405 func makeString(f flag, v string, t Type) Value {
2406 ret := New(t).Elem()
2407 ret.SetString(v)
2408 ret.flag = ret.flag&^flagAddr | f | flagIndir
2409 return ret
2412 func makeBytes(f flag, v []byte, t Type) Value {
2413 ret := New(t).Elem()
2414 ret.SetBytes(v)
2415 ret.flag = ret.flag&^flagAddr | f | flagIndir
2416 return ret
2419 func makeRunes(f flag, v []rune, t Type) Value {
2420 ret := New(t).Elem()
2421 ret.setRunes(v)
2422 ret.flag = ret.flag&^flagAddr | f | flagIndir
2423 return ret
2426 // These conversion functions are returned by convertOp
2427 // for classes of conversions. For example, the first function, cvtInt,
2428 // takes any value v of signed int type and returns the value converted
2429 // to type t, where t is any signed or unsigned int type.
2431 // convertOp: intXX -> [u]intXX
2432 func cvtInt(v Value, t Type) Value {
2433 return makeInt(v.flag&flagRO, uint64(v.Int()), t)
2436 // convertOp: uintXX -> [u]intXX
2437 func cvtUint(v Value, t Type) Value {
2438 return makeInt(v.flag&flagRO, v.Uint(), t)
2441 // convertOp: floatXX -> intXX
2442 func cvtFloatInt(v Value, t Type) Value {
2443 return makeInt(v.flag&flagRO, uint64(int64(v.Float())), t)
2446 // convertOp: floatXX -> uintXX
2447 func cvtFloatUint(v Value, t Type) Value {
2448 return makeInt(v.flag&flagRO, uint64(v.Float()), t)
2451 // convertOp: intXX -> floatXX
2452 func cvtIntFloat(v Value, t Type) Value {
2453 return makeFloat(v.flag&flagRO, float64(v.Int()), t)
2456 // convertOp: uintXX -> floatXX
2457 func cvtUintFloat(v Value, t Type) Value {
2458 return makeFloat(v.flag&flagRO, float64(v.Uint()), t)
2461 // convertOp: floatXX -> floatXX
2462 func cvtFloat(v Value, t Type) Value {
2463 return makeFloat(v.flag&flagRO, v.Float(), t)
2466 // convertOp: complexXX -> complexXX
2467 func cvtComplex(v Value, t Type) Value {
2468 return makeComplex(v.flag&flagRO, v.Complex(), t)
2471 // convertOp: intXX -> string
2472 func cvtIntString(v Value, t Type) Value {
2473 return makeString(v.flag&flagRO, string(v.Int()), t)
2476 // convertOp: uintXX -> string
2477 func cvtUintString(v Value, t Type) Value {
2478 return makeString(v.flag&flagRO, string(v.Uint()), t)
2481 // convertOp: []byte -> string
2482 func cvtBytesString(v Value, t Type) Value {
2483 return makeString(v.flag&flagRO, string(v.Bytes()), t)
2486 // convertOp: string -> []byte
2487 func cvtStringBytes(v Value, t Type) Value {
2488 return makeBytes(v.flag&flagRO, []byte(v.String()), t)
2491 // convertOp: []rune -> string
2492 func cvtRunesString(v Value, t Type) Value {
2493 return makeString(v.flag&flagRO, string(v.runes()), t)
2496 // convertOp: string -> []rune
2497 func cvtStringRunes(v Value, t Type) Value {
2498 return makeRunes(v.flag&flagRO, []rune(v.String()), t)
2501 // convertOp: direct copy
2502 func cvtDirect(v Value, typ Type) Value {
2503 f := v.flag
2504 t := typ.common()
2505 ptr := v.ptr
2506 if f&flagAddr != 0 {
2507 // indirect, mutable word - make a copy
2508 c := unsafe_New(t)
2509 memmove(c, ptr, t.size)
2510 ptr = c
2511 f &^= flagAddr
2513 return Value{t, ptr /* v.scalar, */, v.flag&flagRO | f} // v.flag&flagRO|f == f?
2516 // convertOp: concrete -> interface
2517 func cvtT2I(v Value, typ Type) Value {
2518 target := new(interface{})
2519 x := valueInterface(v, false)
2520 if typ.NumMethod() == 0 {
2521 *target = x
2522 } else {
2523 ifaceE2I(typ.(*rtype), x, unsafe.Pointer(target))
2525 return Value{typ.common(), unsafe.Pointer(target) /* 0, */, v.flag&flagRO | flagIndir | flag(Interface)<<flagKindShift}
2528 // convertOp: interface -> interface
2529 func cvtI2I(v Value, typ Type) Value {
2530 if v.IsNil() {
2531 ret := Zero(typ)
2532 ret.flag |= v.flag & flagRO
2533 return ret
2535 return cvtT2I(v.Elem(), typ)
2538 // implemented in ../pkg/runtime
2539 func chancap(ch unsafe.Pointer) int
2540 func chanclose(ch unsafe.Pointer)
2541 func chanlen(ch unsafe.Pointer) int
2542 func chanrecv(t *rtype, ch unsafe.Pointer, nb bool) (val iword, selected, received bool)
2543 func chansend(t *rtype, ch unsafe.Pointer, val iword, nb bool) bool
2545 func makechan(typ *rtype, size uint64) (ch unsafe.Pointer)
2546 func makemap(t *rtype) (m unsafe.Pointer)
2547 func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
2548 func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
2549 func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
2550 func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
2551 func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
2552 func mapiternext(it unsafe.Pointer)
2553 func maplen(m unsafe.Pointer) int
2555 func call(typ *rtype, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
2556 func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
2558 // Dummy annotation marking that the value x escapes,
2559 // for use in cases where the reflect code is so clever that
2560 // the compiler cannot follow.
2561 func escapes(x interface{}) {
2562 if dummy.b {
2563 dummy.x = x
2567 var dummy struct {
2568 b bool
2569 x interface{}