Black Lives Matter. Support the Equal Justice Initiative.

Source file src/reflect/value.go

Documentation: reflect

     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  	"internal/unsafeheader"
     9  	"math"
    10  	"runtime"
    11  	"unsafe"
    12  )
    13  
    14  const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const
    15  
    16  // Value is the reflection interface to a Go value.
    17  //
    18  // Not all methods apply to all kinds of values. Restrictions,
    19  // if any, are noted in the documentation for each method.
    20  // Use the Kind method to find out the kind of value before
    21  // calling kind-specific methods. Calling a method
    22  // inappropriate to the kind of type causes a run time panic.
    23  //
    24  // The zero Value represents no value.
    25  // Its IsValid method returns false, its Kind method returns Invalid,
    26  // its String method returns "<invalid Value>", and all other methods panic.
    27  // Most functions and methods never return an invalid value.
    28  // If one does, its documentation states the conditions explicitly.
    29  //
    30  // A Value can be used concurrently by multiple goroutines provided that
    31  // the underlying Go value can be used concurrently for the equivalent
    32  // direct operations.
    33  //
    34  // To compare two Values, compare the results of the Interface method.
    35  // Using == on two Values does not compare the underlying values
    36  // they represent.
    37  type Value struct {
    38  	// typ holds the type of the value represented by a Value.
    39  	typ *rtype
    40  
    41  	// Pointer-valued data or, if flagIndir is set, pointer to data.
    42  	// Valid when either flagIndir is set or typ.pointers() is true.
    43  	ptr unsafe.Pointer
    44  
    45  	// flag holds metadata about the value.
    46  	// The lowest bits are flag bits:
    47  	//	- flagStickyRO: obtained via unexported not embedded field, so read-only
    48  	//	- flagEmbedRO: obtained via unexported embedded field, so read-only
    49  	//	- flagIndir: val holds a pointer to the data
    50  	//	- flagAddr: v.CanAddr is true (implies flagIndir)
    51  	//	- flagMethod: v is a method value.
    52  	// The next five bits give the Kind of the value.
    53  	// This repeats typ.Kind() except for method values.
    54  	// The remaining 23+ bits give a method number for method values.
    55  	// If flag.kind() != Func, code can assume that flagMethod is unset.
    56  	// If ifaceIndir(typ), code can assume that flagIndir is set.
    57  	flag
    58  
    59  	// A method value represents a curried method invocation
    60  	// like r.Read for some receiver r. The typ+val+flag bits describe
    61  	// the receiver r, but the flag's Kind bits say Func (methods are
    62  	// functions), and the top bits of the flag give the method number
    63  	// in r's type's method table.
    64  }
    65  
    66  type flag uintptr
    67  
    68  const (
    69  	flagKindWidth        = 5 // there are 27 kinds
    70  	flagKindMask    flag = 1<<flagKindWidth - 1
    71  	flagStickyRO    flag = 1 << 5
    72  	flagEmbedRO     flag = 1 << 6
    73  	flagIndir       flag = 1 << 7
    74  	flagAddr        flag = 1 << 8
    75  	flagMethod      flag = 1 << 9
    76  	flagMethodShift      = 10
    77  	flagRO          flag = flagStickyRO | flagEmbedRO
    78  )
    79  
    80  func (f flag) kind() Kind {
    81  	return Kind(f & flagKindMask)
    82  }
    83  
    84  func (f flag) ro() flag {
    85  	if f&flagRO != 0 {
    86  		return flagStickyRO
    87  	}
    88  	return 0
    89  }
    90  
    91  // pointer returns the underlying pointer represented by v.
    92  // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
    93  func (v Value) pointer() unsafe.Pointer {
    94  	if v.typ.size != ptrSize || !v.typ.pointers() {
    95  		panic("can't call pointer on a non-pointer Value")
    96  	}
    97  	if v.flag&flagIndir != 0 {
    98  		return *(*unsafe.Pointer)(v.ptr)
    99  	}
   100  	return v.ptr
   101  }
   102  
   103  // packEface converts v to the empty interface.
   104  func packEface(v Value) interface{} {
   105  	t := v.typ
   106  	var i interface{}
   107  	e := (*emptyInterface)(unsafe.Pointer(&i))
   108  	// First, fill in the data portion of the interface.
   109  	switch {
   110  	case ifaceIndir(t):
   111  		if v.flag&flagIndir == 0 {
   112  			panic("bad indir")
   113  		}
   114  		// Value is indirect, and so is the interface we're making.
   115  		ptr := v.ptr
   116  		if v.flag&flagAddr != 0 {
   117  			// TODO: pass safe boolean from valueInterface so
   118  			// we don't need to copy if safe==true?
   119  			c := unsafe_New(t)
   120  			typedmemmove(t, c, ptr)
   121  			ptr = c
   122  		}
   123  		e.word = ptr
   124  	case v.flag&flagIndir != 0:
   125  		// Value is indirect, but interface is direct. We need
   126  		// to load the data at v.ptr into the interface data word.
   127  		e.word = *(*unsafe.Pointer)(v.ptr)
   128  	default:
   129  		// Value is direct, and so is the interface.
   130  		e.word = v.ptr
   131  	}
   132  	// Now, fill in the type portion. We're very careful here not
   133  	// to have any operation between the e.word and e.typ assignments
   134  	// that would let the garbage collector observe the partially-built
   135  	// interface value.
   136  	e.typ = t
   137  	return i
   138  }
   139  
   140  // unpackEface converts the empty interface i to a Value.
   141  func unpackEface(i interface{}) Value {
   142  	e := (*emptyInterface)(unsafe.Pointer(&i))
   143  	// NOTE: don't read e.word until we know whether it is really a pointer or not.
   144  	t := e.typ
   145  	if t == nil {
   146  		return Value{}
   147  	}
   148  	f := flag(t.Kind())
   149  	if ifaceIndir(t) {
   150  		f |= flagIndir
   151  	}
   152  	return Value{t, e.word, f}
   153  }
   154  
   155  // A ValueError occurs when a Value method is invoked on
   156  // a Value that does not support it. Such cases are documented
   157  // in the description of each method.
   158  type ValueError struct {
   159  	Method string
   160  	Kind   Kind
   161  }
   162  
   163  func (e *ValueError) Error() string {
   164  	if e.Kind == 0 {
   165  		return "reflect: call of " + e.Method + " on zero Value"
   166  	}
   167  	return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
   168  }
   169  
   170  // methodName returns the name of the calling method,
   171  // assumed to be two stack frames above.
   172  func methodName() string {
   173  	pc, _, _, _ := runtime.Caller(2)
   174  	f := runtime.FuncForPC(pc)
   175  	if f == nil {
   176  		return "unknown method"
   177  	}
   178  	return f.Name()
   179  }
   180  
   181  // methodNameSkip is like methodName, but skips another stack frame.
   182  // This is a separate function so that reflect.flag.mustBe will be inlined.
   183  func methodNameSkip() string {
   184  	pc, _, _, _ := runtime.Caller(3)
   185  	f := runtime.FuncForPC(pc)
   186  	if f == nil {
   187  		return "unknown method"
   188  	}
   189  	return f.Name()
   190  }
   191  
   192  // emptyInterface is the header for an interface{} value.
   193  type emptyInterface struct {
   194  	typ  *rtype
   195  	word unsafe.Pointer
   196  }
   197  
   198  // nonEmptyInterface is the header for an interface value with methods.
   199  type nonEmptyInterface struct {
   200  	// see ../runtime/iface.go:/Itab
   201  	itab *struct {
   202  		ityp *rtype // static interface type
   203  		typ  *rtype // dynamic concrete type
   204  		hash uint32 // copy of typ.hash
   205  		_    [4]byte
   206  		fun  [100000]unsafe.Pointer // method table
   207  	}
   208  	word unsafe.Pointer
   209  }
   210  
   211  // mustBe panics if f's kind is not expected.
   212  // Making this a method on flag instead of on Value
   213  // (and embedding flag in Value) means that we can write
   214  // the very clear v.mustBe(Bool) and have it compile into
   215  // v.flag.mustBe(Bool), which will only bother to copy the
   216  // single important word for the receiver.
   217  func (f flag) mustBe(expected Kind) {
   218  	// TODO(mvdan): use f.kind() again once mid-stack inlining gets better
   219  	if Kind(f&flagKindMask) != expected {
   220  		panic(&ValueError{methodName(), f.kind()})
   221  	}
   222  }
   223  
   224  // mustBeExported panics if f records that the value was obtained using
   225  // an unexported field.
   226  func (f flag) mustBeExported() {
   227  	if f == 0 || f&flagRO != 0 {
   228  		f.mustBeExportedSlow()
   229  	}
   230  }
   231  
   232  func (f flag) mustBeExportedSlow() {
   233  	if f == 0 {
   234  		panic(&ValueError{methodNameSkip(), Invalid})
   235  	}
   236  	if f&flagRO != 0 {
   237  		panic("reflect: " + methodNameSkip() + " using value obtained using unexported field")
   238  	}
   239  }
   240  
   241  // mustBeAssignable panics if f records that the value is not assignable,
   242  // which is to say that either it was obtained using an unexported field
   243  // or it is not addressable.
   244  func (f flag) mustBeAssignable() {
   245  	if f&flagRO != 0 || f&flagAddr == 0 {
   246  		f.mustBeAssignableSlow()
   247  	}
   248  }
   249  
   250  func (f flag) mustBeAssignableSlow() {
   251  	if f == 0 {
   252  		panic(&ValueError{methodNameSkip(), Invalid})
   253  	}
   254  	// Assignable if addressable and not read-only.
   255  	if f&flagRO != 0 {
   256  		panic("reflect: " + methodNameSkip() + " using value obtained using unexported field")
   257  	}
   258  	if f&flagAddr == 0 {
   259  		panic("reflect: " + methodNameSkip() + " using unaddressable value")
   260  	}
   261  }
   262  
   263  // Addr returns a pointer value representing the address of v.
   264  // It panics if CanAddr() returns false.
   265  // Addr is typically used to obtain a pointer to a struct field
   266  // or slice element in order to call a method that requires a
   267  // pointer receiver.
   268  func (v Value) Addr() Value {
   269  	if v.flag&flagAddr == 0 {
   270  		panic("reflect.Value.Addr of unaddressable value")
   271  	}
   272  	// Preserve flagRO instead of using v.flag.ro() so that
   273  	// v.Addr().Elem() is equivalent to v (#32772)
   274  	fl := v.flag & flagRO
   275  	return Value{v.typ.ptrTo(), v.ptr, fl | flag(Ptr)}
   276  }
   277  
   278  // Bool returns v's underlying value.
   279  // It panics if v's kind is not Bool.
   280  func (v Value) Bool() bool {
   281  	v.mustBe(Bool)
   282  	return *(*bool)(v.ptr)
   283  }
   284  
   285  // Bytes returns v's underlying value.
   286  // It panics if v's underlying value is not a slice of bytes.
   287  func (v Value) Bytes() []byte {
   288  	v.mustBe(Slice)
   289  	if v.typ.Elem().Kind() != Uint8 {
   290  		panic("reflect.Value.Bytes of non-byte slice")
   291  	}
   292  	// Slice is always bigger than a word; assume flagIndir.
   293  	return *(*[]byte)(v.ptr)
   294  }
   295  
   296  // runes returns v's underlying value.
   297  // It panics if v's underlying value is not a slice of runes (int32s).
   298  func (v Value) runes() []rune {
   299  	v.mustBe(Slice)
   300  	if v.typ.Elem().Kind() != Int32 {
   301  		panic("reflect.Value.Bytes of non-rune slice")
   302  	}
   303  	// Slice is always bigger than a word; assume flagIndir.
   304  	return *(*[]rune)(v.ptr)
   305  }
   306  
   307  // CanAddr reports whether the value's address can be obtained with Addr.
   308  // Such values are called addressable. A value is addressable if it is
   309  // an element of a slice, an element of an addressable array,
   310  // a field of an addressable struct, or the result of dereferencing a pointer.
   311  // If CanAddr returns false, calling Addr will panic.
   312  func (v Value) CanAddr() bool {
   313  	return v.flag&flagAddr != 0
   314  }
   315  
   316  // CanSet reports whether the value of v can be changed.
   317  // A Value can be changed only if it is addressable and was not
   318  // obtained by the use of unexported struct fields.
   319  // If CanSet returns false, calling Set or any type-specific
   320  // setter (e.g., SetBool, SetInt) will panic.
   321  func (v Value) CanSet() bool {
   322  	return v.flag&(flagAddr|flagRO) == flagAddr
   323  }
   324  
   325  // Call calls the function v with the input arguments in.
   326  // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
   327  // Call panics if v's Kind is not Func.
   328  // It returns the output results as Values.
   329  // As in Go, each input argument must be assignable to the
   330  // type of the function's corresponding input parameter.
   331  // If v is a variadic function, Call creates the variadic slice parameter
   332  // itself, copying in the corresponding values.
   333  func (v Value) Call(in []Value) []Value {
   334  	v.mustBe(Func)
   335  	v.mustBeExported()
   336  	return v.call("Call", in)
   337  }
   338  
   339  // CallSlice calls the variadic function v with the input arguments in,
   340  // assigning the slice in[len(in)-1] to v's final variadic argument.
   341  // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
   342  // CallSlice panics if v's Kind is not Func or if v is not variadic.
   343  // It returns the output results as Values.
   344  // As in Go, each input argument must be assignable to the
   345  // type of the function's corresponding input parameter.
   346  func (v Value) CallSlice(in []Value) []Value {
   347  	v.mustBe(Func)
   348  	v.mustBeExported()
   349  	return v.call("CallSlice", in)
   350  }
   351  
   352  var callGC bool // for testing; see TestCallMethodJump
   353  
   354  func (v Value) call(op string, in []Value) []Value {
   355  	// Get function pointer, type.
   356  	t := (*funcType)(unsafe.Pointer(v.typ))
   357  	var (
   358  		fn       unsafe.Pointer
   359  		rcvr     Value
   360  		rcvrtype *rtype
   361  	)
   362  	if v.flag&flagMethod != 0 {
   363  		rcvr = v
   364  		rcvrtype, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
   365  	} else if v.flag&flagIndir != 0 {
   366  		fn = *(*unsafe.Pointer)(v.ptr)
   367  	} else {
   368  		fn = v.ptr
   369  	}
   370  
   371  	if fn == nil {
   372  		panic("reflect.Value.Call: call of nil function")
   373  	}
   374  
   375  	isSlice := op == "CallSlice"
   376  	n := t.NumIn()
   377  	if isSlice {
   378  		if !t.IsVariadic() {
   379  			panic("reflect: CallSlice of non-variadic function")
   380  		}
   381  		if len(in) < n {
   382  			panic("reflect: CallSlice with too few input arguments")
   383  		}
   384  		if len(in) > n {
   385  			panic("reflect: CallSlice with too many input arguments")
   386  		}
   387  	} else {
   388  		if t.IsVariadic() {
   389  			n--
   390  		}
   391  		if len(in) < n {
   392  			panic("reflect: Call with too few input arguments")
   393  		}
   394  		if !t.IsVariadic() && len(in) > n {
   395  			panic("reflect: Call with too many input arguments")
   396  		}
   397  	}
   398  	for _, x := range in {
   399  		if x.Kind() == Invalid {
   400  			panic("reflect: " + op + " using zero Value argument")
   401  		}
   402  	}
   403  	for i := 0; i < n; i++ {
   404  		if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
   405  			panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
   406  		}
   407  	}
   408  	if !isSlice && t.IsVariadic() {
   409  		// prepare slice for remaining values
   410  		m := len(in) - n
   411  		slice := MakeSlice(t.In(n), m, m)
   412  		elem := t.In(n).Elem()
   413  		for i := 0; i < m; i++ {
   414  			x := in[n+i]
   415  			if xt := x.Type(); !xt.AssignableTo(elem) {
   416  				panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
   417  			}
   418  			slice.Index(i).Set(x)
   419  		}
   420  		origIn := in
   421  		in = make([]Value, n+1)
   422  		copy(in[:n], origIn)
   423  		in[n] = slice
   424  	}
   425  
   426  	nin := len(in)
   427  	if nin != t.NumIn() {
   428  		panic("reflect.Value.Call: wrong argument count")
   429  	}
   430  	nout := t.NumOut()
   431  
   432  	// Compute frame type.
   433  	frametype, _, retOffset, _, framePool := funcLayout(t, rcvrtype)
   434  
   435  	// Allocate a chunk of memory for frame.
   436  	var args unsafe.Pointer
   437  	if nout == 0 {
   438  		args = framePool.Get().(unsafe.Pointer)
   439  	} else {
   440  		// Can't use pool if the function has return values.
   441  		// We will leak pointer to args in ret, so its lifetime is not scoped.
   442  		args = unsafe_New(frametype)
   443  	}
   444  	off := uintptr(0)
   445  
   446  	// Copy inputs into args.
   447  	if rcvrtype != nil {
   448  		storeRcvr(rcvr, args)
   449  		off = ptrSize
   450  	}
   451  	for i, v := range in {
   452  		v.mustBeExported()
   453  		targ := t.In(i).(*rtype)
   454  		a := uintptr(targ.align)
   455  		off = (off + a - 1) &^ (a - 1)
   456  		n := targ.size
   457  		if n == 0 {
   458  			// Not safe to compute args+off pointing at 0 bytes,
   459  			// because that might point beyond the end of the frame,
   460  			// but we still need to call assignTo to check assignability.
   461  			v.assignTo("reflect.Value.Call", targ, nil)
   462  			continue
   463  		}
   464  		addr := add(args, off, "n > 0")
   465  		v = v.assignTo("reflect.Value.Call", targ, addr)
   466  		if v.flag&flagIndir != 0 {
   467  			typedmemmove(targ, addr, v.ptr)
   468  		} else {
   469  			*(*unsafe.Pointer)(addr) = v.ptr
   470  		}
   471  		off += n
   472  	}
   473  
   474  	// Call.
   475  	call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
   476  
   477  	// For testing; see TestCallMethodJump.
   478  	if callGC {
   479  		runtime.GC()
   480  	}
   481  
   482  	var ret []Value
   483  	if nout == 0 {
   484  		typedmemclr(frametype, args)
   485  		framePool.Put(args)
   486  	} else {
   487  		// Zero the now unused input area of args,
   488  		// because the Values returned by this function contain pointers to the args object,
   489  		// and will thus keep the args object alive indefinitely.
   490  		typedmemclrpartial(frametype, args, 0, retOffset)
   491  
   492  		// Wrap Values around return values in args.
   493  		ret = make([]Value, nout)
   494  		off = retOffset
   495  		for i := 0; i < nout; i++ {
   496  			tv := t.Out(i)
   497  			a := uintptr(tv.Align())
   498  			off = (off + a - 1) &^ (a - 1)
   499  			if tv.Size() != 0 {
   500  				fl := flagIndir | flag(tv.Kind())
   501  				ret[i] = Value{tv.common(), add(args, off, "tv.Size() != 0"), fl}
   502  				// Note: this does introduce false sharing between results -
   503  				// if any result is live, they are all live.
   504  				// (And the space for the args is live as well, but as we've
   505  				// cleared that space it isn't as big a deal.)
   506  			} else {
   507  				// For zero-sized return value, args+off may point to the next object.
   508  				// In this case, return the zero value instead.
   509  				ret[i] = Zero(tv)
   510  			}
   511  			off += tv.Size()
   512  		}
   513  	}
   514  
   515  	return ret
   516  }
   517  
   518  // callReflect is the call implementation used by a function
   519  // returned by MakeFunc. In many ways it is the opposite of the
   520  // method Value.call above. The method above converts a call using Values
   521  // into a call of a function with a concrete argument frame, while
   522  // callReflect converts a call of a function with a concrete argument
   523  // frame into a call using Values.
   524  // It is in this file so that it can be next to the call method above.
   525  // The remainder of the MakeFunc implementation is in makefunc.go.
   526  //
   527  // NOTE: This function must be marked as a "wrapper" in the generated code,
   528  // so that the linker can make it work correctly for panic and recover.
   529  // The gc compilers know to do that for the name "reflect.callReflect".
   530  //
   531  // ctxt is the "closure" generated by MakeFunc.
   532  // frame is a pointer to the arguments to that closure on the stack.
   533  // retValid points to a boolean which should be set when the results
   534  // section of frame is set.
   535  func callReflect(ctxt *makeFuncImpl, frame unsafe.Pointer, retValid *bool) {
   536  	ftyp := ctxt.ftyp
   537  	f := ctxt.fn
   538  
   539  	// Copy argument frame into Values.
   540  	ptr := frame
   541  	off := uintptr(0)
   542  	in := make([]Value, 0, int(ftyp.inCount))
   543  	for _, typ := range ftyp.in() {
   544  		off += -off & uintptr(typ.align-1)
   545  		v := Value{typ, nil, flag(typ.Kind())}
   546  		if ifaceIndir(typ) {
   547  			// value cannot be inlined in interface data.
   548  			// Must make a copy, because f might keep a reference to it,
   549  			// and we cannot let f keep a reference to the stack frame
   550  			// after this function returns, not even a read-only reference.
   551  			v.ptr = unsafe_New(typ)
   552  			if typ.size > 0 {
   553  				typedmemmove(typ, v.ptr, add(ptr, off, "typ.size > 0"))
   554  			}
   555  			v.flag |= flagIndir
   556  		} else {
   557  			v.ptr = *(*unsafe.Pointer)(add(ptr, off, "1-ptr"))
   558  		}
   559  		in = append(in, v)
   560  		off += typ.size
   561  	}
   562  
   563  	// Call underlying function.
   564  	out := f(in)
   565  	numOut := ftyp.NumOut()
   566  	if len(out) != numOut {
   567  		panic("reflect: wrong return count from function created by MakeFunc")
   568  	}
   569  
   570  	// Copy results back into argument frame.
   571  	if numOut > 0 {
   572  		off += -off & (ptrSize - 1)
   573  		for i, typ := range ftyp.out() {
   574  			v := out[i]
   575  			if v.typ == nil {
   576  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   577  					" returned zero Value")
   578  			}
   579  			if v.flag&flagRO != 0 {
   580  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   581  					" returned value obtained from unexported field")
   582  			}
   583  			off += -off & uintptr(typ.align-1)
   584  			if typ.size == 0 {
   585  				continue
   586  			}
   587  			addr := add(ptr, off, "typ.size > 0")
   588  
   589  			// Convert v to type typ if v is assignable to a variable
   590  			// of type t in the language spec.
   591  			// See issue 28761.
   592  			if typ.Kind() == Interface {
   593  				// We must clear the destination before calling assignTo,
   594  				// in case assignTo writes (with memory barriers) to the
   595  				// target location used as scratch space. See issue 39541.
   596  				*(*uintptr)(addr) = 0
   597  				*(*uintptr)(add(addr, ptrSize, "typ.size == 2*ptrSize")) = 0
   598  			}
   599  			v = v.assignTo("reflect.MakeFunc", typ, addr)
   600  
   601  			// We are writing to stack. No write barrier.
   602  			if v.flag&flagIndir != 0 {
   603  				memmove(addr, v.ptr, typ.size)
   604  			} else {
   605  				*(*uintptr)(addr) = uintptr(v.ptr)
   606  			}
   607  			off += typ.size
   608  		}
   609  	}
   610  
   611  	// Announce that the return values are valid.
   612  	// After this point the runtime can depend on the return values being valid.
   613  	*retValid = true
   614  
   615  	// We have to make sure that the out slice lives at least until
   616  	// the runtime knows the return values are valid. Otherwise, the
   617  	// return values might not be scanned by anyone during a GC.
   618  	// (out would be dead, and the return slots not yet alive.)
   619  	runtime.KeepAlive(out)
   620  
   621  	// runtime.getArgInfo expects to be able to find ctxt on the
   622  	// stack when it finds our caller, makeFuncStub. Make sure it
   623  	// doesn't get garbage collected.
   624  	runtime.KeepAlive(ctxt)
   625  }
   626  
   627  // methodReceiver returns information about the receiver
   628  // described by v. The Value v may or may not have the
   629  // flagMethod bit set, so the kind cached in v.flag should
   630  // not be used.
   631  // The return value rcvrtype gives the method's actual receiver type.
   632  // The return value t gives the method type signature (without the receiver).
   633  // The return value fn is a pointer to the method code.
   634  func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *rtype, t *funcType, fn unsafe.Pointer) {
   635  	i := methodIndex
   636  	if v.typ.Kind() == Interface {
   637  		tt := (*interfaceType)(unsafe.Pointer(v.typ))
   638  		if uint(i) >= uint(len(tt.methods)) {
   639  			panic("reflect: internal error: invalid method index")
   640  		}
   641  		m := &tt.methods[i]
   642  		if !tt.nameOff(m.name).isExported() {
   643  			panic("reflect: " + op + " of unexported method")
   644  		}
   645  		iface := (*nonEmptyInterface)(v.ptr)
   646  		if iface.itab == nil {
   647  			panic("reflect: " + op + " of method on nil interface value")
   648  		}
   649  		rcvrtype = iface.itab.typ
   650  		fn = unsafe.Pointer(&iface.itab.fun[i])
   651  		t = (*funcType)(unsafe.Pointer(tt.typeOff(m.typ)))
   652  	} else {
   653  		rcvrtype = v.typ
   654  		ms := v.typ.exportedMethods()
   655  		if uint(i) >= uint(len(ms)) {
   656  			panic("reflect: internal error: invalid method index")
   657  		}
   658  		m := ms[i]
   659  		if !v.typ.nameOff(m.name).isExported() {
   660  			panic("reflect: " + op + " of unexported method")
   661  		}
   662  		ifn := v.typ.textOff(m.ifn)
   663  		fn = unsafe.Pointer(&ifn)
   664  		t = (*funcType)(unsafe.Pointer(v.typ.typeOff(m.mtyp)))
   665  	}
   666  	return
   667  }
   668  
   669  // v is a method receiver. Store at p the word which is used to
   670  // encode that receiver at the start of the argument list.
   671  // Reflect uses the "interface" calling convention for
   672  // methods, which always uses one word to record the receiver.
   673  func storeRcvr(v Value, p unsafe.Pointer) {
   674  	t := v.typ
   675  	if t.Kind() == Interface {
   676  		// the interface data word becomes the receiver word
   677  		iface := (*nonEmptyInterface)(v.ptr)
   678  		*(*unsafe.Pointer)(p) = iface.word
   679  	} else if v.flag&flagIndir != 0 && !ifaceIndir(t) {
   680  		*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
   681  	} else {
   682  		*(*unsafe.Pointer)(p) = v.ptr
   683  	}
   684  }
   685  
   686  // align returns the result of rounding x up to a multiple of n.
   687  // n must be a power of two.
   688  func align(x, n uintptr) uintptr {
   689  	return (x + n - 1) &^ (n - 1)
   690  }
   691  
   692  // callMethod is the call implementation used by a function returned
   693  // by makeMethodValue (used by v.Method(i).Interface()).
   694  // It is a streamlined version of the usual reflect call: the caller has
   695  // already laid out the argument frame for us, so we don't have
   696  // to deal with individual Values for each argument.
   697  // It is in this file so that it can be next to the two similar functions above.
   698  // The remainder of the makeMethodValue implementation is in makefunc.go.
   699  //
   700  // NOTE: This function must be marked as a "wrapper" in the generated code,
   701  // so that the linker can make it work correctly for panic and recover.
   702  // The gc compilers know to do that for the name "reflect.callMethod".
   703  //
   704  // ctxt is the "closure" generated by makeVethodValue.
   705  // frame is a pointer to the arguments to that closure on the stack.
   706  // retValid points to a boolean which should be set when the results
   707  // section of frame is set.
   708  func callMethod(ctxt *methodValue, frame unsafe.Pointer, retValid *bool) {
   709  	rcvr := ctxt.rcvr
   710  	rcvrtype, t, fn := methodReceiver("call", rcvr, ctxt.method)
   711  	frametype, argSize, retOffset, _, framePool := funcLayout(t, rcvrtype)
   712  
   713  	// Make a new frame that is one word bigger so we can store the receiver.
   714  	// This space is used for both arguments and return values.
   715  	scratch := framePool.Get().(unsafe.Pointer)
   716  
   717  	// Copy in receiver and rest of args.
   718  	storeRcvr(rcvr, scratch)
   719  	// Align the first arg. The alignment can't be larger than ptrSize.
   720  	argOffset := uintptr(ptrSize)
   721  	if len(t.in()) > 0 {
   722  		argOffset = align(argOffset, uintptr(t.in()[0].align))
   723  	}
   724  	// Avoid constructing out-of-bounds pointers if there are no args.
   725  	if argSize-argOffset > 0 {
   726  		typedmemmovepartial(frametype, add(scratch, argOffset, "argSize > argOffset"), frame, argOffset, argSize-argOffset)
   727  	}
   728  
   729  	// Call.
   730  	// Call copies the arguments from scratch to the stack, calls fn,
   731  	// and then copies the results back into scratch.
   732  	call(frametype, fn, scratch, uint32(frametype.size), uint32(retOffset))
   733  
   734  	// Copy return values.
   735  	// Ignore any changes to args and just copy return values.
   736  	// Avoid constructing out-of-bounds pointers if there are no return values.
   737  	if frametype.size-retOffset > 0 {
   738  		callerRetOffset := retOffset - argOffset
   739  		// This copies to the stack. Write barriers are not needed.
   740  		memmove(add(frame, callerRetOffset, "frametype.size > retOffset"),
   741  			add(scratch, retOffset, "frametype.size > retOffset"),
   742  			frametype.size-retOffset)
   743  	}
   744  
   745  	// Tell the runtime it can now depend on the return values
   746  	// being properly initialized.
   747  	*retValid = true
   748  
   749  	// Clear the scratch space and put it back in the pool.
   750  	// This must happen after the statement above, so that the return
   751  	// values will always be scanned by someone.
   752  	typedmemclr(frametype, scratch)
   753  	framePool.Put(scratch)
   754  
   755  	// See the comment in callReflect.
   756  	runtime.KeepAlive(ctxt)
   757  }
   758  
   759  // funcName returns the name of f, for use in error messages.
   760  func funcName(f func([]Value) []Value) string {
   761  	pc := *(*uintptr)(unsafe.Pointer(&f))
   762  	rf := runtime.FuncForPC(pc)
   763  	if rf != nil {
   764  		return rf.Name()
   765  	}
   766  	return "closure"
   767  }
   768  
   769  // Cap returns v's capacity.
   770  // It panics if v's Kind is not Array, Chan, or Slice.
   771  func (v Value) Cap() int {
   772  	k := v.kind()
   773  	switch k {
   774  	case Array:
   775  		return v.typ.Len()
   776  	case Chan:
   777  		return chancap(v.pointer())
   778  	case Slice:
   779  		// Slice is always bigger than a word; assume flagIndir.
   780  		return (*unsafeheader.Slice)(v.ptr).Cap
   781  	}
   782  	panic(&ValueError{"reflect.Value.Cap", v.kind()})
   783  }
   784  
   785  // Close closes the channel v.
   786  // It panics if v's Kind is not Chan.
   787  func (v Value) Close() {
   788  	v.mustBe(Chan)
   789  	v.mustBeExported()
   790  	chanclose(v.pointer())
   791  }
   792  
   793  // Complex returns v's underlying value, as a complex128.
   794  // It panics if v's Kind is not Complex64 or Complex128
   795  func (v Value) Complex() complex128 {
   796  	k := v.kind()
   797  	switch k {
   798  	case Complex64:
   799  		return complex128(*(*complex64)(v.ptr))
   800  	case Complex128:
   801  		return *(*complex128)(v.ptr)
   802  	}
   803  	panic(&ValueError{"reflect.Value.Complex", v.kind()})
   804  }
   805  
   806  // Elem returns the value that the interface v contains
   807  // or that the pointer v points to.
   808  // It panics if v's Kind is not Interface or Ptr.
   809  // It returns the zero Value if v is nil.
   810  func (v Value) Elem() Value {
   811  	k := v.kind()
   812  	switch k {
   813  	case Interface:
   814  		var eface interface{}
   815  		if v.typ.NumMethod() == 0 {
   816  			eface = *(*interface{})(v.ptr)
   817  		} else {
   818  			eface = (interface{})(*(*interface {
   819  				M()
   820  			})(v.ptr))
   821  		}
   822  		x := unpackEface(eface)
   823  		if x.flag != 0 {
   824  			x.flag |= v.flag.ro()
   825  		}
   826  		return x
   827  	case Ptr:
   828  		ptr := v.ptr
   829  		if v.flag&flagIndir != 0 {
   830  			ptr = *(*unsafe.Pointer)(ptr)
   831  		}
   832  		// The returned value's address is v's value.
   833  		if ptr == nil {
   834  			return Value{}
   835  		}
   836  		tt := (*ptrType)(unsafe.Pointer(v.typ))
   837  		typ := tt.elem
   838  		fl := v.flag&flagRO | flagIndir | flagAddr
   839  		fl |= flag(typ.Kind())
   840  		return Value{typ, ptr, fl}
   841  	}
   842  	panic(&ValueError{"reflect.Value.Elem", v.kind()})
   843  }
   844  
   845  // Field returns the i'th field of the struct v.
   846  // It panics if v's Kind is not Struct or i is out of range.
   847  func (v Value) Field(i int) Value {
   848  	if v.kind() != Struct {
   849  		panic(&ValueError{"reflect.Value.Field", v.kind()})
   850  	}
   851  	tt := (*structType)(unsafe.Pointer(v.typ))
   852  	if uint(i) >= uint(len(tt.fields)) {
   853  		panic("reflect: Field index out of range")
   854  	}
   855  	field := &tt.fields[i]
   856  	typ := field.typ
   857  
   858  	// Inherit permission bits from v, but clear flagEmbedRO.
   859  	fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
   860  	// Using an unexported field forces flagRO.
   861  	if !field.name.isExported() {
   862  		if field.embedded() {
   863  			fl |= flagEmbedRO
   864  		} else {
   865  			fl |= flagStickyRO
   866  		}
   867  	}
   868  	// Either flagIndir is set and v.ptr points at struct,
   869  	// or flagIndir is not set and v.ptr is the actual struct data.
   870  	// In the former case, we want v.ptr + offset.
   871  	// In the latter case, we must have field.offset = 0,
   872  	// so v.ptr + field.offset is still the correct address.
   873  	ptr := add(v.ptr, field.offset(), "same as non-reflect &v.field")
   874  	return Value{typ, ptr, fl}
   875  }
   876  
   877  // FieldByIndex returns the nested field corresponding to index.
   878  // It panics if v's Kind is not struct.
   879  func (v Value) FieldByIndex(index []int) Value {
   880  	if len(index) == 1 {
   881  		return v.Field(index[0])
   882  	}
   883  	v.mustBe(Struct)
   884  	for i, x := range index {
   885  		if i > 0 {
   886  			if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
   887  				if v.IsNil() {
   888  					panic("reflect: indirection through nil pointer to embedded struct")
   889  				}
   890  				v = v.Elem()
   891  			}
   892  		}
   893  		v = v.Field(x)
   894  	}
   895  	return v
   896  }
   897  
   898  // FieldByName returns the struct field with the given name.
   899  // It returns the zero Value if no field was found.
   900  // It panics if v's Kind is not struct.
   901  func (v Value) FieldByName(name string) Value {
   902  	v.mustBe(Struct)
   903  	if f, ok := v.typ.FieldByName(name); ok {
   904  		return v.FieldByIndex(f.Index)
   905  	}
   906  	return Value{}
   907  }
   908  
   909  // FieldByNameFunc returns the struct field with a name
   910  // that satisfies the match function.
   911  // It panics if v's Kind is not struct.
   912  // It returns the zero Value if no field was found.
   913  func (v Value) FieldByNameFunc(match func(string) bool) Value {
   914  	if f, ok := v.typ.FieldByNameFunc(match); ok {
   915  		return v.FieldByIndex(f.Index)
   916  	}
   917  	return Value{}
   918  }
   919  
   920  // Float returns v's underlying value, as a float64.
   921  // It panics if v's Kind is not Float32 or Float64
   922  func (v Value) Float() float64 {
   923  	k := v.kind()
   924  	switch k {
   925  	case Float32:
   926  		return float64(*(*float32)(v.ptr))
   927  	case Float64:
   928  		return *(*float64)(v.ptr)
   929  	}
   930  	panic(&ValueError{"reflect.Value.Float", v.kind()})
   931  }
   932  
   933  var uint8Type = TypeOf(uint8(0)).(*rtype)
   934  
   935  // Index returns v's i'th element.
   936  // It panics if v's Kind is not Array, Slice, or String or i is out of range.
   937  func (v Value) Index(i int) Value {
   938  	switch v.kind() {
   939  	case Array:
   940  		tt := (*arrayType)(unsafe.Pointer(v.typ))
   941  		if uint(i) >= uint(tt.len) {
   942  			panic("reflect: array index out of range")
   943  		}
   944  		typ := tt.elem
   945  		offset := uintptr(i) * typ.size
   946  
   947  		// Either flagIndir is set and v.ptr points at array,
   948  		// or flagIndir is not set and v.ptr is the actual array data.
   949  		// In the former case, we want v.ptr + offset.
   950  		// In the latter case, we must be doing Index(0), so offset = 0,
   951  		// so v.ptr + offset is still the correct address.
   952  		val := add(v.ptr, offset, "same as &v[i], i < tt.len")
   953  		fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array
   954  		return Value{typ, val, fl}
   955  
   956  	case Slice:
   957  		// Element flag same as Elem of Ptr.
   958  		// Addressable, indirect, possibly read-only.
   959  		s := (*unsafeheader.Slice)(v.ptr)
   960  		if uint(i) >= uint(s.Len) {
   961  			panic("reflect: slice index out of range")
   962  		}
   963  		tt := (*sliceType)(unsafe.Pointer(v.typ))
   964  		typ := tt.elem
   965  		val := arrayAt(s.Data, i, typ.size, "i < s.Len")
   966  		fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind())
   967  		return Value{typ, val, fl}
   968  
   969  	case String:
   970  		s := (*unsafeheader.String)(v.ptr)
   971  		if uint(i) >= uint(s.Len) {
   972  			panic("reflect: string index out of range")
   973  		}
   974  		p := arrayAt(s.Data, i, 1, "i < s.Len")
   975  		fl := v.flag.ro() | flag(Uint8) | flagIndir
   976  		return Value{uint8Type, p, fl}
   977  	}
   978  	panic(&ValueError{"reflect.Value.Index", v.kind()})
   979  }
   980  
   981  // Int returns v's underlying value, as an int64.
   982  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
   983  func (v Value) Int() int64 {
   984  	k := v.kind()
   985  	p := v.ptr
   986  	switch k {
   987  	case Int:
   988  		return int64(*(*int)(p))
   989  	case Int8:
   990  		return int64(*(*int8)(p))
   991  	case Int16:
   992  		return int64(*(*int16)(p))
   993  	case Int32:
   994  		return int64(*(*int32)(p))
   995  	case Int64:
   996  		return *(*int64)(p)
   997  	}
   998  	panic(&ValueError{"reflect.Value.Int", v.kind()})
   999  }
  1000  
  1001  // CanInterface reports whether Interface can be used without panicking.
  1002  func (v Value) CanInterface() bool {
  1003  	if v.flag == 0 {
  1004  		panic(&ValueError{"reflect.Value.CanInterface", Invalid})
  1005  	}
  1006  	return v.flag&flagRO == 0
  1007  }
  1008  
  1009  // Interface returns v's current value as an interface{}.
  1010  // It is equivalent to:
  1011  //	var i interface{} = (v's underlying value)
  1012  // It panics if the Value was obtained by accessing
  1013  // unexported struct fields.
  1014  func (v Value) Interface() (i interface{}) {
  1015  	return valueInterface(v, true)
  1016  }
  1017  
  1018  func valueInterface(v Value, safe bool) interface{} {
  1019  	if v.flag == 0 {
  1020  		panic(&ValueError{"reflect.Value.Interface", Invalid})
  1021  	}
  1022  	if safe && v.flag&flagRO != 0 {
  1023  		// Do not allow access to unexported values via Interface,
  1024  		// because they might be pointers that should not be
  1025  		// writable or methods or function that should not be callable.
  1026  		panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
  1027  	}
  1028  	if v.flag&flagMethod != 0 {
  1029  		v = makeMethodValue("Interface", v)
  1030  	}
  1031  
  1032  	if v.kind() == Interface {
  1033  		// Special case: return the element inside the interface.
  1034  		// Empty interface has one layout, all interfaces with
  1035  		// methods have a second layout.
  1036  		if v.NumMethod() == 0 {
  1037  			return *(*interface{})(v.ptr)
  1038  		}
  1039  		return *(*interface {
  1040  			M()
  1041  		})(v.ptr)
  1042  	}
  1043  
  1044  	// TODO: pass safe to packEface so we don't need to copy if safe==true?
  1045  	return packEface(v)
  1046  }
  1047  
  1048  // InterfaceData returns the interface v's value as a uintptr pair.
  1049  // It panics if v's Kind is not Interface.
  1050  func (v Value) InterfaceData() [2]uintptr {
  1051  	// TODO: deprecate this
  1052  	v.mustBe(Interface)
  1053  	// We treat this as a read operation, so we allow
  1054  	// it even for unexported data, because the caller
  1055  	// has to import "unsafe" to turn it into something
  1056  	// that can be abused.
  1057  	// Interface value is always bigger than a word; assume flagIndir.
  1058  	return *(*[2]uintptr)(v.ptr)
  1059  }
  1060  
  1061  // IsNil reports whether its argument v is nil. The argument must be
  1062  // a chan, func, interface, map, pointer, or slice value; if it is
  1063  // not, IsNil panics. Note that IsNil is not always equivalent to a
  1064  // regular comparison with nil in Go. For example, if v was created
  1065  // by calling ValueOf with an uninitialized interface variable i,
  1066  // i==nil will be true but v.IsNil will panic as v will be the zero
  1067  // Value.
  1068  func (v Value) IsNil() bool {
  1069  	k := v.kind()
  1070  	switch k {
  1071  	case Chan, Func, Map, Ptr, UnsafePointer:
  1072  		if v.flag&flagMethod != 0 {
  1073  			return false
  1074  		}
  1075  		ptr := v.ptr
  1076  		if v.flag&flagIndir != 0 {
  1077  			ptr = *(*unsafe.Pointer)(ptr)
  1078  		}
  1079  		return ptr == nil
  1080  	case Interface, Slice:
  1081  		// Both interface and slice are nil if first word is 0.
  1082  		// Both are always bigger than a word; assume flagIndir.
  1083  		return *(*unsafe.Pointer)(v.ptr) == nil
  1084  	}
  1085  	panic(&ValueError{"reflect.Value.IsNil", v.kind()})
  1086  }
  1087  
  1088  // IsValid reports whether v represents a value.
  1089  // It returns false if v is the zero Value.
  1090  // If IsValid returns false, all other methods except String panic.
  1091  // Most functions and methods never return an invalid Value.
  1092  // If one does, its documentation states the conditions explicitly.
  1093  func (v Value) IsValid() bool {
  1094  	return v.flag != 0
  1095  }
  1096  
  1097  // IsZero reports whether v is the zero value for its type.
  1098  // It panics if the argument is invalid.
  1099  func (v Value) IsZero() bool {
  1100  	switch v.kind() {
  1101  	case Bool:
  1102  		return !v.Bool()
  1103  	case Int, Int8, Int16, Int32, Int64:
  1104  		return v.Int() == 0
  1105  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  1106  		return v.Uint() == 0
  1107  	case Float32, Float64:
  1108  		return math.Float64bits(v.Float()) == 0
  1109  	case Complex64, Complex128:
  1110  		c := v.Complex()
  1111  		return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
  1112  	case Array:
  1113  		for i := 0; i < v.Len(); i++ {
  1114  			if !v.Index(i).IsZero() {
  1115  				return false
  1116  			}
  1117  		}
  1118  		return true
  1119  	case Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer:
  1120  		return v.IsNil()
  1121  	case String:
  1122  		return v.Len() == 0
  1123  	case Struct:
  1124  		for i := 0; i < v.NumField(); i++ {
  1125  			if !v.Field(i).IsZero() {
  1126  				return false
  1127  			}
  1128  		}
  1129  		return true
  1130  	default:
  1131  		// This should never happens, but will act as a safeguard for
  1132  		// later, as a default value doesn't makes sense here.
  1133  		panic(&ValueError{"reflect.Value.IsZero", v.Kind()})
  1134  	}
  1135  }
  1136  
  1137  // Kind returns v's Kind.
  1138  // If v is the zero Value (IsValid returns false), Kind returns Invalid.
  1139  func (v Value) Kind() Kind {
  1140  	return v.kind()
  1141  }
  1142  
  1143  // Len returns v's length.
  1144  // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
  1145  func (v Value) Len() int {
  1146  	k := v.kind()
  1147  	switch k {
  1148  	case Array:
  1149  		tt := (*arrayType)(unsafe.Pointer(v.typ))
  1150  		return int(tt.len)
  1151  	case Chan:
  1152  		return chanlen(v.pointer())
  1153  	case Map:
  1154  		return maplen(v.pointer())
  1155  	case Slice:
  1156  		// Slice is bigger than a word; assume flagIndir.
  1157  		return (*unsafeheader.Slice)(v.ptr).Len
  1158  	case String:
  1159  		// String is bigger than a word; assume flagIndir.
  1160  		return (*unsafeheader.String)(v.ptr).Len
  1161  	}
  1162  	panic(&ValueError{"reflect.Value.Len", v.kind()})
  1163  }
  1164  
  1165  // MapIndex returns the value associated with key in the map v.
  1166  // It panics if v's Kind is not Map.
  1167  // It returns the zero Value if key is not found in the map or if v represents a nil map.
  1168  // As in Go, the key's value must be assignable to the map's key type.
  1169  func (v Value) MapIndex(key Value) Value {
  1170  	v.mustBe(Map)
  1171  	tt := (*mapType)(unsafe.Pointer(v.typ))
  1172  
  1173  	// Do not require key to be exported, so that DeepEqual
  1174  	// and other programs can use all the keys returned by
  1175  	// MapKeys as arguments to MapIndex. If either the map
  1176  	// or the key is unexported, though, the result will be
  1177  	// considered unexported. This is consistent with the
  1178  	// behavior for structs, which allow read but not write
  1179  	// of unexported fields.
  1180  	key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
  1181  
  1182  	var k unsafe.Pointer
  1183  	if key.flag&flagIndir != 0 {
  1184  		k = key.ptr
  1185  	} else {
  1186  		k = unsafe.Pointer(&key.ptr)
  1187  	}
  1188  	e := mapaccess(v.typ, v.pointer(), k)
  1189  	if e == nil {
  1190  		return Value{}
  1191  	}
  1192  	typ := tt.elem
  1193  	fl := (v.flag | key.flag).ro()
  1194  	fl |= flag(typ.Kind())
  1195  	return copyVal(typ, fl, e)
  1196  }
  1197  
  1198  // MapKeys returns a slice containing all the keys present in the map,
  1199  // in unspecified order.
  1200  // It panics if v's Kind is not Map.
  1201  // It returns an empty slice if v represents a nil map.
  1202  func (v Value) MapKeys() []Value {
  1203  	v.mustBe(Map)
  1204  	tt := (*mapType)(unsafe.Pointer(v.typ))
  1205  	keyType := tt.key
  1206  
  1207  	fl := v.flag.ro() | flag(keyType.Kind())
  1208  
  1209  	m := v.pointer()
  1210  	mlen := int(0)
  1211  	if m != nil {
  1212  		mlen = maplen(m)
  1213  	}
  1214  	it := mapiterinit(v.typ, m)
  1215  	a := make([]Value, mlen)
  1216  	var i int
  1217  	for i = 0; i < len(a); i++ {
  1218  		key := mapiterkey(it)
  1219  		if key == nil {
  1220  			// Someone deleted an entry from the map since we
  1221  			// called maplen above. It's a data race, but nothing
  1222  			// we can do about it.
  1223  			break
  1224  		}
  1225  		a[i] = copyVal(keyType, fl, key)
  1226  		mapiternext(it)
  1227  	}
  1228  	return a[:i]
  1229  }
  1230  
  1231  // A MapIter is an iterator for ranging over a map.
  1232  // See Value.MapRange.
  1233  type MapIter struct {
  1234  	m  Value
  1235  	it unsafe.Pointer
  1236  }
  1237  
  1238  // Key returns the key of the iterator's current map entry.
  1239  func (it *MapIter) Key() Value {
  1240  	if it.it == nil {
  1241  		panic("MapIter.Key called before Next")
  1242  	}
  1243  	if mapiterkey(it.it) == nil {
  1244  		panic("MapIter.Key called on exhausted iterator")
  1245  	}
  1246  
  1247  	t := (*mapType)(unsafe.Pointer(it.m.typ))
  1248  	ktype := t.key
  1249  	return copyVal(ktype, it.m.flag.ro()|flag(ktype.Kind()), mapiterkey(it.it))
  1250  }
  1251  
  1252  // Value returns the value of the iterator's current map entry.
  1253  func (it *MapIter) Value() Value {
  1254  	if it.it == nil {
  1255  		panic("MapIter.Value called before Next")
  1256  	}
  1257  	if mapiterkey(it.it) == nil {
  1258  		panic("MapIter.Value called on exhausted iterator")
  1259  	}
  1260  
  1261  	t := (*mapType)(unsafe.Pointer(it.m.typ))
  1262  	vtype := t.elem
  1263  	return copyVal(vtype, it.m.flag.ro()|flag(vtype.Kind()), mapiterelem(it.it))
  1264  }
  1265  
  1266  // Next advances the map iterator and reports whether there is another
  1267  // entry. It returns false when the iterator is exhausted; subsequent
  1268  // calls to Key, Value, or Next will panic.
  1269  func (it *MapIter) Next() bool {
  1270  	if it.it == nil {
  1271  		it.it = mapiterinit(it.m.typ, it.m.pointer())
  1272  	} else {
  1273  		if mapiterkey(it.it) == nil {
  1274  			panic("MapIter.Next called on exhausted iterator")
  1275  		}
  1276  		mapiternext(it.it)
  1277  	}
  1278  	return mapiterkey(it.it) != nil
  1279  }
  1280  
  1281  // MapRange returns a range iterator for a map.
  1282  // It panics if v's Kind is not Map.
  1283  //
  1284  // Call Next to advance the iterator, and Key/Value to access each entry.
  1285  // Next returns false when the iterator is exhausted.
  1286  // MapRange follows the same iteration semantics as a range statement.
  1287  //
  1288  // Example:
  1289  //
  1290  //	iter := reflect.ValueOf(m).MapRange()
  1291  // 	for iter.Next() {
  1292  //		k := iter.Key()
  1293  //		v := iter.Value()
  1294  //		...
  1295  //	}
  1296  //
  1297  func (v Value) MapRange() *MapIter {
  1298  	v.mustBe(Map)
  1299  	return &MapIter{m: v}
  1300  }
  1301  
  1302  // copyVal returns a Value containing the map key or value at ptr,
  1303  // allocating a new variable as needed.
  1304  func copyVal(typ *rtype, fl flag, ptr unsafe.Pointer) Value {
  1305  	if ifaceIndir(typ) {
  1306  		// Copy result so future changes to the map
  1307  		// won't change the underlying value.
  1308  		c := unsafe_New(typ)
  1309  		typedmemmove(typ, c, ptr)
  1310  		return Value{typ, c, fl | flagIndir}
  1311  	}
  1312  	return Value{typ, *(*unsafe.Pointer)(ptr), fl}
  1313  }
  1314  
  1315  // Method returns a function value corresponding to v's i'th method.
  1316  // The arguments to a Call on the returned function should not include
  1317  // a receiver; the returned function will always use v as the receiver.
  1318  // Method panics if i is out of range or if v is a nil interface value.
  1319  func (v Value) Method(i int) Value {
  1320  	if v.typ == nil {
  1321  		panic(&ValueError{"reflect.Value.Method", Invalid})
  1322  	}
  1323  	if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) {
  1324  		panic("reflect: Method index out of range")
  1325  	}
  1326  	if v.typ.Kind() == Interface && v.IsNil() {
  1327  		panic("reflect: Method on nil interface value")
  1328  	}
  1329  	fl := v.flag.ro() | (v.flag & flagIndir)
  1330  	fl |= flag(Func)
  1331  	fl |= flag(i)<<flagMethodShift | flagMethod
  1332  	return Value{v.typ, v.ptr, fl}
  1333  }
  1334  
  1335  // NumMethod returns the number of exported methods in the value's method set.
  1336  func (v Value) NumMethod() int {
  1337  	if v.typ == nil {
  1338  		panic(&ValueError{"reflect.Value.NumMethod", Invalid})
  1339  	}
  1340  	if v.flag&flagMethod != 0 {
  1341  		return 0
  1342  	}
  1343  	return v.typ.NumMethod()
  1344  }
  1345  
  1346  // MethodByName returns a function value corresponding to the method
  1347  // of v with the given name.
  1348  // The arguments to a Call on the returned function should not include
  1349  // a receiver; the returned function will always use v as the receiver.
  1350  // It returns the zero Value if no method was found.
  1351  func (v Value) MethodByName(name string) Value {
  1352  	if v.typ == nil {
  1353  		panic(&ValueError{"reflect.Value.MethodByName", Invalid})
  1354  	}
  1355  	if v.flag&flagMethod != 0 {
  1356  		return Value{}
  1357  	}
  1358  	m, ok := v.typ.MethodByName(name)
  1359  	if !ok {
  1360  		return Value{}
  1361  	}
  1362  	return v.Method(m.Index)
  1363  }
  1364  
  1365  // NumField returns the number of fields in the struct v.
  1366  // It panics if v's Kind is not Struct.
  1367  func (v Value) NumField() int {
  1368  	v.mustBe(Struct)
  1369  	tt := (*structType)(unsafe.Pointer(v.typ))
  1370  	return len(tt.fields)
  1371  }
  1372  
  1373  // OverflowComplex reports whether the complex128 x cannot be represented by v's type.
  1374  // It panics if v's Kind is not Complex64 or Complex128.
  1375  func (v Value) OverflowComplex(x complex128) bool {
  1376  	k := v.kind()
  1377  	switch k {
  1378  	case Complex64:
  1379  		return overflowFloat32(real(x)) || overflowFloat32(imag(x))
  1380  	case Complex128:
  1381  		return false
  1382  	}
  1383  	panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
  1384  }
  1385  
  1386  // OverflowFloat reports whether the float64 x cannot be represented by v's type.
  1387  // It panics if v's Kind is not Float32 or Float64.
  1388  func (v Value) OverflowFloat(x float64) bool {
  1389  	k := v.kind()
  1390  	switch k {
  1391  	case Float32:
  1392  		return overflowFloat32(x)
  1393  	case Float64:
  1394  		return false
  1395  	}
  1396  	panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
  1397  }
  1398  
  1399  func overflowFloat32(x float64) bool {
  1400  	if x < 0 {
  1401  		x = -x
  1402  	}
  1403  	return math.MaxFloat32 < x && x <= math.MaxFloat64
  1404  }
  1405  
  1406  // OverflowInt reports whether the int64 x cannot be represented by v's type.
  1407  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
  1408  func (v Value) OverflowInt(x int64) bool {
  1409  	k := v.kind()
  1410  	switch k {
  1411  	case Int, Int8, Int16, Int32, Int64:
  1412  		bitSize := v.typ.size * 8
  1413  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1414  		return x != trunc
  1415  	}
  1416  	panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
  1417  }
  1418  
  1419  // OverflowUint reports whether the uint64 x cannot be represented by v's type.
  1420  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  1421  func (v Value) OverflowUint(x uint64) bool {
  1422  	k := v.kind()
  1423  	switch k {
  1424  	case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
  1425  		bitSize := v.typ.size * 8
  1426  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1427  		return x != trunc
  1428  	}
  1429  	panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
  1430  }
  1431  
  1432  //go:nocheckptr
  1433  // This prevents inlining Value.Pointer when -d=checkptr is enabled,
  1434  // which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer())
  1435  // and make an exception.
  1436  
  1437  // Pointer returns v's value as a uintptr.
  1438  // It returns uintptr instead of unsafe.Pointer so that
  1439  // code using reflect cannot obtain unsafe.Pointers
  1440  // without importing the unsafe package explicitly.
  1441  // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
  1442  //
  1443  // If v's Kind is Func, the returned pointer is an underlying
  1444  // code pointer, but not necessarily enough to identify a
  1445  // single function uniquely. The only guarantee is that the
  1446  // result is zero if and only if v is a nil func Value.
  1447  //
  1448  // If v's Kind is Slice, the returned pointer is to the first
  1449  // element of the slice. If the slice is nil the returned value
  1450  // is 0.  If the slice is empty but non-nil the return value is non-zero.
  1451  func (v Value) Pointer() uintptr {
  1452  	// TODO: deprecate
  1453  	k := v.kind()
  1454  	switch k {
  1455  	case Chan, Map, Ptr, UnsafePointer:
  1456  		return uintptr(v.pointer())
  1457  	case Func:
  1458  		if v.flag&flagMethod != 0 {
  1459  			// As the doc comment says, the returned pointer is an
  1460  			// underlying code pointer but not necessarily enough to
  1461  			// identify a single function uniquely. All method expressions
  1462  			// created via reflect have the same underlying code pointer,
  1463  			// so their Pointers are equal. The function used here must
  1464  			// match the one used in makeMethodValue.
  1465  			f := methodValueCall
  1466  			return **(**uintptr)(unsafe.Pointer(&f))
  1467  		}
  1468  		p := v.pointer()
  1469  		// Non-nil func value points at data block.
  1470  		// First word of data block is actual code.
  1471  		if p != nil {
  1472  			p = *(*unsafe.Pointer)(p)
  1473  		}
  1474  		return uintptr(p)
  1475  
  1476  	case Slice:
  1477  		return (*SliceHeader)(v.ptr).Data
  1478  	}
  1479  	panic(&ValueError{"reflect.Value.Pointer", v.kind()})
  1480  }
  1481  
  1482  // Recv receives and returns a value from the channel v.
  1483  // It panics if v's Kind is not Chan.
  1484  // The receive blocks until a value is ready.
  1485  // The boolean value ok is true if the value x corresponds to a send
  1486  // on the channel, false if it is a zero value received because the channel is closed.
  1487  func (v Value) Recv() (x Value, ok bool) {
  1488  	v.mustBe(Chan)
  1489  	v.mustBeExported()
  1490  	return v.recv(false)
  1491  }
  1492  
  1493  // internal recv, possibly non-blocking (nb).
  1494  // v is known to be a channel.
  1495  func (v Value) recv(nb bool) (val Value, ok bool) {
  1496  	tt := (*chanType)(unsafe.Pointer(v.typ))
  1497  	if ChanDir(tt.dir)&RecvDir == 0 {
  1498  		panic("reflect: recv on send-only channel")
  1499  	}
  1500  	t := tt.elem
  1501  	val = Value{t, nil, flag(t.Kind())}
  1502  	var p unsafe.Pointer
  1503  	if ifaceIndir(t) {
  1504  		p = unsafe_New(t)
  1505  		val.ptr = p
  1506  		val.flag |= flagIndir
  1507  	} else {
  1508  		p = unsafe.Pointer(&val.ptr)
  1509  	}
  1510  	selected, ok := chanrecv(v.pointer(), nb, p)
  1511  	if !selected {
  1512  		val = Value{}
  1513  	}
  1514  	return
  1515  }
  1516  
  1517  // Send sends x on the channel v.
  1518  // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
  1519  // As in Go, x's value must be assignable to the channel's element type.
  1520  func (v Value) Send(x Value) {
  1521  	v.mustBe(Chan)
  1522  	v.mustBeExported()
  1523  	v.send(x, false)
  1524  }
  1525  
  1526  // internal send, possibly non-blocking.
  1527  // v is known to be a channel.
  1528  func (v Value) send(x Value, nb bool) (selected bool) {
  1529  	tt := (*chanType)(unsafe.Pointer(v.typ))
  1530  	if ChanDir(tt.dir)&SendDir == 0 {
  1531  		panic("reflect: send on recv-only channel")
  1532  	}
  1533  	x.mustBeExported()
  1534  	x = x.assignTo("reflect.Value.Send", tt.elem, nil)
  1535  	var p unsafe.Pointer
  1536  	if x.flag&flagIndir != 0 {
  1537  		p = x.ptr
  1538  	} else {
  1539  		p = unsafe.Pointer(&x.ptr)
  1540  	}
  1541  	return chansend(v.pointer(), p, nb)
  1542  }
  1543  
  1544  // Set assigns x to the value v.
  1545  // It panics if CanSet returns false.
  1546  // As in Go, x's value must be assignable to v's type.
  1547  func (v Value) Set(x Value) {
  1548  	v.mustBeAssignable()
  1549  	x.mustBeExported() // do not let unexported x leak
  1550  	var target unsafe.Pointer
  1551  	if v.kind() == Interface {
  1552  		target = v.ptr
  1553  	}
  1554  	x = x.assignTo("reflect.Set", v.typ, target)
  1555  	if x.flag&flagIndir != 0 {
  1556  		typedmemmove(v.typ, v.ptr, x.ptr)
  1557  	} else {
  1558  		*(*unsafe.Pointer)(v.ptr) = x.ptr
  1559  	}
  1560  }
  1561  
  1562  // SetBool sets v's underlying value.
  1563  // It panics if v's Kind is not Bool or if CanSet() is false.
  1564  func (v Value) SetBool(x bool) {
  1565  	v.mustBeAssignable()
  1566  	v.mustBe(Bool)
  1567  	*(*bool)(v.ptr) = x
  1568  }
  1569  
  1570  // SetBytes sets v's underlying value.
  1571  // It panics if v's underlying value is not a slice of bytes.
  1572  func (v Value) SetBytes(x []byte) {
  1573  	v.mustBeAssignable()
  1574  	v.mustBe(Slice)
  1575  	if v.typ.Elem().Kind() != Uint8 {
  1576  		panic("reflect.Value.SetBytes of non-byte slice")
  1577  	}
  1578  	*(*[]byte)(v.ptr) = x
  1579  }
  1580  
  1581  // setRunes sets v's underlying value.
  1582  // It panics if v's underlying value is not a slice of runes (int32s).
  1583  func (v Value) setRunes(x []rune) {
  1584  	v.mustBeAssignable()
  1585  	v.mustBe(Slice)
  1586  	if v.typ.Elem().Kind() != Int32 {
  1587  		panic("reflect.Value.setRunes of non-rune slice")
  1588  	}
  1589  	*(*[]rune)(v.ptr) = x
  1590  }
  1591  
  1592  // SetComplex sets v's underlying value to x.
  1593  // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
  1594  func (v Value) SetComplex(x complex128) {
  1595  	v.mustBeAssignable()
  1596  	switch k := v.kind(); k {
  1597  	default:
  1598  		panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
  1599  	case Complex64:
  1600  		*(*complex64)(v.ptr) = complex64(x)
  1601  	case Complex128:
  1602  		*(*complex128)(v.ptr) = x
  1603  	}
  1604  }
  1605  
  1606  // SetFloat sets v's underlying value to x.
  1607  // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
  1608  func (v Value) SetFloat(x float64) {
  1609  	v.mustBeAssignable()
  1610  	switch k := v.kind(); k {
  1611  	default:
  1612  		panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
  1613  	case Float32:
  1614  		*(*float32)(v.ptr) = float32(x)
  1615  	case Float64:
  1616  		*(*float64)(v.ptr) = x
  1617  	}
  1618  }
  1619  
  1620  // SetInt sets v's underlying value to x.
  1621  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
  1622  func (v Value) SetInt(x int64) {
  1623  	v.mustBeAssignable()
  1624  	switch k := v.kind(); k {
  1625  	default:
  1626  		panic(&ValueError{"reflect.Value.SetInt", v.kind()})
  1627  	case Int:
  1628  		*(*int)(v.ptr) = int(x)
  1629  	case Int8:
  1630  		*(*int8)(v.ptr) = int8(x)
  1631  	case Int16:
  1632  		*(*int16)(v.ptr) = int16(x)
  1633  	case Int32:
  1634  		*(*int32)(v.ptr) = int32(x)
  1635  	case Int64:
  1636  		*(*int64)(v.ptr) = x
  1637  	}
  1638  }
  1639  
  1640  // SetLen sets v's length to n.
  1641  // It panics if v's Kind is not Slice or if n is negative or
  1642  // greater than the capacity of the slice.
  1643  func (v Value) SetLen(n int) {
  1644  	v.mustBeAssignable()
  1645  	v.mustBe(Slice)
  1646  	s := (*unsafeheader.Slice)(v.ptr)
  1647  	if uint(n) > uint(s.Cap) {
  1648  		panic("reflect: slice length out of range in SetLen")
  1649  	}
  1650  	s.Len = n
  1651  }
  1652  
  1653  // SetCap sets v's capacity to n.
  1654  // It panics if v's Kind is not Slice or if n is smaller than the length or
  1655  // greater than the capacity of the slice.
  1656  func (v Value) SetCap(n int) {
  1657  	v.mustBeAssignable()
  1658  	v.mustBe(Slice)
  1659  	s := (*unsafeheader.Slice)(v.ptr)
  1660  	if n < s.Len || n > s.Cap {
  1661  		panic("reflect: slice capacity out of range in SetCap")
  1662  	}
  1663  	s.Cap = n
  1664  }
  1665  
  1666  // SetMapIndex sets the element associated with key in the map v to elem.
  1667  // It panics if v's Kind is not Map.
  1668  // If elem is the zero Value, SetMapIndex deletes the key from the map.
  1669  // Otherwise if v holds a nil map, SetMapIndex will panic.
  1670  // As in Go, key's elem must be assignable to the map's key type,
  1671  // and elem's value must be assignable to the map's elem type.
  1672  func (v Value) SetMapIndex(key, elem Value) {
  1673  	v.mustBe(Map)
  1674  	v.mustBeExported()
  1675  	key.mustBeExported()
  1676  	tt := (*mapType)(unsafe.Pointer(v.typ))
  1677  	key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
  1678  	var k unsafe.Pointer
  1679  	if key.flag&flagIndir != 0 {
  1680  		k = key.ptr
  1681  	} else {
  1682  		k = unsafe.Pointer(&key.ptr)
  1683  	}
  1684  	if elem.typ == nil {
  1685  		mapdelete(v.typ, v.pointer(), k)
  1686  		return
  1687  	}
  1688  	elem.mustBeExported()
  1689  	elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
  1690  	var e unsafe.Pointer
  1691  	if elem.flag&flagIndir != 0 {
  1692  		e = elem.ptr
  1693  	} else {
  1694  		e = unsafe.Pointer(&elem.ptr)
  1695  	}
  1696  	mapassign(v.typ, v.pointer(), k, e)
  1697  }
  1698  
  1699  // SetUint sets v's underlying value to x.
  1700  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
  1701  func (v Value) SetUint(x uint64) {
  1702  	v.mustBeAssignable()
  1703  	switch k := v.kind(); k {
  1704  	default:
  1705  		panic(&ValueError{"reflect.Value.SetUint", v.kind()})
  1706  	case Uint:
  1707  		*(*uint)(v.ptr) = uint(x)
  1708  	case Uint8:
  1709  		*(*uint8)(v.ptr) = uint8(x)
  1710  	case Uint16:
  1711  		*(*uint16)(v.ptr) = uint16(x)
  1712  	case Uint32:
  1713  		*(*uint32)(v.ptr) = uint32(x)
  1714  	case Uint64:
  1715  		*(*uint64)(v.ptr) = x
  1716  	case Uintptr:
  1717  		*(*uintptr)(v.ptr) = uintptr(x)
  1718  	}
  1719  }
  1720  
  1721  // SetPointer sets the unsafe.Pointer value v to x.
  1722  // It panics if v's Kind is not UnsafePointer.
  1723  func (v Value) SetPointer(x unsafe.Pointer) {
  1724  	v.mustBeAssignable()
  1725  	v.mustBe(UnsafePointer)
  1726  	*(*unsafe.Pointer)(v.ptr) = x
  1727  }
  1728  
  1729  // SetString sets v's underlying value to x.
  1730  // It panics if v's Kind is not String or if CanSet() is false.
  1731  func (v Value) SetString(x string) {
  1732  	v.mustBeAssignable()
  1733  	v.mustBe(String)
  1734  	*(*string)(v.ptr) = x
  1735  }
  1736  
  1737  // Slice returns v[i:j].
  1738  // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
  1739  // or if the indexes are out of bounds.
  1740  func (v Value) Slice(i, j int) Value {
  1741  	var (
  1742  		cap  int
  1743  		typ  *sliceType
  1744  		base unsafe.Pointer
  1745  	)
  1746  	switch kind := v.kind(); kind {
  1747  	default:
  1748  		panic(&ValueError{"reflect.Value.Slice", v.kind()})
  1749  
  1750  	case Array:
  1751  		if v.flag&flagAddr == 0 {
  1752  			panic("reflect.Value.Slice: slice of unaddressable array")
  1753  		}
  1754  		tt := (*arrayType)(unsafe.Pointer(v.typ))
  1755  		cap = int(tt.len)
  1756  		typ = (*sliceType)(unsafe.Pointer(tt.slice))
  1757  		base = v.ptr
  1758  
  1759  	case Slice:
  1760  		typ = (*sliceType)(unsafe.Pointer(v.typ))
  1761  		s := (*unsafeheader.Slice)(v.ptr)
  1762  		base = s.Data
  1763  		cap = s.Cap
  1764  
  1765  	case String:
  1766  		s := (*unsafeheader.String)(v.ptr)
  1767  		if i < 0 || j < i || j > s.Len {
  1768  			panic("reflect.Value.Slice: string slice index out of bounds")
  1769  		}
  1770  		var t unsafeheader.String
  1771  		if i < s.Len {
  1772  			t = unsafeheader.String{Data: arrayAt(s.Data, i, 1, "i < s.Len"), Len: j - i}
  1773  		}
  1774  		return Value{v.typ, unsafe.Pointer(&t), v.flag}
  1775  	}
  1776  
  1777  	if i < 0 || j < i || j > cap {
  1778  		panic("reflect.Value.Slice: slice index out of bounds")
  1779  	}
  1780  
  1781  	// Declare slice so that gc can see the base pointer in it.
  1782  	var x []unsafe.Pointer
  1783  
  1784  	// Reinterpret as *unsafeheader.Slice to edit.
  1785  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  1786  	s.Len = j - i
  1787  	s.Cap = cap - i
  1788  	if cap-i > 0 {
  1789  		s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap")
  1790  	} else {
  1791  		// do not advance pointer, to avoid pointing beyond end of slice
  1792  		s.Data = base
  1793  	}
  1794  
  1795  	fl := v.flag.ro() | flagIndir | flag(Slice)
  1796  	return Value{typ.common(), unsafe.Pointer(&x), fl}
  1797  }
  1798  
  1799  // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
  1800  // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
  1801  // or if the indexes are out of bounds.
  1802  func (v Value) Slice3(i, j, k int) Value {
  1803  	var (
  1804  		cap  int
  1805  		typ  *sliceType
  1806  		base unsafe.Pointer
  1807  	)
  1808  	switch kind := v.kind(); kind {
  1809  	default:
  1810  		panic(&ValueError{"reflect.Value.Slice3", v.kind()})
  1811  
  1812  	case Array:
  1813  		if v.flag&flagAddr == 0 {
  1814  			panic("reflect.Value.Slice3: slice of unaddressable array")
  1815  		}
  1816  		tt := (*arrayType)(unsafe.Pointer(v.typ))
  1817  		cap = int(tt.len)
  1818  		typ = (*sliceType)(unsafe.Pointer(tt.slice))
  1819  		base = v.ptr
  1820  
  1821  	case Slice:
  1822  		typ = (*sliceType)(unsafe.Pointer(v.typ))
  1823  		s := (*unsafeheader.Slice)(v.ptr)
  1824  		base = s.Data
  1825  		cap = s.Cap
  1826  	}
  1827  
  1828  	if i < 0 || j < i || k < j || k > cap {
  1829  		panic("reflect.Value.Slice3: slice index out of bounds")
  1830  	}
  1831  
  1832  	// Declare slice so that the garbage collector
  1833  	// can see the base pointer in it.
  1834  	var x []unsafe.Pointer
  1835  
  1836  	// Reinterpret as *unsafeheader.Slice to edit.
  1837  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  1838  	s.Len = j - i
  1839  	s.Cap = k - i
  1840  	if k-i > 0 {
  1841  		s.Data = arrayAt(base, i, typ.elem.Size(), "i < k <= cap")
  1842  	} else {
  1843  		// do not advance pointer, to avoid pointing beyond end of slice
  1844  		s.Data = base
  1845  	}
  1846  
  1847  	fl := v.flag.ro() | flagIndir | flag(Slice)
  1848  	return Value{typ.common(), unsafe.Pointer(&x), fl}
  1849  }
  1850  
  1851  // String returns the string v's underlying value, as a string.
  1852  // String is a special case because of Go's String method convention.
  1853  // Unlike the other getters, it does not panic if v's Kind is not String.
  1854  // Instead, it returns a string of the form "<T value>" where T is v's type.
  1855  // The fmt package treats Values specially. It does not call their String
  1856  // method implicitly but instead prints the concrete values they hold.
  1857  func (v Value) String() string {
  1858  	switch k := v.kind(); k {
  1859  	case Invalid:
  1860  		return "<invalid Value>"
  1861  	case String:
  1862  		return *(*string)(v.ptr)
  1863  	}
  1864  	// If you call String on a reflect.Value of other type, it's better to
  1865  	// print something than to panic. Useful in debugging.
  1866  	return "<" + v.Type().String() + " Value>"
  1867  }
  1868  
  1869  // TryRecv attempts to receive a value from the channel v but will not block.
  1870  // It panics if v's Kind is not Chan.
  1871  // If the receive delivers a value, x is the transferred value and ok is true.
  1872  // If the receive cannot finish without blocking, x is the zero Value and ok is false.
  1873  // If the channel is closed, x is the zero value for the channel's element type and ok is false.
  1874  func (v Value) TryRecv() (x Value, ok bool) {
  1875  	v.mustBe(Chan)
  1876  	v.mustBeExported()
  1877  	return v.recv(true)
  1878  }
  1879  
  1880  // TrySend attempts to send x on the channel v but will not block.
  1881  // It panics if v's Kind is not Chan.
  1882  // It reports whether the value was sent.
  1883  // As in Go, x's value must be assignable to the channel's element type.
  1884  func (v Value) TrySend(x Value) bool {
  1885  	v.mustBe(Chan)
  1886  	v.mustBeExported()
  1887  	return v.send(x, true)
  1888  }
  1889  
  1890  // Type returns v's type.
  1891  func (v Value) Type() Type {
  1892  	f := v.flag
  1893  	if f == 0 {
  1894  		panic(&ValueError{"reflect.Value.Type", Invalid})
  1895  	}
  1896  	if f&flagMethod == 0 {
  1897  		// Easy case
  1898  		return v.typ
  1899  	}
  1900  
  1901  	// Method value.
  1902  	// v.typ describes the receiver, not the method type.
  1903  	i := int(v.flag) >> flagMethodShift
  1904  	if v.typ.Kind() == Interface {
  1905  		// Method on interface.
  1906  		tt := (*interfaceType)(unsafe.Pointer(v.typ))
  1907  		if uint(i) >= uint(len(tt.methods)) {
  1908  			panic("reflect: internal error: invalid method index")
  1909  		}
  1910  		m := &tt.methods[i]
  1911  		return v.typ.typeOff(m.typ)
  1912  	}
  1913  	// Method on concrete type.
  1914  	ms := v.typ.exportedMethods()
  1915  	if uint(i) >= uint(len(ms)) {
  1916  		panic("reflect: internal error: invalid method index")
  1917  	}
  1918  	m := ms[i]
  1919  	return v.typ.typeOff(m.mtyp)
  1920  }
  1921  
  1922  // Uint returns v's underlying value, as a uint64.
  1923  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  1924  func (v Value) Uint() uint64 {
  1925  	k := v.kind()
  1926  	p := v.ptr
  1927  	switch k {
  1928  	case Uint:
  1929  		return uint64(*(*uint)(p))
  1930  	case Uint8:
  1931  		return uint64(*(*uint8)(p))
  1932  	case Uint16:
  1933  		return uint64(*(*uint16)(p))
  1934  	case Uint32:
  1935  		return uint64(*(*uint32)(p))
  1936  	case Uint64:
  1937  		return *(*uint64)(p)
  1938  	case Uintptr:
  1939  		return uint64(*(*uintptr)(p))
  1940  	}
  1941  	panic(&ValueError{"reflect.Value.Uint", v.kind()})
  1942  }
  1943  
  1944  //go:nocheckptr
  1945  // This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled,
  1946  // which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr())
  1947  // and make an exception.
  1948  
  1949  // UnsafeAddr returns a pointer to v's data.
  1950  // It is for advanced clients that also import the "unsafe" package.
  1951  // It panics if v is not addressable.
  1952  func (v Value) UnsafeAddr() uintptr {
  1953  	// TODO: deprecate
  1954  	if v.typ == nil {
  1955  		panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
  1956  	}
  1957  	if v.flag&flagAddr == 0 {
  1958  		panic("reflect.Value.UnsafeAddr of unaddressable value")
  1959  	}
  1960  	return uintptr(v.ptr)
  1961  }
  1962  
  1963  // StringHeader is the runtime representation of a string.
  1964  // It cannot be used safely or portably and its representation may
  1965  // change in a later release.
  1966  // Moreover, the Data field is not sufficient to guarantee the data
  1967  // it references will not be garbage collected, so programs must keep
  1968  // a separate, correctly typed pointer to the underlying data.
  1969  type StringHeader struct {
  1970  	Data uintptr
  1971  	Len  int
  1972  }
  1973  
  1974  // SliceHeader is the runtime representation of a slice.
  1975  // It cannot be used safely or portably and its representation may
  1976  // change in a later release.
  1977  // Moreover, the Data field is not sufficient to guarantee the data
  1978  // it references will not be garbage collected, so programs must keep
  1979  // a separate, correctly typed pointer to the underlying data.
  1980  type SliceHeader struct {
  1981  	Data uintptr
  1982  	Len  int
  1983  	Cap  int
  1984  }
  1985  
  1986  func typesMustMatch(what string, t1, t2 Type) {
  1987  	if t1 != t2 {
  1988  		panic(what + ": " + t1.String() + " != " + t2.String())
  1989  	}
  1990  }
  1991  
  1992  // arrayAt returns the i-th element of p,
  1993  // an array whose elements are eltSize bytes wide.
  1994  // The array pointed at by p must have at least i+1 elements:
  1995  // it is invalid (but impossible to check here) to pass i >= len,
  1996  // because then the result will point outside the array.
  1997  // whySafe must explain why i < len. (Passing "i < len" is fine;
  1998  // the benefit is to surface this assumption at the call site.)
  1999  func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
  2000  	return add(p, uintptr(i)*eltSize, "i < len")
  2001  }
  2002  
  2003  // grow grows the slice s so that it can hold extra more values, allocating
  2004  // more capacity if needed. It also returns the old and new slice lengths.
  2005  func grow(s Value, extra int) (Value, int, int) {
  2006  	i0 := s.Len()
  2007  	i1 := i0 + extra
  2008  	if i1 < i0 {
  2009  		panic("reflect.Append: slice overflow")
  2010  	}
  2011  	m := s.Cap()
  2012  	if i1 <= m {
  2013  		return s.Slice(0, i1), i0, i1
  2014  	}
  2015  	if m == 0 {
  2016  		m = extra
  2017  	} else {
  2018  		for m < i1 {
  2019  			if i0 < 1024 {
  2020  				m += m
  2021  			} else {
  2022  				m += m / 4
  2023  			}
  2024  		}
  2025  	}
  2026  	t := MakeSlice(s.Type(), i1, m)
  2027  	Copy(t, s)
  2028  	return t, i0, i1
  2029  }
  2030  
  2031  // Append appends the values x to a slice s and returns the resulting slice.
  2032  // As in Go, each x's value must be assignable to the slice's element type.
  2033  func Append(s Value, x ...Value) Value {
  2034  	s.mustBe(Slice)
  2035  	s, i0, i1 := grow(s, len(x))
  2036  	for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
  2037  		s.Index(i).Set(x[j])
  2038  	}
  2039  	return s
  2040  }
  2041  
  2042  // AppendSlice appends a slice t to a slice s and returns the resulting slice.
  2043  // The slices s and t must have the same element type.
  2044  func AppendSlice(s, t Value) Value {
  2045  	s.mustBe(Slice)
  2046  	t.mustBe(Slice)
  2047  	typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
  2048  	s, i0, i1 := grow(s, t.Len())
  2049  	Copy(s.Slice(i0, i1), t)
  2050  	return s
  2051  }
  2052  
  2053  // Copy copies the contents of src into dst until either
  2054  // dst has been filled or src has been exhausted.
  2055  // It returns the number of elements copied.
  2056  // Dst and src each must have kind Slice or Array, and
  2057  // dst and src must have the same element type.
  2058  //
  2059  // As a special case, src can have kind String if the element type of dst is kind Uint8.
  2060  func Copy(dst, src Value) int {
  2061  	dk := dst.kind()
  2062  	if dk != Array && dk != Slice {
  2063  		panic(&ValueError{"reflect.Copy", dk})
  2064  	}
  2065  	if dk == Array {
  2066  		dst.mustBeAssignable()
  2067  	}
  2068  	dst.mustBeExported()
  2069  
  2070  	sk := src.kind()
  2071  	var stringCopy bool
  2072  	if sk != Array && sk != Slice {
  2073  		stringCopy = sk == String && dst.typ.Elem().Kind() == Uint8
  2074  		if !stringCopy {
  2075  			panic(&ValueError{"reflect.Copy", sk})
  2076  		}
  2077  	}
  2078  	src.mustBeExported()
  2079  
  2080  	de := dst.typ.Elem()
  2081  	if !stringCopy {
  2082  		se := src.typ.Elem()
  2083  		typesMustMatch("reflect.Copy", de, se)
  2084  	}
  2085  
  2086  	var ds, ss unsafeheader.Slice
  2087  	if dk == Array {
  2088  		ds.Data = dst.ptr
  2089  		ds.Len = dst.Len()
  2090  		ds.Cap = ds.Len
  2091  	} else {
  2092  		ds = *(*unsafeheader.Slice)(dst.ptr)
  2093  	}
  2094  	if sk == Array {
  2095  		ss.Data = src.ptr
  2096  		ss.Len = src.Len()
  2097  		ss.Cap = ss.Len
  2098  	} else if sk == Slice {
  2099  		ss = *(*unsafeheader.Slice)(src.ptr)
  2100  	} else {
  2101  		sh := *(*unsafeheader.String)(src.ptr)
  2102  		ss.Data = sh.Data
  2103  		ss.Len = sh.Len
  2104  		ss.Cap = sh.Len
  2105  	}
  2106  
  2107  	return typedslicecopy(de.common(), ds, ss)
  2108  }
  2109  
  2110  // A runtimeSelect is a single case passed to rselect.
  2111  // This must match ../runtime/select.go:/runtimeSelect
  2112  type runtimeSelect struct {
  2113  	dir SelectDir      // SelectSend, SelectRecv or SelectDefault
  2114  	typ *rtype         // channel type
  2115  	ch  unsafe.Pointer // channel
  2116  	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
  2117  }
  2118  
  2119  // rselect runs a select. It returns the index of the chosen case.
  2120  // If the case was a receive, val is filled in with the received value.
  2121  // The conventional OK bool indicates whether the receive corresponds
  2122  // to a sent value.
  2123  //go:noescape
  2124  func rselect([]runtimeSelect) (chosen int, recvOK bool)
  2125  
  2126  // A SelectDir describes the communication direction of a select case.
  2127  type SelectDir int
  2128  
  2129  // NOTE: These values must match ../runtime/select.go:/selectDir.
  2130  
  2131  const (
  2132  	_             SelectDir = iota
  2133  	SelectSend              // case Chan <- Send
  2134  	SelectRecv              // case <-Chan:
  2135  	SelectDefault           // default
  2136  )
  2137  
  2138  // A SelectCase describes a single case in a select operation.
  2139  // The kind of case depends on Dir, the communication direction.
  2140  //
  2141  // If Dir is SelectDefault, the case represents a default case.
  2142  // Chan and Send must be zero Values.
  2143  //
  2144  // If Dir is SelectSend, the case represents a send operation.
  2145  // Normally Chan's underlying value must be a channel, and Send's underlying value must be
  2146  // assignable to the channel's element type. As a special case, if Chan is a zero Value,
  2147  // then the case is ignored, and the field Send will also be ignored and may be either zero
  2148  // or non-zero.
  2149  //
  2150  // If Dir is SelectRecv, the case represents a receive operation.
  2151  // Normally Chan's underlying value must be a channel and Send must be a zero Value.
  2152  // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
  2153  // When a receive operation is selected, the received Value is returned by Select.
  2154  //
  2155  type SelectCase struct {
  2156  	Dir  SelectDir // direction of case
  2157  	Chan Value     // channel to use (for send or receive)
  2158  	Send Value     // value to send (for send)
  2159  }
  2160  
  2161  // Select executes a select operation described by the list of cases.
  2162  // Like the Go select statement, it blocks until at least one of the cases
  2163  // can proceed, makes a uniform pseudo-random choice,
  2164  // and then executes that case. It returns the index of the chosen case
  2165  // and, if that case was a receive operation, the value received and a
  2166  // boolean indicating whether the value corresponds to a send on the channel
  2167  // (as opposed to a zero value received because the channel is closed).
  2168  // Select supports a maximum of 65536 cases.
  2169  func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
  2170  	if len(cases) > 65536 {
  2171  		panic("reflect.Select: too many cases (max 65536)")
  2172  	}
  2173  	// NOTE: Do not trust that caller is not modifying cases data underfoot.
  2174  	// The range is safe because the caller cannot modify our copy of the len
  2175  	// and each iteration makes its own copy of the value c.
  2176  	var runcases []runtimeSelect
  2177  	if len(cases) > 4 {
  2178  		// Slice is heap allocated due to runtime dependent capacity.
  2179  		runcases = make([]runtimeSelect, len(cases))
  2180  	} else {
  2181  		// Slice can be stack allocated due to constant capacity.
  2182  		runcases = make([]runtimeSelect, len(cases), 4)
  2183  	}
  2184  
  2185  	haveDefault := false
  2186  	for i, c := range cases {
  2187  		rc := &runcases[i]
  2188  		rc.dir = c.Dir
  2189  		switch c.Dir {
  2190  		default:
  2191  			panic("reflect.Select: invalid Dir")
  2192  
  2193  		case SelectDefault: // default
  2194  			if haveDefault {
  2195  				panic("reflect.Select: multiple default cases")
  2196  			}
  2197  			haveDefault = true
  2198  			if c.Chan.IsValid() {
  2199  				panic("reflect.Select: default case has Chan value")
  2200  			}
  2201  			if c.Send.IsValid() {
  2202  				panic("reflect.Select: default case has Send value")
  2203  			}
  2204  
  2205  		case SelectSend:
  2206  			ch := c.Chan
  2207  			if !ch.IsValid() {
  2208  				break
  2209  			}
  2210  			ch.mustBe(Chan)
  2211  			ch.mustBeExported()
  2212  			tt := (*chanType)(unsafe.Pointer(ch.typ))
  2213  			if ChanDir(tt.dir)&SendDir == 0 {
  2214  				panic("reflect.Select: SendDir case using recv-only channel")
  2215  			}
  2216  			rc.ch = ch.pointer()
  2217  			rc.typ = &tt.rtype
  2218  			v := c.Send
  2219  			if !v.IsValid() {
  2220  				panic("reflect.Select: SendDir case missing Send value")
  2221  			}
  2222  			v.mustBeExported()
  2223  			v = v.assignTo("reflect.Select", tt.elem, nil)
  2224  			if v.flag&flagIndir != 0 {
  2225  				rc.val = v.ptr
  2226  			} else {
  2227  				rc.val = unsafe.Pointer(&v.ptr)
  2228  			}
  2229  
  2230  		case SelectRecv:
  2231  			if c.Send.IsValid() {
  2232  				panic("reflect.Select: RecvDir case has Send value")
  2233  			}
  2234  			ch := c.Chan
  2235  			if !ch.IsValid() {
  2236  				break
  2237  			}
  2238  			ch.mustBe(Chan)
  2239  			ch.mustBeExported()
  2240  			tt := (*chanType)(unsafe.Pointer(ch.typ))
  2241  			if ChanDir(tt.dir)&RecvDir == 0 {
  2242  				panic("reflect.Select: RecvDir case using send-only channel")
  2243  			}
  2244  			rc.ch = ch.pointer()
  2245  			rc.typ = &tt.rtype
  2246  			rc.val = unsafe_New(tt.elem)
  2247  		}
  2248  	}
  2249  
  2250  	chosen, recvOK = rselect(runcases)
  2251  	if runcases[chosen].dir == SelectRecv {
  2252  		tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
  2253  		t := tt.elem
  2254  		p := runcases[chosen].val
  2255  		fl := flag(t.Kind())
  2256  		if ifaceIndir(t) {
  2257  			recv = Value{t, p, fl | flagIndir}
  2258  		} else {
  2259  			recv = Value{t, *(*unsafe.Pointer)(p), fl}
  2260  		}
  2261  	}
  2262  	return chosen, recv, recvOK
  2263  }
  2264  
  2265  /*
  2266   * constructors
  2267   */
  2268  
  2269  // implemented in package runtime
  2270  func unsafe_New(*rtype) unsafe.Pointer
  2271  func unsafe_NewArray(*rtype, int) unsafe.Pointer
  2272  
  2273  // MakeSlice creates a new zero-initialized slice value
  2274  // for the specified slice type, length, and capacity.
  2275  func MakeSlice(typ Type, len, cap int) Value {
  2276  	if typ.Kind() != Slice {
  2277  		panic("reflect.MakeSlice of non-slice type")
  2278  	}
  2279  	if len < 0 {
  2280  		panic("reflect.MakeSlice: negative len")
  2281  	}
  2282  	if cap < 0 {
  2283  		panic("reflect.MakeSlice: negative cap")
  2284  	}
  2285  	if len > cap {
  2286  		panic("reflect.MakeSlice: len > cap")
  2287  	}
  2288  
  2289  	s := unsafeheader.Slice{Data: unsafe_NewArray(typ.Elem().(*rtype), cap), Len: len, Cap: cap}
  2290  	return Value{typ.(*rtype), unsafe.Pointer(&s), flagIndir | flag(Slice)}
  2291  }
  2292  
  2293  // MakeChan creates a new channel with the specified type and buffer size.
  2294  func MakeChan(typ Type, buffer int) Value {
  2295  	if typ.Kind() != Chan {
  2296  		panic("reflect.MakeChan of non-chan type")
  2297  	}
  2298  	if buffer < 0 {
  2299  		panic("reflect.MakeChan: negative buffer size")
  2300  	}
  2301  	if typ.ChanDir() != BothDir {
  2302  		panic("reflect.MakeChan: unidirectional channel type")
  2303  	}
  2304  	t := typ.(*rtype)
  2305  	ch := makechan(t, buffer)
  2306  	return Value{t, ch, flag(Chan)}
  2307  }
  2308  
  2309  // MakeMap creates a new map with the specified type.
  2310  func MakeMap(typ Type) Value {
  2311  	return MakeMapWithSize(typ, 0)
  2312  }
  2313  
  2314  // MakeMapWithSize creates a new map with the specified type
  2315  // and initial space for approximately n elements.
  2316  func MakeMapWithSize(typ Type, n int) Value {
  2317  	if typ.Kind() != Map {
  2318  		panic("reflect.MakeMapWithSize of non-map type")
  2319  	}
  2320  	t := typ.(*rtype)
  2321  	m := makemap(t, n)
  2322  	return Value{t, m, flag(Map)}
  2323  }
  2324  
  2325  // Indirect returns the value that v points to.
  2326  // If v is a nil pointer, Indirect returns a zero Value.
  2327  // If v is not a pointer, Indirect returns v.
  2328  func Indirect(v Value) Value {
  2329  	if v.Kind() != Ptr {
  2330  		return v
  2331  	}
  2332  	return v.Elem()
  2333  }
  2334  
  2335  // ValueOf returns a new Value initialized to the concrete value
  2336  // stored in the interface i. ValueOf(nil) returns the zero Value.
  2337  func ValueOf(i interface{}) Value {
  2338  	if i == nil {
  2339  		return Value{}
  2340  	}
  2341  
  2342  	// TODO: Maybe allow contents of a Value to live on the stack.
  2343  	// For now we make the contents always escape to the heap. It
  2344  	// makes life easier in a few places (see chanrecv/mapassign
  2345  	// comment below).
  2346  	escapes(i)
  2347  
  2348  	return unpackEface(i)
  2349  }
  2350  
  2351  // Zero returns a Value representing the zero value for the specified type.
  2352  // The result is different from the zero value of the Value struct,
  2353  // which represents no value at all.
  2354  // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
  2355  // The returned value is neither addressable nor settable.
  2356  func Zero(typ Type) Value {
  2357  	if typ == nil {
  2358  		panic("reflect: Zero(nil)")
  2359  	}
  2360  	t := typ.(*rtype)
  2361  	fl := flag(t.Kind())
  2362  	if ifaceIndir(t) {
  2363  		return Value{t, unsafe_New(t), fl | flagIndir}
  2364  	}
  2365  	return Value{t, nil, fl}
  2366  }
  2367  
  2368  // New returns a Value representing a pointer to a new zero value
  2369  // for the specified type. That is, the returned Value's Type is PtrTo(typ).
  2370  func New(typ Type) Value {
  2371  	if typ == nil {
  2372  		panic("reflect: New(nil)")
  2373  	}
  2374  	t := typ.(*rtype)
  2375  	ptr := unsafe_New(t)
  2376  	fl := flag(Ptr)
  2377  	return Value{t.ptrTo(), ptr, fl}
  2378  }
  2379  
  2380  // NewAt returns a Value representing a pointer to a value of the
  2381  // specified type, using p as that pointer.
  2382  func NewAt(typ Type, p unsafe.Pointer) Value {
  2383  	fl := flag(Ptr)
  2384  	t := typ.(*rtype)
  2385  	return Value{t.ptrTo(), p, fl}
  2386  }
  2387  
  2388  // assignTo returns a value v that can be assigned directly to typ.
  2389  // It panics if v is not assignable to typ.
  2390  // For a conversion to an interface type, target is a suggested scratch space to use.
  2391  // target must be initialized memory (or nil).
  2392  func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value {
  2393  	if v.flag&flagMethod != 0 {
  2394  		v = makeMethodValue(context, v)
  2395  	}
  2396  
  2397  	switch {
  2398  	case directlyAssignable(dst, v.typ):
  2399  		// Overwrite type so that they match.
  2400  		// Same memory layout, so no harm done.
  2401  		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
  2402  		fl |= flag(dst.Kind())
  2403  		return Value{dst, v.ptr, fl}
  2404  
  2405  	case implements(dst, v.typ):
  2406  		if target == nil {
  2407  			target = unsafe_New(dst)
  2408  		}
  2409  		if v.Kind() == Interface && v.IsNil() {
  2410  			// A nil ReadWriter passed to nil Reader is OK,
  2411  			// but using ifaceE2I below will panic.
  2412  			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
  2413  			return Value{dst, nil, flag(Interface)}
  2414  		}
  2415  		x := valueInterface(v, false)
  2416  		if dst.NumMethod() == 0 {
  2417  			*(*interface{})(target) = x
  2418  		} else {
  2419  			ifaceE2I(dst, x, target)
  2420  		}
  2421  		return Value{dst, target, flagIndir | flag(Interface)}
  2422  	}
  2423  
  2424  	// Failed.
  2425  	panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
  2426  }
  2427  
  2428  // Convert returns the value v converted to type t.
  2429  // If the usual Go conversion rules do not allow conversion
  2430  // of the value v to type t, Convert panics.
  2431  func (v Value) Convert(t Type) Value {
  2432  	if v.flag&flagMethod != 0 {
  2433  		v = makeMethodValue("Convert", v)
  2434  	}
  2435  	op := convertOp(t.common(), v.typ)
  2436  	if op == nil {
  2437  		panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
  2438  	}
  2439  	return op(v, t)
  2440  }
  2441  
  2442  // convertOp returns the function to convert a value of type src
  2443  // to a value of type dst. If the conversion is illegal, convertOp returns nil.
  2444  func convertOp(dst, src *rtype) func(Value, Type) Value {
  2445  	switch src.Kind() {
  2446  	case Int, Int8, Int16, Int32, Int64:
  2447  		switch dst.Kind() {
  2448  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2449  			return cvtInt
  2450  		case Float32, Float64:
  2451  			return cvtIntFloat
  2452  		case String:
  2453  			return cvtIntString
  2454  		}
  2455  
  2456  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2457  		switch dst.Kind() {
  2458  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2459  			return cvtUint
  2460  		case Float32, Float64:
  2461  			return cvtUintFloat
  2462  		case String:
  2463  			return cvtUintString
  2464  		}
  2465  
  2466  	case Float32, Float64:
  2467  		switch dst.Kind() {
  2468  		case Int, Int8, Int16, Int32, Int64:
  2469  			return cvtFloatInt
  2470  		case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2471  			return cvtFloatUint
  2472  		case Float32, Float64:
  2473  			return cvtFloat
  2474  		}
  2475  
  2476  	case Complex64, Complex128:
  2477  		switch dst.Kind() {
  2478  		case Complex64, Complex128:
  2479  			return cvtComplex
  2480  		}
  2481  
  2482  	case String:
  2483  		if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
  2484  			switch dst.Elem().Kind() {
  2485  			case Uint8:
  2486  				return cvtStringBytes
  2487  			case Int32:
  2488  				return cvtStringRunes
  2489  			}
  2490  		}
  2491  
  2492  	case Slice:
  2493  		if dst.Kind() == String && src.Elem().PkgPath() == "" {
  2494  			switch src.Elem().Kind() {
  2495  			case Uint8:
  2496  				return cvtBytesString
  2497  			case Int32:
  2498  				return cvtRunesString
  2499  			}
  2500  		}
  2501  
  2502  	case Chan:
  2503  		if dst.Kind() == Chan && specialChannelAssignability(dst, src) {
  2504  			return cvtDirect
  2505  		}
  2506  	}
  2507  
  2508  	// dst and src have same underlying type.
  2509  	if haveIdenticalUnderlyingType(dst, src, false) {
  2510  		return cvtDirect
  2511  	}
  2512  
  2513  	// dst and src are non-defined pointer types with same underlying base type.
  2514  	if dst.Kind() == Ptr && dst.Name() == "" &&
  2515  		src.Kind() == Ptr && src.Name() == "" &&
  2516  		haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) {
  2517  		return cvtDirect
  2518  	}
  2519  
  2520  	if implements(dst, src) {
  2521  		if src.Kind() == Interface {
  2522  			return cvtI2I
  2523  		}
  2524  		return cvtT2I
  2525  	}
  2526  
  2527  	return nil
  2528  }
  2529  
  2530  // makeInt returns a Value of type t equal to bits (possibly truncated),
  2531  // where t is a signed or unsigned int type.
  2532  func makeInt(f flag, bits uint64, t Type) Value {
  2533  	typ := t.common()
  2534  	ptr := unsafe_New(typ)
  2535  	switch typ.size {
  2536  	case 1:
  2537  		*(*uint8)(ptr) = uint8(bits)
  2538  	case 2:
  2539  		*(*uint16)(ptr) = uint16(bits)
  2540  	case 4:
  2541  		*(*uint32)(ptr) = uint32(bits)
  2542  	case 8:
  2543  		*(*uint64)(ptr) = bits
  2544  	}
  2545  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2546  }
  2547  
  2548  // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
  2549  // where t is a float32 or float64 type.
  2550  func makeFloat(f flag, v float64, t Type) Value {
  2551  	typ := t.common()
  2552  	ptr := unsafe_New(typ)
  2553  	switch typ.size {
  2554  	case 4:
  2555  		*(*float32)(ptr) = float32(v)
  2556  	case 8:
  2557  		*(*float64)(ptr) = v
  2558  	}
  2559  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2560  }
  2561  
  2562  // makeFloat returns a Value of type t equal to v, where t is a float32 type.
  2563  func makeFloat32(f flag, v float32, t Type) Value {
  2564  	typ := t.common()
  2565  	ptr := unsafe_New(typ)
  2566  	*(*float32)(ptr) = v
  2567  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2568  }
  2569  
  2570  // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
  2571  // where t is a complex64 or complex128 type.
  2572  func makeComplex(f flag, v complex128, t Type) Value {
  2573  	typ := t.common()
  2574  	ptr := unsafe_New(typ)
  2575  	switch typ.size {
  2576  	case 8:
  2577  		*(*complex64)(ptr) = complex64(v)
  2578  	case 16:
  2579  		*(*complex128)(ptr) = v
  2580  	}
  2581  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2582  }
  2583  
  2584  func makeString(f flag, v string, t Type) Value {
  2585  	ret := New(t).Elem()
  2586  	ret.SetString(v)
  2587  	ret.flag = ret.flag&^flagAddr | f
  2588  	return ret
  2589  }
  2590  
  2591  func makeBytes(f flag, v []byte, t Type) Value {
  2592  	ret := New(t).Elem()
  2593  	ret.SetBytes(v)
  2594  	ret.flag = ret.flag&^flagAddr | f
  2595  	return ret
  2596  }
  2597  
  2598  func makeRunes(f flag, v []rune, t Type) Value {
  2599  	ret := New(t).Elem()
  2600  	ret.setRunes(v)
  2601  	ret.flag = ret.flag&^flagAddr | f
  2602  	return ret
  2603  }
  2604  
  2605  // These conversion functions are returned by convertOp
  2606  // for classes of conversions. For example, the first function, cvtInt,
  2607  // takes any value v of signed int type and returns the value converted
  2608  // to type t, where t is any signed or unsigned int type.
  2609  
  2610  // convertOp: intXX -> [u]intXX
  2611  func cvtInt(v Value, t Type) Value {
  2612  	return makeInt(v.flag.ro(), uint64(v.Int()), t)
  2613  }
  2614  
  2615  // convertOp: uintXX -> [u]intXX
  2616  func cvtUint(v Value, t Type) Value {
  2617  	return makeInt(v.flag.ro(), v.Uint(), t)
  2618  }
  2619  
  2620  // convertOp: floatXX -> intXX
  2621  func cvtFloatInt(v Value, t Type) Value {
  2622  	return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
  2623  }
  2624  
  2625  // convertOp: floatXX -> uintXX
  2626  func cvtFloatUint(v Value, t Type) Value {
  2627  	return makeInt(v.flag.ro(), uint64(v.Float()), t)
  2628  }
  2629  
  2630  // convertOp: intXX -> floatXX
  2631  func cvtIntFloat(v Value, t Type) Value {
  2632  	return makeFloat(v.flag.ro(), float64(v.Int()), t)
  2633  }
  2634  
  2635  // convertOp: uintXX -> floatXX
  2636  func cvtUintFloat(v Value, t Type) Value {
  2637  	return makeFloat(v.flag.ro(), float64(v.Uint()), t)
  2638  }
  2639  
  2640  // convertOp: floatXX -> floatXX
  2641  func cvtFloat(v Value, t Type) Value {
  2642  	if v.Type().Kind() == Float32 && t.Kind() == Float32 {
  2643  		// Don't do any conversion if both types have underlying type float32.
  2644  		// This avoids converting to float64 and back, which will
  2645  		// convert a signaling NaN to a quiet NaN. See issue 36400.
  2646  		return makeFloat32(v.flag.ro(), *(*float32)(v.ptr), t)
  2647  	}
  2648  	return makeFloat(v.flag.ro(), v.Float(), t)
  2649  }
  2650  
  2651  // convertOp: complexXX -> complexXX
  2652  func cvtComplex(v Value, t Type) Value {
  2653  	return makeComplex(v.flag.ro(), v.Complex(), t)
  2654  }
  2655  
  2656  // convertOp: intXX -> string
  2657  func cvtIntString(v Value, t Type) Value {
  2658  	return makeString(v.flag.ro(), string(rune(v.Int())), t)
  2659  }
  2660  
  2661  // convertOp: uintXX -> string
  2662  func cvtUintString(v Value, t Type) Value {
  2663  	return makeString(v.flag.ro(), string(rune(v.Uint())), t)
  2664  }
  2665  
  2666  // convertOp: []byte -> string
  2667  func cvtBytesString(v Value, t Type) Value {
  2668  	return makeString(v.flag.ro(), string(v.Bytes()), t)
  2669  }
  2670  
  2671  // convertOp: string -> []byte
  2672  func cvtStringBytes(v Value, t Type) Value {
  2673  	return makeBytes(v.flag.ro(), []byte(v.String()), t)
  2674  }
  2675  
  2676  // convertOp: []rune -> string
  2677  func cvtRunesString(v Value, t Type) Value {
  2678  	return makeString(v.flag.ro(), string(v.runes()), t)
  2679  }
  2680  
  2681  // convertOp: string -> []rune
  2682  func cvtStringRunes(v Value, t Type) Value {
  2683  	return makeRunes(v.flag.ro(), []rune(v.String()), t)
  2684  }
  2685  
  2686  // convertOp: direct copy
  2687  func cvtDirect(v Value, typ Type) Value {
  2688  	f := v.flag
  2689  	t := typ.common()
  2690  	ptr := v.ptr
  2691  	if f&flagAddr != 0 {
  2692  		// indirect, mutable word - make a copy
  2693  		c := unsafe_New(t)
  2694  		typedmemmove(t, c, ptr)
  2695  		ptr = c
  2696  		f &^= flagAddr
  2697  	}
  2698  	return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
  2699  }
  2700  
  2701  // convertOp: concrete -> interface
  2702  func cvtT2I(v Value, typ Type) Value {
  2703  	target := unsafe_New(typ.common())
  2704  	x := valueInterface(v, false)
  2705  	if typ.NumMethod() == 0 {
  2706  		*(*interface{})(target) = x
  2707  	} else {
  2708  		ifaceE2I(typ.(*rtype), x, target)
  2709  	}
  2710  	return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
  2711  }
  2712  
  2713  // convertOp: interface -> interface
  2714  func cvtI2I(v Value, typ Type) Value {
  2715  	if v.IsNil() {
  2716  		ret := Zero(typ)
  2717  		ret.flag |= v.flag.ro()
  2718  		return ret
  2719  	}
  2720  	return cvtT2I(v.Elem(), typ)
  2721  }
  2722  
  2723  // implemented in ../runtime
  2724  func chancap(ch unsafe.Pointer) int
  2725  func chanclose(ch unsafe.Pointer)
  2726  func chanlen(ch unsafe.Pointer) int
  2727  
  2728  // Note: some of the noescape annotations below are technically a lie,
  2729  // but safe in the context of this package. Functions like chansend
  2730  // and mapassign don't escape the referent, but may escape anything
  2731  // the referent points to (they do shallow copies of the referent).
  2732  // It is safe in this package because the referent may only point
  2733  // to something a Value may point to, and that is always in the heap
  2734  // (due to the escapes() call in ValueOf).
  2735  
  2736  //go:noescape
  2737  func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
  2738  
  2739  //go:noescape
  2740  func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
  2741  
  2742  func makechan(typ *rtype, size int) (ch unsafe.Pointer)
  2743  func makemap(t *rtype, cap int) (m unsafe.Pointer)
  2744  
  2745  //go:noescape
  2746  func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
  2747  
  2748  //go:noescape
  2749  func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
  2750  
  2751  //go:noescape
  2752  func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
  2753  
  2754  // m escapes into the return value, but the caller of mapiterinit
  2755  // doesn't let the return value escape.
  2756  //go:noescape
  2757  func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
  2758  
  2759  //go:noescape
  2760  func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
  2761  
  2762  //go:noescape
  2763  func mapiterelem(it unsafe.Pointer) (elem unsafe.Pointer)
  2764  
  2765  //go:noescape
  2766  func mapiternext(it unsafe.Pointer)
  2767  
  2768  //go:noescape
  2769  func maplen(m unsafe.Pointer) int
  2770  
  2771  // call calls fn with a copy of the n argument bytes pointed at by arg.
  2772  // After fn returns, reflectcall copies n-retoffset result bytes
  2773  // back into arg+retoffset before returning. If copying result bytes back,
  2774  // the caller must pass the argument frame type as argtype, so that
  2775  // call can execute appropriate write barriers during the copy.
  2776  //
  2777  //go:linkname call runtime.reflectcall
  2778  func call(argtype *rtype, fn, arg unsafe.Pointer, n uint32, retoffset uint32)
  2779  
  2780  func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
  2781  
  2782  // memmove copies size bytes to dst from src. No write barriers are used.
  2783  //go:noescape
  2784  func memmove(dst, src unsafe.Pointer, size uintptr)
  2785  
  2786  // typedmemmove copies a value of type t to dst from src.
  2787  //go:noescape
  2788  func typedmemmove(t *rtype, dst, src unsafe.Pointer)
  2789  
  2790  // typedmemmovepartial is like typedmemmove but assumes that
  2791  // dst and src point off bytes into the value and only copies size bytes.
  2792  //go:noescape
  2793  func typedmemmovepartial(t *rtype, dst, src unsafe.Pointer, off, size uintptr)
  2794  
  2795  // typedmemclr zeros the value at ptr of type t.
  2796  //go:noescape
  2797  func typedmemclr(t *rtype, ptr unsafe.Pointer)
  2798  
  2799  // typedmemclrpartial is like typedmemclr but assumes that
  2800  // dst points off bytes into the value and only clears size bytes.
  2801  //go:noescape
  2802  func typedmemclrpartial(t *rtype, ptr unsafe.Pointer, off, size uintptr)
  2803  
  2804  // typedslicecopy copies a slice of elemType values from src to dst,
  2805  // returning the number of elements copied.
  2806  //go:noescape
  2807  func typedslicecopy(elemType *rtype, dst, src unsafeheader.Slice) int
  2808  
  2809  //go:noescape
  2810  func typehash(t *rtype, p unsafe.Pointer, h uintptr) uintptr
  2811  
  2812  // Dummy annotation marking that the value x escapes,
  2813  // for use in cases where the reflect code is so clever that
  2814  // the compiler cannot follow.
  2815  func escapes(x interface{}) {
  2816  	if dummy.b {
  2817  		dummy.x = x
  2818  	}
  2819  }
  2820  
  2821  var dummy struct {
  2822  	b bool
  2823  	x interface{}
  2824  }
  2825  

View as plain text