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