github.com/goplus/xtypes@v0.2.1/internal/reflect/value.go (about)

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