src/pkg/reflect/value.go - The Go Programming Language

Golang

Source file src/pkg/reflect/value.go

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