OSDN Git Service

Update Go library to r60.3 release.
[pf3gnuchains/gcc-fork.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 ptrSize = unsafe.Sizeof((*byte)(nil))
15 const cannotSet = "cannot set value obtained from unexported struct field"
16
17 // TODO: This will have to go away when
18 // the new gc goes in.
19 func memmove(adst, asrc unsafe.Pointer, n uintptr) {
20         dst := uintptr(adst)
21         src := uintptr(asrc)
22         switch {
23         case src < dst && src+n > dst:
24                 // byte copy backward
25                 // careful: i is unsigned
26                 for i := n; i > 0; {
27                         i--
28                         *(*byte)(unsafe.Pointer(dst + i)) = *(*byte)(unsafe.Pointer(src + i))
29                 }
30         case (n|src|dst)&(ptrSize-1) != 0:
31                 // byte copy forward
32                 for i := uintptr(0); i < n; i++ {
33                         *(*byte)(unsafe.Pointer(dst + i)) = *(*byte)(unsafe.Pointer(src + i))
34                 }
35         default:
36                 // word copy forward
37                 for i := uintptr(0); i < n; i += ptrSize {
38                         *(*uintptr)(unsafe.Pointer(dst + i)) = *(*uintptr)(unsafe.Pointer(src + i))
39                 }
40         }
41 }
42
43 // Value is the reflection interface to a Go value.
44 //
45 // Not all methods apply to all kinds of values.  Restrictions,
46 // if any, are noted in the documentation for each method.
47 // Use the Kind method to find out the kind of value before
48 // calling kind-specific methods.  Calling a method
49 // inappropriate to the kind of type causes a run time panic.
50 //
51 // The zero Value represents no value.
52 // Its IsValid method returns false, its Kind method returns Invalid,
53 // its String method returns "<invalid Value>", and all other methods panic.
54 // Most functions and methods never return an invalid value.
55 // If one does, its documentation states the conditions explicitly.
56 //
57 // The fields of Value are exported so that clients can copy and
58 // pass Values around, but they should not be edited or inspected
59 // directly.  A future language change may make it possible not to
60 // export these fields while still keeping Values usable as values.
61 type Value struct {
62         Internal       interface{}
63         InternalMethod int
64 }
65
66 // A ValueError occurs when a Value method is invoked on
67 // a Value that does not support it.  Such cases are documented
68 // in the description of each method.
69 type ValueError struct {
70         Method string
71         Kind   Kind
72 }
73
74 func (e *ValueError) String() string {
75         if e.Kind == 0 {
76                 return "reflect: call of " + e.Method + " on zero Value"
77         }
78         return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
79 }
80
81 // methodName returns the name of the calling method,
82 // assumed to be two stack frames above.
83 func methodName() string {
84         pc, _, _, _ := runtime.Caller(2)
85         f := runtime.FuncForPC(pc)
86         if f == nil {
87                 return "unknown method"
88         }
89         return f.Name()
90 }
91
92 // An iword is the word that would be stored in an
93 // interface to represent a given value v.  Specifically, if v is
94 // bigger than a pointer, its word is a pointer to v's data.
95 // Otherwise, its word is a zero uintptr with the data stored
96 // in the leading bytes.
97 type iword uintptr
98
99 func loadIword(p unsafe.Pointer, size uintptr) iword {
100         // Run the copy ourselves instead of calling memmove
101         // to avoid moving v to the heap.
102         w := iword(0)
103         switch size {
104         default:
105                 panic("reflect: internal error: loadIword of " + strconv.Itoa(int(size)) + "-byte value")
106         case 0:
107         case 1:
108                 *(*uint8)(unsafe.Pointer(&w)) = *(*uint8)(p)
109         case 2:
110                 *(*uint16)(unsafe.Pointer(&w)) = *(*uint16)(p)
111         case 3:
112                 *(*[3]byte)(unsafe.Pointer(&w)) = *(*[3]byte)(p)
113         case 4:
114                 *(*uint32)(unsafe.Pointer(&w)) = *(*uint32)(p)
115         case 5:
116                 *(*[5]byte)(unsafe.Pointer(&w)) = *(*[5]byte)(p)
117         case 6:
118                 *(*[6]byte)(unsafe.Pointer(&w)) = *(*[6]byte)(p)
119         case 7:
120                 *(*[7]byte)(unsafe.Pointer(&w)) = *(*[7]byte)(p)
121         case 8:
122                 *(*uint64)(unsafe.Pointer(&w)) = *(*uint64)(p)
123         }
124         return w
125 }
126
127 func storeIword(p unsafe.Pointer, w iword, size uintptr) {
128         // Run the copy ourselves instead of calling memmove
129         // to avoid moving v to the heap.
130         switch size {
131         default:
132                 panic("reflect: internal error: storeIword of " + strconv.Itoa(int(size)) + "-byte value")
133         case 0:
134         case 1:
135                 *(*uint8)(p) = *(*uint8)(unsafe.Pointer(&w))
136         case 2:
137                 *(*uint16)(p) = *(*uint16)(unsafe.Pointer(&w))
138         case 3:
139                 *(*[3]byte)(p) = *(*[3]byte)(unsafe.Pointer(&w))
140         case 4:
141                 *(*uint32)(p) = *(*uint32)(unsafe.Pointer(&w))
142         case 5:
143                 *(*[5]byte)(p) = *(*[5]byte)(unsafe.Pointer(&w))
144         case 6:
145                 *(*[6]byte)(p) = *(*[6]byte)(unsafe.Pointer(&w))
146         case 7:
147                 *(*[7]byte)(p) = *(*[7]byte)(unsafe.Pointer(&w))
148         case 8:
149                 *(*uint64)(p) = *(*uint64)(unsafe.Pointer(&w))
150         }
151 }
152
153 // emptyInterface is the header for an interface{} value.
154 type emptyInterface struct {
155         typ  *runtime.Type
156         word iword
157 }
158
159 // nonEmptyInterface is the header for a interface value with methods.
160 type nonEmptyInterface struct {
161         // see ../runtime/iface.c:/Itab
162         itab *struct {
163                 typ    *runtime.Type // dynamic concrete type
164                 fun    [100000]unsafe.Pointer // method table
165         }
166         word iword
167 }
168
169 // Regarding the implementation of Value:
170 //
171 // The Internal interface is a true interface value in the Go sense,
172 // but it also serves as a (type, address) pair in which one cannot
173 // be changed separately from the other.  That is, it serves as a way
174 // to prevent unsafe mutations of the Internal state even though
175 // we cannot (yet?) hide the field while preserving the ability for
176 // clients to make copies of Values.
177 //
178 // The internal method converts a Value into the expanded internalValue struct.
179 // If we could avoid exporting fields we'd probably make internalValue the
180 // definition of Value.
181 //
182 // If a Value is addressable (CanAddr returns true), then the Internal
183 // interface value holds a pointer to the actual field data, and Set stores
184 // through that pointer.  If a Value is not addressable (CanAddr returns false),
185 // then the Internal interface value holds the actual value.
186 //
187 // In addition to whether a value is addressable, we track whether it was
188 // obtained by using an unexported struct field.  Such values are allowed
189 // to be read, mainly to make fmt.Print more useful, but they are not
190 // allowed to be written.  We call such values read-only.
191 //
192 // A Value can be set (via the Set, SetUint, etc. methods) only if it is both
193 // addressable and not read-only.
194 //
195 // The two permission bits - addressable and read-only - are stored in
196 // the bottom two bits of the type pointer in the interface value.
197 //
198 //      ordinary value: Internal = value
199 //      addressable value: Internal = value, Internal.typ |= flagAddr
200 //      read-only value: Internal = value, Internal.typ |= flagRO
201 //      addressable, read-only value: Internal = value, Internal.typ |= flagAddr | flagRO
202 //
203 // It is important that the read-only values have the extra bit set
204 // (as opposed to using the bit to mean writable), because client code
205 // can grab the interface field and try to use it.  Having the extra bit
206 // set makes the type pointer compare not equal to any real type,
207 // so that a client cannot, say, write through v.Internal.(*int).
208 // The runtime routines that access interface types reject types with
209 // low bits set.
210 //
211 // If a Value fv = v.Method(i), then fv = v with the InternalMethod
212 // field set to i+1.  Methods are never addressable.
213 //
214 // All in all, this is a lot of effort just to avoid making this new API
215 // depend on a language change we'll probably do anyway, but
216 // it's helpful to keep the two separate, and much of the logic is
217 // necessary to implement the Interface method anyway.
218
219 const (
220         flagAddr uint32 = 1 << iota // holds address of value
221         flagRO                      // read-only
222
223         reflectFlags = 3
224 )
225
226 // An internalValue is the unpacked form of a Value.
227 // The zero Value unpacks to a zero internalValue
228 type internalValue struct {
229         typ       *commonType // type of value
230         kind      Kind        // kind of value
231         flag      uint32
232         word      iword
233         addr      unsafe.Pointer
234         rcvr      iword
235         method    bool
236         nilmethod bool
237 }
238
239 func (v Value) internal() internalValue {
240         var iv internalValue
241         eface := *(*emptyInterface)(unsafe.Pointer(&v.Internal))
242         p := uintptr(unsafe.Pointer(eface.typ))
243         iv.typ = toCommonType((*runtime.Type)(unsafe.Pointer(p &^ reflectFlags)))
244         if iv.typ == nil {
245                 return iv
246         }
247         iv.flag = uint32(p & reflectFlags)
248         iv.word = eface.word
249         if iv.flag&flagAddr != 0 {
250                 iv.addr = unsafe.Pointer(uintptr(iv.word))
251                 iv.typ = iv.typ.Elem().common()
252                 if Kind(iv.typ.kind) == Ptr || Kind(iv.typ.kind) == UnsafePointer {
253                         iv.word = loadIword(iv.addr, iv.typ.size)
254                 }
255         } else {
256                 if Kind(iv.typ.kind) != Ptr && Kind(iv.typ.kind) != UnsafePointer {
257                         iv.addr = unsafe.Pointer(uintptr(iv.word))
258                 }
259         }
260         iv.kind = iv.typ.Kind()
261
262         // Is this a method?  If so, iv describes the receiver.
263         // Rewrite to describe the method function.
264         if v.InternalMethod != 0 {
265                 // If this Value is a method value (x.Method(i) for some Value x)
266                 // then we will invoke it using the interface form of the method,
267                 // which always passes the receiver as a single word.
268                 // Record that information.
269                 i := v.InternalMethod - 1
270                 if iv.kind == Interface {
271                         it := (*interfaceType)(unsafe.Pointer(iv.typ))
272                         if i < 0 || i >= len(it.methods) {
273                                 panic("reflect: broken Value")
274                         }
275                         m := &it.methods[i]
276                         if m.pkgPath != nil {
277                                 iv.flag |= flagRO
278                         }
279                         iv.typ = toCommonType(m.typ)
280                         iface := (*nonEmptyInterface)(iv.addr)
281                         if iface.itab == nil {
282                                 iv.word = 0
283                                 iv.nilmethod = true
284                         } else {
285                                 iv.word = iword(uintptr(iface.itab.fun[i]))
286                         }
287                         iv.rcvr = iface.word
288                 } else {
289                         ut := iv.typ.uncommon()
290                         if ut == nil || i < 0 || i >= len(ut.methods) {
291                                 panic("reflect: broken Value")
292                         }
293                         m := &ut.methods[i]
294                         if m.pkgPath != nil {
295                                 iv.flag |= flagRO
296                         }
297                         iv.typ = toCommonType(m.mtyp)
298                         iv.rcvr = iv.word
299                         iv.word = iword(uintptr(m.tfn))
300                 }
301                 if iv.word != 0 {
302                         p := new(iword)
303                         *p = iv.word
304                         iv.word = iword(uintptr(unsafe.Pointer(p)))
305                 }
306                 iv.kind = Func
307                 iv.method = true
308                 iv.flag &^= flagAddr
309                 iv.addr = unsafe.Pointer(uintptr(iv.word))
310         }
311
312         return iv
313 }
314
315 // packValue returns a Value with the given flag bits, type, and interface word.
316 func packValue(flag uint32, typ *runtime.Type, word iword) Value {
317         if typ == nil {
318                 panic("packValue")
319         }
320         t := uintptr(unsafe.Pointer(typ))
321         t |= uintptr(flag)
322         eface := emptyInterface{(*runtime.Type)(unsafe.Pointer(t)), word}
323         return Value{Internal: *(*interface{})(unsafe.Pointer(&eface))}
324 }
325
326 // valueFromAddr returns a Value using the given type and address.
327 func valueFromAddr(flag uint32, typ Type, addr unsafe.Pointer) Value {
328         if flag&flagAddr != 0 {
329                 // Addressable, so the internal value is
330                 // an interface containing a pointer to the real value.
331                 return packValue(flag, PtrTo(typ).runtimeType(), iword(uintptr(addr)))
332         }
333
334         var w iword
335         if k := typ.Kind(); k == Ptr || k == UnsafePointer {
336                 // In line, so the interface word is the actual value.
337                 w = loadIword(addr, typ.Size())
338         } else {
339                 // Not in line: the interface word is the address.
340                 w = iword(uintptr(addr))
341         }
342         return packValue(flag, typ.runtimeType(), w)
343 }
344
345 // valueFromIword returns a Value using the given type and interface word.
346 func valueFromIword(flag uint32, typ Type, w iword) Value {
347         if flag&flagAddr != 0 {
348                 panic("reflect: internal error: valueFromIword addressable")
349         }
350         return packValue(flag, typ.runtimeType(), w)
351 }
352
353 func (iv internalValue) mustBe(want Kind) {
354         if iv.kind != want {
355                 panic(&ValueError{methodName(), iv.kind})
356         }
357 }
358
359 func (iv internalValue) mustBeExported() {
360         if iv.kind == 0 {
361                 panic(&ValueError{methodName(), iv.kind})
362         }
363         if iv.flag&flagRO != 0 {
364                 panic(methodName() + " using value obtained using unexported field")
365         }
366 }
367
368 func (iv internalValue) mustBeAssignable() {
369         if iv.kind == 0 {
370                 panic(&ValueError{methodName(), iv.kind})
371         }
372         // Assignable if addressable and not read-only.
373         if iv.flag&flagRO != 0 {
374                 panic(methodName() + " using value obtained using unexported field")
375         }
376         if iv.flag&flagAddr == 0 {
377                 panic(methodName() + " using unaddressable value")
378         }
379 }
380
381 // Addr returns a pointer value representing the address of v.
382 // It panics if CanAddr() returns false.
383 // Addr is typically used to obtain a pointer to a struct field
384 // or slice element in order to call a method that requires a
385 // pointer receiver.
386 func (v Value) Addr() Value {
387         iv := v.internal()
388         if iv.flag&flagAddr == 0 {
389                 panic("reflect.Value.Addr of unaddressable value")
390         }
391         return valueFromIword(iv.flag&flagRO, PtrTo(iv.typ.toType()), iword(uintptr(iv.addr)))
392 }
393
394 // Bool returns v's underlying value.
395 // It panics if v's kind is not Bool.
396 func (v Value) Bool() bool {
397         iv := v.internal()
398         iv.mustBe(Bool)
399         return *(*bool)(unsafe.Pointer(iv.addr))
400 }
401
402 // CanAddr returns true if the value's address can be obtained with Addr.
403 // Such values are called addressable.  A value is addressable if it is
404 // an element of a slice, an element of an addressable array,
405 // a field of an addressable struct, or the result of dereferencing a pointer.
406 // If CanAddr returns false, calling Addr will panic.
407 func (v Value) CanAddr() bool {
408         iv := v.internal()
409         return iv.flag&flagAddr != 0
410 }
411
412 // CanSet returns true if the value of v can be changed.
413 // A Value can be changed only if it is addressable and was not
414 // obtained by the use of unexported struct fields.
415 // If CanSet returns false, calling Set or any type-specific
416 // setter (e.g., SetBool, SetInt64) will panic.
417 func (v Value) CanSet() bool {
418         iv := v.internal()
419         return iv.flag&(flagAddr|flagRO) == flagAddr
420 }
421
422 // Call calls the function v with the input arguments in.
423 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
424 // Call panics if v's Kind is not Func.
425 // It returns the output results as Values.
426 // As in Go, each input argument must be assignable to the
427 // type of the function's corresponding input parameter.
428 // If v is a variadic function, Call creates the variadic slice parameter
429 // itself, copying in the corresponding values.
430 func (v Value) Call(in []Value) []Value {
431         iv := v.internal()
432         iv.mustBe(Func)
433         iv.mustBeExported()
434         return iv.call("Call", in)
435 }
436
437 // CallSlice calls the variadic function v with the input arguments in,
438 // assigning the slice in[len(in)-1] to v's final variadic argument.  
439 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]...).
440 // Call panics if v's Kind is not Func or if v is not variadic.
441 // It returns the output results as Values.
442 // As in Go, each input argument must be assignable to the
443 // type of the function's corresponding input parameter.
444 func (v Value) CallSlice(in []Value) []Value {
445         iv := v.internal()
446         iv.mustBe(Func)
447         iv.mustBeExported()
448         return iv.call("CallSlice", in)
449 }
450
451 func (iv internalValue) call(method string, in []Value) []Value {
452         if iv.word == 0 {
453                 if iv.nilmethod {
454                         panic("reflect.Value.Call: call of method on nil interface value")
455                 }
456                 panic("reflect.Value.Call: call of nil function")
457         }
458
459         isSlice := method == "CallSlice"
460         t := iv.typ
461         n := t.NumIn()
462         if isSlice {
463                 if !t.IsVariadic() {
464                         panic("reflect: CallSlice of non-variadic function")
465                 }
466                 if len(in) < n {
467                         panic("reflect: CallSlice with too few input arguments")
468                 }
469                 if len(in) > n {
470                         panic("reflect: CallSlice with too many input arguments")
471                 }
472         } else {
473                 if t.IsVariadic() {
474                         n--
475                 }
476                 if len(in) < n {
477                         panic("reflect: Call with too few input arguments")
478                 }
479                 if !t.IsVariadic() && len(in) > n {
480                         panic("reflect: Call with too many input arguments")
481                 }
482         }
483         for _, x := range in {
484                 if x.Kind() == Invalid {
485                         panic("reflect: " + method + " using zero Value argument")
486                 }
487         }
488         for i := 0; i < n; i++ {
489                 if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
490                         panic("reflect: " + method + " using " + xt.String() + " as type " + targ.String())
491                 }
492         }
493         if !isSlice && t.IsVariadic() {
494                 // prepare slice for remaining values
495                 m := len(in) - n
496                 slice := MakeSlice(t.In(n), m, m)
497                 elem := t.In(n).Elem()
498                 for i := 0; i < m; i++ {
499                         x := in[n+i]
500                         if xt := x.Type(); !xt.AssignableTo(elem) {
501                                 panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + method)
502                         }
503                         slice.Index(i).Set(x)
504                 }
505                 origIn := in
506                 in = make([]Value, n+1)
507                 copy(in[:n], origIn)
508                 in[n] = slice
509         }
510
511         nin := len(in)
512         if nin != t.NumIn() {
513                 panic("reflect.Value.Call: wrong argument count")
514         }
515         nout := t.NumOut()
516
517         if iv.method {
518                 nin++
519         }
520         params := make([]unsafe.Pointer, nin)
521         delta := 0
522         off := 0
523         if iv.method {
524                 // Hard-wired first argument.
525                 p := new(iword)
526                 *p = iv.rcvr
527                 params[0] = unsafe.Pointer(p)
528                 off = 1
529         }
530
531         first_pointer := false
532         for i, v := range in {
533                 siv := v.internal()
534                 siv.mustBeExported()
535                 targ := t.In(i).(*commonType)
536                 siv = convertForAssignment("reflect.Value.Call", nil, targ, siv)
537                 if siv.addr == nil {
538                         p := new(unsafe.Pointer)
539                         *p = unsafe.Pointer(uintptr(siv.word))
540                         params[off] = unsafe.Pointer(p)
541                 } else {
542                         params[off] = siv.addr
543                 }
544                 if i == 0 && Kind(targ.kind) != Ptr && !iv.method && isMethod(iv.typ) {
545                         p := new(unsafe.Pointer)
546                         *p = params[off]
547                         params[off] = unsafe.Pointer(p)
548                         first_pointer = true
549                 }
550                 off++
551         }
552
553         ret := make([]Value, nout)
554         results := make([]unsafe.Pointer, nout)
555         for i := 0; i < nout; i++ {
556                 v := New(t.Out(i))
557                 results[i] = unsafe.Pointer(v.Pointer())
558                 ret[i] = Indirect(v)
559         }
560
561         var pp *unsafe.Pointer
562         if len(params) > 0 {
563                 pp = &params[0]
564         }
565         var pr *unsafe.Pointer
566         if len(results) > 0 {
567                 pr = &results[0]
568         }
569
570         call(t, *(*unsafe.Pointer)(iv.addr), iv.method, first_pointer, pp, pr)
571
572         return ret
573 }
574
575 // gccgo specific test to see if typ is a method.  We can tell by
576 // looking at the string to see if there is a receiver.  We need this
577 // because for gccgo all methods take pointer receivers.
578 func isMethod(t *commonType) bool {
579         if Kind(t.kind) != Func {
580                 return false
581         }
582         s := *t.string
583         parens := 0
584         params := 0
585         sawRet := false
586         for i, c := range s {
587                 if c == '(' {
588                         parens++
589                         params++
590                 } else if c == ')' {
591                         parens--
592                 } else if parens == 0 && c == ' ' && s[i + 1] != '(' && !sawRet {
593                         params++
594                         sawRet = true
595                 }
596         }
597         return params > 2
598 }
599
600 // Cap returns v's capacity.
601 // It panics if v's Kind is not Array, Chan, or Slice.
602 func (v Value) Cap() int {
603         iv := v.internal()
604         switch iv.kind {
605         case Array:
606                 return iv.typ.Len()
607         case Chan:
608                 return int(chancap(*(*iword)(iv.addr)))
609         case Slice:
610                 return (*SliceHeader)(iv.addr).Cap
611         }
612         panic(&ValueError{"reflect.Value.Cap", iv.kind})
613 }
614
615 // Close closes the channel v.
616 // It panics if v's Kind is not Chan.
617 func (v Value) Close() {
618         iv := v.internal()
619         iv.mustBe(Chan)
620         iv.mustBeExported()
621         ch := *(*iword)(iv.addr)
622         chanclose(ch)
623 }
624
625 // Complex returns v's underlying value, as a complex128.
626 // It panics if v's Kind is not Complex64 or Complex128
627 func (v Value) Complex() complex128 {
628         iv := v.internal()
629         switch iv.kind {
630         case Complex64:
631                 return complex128(*(*complex64)(iv.addr))
632         case Complex128:
633                 return *(*complex128)(iv.addr)
634         }
635         panic(&ValueError{"reflect.Value.Complex", iv.kind})
636 }
637
638 // Elem returns the value that the interface v contains
639 // or that the pointer v points to.
640 // It panics if v's Kind is not Interface or Ptr.
641 // It returns the zero Value if v is nil.
642 func (v Value) Elem() Value {
643         iv := v.internal()
644         return iv.Elem()
645 }
646
647 func (iv internalValue) Elem() Value {
648         switch iv.kind {
649         case Interface:
650                 // Empty interface and non-empty interface have different layouts.
651                 // Convert to empty interface.
652                 var eface emptyInterface
653                 if iv.typ.NumMethod() == 0 {
654                         eface = *(*emptyInterface)(iv.addr)
655                 } else {
656                         iface := (*nonEmptyInterface)(iv.addr)
657                         if iface.itab != nil {
658                                 eface.typ = iface.itab.typ
659                         }
660                         eface.word = iface.word
661                 }
662                 if eface.typ == nil {
663                         return Value{}
664                 }
665                 return valueFromIword(iv.flag&flagRO, toType(eface.typ), eface.word)
666
667         case Ptr:
668                 // The returned value's address is v's value.
669                 if iv.word == 0 {
670                         return Value{}
671                 }
672                 return valueFromAddr(iv.flag&flagRO|flagAddr, iv.typ.Elem(), unsafe.Pointer(uintptr(iv.word)))
673         }
674         panic(&ValueError{"reflect.Value.Elem", iv.kind})
675 }
676
677 // Field returns the i'th field of the struct v.
678 // It panics if v's Kind is not Struct or i is out of range.
679 func (v Value) Field(i int) Value {
680         iv := v.internal()
681         iv.mustBe(Struct)
682         t := iv.typ.toType()
683         if i < 0 || i >= t.NumField() {
684                 panic("reflect: Field index out of range")
685         }
686         f := t.Field(i)
687
688         // Inherit permission bits from v.
689         flag := iv.flag
690         // Using an unexported field forces flagRO.
691         if f.PkgPath != "" {
692                 flag |= flagRO
693         }
694         return valueFromValueOffset(flag, f.Type, iv, f.Offset)
695 }
696
697 // valueFromValueOffset returns a sub-value of outer
698 // (outer is an array or a struct) with the given flag and type
699 // starting at the given byte offset into outer.
700 func valueFromValueOffset(flag uint32, typ Type, outer internalValue, offset uintptr) Value {
701         if outer.addr != nil {
702                 return valueFromAddr(flag, typ, unsafe.Pointer(uintptr(outer.addr)+offset))
703         }
704
705         // outer is so tiny it is in line.
706         // We have to use outer.word and derive
707         // the new word (it cannot possibly be bigger).
708         // In line, so not addressable.
709         if flag&flagAddr != 0 {
710                 panic("reflect: internal error: misuse of valueFromValueOffset")
711         }
712         b := *(*[ptrSize]byte)(unsafe.Pointer(&outer.word))
713         for i := uintptr(0); i < typ.Size(); i++ {
714                 b[i] = b[offset+i]
715         }
716         for i := typ.Size(); i < ptrSize; i++ {
717                 b[i] = 0
718         }
719         w := *(*iword)(unsafe.Pointer(&b))
720         return valueFromIword(flag, typ, w)
721 }
722
723 // FieldByIndex returns the nested field corresponding to index.
724 // It panics if v's Kind is not struct.
725 func (v Value) FieldByIndex(index []int) Value {
726         v.internal().mustBe(Struct)
727         for i, x := range index {
728                 if i > 0 {
729                         if v.Kind() == Ptr && v.Elem().Kind() == Struct {
730                                 v = v.Elem()
731                         }
732                 }
733                 v = v.Field(x)
734         }
735         return v
736 }
737
738 // FieldByName returns the struct field with the given name.
739 // It returns the zero Value if no field was found.
740 // It panics if v's Kind is not struct.
741 func (v Value) FieldByName(name string) Value {
742         iv := v.internal()
743         iv.mustBe(Struct)
744         if f, ok := iv.typ.FieldByName(name); ok {
745                 return v.FieldByIndex(f.Index)
746         }
747         return Value{}
748 }
749
750 // FieldByNameFunc returns the struct field with a name
751 // that satisfies the match function.
752 // It panics if v's Kind is not struct.
753 // It returns the zero Value if no field was found.
754 func (v Value) FieldByNameFunc(match func(string) bool) Value {
755         v.internal().mustBe(Struct)
756         if f, ok := v.Type().FieldByNameFunc(match); ok {
757                 return v.FieldByIndex(f.Index)
758         }
759         return Value{}
760 }
761
762 // Float returns v's underlying value, as an float64.
763 // It panics if v's Kind is not Float32 or Float64
764 func (v Value) Float() float64 {
765         iv := v.internal()
766         switch iv.kind {
767         case Float32:
768                 return float64(*(*float32)(iv.addr))
769         case Float64:
770                 return *(*float64)(iv.addr)
771         }
772         panic(&ValueError{"reflect.Value.Float", iv.kind})
773 }
774
775 // Index returns v's i'th element.
776 // It panics if v's Kind is not Array or Slice or i is out of range.
777 func (v Value) Index(i int) Value {
778         iv := v.internal()
779         switch iv.kind {
780         default:
781                 panic(&ValueError{"reflect.Value.Index", iv.kind})
782         case Array:
783                 flag := iv.flag // element flag same as overall array
784                 t := iv.typ.toType()
785                 if i < 0 || i > t.Len() {
786                         panic("reflect: array index out of range")
787                 }
788                 typ := t.Elem()
789                 return valueFromValueOffset(flag, typ, iv, uintptr(i)*typ.Size())
790
791         case Slice:
792                 // Element flag same as Elem of Ptr.
793                 // Addressable, possibly read-only.
794                 flag := iv.flag&flagRO | flagAddr
795                 s := (*SliceHeader)(iv.addr)
796                 if i < 0 || i >= s.Len {
797                         panic("reflect: slice index out of range")
798                 }
799                 typ := iv.typ.Elem()
800                 addr := unsafe.Pointer(s.Data + uintptr(i)*typ.Size())
801                 return valueFromAddr(flag, typ, addr)
802         }
803
804         panic("not reached")
805 }
806
807 // Int returns v's underlying value, as an int64.
808 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
809 func (v Value) Int() int64 {
810         iv := v.internal()
811         switch iv.kind {
812         case Int:
813                 return int64(*(*int)(iv.addr))
814         case Int8:
815                 return int64(*(*int8)(iv.addr))
816         case Int16:
817                 return int64(*(*int16)(iv.addr))
818         case Int32:
819                 return int64(*(*int32)(iv.addr))
820         case Int64:
821                 return *(*int64)(iv.addr)
822         }
823         panic(&ValueError{"reflect.Value.Int", iv.kind})
824 }
825
826 // CanInterface returns true if Interface can be used without panicking.
827 func (v Value) CanInterface() bool {
828         iv := v.internal()
829         if iv.kind == Invalid {
830                 panic(&ValueError{"reflect.Value.CanInterface", iv.kind})
831         }
832         return v.InternalMethod == 0 && iv.flag&flagRO == 0
833 }
834
835 // Interface returns v's value as an interface{}.
836 // If v is a method obtained by invoking Value.Method
837 // (as opposed to Type.Method), Interface cannot return an
838 // interface value, so it panics.
839 func (v Value) Interface() interface{} {
840         return valueInterface(v, true)
841 }
842
843 func valueInterface(v Value, safe bool) interface{} {
844         iv := v.internal()
845         return iv.valueInterface(safe)
846 }
847
848 func (iv internalValue) valueInterface(safe bool) interface{} {
849         if iv.kind == 0 {
850                 panic(&ValueError{"reflect.Value.Interface", iv.kind})
851         }
852         if iv.method {
853                 panic("reflect.Value.Interface: cannot create interface value for method with bound receiver")
854         }
855
856         if safe && iv.flag&flagRO != 0 {
857                 // Do not allow access to unexported values via Interface,
858                 // because they might be pointers that should not be 
859                 // writable or methods or function that should not be callable.
860                 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
861         }
862         if iv.kind == Interface {
863                 // Special case: return the element inside the interface.
864                 // Won't recurse further because an interface cannot contain an interface.
865                 if iv.IsNil() {
866                         return nil
867                 }
868                 return iv.Elem().Interface()
869         }
870
871         // Non-interface value.
872         var eface emptyInterface
873         eface.typ = iv.typ.runtimeType()
874         eface.word = iv.word
875         return *(*interface{})(unsafe.Pointer(&eface))
876 }
877
878 // InterfaceData returns the interface v's value as a uintptr pair.
879 // It panics if v's Kind is not Interface.
880 func (v Value) InterfaceData() [2]uintptr {
881         iv := v.internal()
882         iv.mustBe(Interface)
883         // We treat this as a read operation, so we allow
884         // it even for unexported data, because the caller
885         // has to import "unsafe" to turn it into something
886         // that can be abused.
887         return *(*[2]uintptr)(iv.addr)
888 }
889
890 // IsNil returns true if v is a nil value.
891 // It panics if v's Kind is not Chan, Func, Interface, Map, Ptr, or Slice.
892 func (v Value) IsNil() bool {
893         return v.internal().IsNil()
894 }
895
896 func (iv internalValue) IsNil() bool {
897         switch iv.kind {
898         case Ptr:
899                 if iv.method {
900                         panic("reflect: IsNil of method Value")
901                 }
902                 return iv.word == 0
903         case Chan, Func, Map:
904                 if iv.method {
905                         panic("reflect: IsNil of method Value")
906                 }
907                 return *(*uintptr)(iv.addr) == 0
908         case Interface, Slice:
909                 // Both interface and slice are nil if first word is 0.
910                 return *(*uintptr)(iv.addr) == 0
911         }
912         panic(&ValueError{"reflect.Value.IsNil", iv.kind})
913 }
914
915 // IsValid returns true if v represents a value.
916 // It returns false if v is the zero Value.
917 // If IsValid returns false, all other methods except String panic.
918 // Most functions and methods never return an invalid value.
919 // If one does, its documentation states the conditions explicitly.
920 func (v Value) IsValid() bool {
921         return v.Internal != nil
922 }
923
924 // Kind returns v's Kind.
925 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
926 func (v Value) Kind() Kind {
927         return v.internal().kind
928 }
929
930 // Len returns v's length.
931 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
932 func (v Value) Len() int {
933         iv := v.internal()
934         switch iv.kind {
935         case Array:
936                 return iv.typ.Len()
937         case Chan:
938                 return int(chanlen(*(*iword)(iv.addr)))
939         case Map:
940                 return int(maplen(*(*iword)(iv.addr)))
941         case Slice:
942                 return (*SliceHeader)(iv.addr).Len
943         case String:
944                 return (*StringHeader)(iv.addr).Len
945         }
946         panic(&ValueError{"reflect.Value.Len", iv.kind})
947 }
948
949 // MapIndex returns the value associated with key in the map v.
950 // It panics if v's Kind is not Map.
951 // It returns the zero Value if key is not found in the map or if v represents a nil map.
952 // As in Go, the key's value must be assignable to the map's key type.
953 func (v Value) MapIndex(key Value) Value {
954         iv := v.internal()
955         iv.mustBe(Map)
956         typ := iv.typ.toType()
957
958         // Do not require ikey to be exported, so that DeepEqual
959         // and other programs can use all the keys returned by
960         // MapKeys as arguments to MapIndex.  If either the map
961         // or the key is unexported, though, the result will be
962         // considered unexported.
963
964         ikey := key.internal()
965         ikey = convertForAssignment("reflect.Value.MapIndex", nil, typ.Key(), ikey)
966         if iv.word == 0 {
967                 return Value{}
968         }
969
970         flag := (iv.flag | ikey.flag) & flagRO
971         elemType := typ.Elem()
972         elemWord, ok := mapaccess(typ.runtimeType(), *(*iword)(iv.addr), ikey.word)
973         if !ok {
974                 return Value{}
975         }
976         return valueFromIword(flag, elemType, elemWord)
977 }
978
979 // MapKeys returns a slice containing all the keys present in the map,
980 // in unspecified order.
981 // It panics if v's Kind is not Map.
982 // It returns an empty slice if v represents a nil map.
983 func (v Value) MapKeys() []Value {
984         iv := v.internal()
985         iv.mustBe(Map)
986         keyType := iv.typ.Key()
987
988         flag := iv.flag & flagRO
989         m := *(*iword)(iv.addr)
990         mlen := int32(0)
991         if m != 0 {
992                 mlen = maplen(m)
993         }
994         it := mapiterinit(iv.typ.runtimeType(), m)
995         a := make([]Value, mlen)
996         var i int
997         for i = 0; i < len(a); i++ {
998                 keyWord, ok := mapiterkey(it)
999                 if !ok {
1000                         break
1001                 }
1002                 a[i] = valueFromIword(flag, keyType, keyWord)
1003                 mapiternext(it)
1004         }
1005         return a[:i]
1006 }
1007
1008 // Method returns a function value corresponding to v's i'th method.
1009 // The arguments to a Call on the returned function should not include
1010 // a receiver; the returned function will always use v as the receiver.
1011 // Method panics if i is out of range.
1012 func (v Value) Method(i int) Value {
1013         iv := v.internal()
1014         if iv.kind == Invalid {
1015                 panic(&ValueError{"reflect.Value.Method", Invalid})
1016         }
1017         if i < 0 || i >= iv.typ.NumMethod() {
1018                 panic("reflect: Method index out of range")
1019         }
1020         return Value{v.Internal, i + 1}
1021 }
1022
1023 // NumMethod returns the number of methods in the value's method set.
1024 func (v Value) NumMethod() int {
1025         iv := v.internal()
1026         if iv.kind == Invalid {
1027                 panic(&ValueError{"reflect.Value.NumMethod", Invalid})
1028         }
1029         return iv.typ.NumMethod()
1030 }
1031
1032 // MethodByName returns a function value corresponding to the method
1033 // of v with the given name.
1034 // The arguments to a Call on the returned function should not include
1035 // a receiver; the returned function will always use v as the receiver.
1036 // It returns the zero Value if no method was found.
1037 func (v Value) MethodByName(name string) Value {
1038         iv := v.internal()
1039         if iv.kind == Invalid {
1040                 panic(&ValueError{"reflect.Value.MethodByName", Invalid})
1041         }
1042         m, ok := iv.typ.MethodByName(name)
1043         if ok {
1044                 return Value{v.Internal, m.Index + 1}
1045         }
1046         return Value{}
1047 }
1048
1049 // NumField returns the number of fields in the struct v.
1050 // It panics if v's Kind is not Struct.
1051 func (v Value) NumField() int {
1052         iv := v.internal()
1053         iv.mustBe(Struct)
1054         return iv.typ.NumField()
1055 }
1056
1057 // OverflowComplex returns true if the complex128 x cannot be represented by v's type.
1058 // It panics if v's Kind is not Complex64 or Complex128.
1059 func (v Value) OverflowComplex(x complex128) bool {
1060         iv := v.internal()
1061         switch iv.kind {
1062         case Complex64:
1063                 return overflowFloat32(real(x)) || overflowFloat32(imag(x))
1064         case Complex128:
1065                 return false
1066         }
1067         panic(&ValueError{"reflect.Value.OverflowComplex", iv.kind})
1068 }
1069
1070 // OverflowFloat returns true if the float64 x cannot be represented by v's type.
1071 // It panics if v's Kind is not Float32 or Float64.
1072 func (v Value) OverflowFloat(x float64) bool {
1073         iv := v.internal()
1074         switch iv.kind {
1075         case Float32:
1076                 return overflowFloat32(x)
1077         case Float64:
1078                 return false
1079         }
1080         panic(&ValueError{"reflect.Value.OverflowFloat", iv.kind})
1081 }
1082
1083 func overflowFloat32(x float64) bool {
1084         if x < 0 {
1085                 x = -x
1086         }
1087         return math.MaxFloat32 <= x && x <= math.MaxFloat64
1088 }
1089
1090 // OverflowInt returns true if the int64 x cannot be represented by v's type.
1091 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1092 func (v Value) OverflowInt(x int64) bool {
1093         iv := v.internal()
1094         switch iv.kind {
1095         case Int, Int8, Int16, Int32, Int64:
1096                 bitSize := iv.typ.size * 8
1097                 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1098                 return x != trunc
1099         }
1100         panic(&ValueError{"reflect.Value.OverflowInt", iv.kind})
1101 }
1102
1103 // OverflowUint returns true if the uint64 x cannot be represented by v's type.
1104 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1105 func (v Value) OverflowUint(x uint64) bool {
1106         iv := v.internal()
1107         switch iv.kind {
1108         case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
1109                 bitSize := iv.typ.size * 8
1110                 trunc := (x << (64 - bitSize)) >> (64 - bitSize)
1111                 return x != trunc
1112         }
1113         panic(&ValueError{"reflect.Value.OverflowUint", iv.kind})
1114 }
1115
1116 // Pointer returns v's value as a uintptr.
1117 // It returns uintptr instead of unsafe.Pointer so that
1118 // code using reflect cannot obtain unsafe.Pointers
1119 // without importing the unsafe package explicitly.
1120 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1121 func (v Value) Pointer() uintptr {
1122         iv := v.internal()
1123         switch iv.kind {
1124         case Ptr, UnsafePointer:
1125                 if iv.kind == Func && v.InternalMethod != 0 {
1126                         panic("reflect.Value.Pointer of method Value")
1127                 }
1128                 return uintptr(iv.word)
1129         case Chan, Func, Map:
1130                 if iv.kind == Func && v.InternalMethod != 0 {
1131                         panic("reflect.Value.Pointer of method Value")
1132                 }
1133                 return *(*uintptr)(iv.addr)
1134         case Slice:
1135                 return (*SliceHeader)(iv.addr).Data
1136         }
1137         panic(&ValueError{"reflect.Value.Pointer", iv.kind})
1138 }
1139
1140 // Recv receives and returns a value from the channel v.
1141 // It panics if v's Kind is not Chan.
1142 // The receive blocks until a value is ready.
1143 // The boolean value ok is true if the value x corresponds to a send
1144 // on the channel, false if it is a zero value received because the channel is closed.
1145 func (v Value) Recv() (x Value, ok bool) {
1146         iv := v.internal()
1147         iv.mustBe(Chan)
1148         iv.mustBeExported()
1149         return iv.recv(false)
1150 }
1151
1152 // internal recv, possibly non-blocking (nb)
1153 func (iv internalValue) recv(nb bool) (val Value, ok bool) {
1154         t := iv.typ.toType()
1155         if t.ChanDir()&RecvDir == 0 {
1156                 panic("recv on send-only channel")
1157         }
1158         ch := *(*iword)(iv.addr)
1159         if ch == 0 {
1160                 panic("recv on nil channel")
1161         }
1162         valWord, selected, ok := chanrecv(iv.typ.runtimeType(), ch, nb)
1163         if selected {
1164                 val = valueFromIword(0, t.Elem(), valWord)
1165         }
1166         return
1167 }
1168
1169 // Send sends x on the channel v.
1170 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1171 // As in Go, x's value must be assignable to the channel's element type.
1172 func (v Value) Send(x Value) {
1173         iv := v.internal()
1174         iv.mustBe(Chan)
1175         iv.mustBeExported()
1176         iv.send(x, false)
1177 }
1178
1179 // internal send, possibly non-blocking
1180 func (iv internalValue) send(x Value, nb bool) (selected bool) {
1181         t := iv.typ.toType()
1182         if t.ChanDir()&SendDir == 0 {
1183                 panic("send on recv-only channel")
1184         }
1185         ix := x.internal()
1186         ix.mustBeExported() // do not let unexported x leak
1187         ix = convertForAssignment("reflect.Value.Send", nil, t.Elem(), ix)
1188         ch := *(*iword)(iv.addr)
1189         if ch == 0 {
1190                 panic("send on nil channel")
1191         }
1192         return chansend(iv.typ.runtimeType(), ch, ix.word, nb)
1193 }
1194
1195 // Set assigns x to the value v.
1196 // It panics if CanSet returns false.
1197 // As in Go, x's value must be assignable to v's type.
1198 func (v Value) Set(x Value) {
1199         iv := v.internal()
1200         ix := x.internal()
1201
1202         iv.mustBeAssignable()
1203         ix.mustBeExported() // do not let unexported x leak
1204
1205         ix = convertForAssignment("reflect.Set", iv.addr, iv.typ, ix)
1206
1207         n := ix.typ.size
1208         if Kind(ix.typ.kind) == Ptr || Kind(ix.typ.kind) == UnsafePointer {
1209                 storeIword(iv.addr, ix.word, n)
1210         } else {
1211                 memmove(iv.addr, ix.addr, n)
1212         }
1213 }
1214
1215 // SetBool sets v's underlying value.
1216 // It panics if v's Kind is not Bool or if CanSet() is false.
1217 func (v Value) SetBool(x bool) {
1218         iv := v.internal()
1219         iv.mustBeAssignable()
1220         iv.mustBe(Bool)
1221         *(*bool)(iv.addr) = x
1222 }
1223
1224 // SetComplex sets v's underlying value to x.
1225 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1226 func (v Value) SetComplex(x complex128) {
1227         iv := v.internal()
1228         iv.mustBeAssignable()
1229         switch iv.kind {
1230         default:
1231                 panic(&ValueError{"reflect.Value.SetComplex", iv.kind})
1232         case Complex64:
1233                 *(*complex64)(iv.addr) = complex64(x)
1234         case Complex128:
1235                 *(*complex128)(iv.addr) = x
1236         }
1237 }
1238
1239 // SetFloat sets v's underlying value to x.
1240 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1241 func (v Value) SetFloat(x float64) {
1242         iv := v.internal()
1243         iv.mustBeAssignable()
1244         switch iv.kind {
1245         default:
1246                 panic(&ValueError{"reflect.Value.SetFloat", iv.kind})
1247         case Float32:
1248                 *(*float32)(iv.addr) = float32(x)
1249         case Float64:
1250                 *(*float64)(iv.addr) = x
1251         }
1252 }
1253
1254 // SetInt sets v's underlying value to x.
1255 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1256 func (v Value) SetInt(x int64) {
1257         iv := v.internal()
1258         iv.mustBeAssignable()
1259         switch iv.kind {
1260         default:
1261                 panic(&ValueError{"reflect.Value.SetInt", iv.kind})
1262         case Int:
1263                 *(*int)(iv.addr) = int(x)
1264         case Int8:
1265                 *(*int8)(iv.addr) = int8(x)
1266         case Int16:
1267                 *(*int16)(iv.addr) = int16(x)
1268         case Int32:
1269                 *(*int32)(iv.addr) = int32(x)
1270         case Int64:
1271                 *(*int64)(iv.addr) = x
1272         }
1273 }
1274
1275 // SetLen sets v's length to n.
1276 // It panics if v's Kind is not Slice.
1277 func (v Value) SetLen(n int) {
1278         iv := v.internal()
1279         iv.mustBeAssignable()
1280         iv.mustBe(Slice)
1281         s := (*SliceHeader)(iv.addr)
1282         if n < 0 || n > int(s.Cap) {
1283                 panic("reflect: slice length out of range in SetLen")
1284         }
1285         s.Len = n
1286 }
1287
1288 // SetMapIndex sets the value associated with key in the map v to val.
1289 // It panics if v's Kind is not Map.
1290 // If val is the zero Value, SetMapIndex deletes the key from the map.
1291 // As in Go, key's value must be assignable to the map's key type,
1292 // and val's value must be assignable to the map's value type.
1293 func (v Value) SetMapIndex(key, val Value) {
1294         iv := v.internal()
1295         ikey := key.internal()
1296         ival := val.internal()
1297
1298         iv.mustBe(Map)
1299         iv.mustBeExported()
1300
1301         ikey.mustBeExported()
1302         ikey = convertForAssignment("reflect.Value.SetMapIndex", nil, iv.typ.Key(), ikey)
1303
1304         if ival.kind != Invalid {
1305                 ival.mustBeExported()
1306                 ival = convertForAssignment("reflect.Value.SetMapIndex", nil, iv.typ.Elem(), ival)
1307         }
1308
1309         mapassign(iv.typ.runtimeType(), *(*iword)(iv.addr), ikey.word, ival.word, ival.kind != Invalid)
1310 }
1311
1312 // SetUint sets v's underlying value to x.
1313 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1314 func (v Value) SetUint(x uint64) {
1315         iv := v.internal()
1316         iv.mustBeAssignable()
1317         switch iv.kind {
1318         default:
1319                 panic(&ValueError{"reflect.Value.SetUint", iv.kind})
1320         case Uint:
1321                 *(*uint)(iv.addr) = uint(x)
1322         case Uint8:
1323                 *(*uint8)(iv.addr) = uint8(x)
1324         case Uint16:
1325                 *(*uint16)(iv.addr) = uint16(x)
1326         case Uint32:
1327                 *(*uint32)(iv.addr) = uint32(x)
1328         case Uint64:
1329                 *(*uint64)(iv.addr) = x
1330         case Uintptr:
1331                 *(*uintptr)(iv.addr) = uintptr(x)
1332         }
1333 }
1334
1335 // SetPointer sets the unsafe.Pointer value v to x.
1336 // It panics if v's Kind is not UnsafePointer.
1337 func (v Value) SetPointer(x unsafe.Pointer) {
1338         iv := v.internal()
1339         iv.mustBeAssignable()
1340         iv.mustBe(UnsafePointer)
1341         *(*unsafe.Pointer)(iv.addr) = x
1342 }
1343
1344 // SetString sets v's underlying value to x.
1345 // It panics if v's Kind is not String or if CanSet() is false.
1346 func (v Value) SetString(x string) {
1347         iv := v.internal()
1348         iv.mustBeAssignable()
1349         iv.mustBe(String)
1350         *(*string)(iv.addr) = x
1351 }
1352
1353 // Slice returns a slice of v.
1354 // It panics if v's Kind is not Array or Slice.
1355 func (v Value) Slice(beg, end int) Value {
1356         iv := v.internal()
1357         if iv.kind != Array && iv.kind != Slice {
1358                 panic(&ValueError{"reflect.Value.Slice", iv.kind})
1359         }
1360         cap := v.Cap()
1361         if beg < 0 || end < beg || end > cap {
1362                 panic("reflect.Value.Slice: slice index out of bounds")
1363         }
1364         var typ Type
1365         var base uintptr
1366         switch iv.kind {
1367         case Array:
1368                 if iv.flag&flagAddr == 0 {
1369                         panic("reflect.Value.Slice: slice of unaddressable array")
1370                 }
1371                 typ = toType((*arrayType)(unsafe.Pointer(iv.typ)).slice)
1372                 base = uintptr(iv.addr)
1373         case Slice:
1374                 typ = iv.typ.toType()
1375                 base = (*SliceHeader)(iv.addr).Data
1376         }
1377         s := new(SliceHeader)
1378         s.Data = base + uintptr(beg)*typ.Elem().Size()
1379         s.Len = end - beg
1380         s.Cap = cap - beg
1381         return valueFromAddr(iv.flag&flagRO, typ, unsafe.Pointer(s))
1382 }
1383
1384 // String returns the string v's underlying value, as a string.
1385 // String is a special case because of Go's String method convention.
1386 // Unlike the other getters, it does not panic if v's Kind is not String.
1387 // Instead, it returns a string of the form "<T value>" where T is v's type.
1388 func (v Value) String() string {
1389         iv := v.internal()
1390         switch iv.kind {
1391         case Invalid:
1392                 return "<invalid Value>"
1393         case String:
1394                 return *(*string)(iv.addr)
1395         }
1396         return "<" + iv.typ.String() + " Value>"
1397 }
1398
1399 // TryRecv attempts to receive a value from the channel v but will not block.
1400 // It panics if v's Kind is not Chan.
1401 // If the receive cannot finish without blocking, x is the zero Value.
1402 // The boolean ok is true if the value x corresponds to a send
1403 // on the channel, false if it is a zero value received because the channel is closed.
1404 func (v Value) TryRecv() (x Value, ok bool) {
1405         iv := v.internal()
1406         iv.mustBe(Chan)
1407         iv.mustBeExported()
1408         return iv.recv(true)
1409 }
1410
1411 // TrySend attempts to send x on the channel v but will not block.
1412 // It panics if v's Kind is not Chan.
1413 // It returns true if the value was sent, false otherwise.
1414 // As in Go, x's value must be assignable to the channel's element type.
1415 func (v Value) TrySend(x Value) bool {
1416         iv := v.internal()
1417         iv.mustBe(Chan)
1418         iv.mustBeExported()
1419         return iv.send(x, true)
1420 }
1421
1422 // Type returns v's type.
1423 func (v Value) Type() Type {
1424         t := v.internal().typ
1425         if t == nil {
1426                 panic(&ValueError{"reflect.Value.Type", Invalid})
1427         }
1428         return t.toType()
1429 }
1430
1431 // Uint returns v's underlying value, as a uint64.
1432 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1433 func (v Value) Uint() uint64 {
1434         iv := v.internal()
1435         switch iv.kind {
1436         case Uint:
1437                 return uint64(*(*uint)(iv.addr))
1438         case Uint8:
1439                 return uint64(*(*uint8)(iv.addr))
1440         case Uint16:
1441                 return uint64(*(*uint16)(iv.addr))
1442         case Uint32:
1443                 return uint64(*(*uint32)(iv.addr))
1444         case Uintptr:
1445                 return uint64(*(*uintptr)(iv.addr))
1446         case Uint64:
1447                 return *(*uint64)(iv.addr)
1448         }
1449         panic(&ValueError{"reflect.Value.Uint", iv.kind})
1450 }
1451
1452 // UnsafeAddr returns a pointer to v's data.
1453 // It is for advanced clients that also import the "unsafe" package.
1454 // It panics if v is not addressable.
1455 func (v Value) UnsafeAddr() uintptr {
1456         iv := v.internal()
1457         if iv.kind == Invalid {
1458                 panic(&ValueError{"reflect.Value.UnsafeAddr", iv.kind})
1459         }
1460         if iv.flag&flagAddr == 0 {
1461                 panic("reflect.Value.UnsafeAddr of unaddressable value")
1462         }
1463         return uintptr(iv.addr)
1464 }
1465
1466 // StringHeader is the runtime representation of a string.
1467 // It cannot be used safely or portably.
1468 type StringHeader struct {
1469         Data uintptr
1470         Len  int
1471 }
1472
1473 // SliceHeader is the runtime representation of a slice.
1474 // It cannot be used safely or portably.
1475 type SliceHeader struct {
1476         Data uintptr
1477         Len  int
1478         Cap  int
1479 }
1480
1481 func typesMustMatch(what string, t1, t2 Type) {
1482         if t1 != t2 {
1483                 panic("reflect: " + what + ": " + t1.String() + " != " + t2.String())
1484         }
1485 }
1486
1487 // grow grows the slice s so that it can hold extra more values, allocating
1488 // more capacity if needed. It also returns the old and new slice lengths.
1489 func grow(s Value, extra int) (Value, int, int) {
1490         i0 := s.Len()
1491         i1 := i0 + extra
1492         if i1 < i0 {
1493                 panic("reflect.Append: slice overflow")
1494         }
1495         m := s.Cap()
1496         if i1 <= m {
1497                 return s.Slice(0, i1), i0, i1
1498         }
1499         if m == 0 {
1500                 m = extra
1501         } else {
1502                 for m < i1 {
1503                         if i0 < 1024 {
1504                                 m += m
1505                         } else {
1506                                 m += m / 4
1507                         }
1508                 }
1509         }
1510         t := MakeSlice(s.Type(), i1, m)
1511         Copy(t, s)
1512         return t, i0, i1
1513 }
1514
1515 // Append appends the values x to a slice s and returns the resulting slice.
1516 // As in Go, each x's value must be assignable to the slice's element type.
1517 func Append(s Value, x ...Value) Value {
1518         s.internal().mustBe(Slice)
1519         s, i0, i1 := grow(s, len(x))
1520         for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
1521                 s.Index(i).Set(x[j])
1522         }
1523         return s
1524 }
1525
1526 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1527 // The slices s and t must have the same element type.
1528 func AppendSlice(s, t Value) Value {
1529         s.internal().mustBe(Slice)
1530         t.internal().mustBe(Slice)
1531         typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
1532         s, i0, i1 := grow(s, t.Len())
1533         Copy(s.Slice(i0, i1), t)
1534         return s
1535 }
1536
1537 // Copy copies the contents of src into dst until either
1538 // dst has been filled or src has been exhausted.
1539 // It returns the number of elements copied.
1540 // Dst and src each must have kind Slice or Array, and
1541 // dst and src must have the same element type.
1542 func Copy(dst, src Value) int {
1543         idst := dst.internal()
1544         isrc := src.internal()
1545
1546         if idst.kind != Array && idst.kind != Slice {
1547                 panic(&ValueError{"reflect.Copy", idst.kind})
1548         }
1549         if idst.kind == Array {
1550                 idst.mustBeAssignable()
1551         }
1552         idst.mustBeExported()
1553         if isrc.kind != Array && isrc.kind != Slice {
1554                 panic(&ValueError{"reflect.Copy", isrc.kind})
1555         }
1556         isrc.mustBeExported()
1557
1558         de := idst.typ.Elem()
1559         se := isrc.typ.Elem()
1560         typesMustMatch("reflect.Copy", de, se)
1561
1562         n := dst.Len()
1563         if sn := src.Len(); n > sn {
1564                 n = sn
1565         }
1566
1567         // If sk is an in-line array, cannot take its address.
1568         // Instead, copy element by element.
1569         if isrc.addr == nil {
1570                 for i := 0; i < n; i++ {
1571                         dst.Index(i).Set(src.Index(i))
1572                 }
1573                 return n
1574         }
1575
1576         // Copy via memmove.
1577         var da, sa unsafe.Pointer
1578         if idst.kind == Array {
1579                 da = idst.addr
1580         } else {
1581                 da = unsafe.Pointer((*SliceHeader)(idst.addr).Data)
1582         }
1583         if isrc.kind == Array {
1584                 sa = isrc.addr
1585         } else {
1586                 sa = unsafe.Pointer((*SliceHeader)(isrc.addr).Data)
1587         }
1588         memmove(da, sa, uintptr(n)*de.Size())
1589         return n
1590 }
1591
1592 /*
1593  * constructors
1594  */
1595
1596 // MakeSlice creates a new zero-initialized slice value
1597 // for the specified slice type, length, and capacity.
1598 func MakeSlice(typ Type, len, cap int) Value {
1599         if typ.Kind() != Slice {
1600                 panic("reflect: MakeSlice of non-slice type")
1601         }
1602         s := &SliceHeader{
1603                 Data: uintptr(unsafe.NewArray(typ.Elem(), cap)),
1604                 Len:  len,
1605                 Cap:  cap,
1606         }
1607         return valueFromAddr(0, typ, unsafe.Pointer(s))
1608 }
1609
1610 // MakeChan creates a new channel with the specified type and buffer size.
1611 func MakeChan(typ Type, buffer int) Value {
1612         if typ.Kind() != Chan {
1613                 panic("reflect: MakeChan of non-chan type")
1614         }
1615         if buffer < 0 {
1616                 panic("MakeChan: negative buffer size")
1617         }
1618         if typ.ChanDir() != BothDir {
1619                 panic("MakeChan: unidirectional channel type")
1620         }
1621         ch := makechan(typ.runtimeType(), uint32(buffer))
1622         return valueFromIword(0, typ, ch)
1623 }
1624
1625 // MakeMap creates a new map of the specified type.
1626 func MakeMap(typ Type) Value {
1627         if typ.Kind() != Map {
1628                 panic("reflect: MakeMap of non-map type")
1629         }
1630         m := makemap(typ.runtimeType())
1631         return valueFromIword(0, typ, m)
1632 }
1633
1634 // Indirect returns the value that v points to.
1635 // If v is a nil pointer, Indirect returns a nil Value.
1636 // If v is not a pointer, Indirect returns v.
1637 func Indirect(v Value) Value {
1638         if v.Kind() != Ptr {
1639                 return v
1640         }
1641         return v.Elem()
1642 }
1643
1644 // ValueOf returns a new Value initialized to the concrete value
1645 // stored in the interface i.  ValueOf(nil) returns the zero Value.
1646 func ValueOf(i interface{}) Value {
1647         if i == nil {
1648                 return Value{}
1649         }
1650         // For an interface value with the noAddr bit set,
1651         // the representation is identical to an empty interface.
1652         eface := *(*emptyInterface)(unsafe.Pointer(&i))
1653         return packValue(0, eface.typ, eface.word)
1654 }
1655
1656 // Zero returns a Value representing a zero value for the specified type.
1657 // The result is different from the zero value of the Value struct,
1658 // which represents no value at all.
1659 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
1660 func Zero(typ Type) Value {
1661         if typ == nil {
1662                 panic("reflect: Zero(nil)")
1663         }
1664         if typ.Kind() == Ptr || typ.Kind() == UnsafePointer {
1665                 return valueFromIword(0, typ, 0)
1666         }
1667         return valueFromAddr(0, typ, unsafe.New(typ))
1668 }
1669
1670 // New returns a Value representing a pointer to a new zero value
1671 // for the specified type.  That is, the returned Value's Type is PtrTo(t).
1672 func New(typ Type) Value {
1673         if typ == nil {
1674                 panic("reflect: New(nil)")
1675         }
1676         ptr := unsafe.New(typ)
1677         return valueFromIword(0, PtrTo(typ), iword(uintptr(ptr)))
1678 }
1679
1680 // convertForAssignment 
1681 func convertForAssignment(what string, addr unsafe.Pointer, dst Type, iv internalValue) internalValue {
1682         if iv.method {
1683                 panic(what + ": cannot assign method value to type " + dst.String())
1684         }
1685
1686         dst1 := dst.(*commonType)
1687         if directlyAssignable(dst1, iv.typ) {
1688                 // Overwrite type so that they match.
1689                 // Same memory layout, so no harm done.
1690                 iv.typ = dst1
1691                 return iv
1692         }
1693         if implements(dst1, iv.typ) {
1694                 if addr == nil {
1695                         addr = unsafe.Pointer(new(interface{}))
1696                 }
1697                 x := iv.valueInterface(false)
1698                 if dst.NumMethod() == 0 {
1699                         *(*interface{})(addr) = x
1700                 } else {
1701                         ifaceE2I(dst1.runtimeType(), x, addr)
1702                 }
1703                 iv.addr = addr
1704                 iv.word = iword(uintptr(addr))
1705                 iv.typ = dst1
1706                 return iv
1707         }
1708
1709         // Failed.
1710         panic(what + ": value of type " + iv.typ.String() + " is not assignable to type " + dst.String())
1711 }
1712
1713 // implemented in ../pkg/runtime
1714 func chancap(ch iword) int32
1715 func chanclose(ch iword)
1716 func chanlen(ch iword) int32
1717 func chanrecv(t *runtime.Type, ch iword, nb bool) (val iword, selected, received bool)
1718 func chansend(t *runtime.Type, ch iword, val iword, nb bool) bool
1719
1720 func makechan(typ *runtime.Type, size uint32) (ch iword)
1721 func makemap(t *runtime.Type) iword
1722 func mapaccess(t *runtime.Type, m iword, key iword) (val iword, ok bool)
1723 func mapassign(t *runtime.Type, m iword, key, val iword, ok bool)
1724 func mapiterinit(t *runtime.Type, m iword) *byte
1725 func mapiterkey(it *byte) (key iword, ok bool)
1726 func mapiternext(it *byte)
1727 func maplen(m iword) int32
1728
1729 func call(typ *commonType, fnaddr unsafe.Pointer, isInterface bool, isMethod bool, params *unsafe.Pointer, results *unsafe.Pointer)
1730 func ifaceE2I(t *runtime.Type, src interface{}, dst unsafe.Pointer)