OSDN Git Service

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