Source file src/reflect/value.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package reflect
     6  
     7  import (
     8  	"errors"
     9  	"internal/abi"
    10  	"internal/goarch"
    11  	"internal/itoa"
    12  	"internal/unsafeheader"
    13  	"math"
    14  	"runtime"
    15  	"unsafe"
    16  )
    17  
    18  // Value is the reflection interface to a Go value.
    19  //
    20  // Not all methods apply to all kinds of values. Restrictions,
    21  // if any, are noted in the documentation for each method.
    22  // Use the Kind method to find out the kind of value before
    23  // calling kind-specific methods. Calling a method
    24  // inappropriate to the kind of type causes a run time panic.
    25  //
    26  // The zero Value represents no value.
    27  // Its IsValid method returns false, its Kind method returns Invalid,
    28  // its String method returns "<invalid Value>", and all other methods panic.
    29  // Most functions and methods never return an invalid value.
    30  // If one does, its documentation states the conditions explicitly.
    31  //
    32  // A Value can be used concurrently by multiple goroutines provided that
    33  // the underlying Go value can be used concurrently for the equivalent
    34  // direct operations.
    35  //
    36  // To compare two Values, compare the results of the Interface method.
    37  // Using == on two Values does not compare the underlying values
    38  // they represent.
    39  type Value struct {
    40  	// typ_ holds the type of the value represented by a Value.
    41  	// Access using the typ method to avoid escape of v.
    42  	typ_ *abi.Type
    43  
    44  	// Pointer-valued data or, if flagIndir is set, pointer to data.
    45  	// Valid when either flagIndir is set or typ.pointers() is true.
    46  	ptr unsafe.Pointer
    47  
    48  	// flag holds metadata about the value.
    49  	//
    50  	// The lowest five bits give the Kind of the value, mirroring typ.Kind().
    51  	//
    52  	// The next set of bits are flag bits:
    53  	//	- flagStickyRO: obtained via unexported not embedded field, so read-only
    54  	//	- flagEmbedRO: obtained via unexported embedded field, so read-only
    55  	//	- flagIndir: val holds a pointer to the data
    56  	//	- flagAddr: v.CanAddr is true (implies flagIndir and ptr is non-nil)
    57  	//	- flagMethod: v is a method value.
    58  	// If ifaceIndir(typ), code can assume that flagIndir is set.
    59  	//
    60  	// The remaining 22+ bits give a method number for method values.
    61  	// If flag.kind() != Func, code can assume that flagMethod is unset.
    62  	flag
    63  
    64  	// A method value represents a curried method invocation
    65  	// like r.Read for some receiver r. The typ+val+flag bits describe
    66  	// the receiver r, but the flag's Kind bits say Func (methods are
    67  	// functions), and the top bits of the flag give the method number
    68  	// in r's type's method table.
    69  }
    70  
    71  type flag uintptr
    72  
    73  const (
    74  	flagKindWidth        = 5 // there are 27 kinds
    75  	flagKindMask    flag = 1<<flagKindWidth - 1
    76  	flagStickyRO    flag = 1 << 5
    77  	flagEmbedRO     flag = 1 << 6
    78  	flagIndir       flag = 1 << 7
    79  	flagAddr        flag = 1 << 8
    80  	flagMethod      flag = 1 << 9
    81  	flagMethodShift      = 10
    82  	flagRO          flag = flagStickyRO | flagEmbedRO
    83  )
    84  
    85  func (f flag) kind() Kind {
    86  	return Kind(f & flagKindMask)
    87  }
    88  
    89  func (f flag) ro() flag {
    90  	if f&flagRO != 0 {
    91  		return flagStickyRO
    92  	}
    93  	return 0
    94  }
    95  
    96  func (v Value) typ() *abi.Type {
    97  	// Types are either static (for compiler-created types) or
    98  	// heap-allocated but always reachable (for reflection-created
    99  	// types, held in the central map). So there is no need to
   100  	// escape types. noescape here help avoid unnecessary escape
   101  	// of v.
   102  	return (*abi.Type)(noescape(unsafe.Pointer(v.typ_)))
   103  }
   104  
   105  // pointer returns the underlying pointer represented by v.
   106  // v.Kind() must be Pointer, Map, Chan, Func, or UnsafePointer
   107  // if v.Kind() == Pointer, the base type must not be not-in-heap.
   108  func (v Value) pointer() unsafe.Pointer {
   109  	if v.typ().Size() != goarch.PtrSize || !v.typ().Pointers() {
   110  		panic("can't call pointer on a non-pointer Value")
   111  	}
   112  	if v.flag&flagIndir != 0 {
   113  		return *(*unsafe.Pointer)(v.ptr)
   114  	}
   115  	return v.ptr
   116  }
   117  
   118  // packEface converts v to the empty interface.
   119  func packEface(v Value) any {
   120  	t := v.typ()
   121  	var i any
   122  	e := (*emptyInterface)(unsafe.Pointer(&i))
   123  	// First, fill in the data portion of the interface.
   124  	switch {
   125  	case t.IfaceIndir():
   126  		if v.flag&flagIndir == 0 {
   127  			panic("bad indir")
   128  		}
   129  		// Value is indirect, and so is the interface we're making.
   130  		ptr := v.ptr
   131  		if v.flag&flagAddr != 0 {
   132  			// TODO: pass safe boolean from valueInterface so
   133  			// we don't need to copy if safe==true?
   134  			c := unsafe_New(t)
   135  			typedmemmove(t, c, ptr)
   136  			ptr = c
   137  		}
   138  		e.word = ptr
   139  	case v.flag&flagIndir != 0:
   140  		// Value is indirect, but interface is direct. We need
   141  		// to load the data at v.ptr into the interface data word.
   142  		e.word = *(*unsafe.Pointer)(v.ptr)
   143  	default:
   144  		// Value is direct, and so is the interface.
   145  		e.word = v.ptr
   146  	}
   147  	// Now, fill in the type portion. We're very careful here not
   148  	// to have any operation between the e.word and e.typ assignments
   149  	// that would let the garbage collector observe the partially-built
   150  	// interface value.
   151  	e.typ = t
   152  	return i
   153  }
   154  
   155  // unpackEface converts the empty interface i to a Value.
   156  func unpackEface(i any) Value {
   157  	e := (*emptyInterface)(unsafe.Pointer(&i))
   158  	// NOTE: don't read e.word until we know whether it is really a pointer or not.
   159  	t := e.typ
   160  	if t == nil {
   161  		return Value{}
   162  	}
   163  	f := flag(t.Kind())
   164  	if t.IfaceIndir() {
   165  		f |= flagIndir
   166  	}
   167  	return Value{t, e.word, f}
   168  }
   169  
   170  // A ValueError occurs when a Value method is invoked on
   171  // a Value that does not support it. Such cases are documented
   172  // in the description of each method.
   173  type ValueError struct {
   174  	Method string
   175  	Kind   Kind
   176  }
   177  
   178  func (e *ValueError) Error() string {
   179  	if e.Kind == 0 {
   180  		return "reflect: call of " + e.Method + " on zero Value"
   181  	}
   182  	return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
   183  }
   184  
   185  // valueMethodName returns the name of the exported calling method on Value.
   186  func valueMethodName() string {
   187  	var pc [5]uintptr
   188  	n := runtime.Callers(1, pc[:])
   189  	frames := runtime.CallersFrames(pc[:n])
   190  	var frame runtime.Frame
   191  	for more := true; more; {
   192  		const prefix = "reflect.Value."
   193  		frame, more = frames.Next()
   194  		name := frame.Function
   195  		if len(name) > len(prefix) && name[:len(prefix)] == prefix {
   196  			methodName := name[len(prefix):]
   197  			if len(methodName) > 0 && 'A' <= methodName[0] && methodName[0] <= 'Z' {
   198  				return name
   199  			}
   200  		}
   201  	}
   202  	return "unknown method"
   203  }
   204  
   205  // emptyInterface is the header for an interface{} value.
   206  type emptyInterface struct {
   207  	typ  *abi.Type
   208  	word unsafe.Pointer
   209  }
   210  
   211  // nonEmptyInterface is the header for an interface value with methods.
   212  type nonEmptyInterface struct {
   213  	// see ../runtime/iface.go:/Itab
   214  	itab *struct {
   215  		ityp *abi.Type // static interface type
   216  		typ  *abi.Type // dynamic concrete type
   217  		hash uint32    // copy of typ.hash
   218  		_    [4]byte
   219  		fun  [100000]unsafe.Pointer // method table
   220  	}
   221  	word unsafe.Pointer
   222  }
   223  
   224  // mustBe panics if f's kind is not expected.
   225  // Making this a method on flag instead of on Value
   226  // (and embedding flag in Value) means that we can write
   227  // the very clear v.mustBe(Bool) and have it compile into
   228  // v.flag.mustBe(Bool), which will only bother to copy the
   229  // single important word for the receiver.
   230  func (f flag) mustBe(expected Kind) {
   231  	// TODO(mvdan): use f.kind() again once mid-stack inlining gets better
   232  	if Kind(f&flagKindMask) != expected {
   233  		panic(&ValueError{valueMethodName(), f.kind()})
   234  	}
   235  }
   236  
   237  // mustBeExported panics if f records that the value was obtained using
   238  // an unexported field.
   239  func (f flag) mustBeExported() {
   240  	if f == 0 || f&flagRO != 0 {
   241  		f.mustBeExportedSlow()
   242  	}
   243  }
   244  
   245  func (f flag) mustBeExportedSlow() {
   246  	if f == 0 {
   247  		panic(&ValueError{valueMethodName(), Invalid})
   248  	}
   249  	if f&flagRO != 0 {
   250  		panic("reflect: " + valueMethodName() + " using value obtained using unexported field")
   251  	}
   252  }
   253  
   254  // mustBeAssignable panics if f records that the value is not assignable,
   255  // which is to say that either it was obtained using an unexported field
   256  // or it is not addressable.
   257  func (f flag) mustBeAssignable() {
   258  	if f&flagRO != 0 || f&flagAddr == 0 {
   259  		f.mustBeAssignableSlow()
   260  	}
   261  }
   262  
   263  func (f flag) mustBeAssignableSlow() {
   264  	if f == 0 {
   265  		panic(&ValueError{valueMethodName(), Invalid})
   266  	}
   267  	// Assignable if addressable and not read-only.
   268  	if f&flagRO != 0 {
   269  		panic("reflect: " + valueMethodName() + " using value obtained using unexported field")
   270  	}
   271  	if f&flagAddr == 0 {
   272  		panic("reflect: " + valueMethodName() + " using unaddressable value")
   273  	}
   274  }
   275  
   276  // Addr returns a pointer value representing the address of v.
   277  // It panics if CanAddr() returns false.
   278  // Addr is typically used to obtain a pointer to a struct field
   279  // or slice element in order to call a method that requires a
   280  // pointer receiver.
   281  func (v Value) Addr() Value {
   282  	if v.flag&flagAddr == 0 {
   283  		panic("reflect.Value.Addr of unaddressable value")
   284  	}
   285  	// Preserve flagRO instead of using v.flag.ro() so that
   286  	// v.Addr().Elem() is equivalent to v (#32772)
   287  	fl := v.flag & flagRO
   288  	return Value{ptrTo(v.typ()), v.ptr, fl | flag(Pointer)}
   289  }
   290  
   291  // Bool returns v's underlying value.
   292  // It panics if v's kind is not Bool.
   293  func (v Value) Bool() bool {
   294  	// panicNotBool is split out to keep Bool inlineable.
   295  	if v.kind() != Bool {
   296  		v.panicNotBool()
   297  	}
   298  	return *(*bool)(v.ptr)
   299  }
   300  
   301  func (v Value) panicNotBool() {
   302  	v.mustBe(Bool)
   303  }
   304  
   305  var bytesType = rtypeOf(([]byte)(nil))
   306  
   307  // Bytes returns v's underlying value.
   308  // It panics if v's underlying value is not a slice of bytes or
   309  // an addressable array of bytes.
   310  func (v Value) Bytes() []byte {
   311  	// bytesSlow is split out to keep Bytes inlineable for unnamed []byte.
   312  	if v.typ_ == bytesType { // ok to use v.typ_ directly as comparison doesn't cause escape
   313  		return *(*[]byte)(v.ptr)
   314  	}
   315  	return v.bytesSlow()
   316  }
   317  
   318  func (v Value) bytesSlow() []byte {
   319  	switch v.kind() {
   320  	case Slice:
   321  		if v.typ().Elem().Kind() != abi.Uint8 {
   322  			panic("reflect.Value.Bytes of non-byte slice")
   323  		}
   324  		// Slice is always bigger than a word; assume flagIndir.
   325  		return *(*[]byte)(v.ptr)
   326  	case Array:
   327  		if v.typ().Elem().Kind() != abi.Uint8 {
   328  			panic("reflect.Value.Bytes of non-byte array")
   329  		}
   330  		if !v.CanAddr() {
   331  			panic("reflect.Value.Bytes of unaddressable byte array")
   332  		}
   333  		p := (*byte)(v.ptr)
   334  		n := int((*arrayType)(unsafe.Pointer(v.typ())).Len)
   335  		return unsafe.Slice(p, n)
   336  	}
   337  	panic(&ValueError{"reflect.Value.Bytes", v.kind()})
   338  }
   339  
   340  // runes returns v's underlying value.
   341  // It panics if v's underlying value is not a slice of runes (int32s).
   342  func (v Value) runes() []rune {
   343  	v.mustBe(Slice)
   344  	if v.typ().Elem().Kind() != abi.Int32 {
   345  		panic("reflect.Value.Bytes of non-rune slice")
   346  	}
   347  	// Slice is always bigger than a word; assume flagIndir.
   348  	return *(*[]rune)(v.ptr)
   349  }
   350  
   351  // CanAddr reports whether the value's address can be obtained with Addr.
   352  // Such values are called addressable. A value is addressable if it is
   353  // an element of a slice, an element of an addressable array,
   354  // a field of an addressable struct, or the result of dereferencing a pointer.
   355  // If CanAddr returns false, calling Addr will panic.
   356  func (v Value) CanAddr() bool {
   357  	return v.flag&flagAddr != 0
   358  }
   359  
   360  // CanSet reports whether the value of v can be changed.
   361  // A Value can be changed only if it is addressable and was not
   362  // obtained by the use of unexported struct fields.
   363  // If CanSet returns false, calling Set or any type-specific
   364  // setter (e.g., SetBool, SetInt) will panic.
   365  func (v Value) CanSet() bool {
   366  	return v.flag&(flagAddr|flagRO) == flagAddr
   367  }
   368  
   369  // Call calls the function v with the input arguments in.
   370  // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
   371  // Call panics if v's Kind is not Func.
   372  // It returns the output results as Values.
   373  // As in Go, each input argument must be assignable to the
   374  // type of the function's corresponding input parameter.
   375  // If v is a variadic function, Call creates the variadic slice parameter
   376  // itself, copying in the corresponding values.
   377  func (v Value) Call(in []Value) []Value {
   378  	v.mustBe(Func)
   379  	v.mustBeExported()
   380  	return v.call("Call", in)
   381  }
   382  
   383  // CallSlice calls the variadic function v with the input arguments in,
   384  // assigning the slice in[len(in)-1] to v's final variadic argument.
   385  // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
   386  // CallSlice panics if v's Kind is not Func or if v is not variadic.
   387  // It returns the output results as Values.
   388  // As in Go, each input argument must be assignable to the
   389  // type of the function's corresponding input parameter.
   390  func (v Value) CallSlice(in []Value) []Value {
   391  	v.mustBe(Func)
   392  	v.mustBeExported()
   393  	return v.call("CallSlice", in)
   394  }
   395  
   396  var callGC bool // for testing; see TestCallMethodJump and TestCallArgLive
   397  
   398  const debugReflectCall = false
   399  
   400  func (v Value) call(op string, in []Value) []Value {
   401  	// Get function pointer, type.
   402  	t := (*funcType)(unsafe.Pointer(v.typ()))
   403  	var (
   404  		fn       unsafe.Pointer
   405  		rcvr     Value
   406  		rcvrtype *abi.Type
   407  	)
   408  	if v.flag&flagMethod != 0 {
   409  		rcvr = v
   410  		rcvrtype, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
   411  	} else if v.flag&flagIndir != 0 {
   412  		fn = *(*unsafe.Pointer)(v.ptr)
   413  	} else {
   414  		fn = v.ptr
   415  	}
   416  
   417  	if fn == nil {
   418  		panic("reflect.Value.Call: call of nil function")
   419  	}
   420  
   421  	isSlice := op == "CallSlice"
   422  	n := t.NumIn()
   423  	isVariadic := t.IsVariadic()
   424  	if isSlice {
   425  		if !isVariadic {
   426  			panic("reflect: CallSlice of non-variadic function")
   427  		}
   428  		if len(in) < n {
   429  			panic("reflect: CallSlice with too few input arguments")
   430  		}
   431  		if len(in) > n {
   432  			panic("reflect: CallSlice with too many input arguments")
   433  		}
   434  	} else {
   435  		if isVariadic {
   436  			n--
   437  		}
   438  		if len(in) < n {
   439  			panic("reflect: Call with too few input arguments")
   440  		}
   441  		if !isVariadic && len(in) > n {
   442  			panic("reflect: Call with too many input arguments")
   443  		}
   444  	}
   445  	for _, x := range in {
   446  		if x.Kind() == Invalid {
   447  			panic("reflect: " + op + " using zero Value argument")
   448  		}
   449  	}
   450  	for i := 0; i < n; i++ {
   451  		if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(toRType(targ)) {
   452  			panic("reflect: " + op + " using " + xt.String() + " as type " + stringFor(targ))
   453  		}
   454  	}
   455  	if !isSlice && isVariadic {
   456  		// prepare slice for remaining values
   457  		m := len(in) - n
   458  		slice := MakeSlice(toRType(t.In(n)), m, m)
   459  		elem := toRType(t.In(n)).Elem() // FIXME cast to slice type and Elem()
   460  		for i := 0; i < m; i++ {
   461  			x := in[n+i]
   462  			if xt := x.Type(); !xt.AssignableTo(elem) {
   463  				panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
   464  			}
   465  			slice.Index(i).Set(x)
   466  		}
   467  		origIn := in
   468  		in = make([]Value, n+1)
   469  		copy(in[:n], origIn)
   470  		in[n] = slice
   471  	}
   472  
   473  	nin := len(in)
   474  	if nin != t.NumIn() {
   475  		panic("reflect.Value.Call: wrong argument count")
   476  	}
   477  	nout := t.NumOut()
   478  
   479  	// Register argument space.
   480  	var regArgs abi.RegArgs
   481  
   482  	// Compute frame type.
   483  	frametype, framePool, abid := funcLayout(t, rcvrtype)
   484  
   485  	// Allocate a chunk of memory for frame if needed.
   486  	var stackArgs unsafe.Pointer
   487  	if frametype.Size() != 0 {
   488  		if nout == 0 {
   489  			stackArgs = framePool.Get().(unsafe.Pointer)
   490  		} else {
   491  			// Can't use pool if the function has return values.
   492  			// We will leak pointer to args in ret, so its lifetime is not scoped.
   493  			stackArgs = unsafe_New(frametype)
   494  		}
   495  	}
   496  	frameSize := frametype.Size()
   497  
   498  	if debugReflectCall {
   499  		println("reflect.call", stringFor(&t.Type))
   500  		abid.dump()
   501  	}
   502  
   503  	// Copy inputs into args.
   504  
   505  	// Handle receiver.
   506  	inStart := 0
   507  	if rcvrtype != nil {
   508  		// Guaranteed to only be one word in size,
   509  		// so it will only take up exactly 1 abiStep (either
   510  		// in a register or on the stack).
   511  		switch st := abid.call.steps[0]; st.kind {
   512  		case abiStepStack:
   513  			storeRcvr(rcvr, stackArgs)
   514  		case abiStepPointer:
   515  			storeRcvr(rcvr, unsafe.Pointer(&regArgs.Ptrs[st.ireg]))
   516  			fallthrough
   517  		case abiStepIntReg:
   518  			storeRcvr(rcvr, unsafe.Pointer(&regArgs.Ints[st.ireg]))
   519  		case abiStepFloatReg:
   520  			storeRcvr(rcvr, unsafe.Pointer(&regArgs.Floats[st.freg]))
   521  		default:
   522  			panic("unknown ABI parameter kind")
   523  		}
   524  		inStart = 1
   525  	}
   526  
   527  	// Handle arguments.
   528  	for i, v := range in {
   529  		v.mustBeExported()
   530  		targ := toRType(t.In(i))
   531  		// TODO(mknyszek): Figure out if it's possible to get some
   532  		// scratch space for this assignment check. Previously, it
   533  		// was possible to use space in the argument frame.
   534  		v = v.assignTo("reflect.Value.Call", &targ.t, nil)
   535  	stepsLoop:
   536  		for _, st := range abid.call.stepsForValue(i + inStart) {
   537  			switch st.kind {
   538  			case abiStepStack:
   539  				// Copy values to the "stack."
   540  				addr := add(stackArgs, st.stkOff, "precomputed stack arg offset")
   541  				if v.flag&flagIndir != 0 {
   542  					typedmemmove(&targ.t, addr, v.ptr)
   543  				} else {
   544  					*(*unsafe.Pointer)(addr) = v.ptr
   545  				}
   546  				// There's only one step for a stack-allocated value.
   547  				break stepsLoop
   548  			case abiStepIntReg, abiStepPointer:
   549  				// Copy values to "integer registers."
   550  				if v.flag&flagIndir != 0 {
   551  					offset := add(v.ptr, st.offset, "precomputed value offset")
   552  					if st.kind == abiStepPointer {
   553  						// Duplicate this pointer in the pointer area of the
   554  						// register space. Otherwise, there's the potential for
   555  						// this to be the last reference to v.ptr.
   556  						regArgs.Ptrs[st.ireg] = *(*unsafe.Pointer)(offset)
   557  					}
   558  					intToReg(&regArgs, st.ireg, st.size, offset)
   559  				} else {
   560  					if st.kind == abiStepPointer {
   561  						// See the comment in abiStepPointer case above.
   562  						regArgs.Ptrs[st.ireg] = v.ptr
   563  					}
   564  					regArgs.Ints[st.ireg] = uintptr(v.ptr)
   565  				}
   566  			case abiStepFloatReg:
   567  				// Copy values to "float registers."
   568  				if v.flag&flagIndir == 0 {
   569  					panic("attempted to copy pointer to FP register")
   570  				}
   571  				offset := add(v.ptr, st.offset, "precomputed value offset")
   572  				floatToReg(&regArgs, st.freg, st.size, offset)
   573  			default:
   574  				panic("unknown ABI part kind")
   575  			}
   576  		}
   577  	}
   578  	// TODO(mknyszek): Remove this when we no longer have
   579  	// caller reserved spill space.
   580  	frameSize = align(frameSize, goarch.PtrSize)
   581  	frameSize += abid.spill
   582  
   583  	// Mark pointers in registers for the return path.
   584  	regArgs.ReturnIsPtr = abid.outRegPtrs
   585  
   586  	if debugReflectCall {
   587  		regArgs.Dump()
   588  	}
   589  
   590  	// For testing; see TestCallArgLive.
   591  	if callGC {
   592  		runtime.GC()
   593  	}
   594  
   595  	// Call.
   596  	call(frametype, fn, stackArgs, uint32(frametype.Size()), uint32(abid.retOffset), uint32(frameSize), &regArgs)
   597  
   598  	// For testing; see TestCallMethodJump.
   599  	if callGC {
   600  		runtime.GC()
   601  	}
   602  
   603  	var ret []Value
   604  	if nout == 0 {
   605  		if stackArgs != nil {
   606  			typedmemclr(frametype, stackArgs)
   607  			framePool.Put(stackArgs)
   608  		}
   609  	} else {
   610  		if stackArgs != nil {
   611  			// Zero the now unused input area of args,
   612  			// because the Values returned by this function contain pointers to the args object,
   613  			// and will thus keep the args object alive indefinitely.
   614  			typedmemclrpartial(frametype, stackArgs, 0, abid.retOffset)
   615  		}
   616  
   617  		// Wrap Values around return values in args.
   618  		ret = make([]Value, nout)
   619  		for i := 0; i < nout; i++ {
   620  			tv := t.Out(i)
   621  			if tv.Size() == 0 {
   622  				// For zero-sized return value, args+off may point to the next object.
   623  				// In this case, return the zero value instead.
   624  				ret[i] = Zero(toRType(tv))
   625  				continue
   626  			}
   627  			steps := abid.ret.stepsForValue(i)
   628  			if st := steps[0]; st.kind == abiStepStack {
   629  				// This value is on the stack. If part of a value is stack
   630  				// allocated, the entire value is according to the ABI. So
   631  				// just make an indirection into the allocated frame.
   632  				fl := flagIndir | flag(tv.Kind())
   633  				ret[i] = Value{tv, add(stackArgs, st.stkOff, "tv.Size() != 0"), fl}
   634  				// Note: this does introduce false sharing between results -
   635  				// if any result is live, they are all live.
   636  				// (And the space for the args is live as well, but as we've
   637  				// cleared that space it isn't as big a deal.)
   638  				continue
   639  			}
   640  
   641  			// Handle pointers passed in registers.
   642  			if !ifaceIndir(tv) {
   643  				// Pointer-valued data gets put directly
   644  				// into v.ptr.
   645  				if steps[0].kind != abiStepPointer {
   646  					print("kind=", steps[0].kind, ", type=", stringFor(tv), "\n")
   647  					panic("mismatch between ABI description and types")
   648  				}
   649  				ret[i] = Value{tv, regArgs.Ptrs[steps[0].ireg], flag(tv.Kind())}
   650  				continue
   651  			}
   652  
   653  			// All that's left is values passed in registers that we need to
   654  			// create space for and copy values back into.
   655  			//
   656  			// TODO(mknyszek): We make a new allocation for each register-allocated
   657  			// value, but previously we could always point into the heap-allocated
   658  			// stack frame. This is a regression that could be fixed by adding
   659  			// additional space to the allocated stack frame and storing the
   660  			// register-allocated return values into the allocated stack frame and
   661  			// referring there in the resulting Value.
   662  			s := unsafe_New(tv)
   663  			for _, st := range steps {
   664  				switch st.kind {
   665  				case abiStepIntReg:
   666  					offset := add(s, st.offset, "precomputed value offset")
   667  					intFromReg(&regArgs, st.ireg, st.size, offset)
   668  				case abiStepPointer:
   669  					s := add(s, st.offset, "precomputed value offset")
   670  					*((*unsafe.Pointer)(s)) = regArgs.Ptrs[st.ireg]
   671  				case abiStepFloatReg:
   672  					offset := add(s, st.offset, "precomputed value offset")
   673  					floatFromReg(&regArgs, st.freg, st.size, offset)
   674  				case abiStepStack:
   675  					panic("register-based return value has stack component")
   676  				default:
   677  					panic("unknown ABI part kind")
   678  				}
   679  			}
   680  			ret[i] = Value{tv, s, flagIndir | flag(tv.Kind())}
   681  		}
   682  	}
   683  
   684  	return ret
   685  }
   686  
   687  // callReflect is the call implementation used by a function
   688  // returned by MakeFunc. In many ways it is the opposite of the
   689  // method Value.call above. The method above converts a call using Values
   690  // into a call of a function with a concrete argument frame, while
   691  // callReflect converts a call of a function with a concrete argument
   692  // frame into a call using Values.
   693  // It is in this file so that it can be next to the call method above.
   694  // The remainder of the MakeFunc implementation is in makefunc.go.
   695  //
   696  // NOTE: This function must be marked as a "wrapper" in the generated code,
   697  // so that the linker can make it work correctly for panic and recover.
   698  // The gc compilers know to do that for the name "reflect.callReflect".
   699  //
   700  // ctxt is the "closure" generated by MakeFunc.
   701  // frame is a pointer to the arguments to that closure on the stack.
   702  // retValid points to a boolean which should be set when the results
   703  // section of frame is set.
   704  //
   705  // regs contains the argument values passed in registers and will contain
   706  // the values returned from ctxt.fn in registers.
   707  func callReflect(ctxt *makeFuncImpl, frame unsafe.Pointer, retValid *bool, regs *abi.RegArgs) {
   708  	if callGC {
   709  		// Call GC upon entry during testing.
   710  		// Getting our stack scanned here is the biggest hazard, because
   711  		// our caller (makeFuncStub) could have failed to place the last
   712  		// pointer to a value in regs' pointer space, in which case it
   713  		// won't be visible to the GC.
   714  		runtime.GC()
   715  	}
   716  	ftyp := ctxt.ftyp
   717  	f := ctxt.fn
   718  
   719  	_, _, abid := funcLayout(ftyp, nil)
   720  
   721  	// Copy arguments into Values.
   722  	ptr := frame
   723  	in := make([]Value, 0, int(ftyp.InCount))
   724  	for i, typ := range ftyp.InSlice() {
   725  		if typ.Size() == 0 {
   726  			in = append(in, Zero(toRType(typ)))
   727  			continue
   728  		}
   729  		v := Value{typ, nil, flag(typ.Kind())}
   730  		steps := abid.call.stepsForValue(i)
   731  		if st := steps[0]; st.kind == abiStepStack {
   732  			if ifaceIndir(typ) {
   733  				// value cannot be inlined in interface data.
   734  				// Must make a copy, because f might keep a reference to it,
   735  				// and we cannot let f keep a reference to the stack frame
   736  				// after this function returns, not even a read-only reference.
   737  				v.ptr = unsafe_New(typ)
   738  				if typ.Size() > 0 {
   739  					typedmemmove(typ, v.ptr, add(ptr, st.stkOff, "typ.size > 0"))
   740  				}
   741  				v.flag |= flagIndir
   742  			} else {
   743  				v.ptr = *(*unsafe.Pointer)(add(ptr, st.stkOff, "1-ptr"))
   744  			}
   745  		} else {
   746  			if ifaceIndir(typ) {
   747  				// All that's left is values passed in registers that we need to
   748  				// create space for the values.
   749  				v.flag |= flagIndir
   750  				v.ptr = unsafe_New(typ)
   751  				for _, st := range steps {
   752  					switch st.kind {
   753  					case abiStepIntReg:
   754  						offset := add(v.ptr, st.offset, "precomputed value offset")
   755  						intFromReg(regs, st.ireg, st.size, offset)
   756  					case abiStepPointer:
   757  						s := add(v.ptr, st.offset, "precomputed value offset")
   758  						*((*unsafe.Pointer)(s)) = regs.Ptrs[st.ireg]
   759  					case abiStepFloatReg:
   760  						offset := add(v.ptr, st.offset, "precomputed value offset")
   761  						floatFromReg(regs, st.freg, st.size, offset)
   762  					case abiStepStack:
   763  						panic("register-based return value has stack component")
   764  					default:
   765  						panic("unknown ABI part kind")
   766  					}
   767  				}
   768  			} else {
   769  				// Pointer-valued data gets put directly
   770  				// into v.ptr.
   771  				if steps[0].kind != abiStepPointer {
   772  					print("kind=", steps[0].kind, ", type=", stringFor(typ), "\n")
   773  					panic("mismatch between ABI description and types")
   774  				}
   775  				v.ptr = regs.Ptrs[steps[0].ireg]
   776  			}
   777  		}
   778  		in = append(in, v)
   779  	}
   780  
   781  	// Call underlying function.
   782  	out := f(in)
   783  	numOut := ftyp.NumOut()
   784  	if len(out) != numOut {
   785  		panic("reflect: wrong return count from function created by MakeFunc")
   786  	}
   787  
   788  	// Copy results back into argument frame and register space.
   789  	if numOut > 0 {
   790  		for i, typ := range ftyp.OutSlice() {
   791  			v := out[i]
   792  			if v.typ() == nil {
   793  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   794  					" returned zero Value")
   795  			}
   796  			if v.flag&flagRO != 0 {
   797  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   798  					" returned value obtained from unexported field")
   799  			}
   800  			if typ.Size() == 0 {
   801  				continue
   802  			}
   803  
   804  			// Convert v to type typ if v is assignable to a variable
   805  			// of type t in the language spec.
   806  			// See issue 28761.
   807  			//
   808  			//
   809  			// TODO(mknyszek): In the switch to the register ABI we lost
   810  			// the scratch space here for the register cases (and
   811  			// temporarily for all the cases).
   812  			//
   813  			// If/when this happens, take note of the following:
   814  			//
   815  			// We must clear the destination before calling assignTo,
   816  			// in case assignTo writes (with memory barriers) to the
   817  			// target location used as scratch space. See issue 39541.
   818  			v = v.assignTo("reflect.MakeFunc", typ, nil)
   819  		stepsLoop:
   820  			for _, st := range abid.ret.stepsForValue(i) {
   821  				switch st.kind {
   822  				case abiStepStack:
   823  					// Copy values to the "stack."
   824  					addr := add(ptr, st.stkOff, "precomputed stack arg offset")
   825  					// Do not use write barriers. The stack space used
   826  					// for this call is not adequately zeroed, and we
   827  					// are careful to keep the arguments alive until we
   828  					// return to makeFuncStub's caller.
   829  					if v.flag&flagIndir != 0 {
   830  						memmove(addr, v.ptr, st.size)
   831  					} else {
   832  						// This case must be a pointer type.
   833  						*(*uintptr)(addr) = uintptr(v.ptr)
   834  					}
   835  					// There's only one step for a stack-allocated value.
   836  					break stepsLoop
   837  				case abiStepIntReg, abiStepPointer:
   838  					// Copy values to "integer registers."
   839  					if v.flag&flagIndir != 0 {
   840  						offset := add(v.ptr, st.offset, "precomputed value offset")
   841  						intToReg(regs, st.ireg, st.size, offset)
   842  					} else {
   843  						// Only populate the Ints space on the return path.
   844  						// This is safe because out is kept alive until the
   845  						// end of this function, and the return path through
   846  						// makeFuncStub has no preemption, so these pointers
   847  						// are always visible to the GC.
   848  						regs.Ints[st.ireg] = uintptr(v.ptr)
   849  					}
   850  				case abiStepFloatReg:
   851  					// Copy values to "float registers."
   852  					if v.flag&flagIndir == 0 {
   853  						panic("attempted to copy pointer to FP register")
   854  					}
   855  					offset := add(v.ptr, st.offset, "precomputed value offset")
   856  					floatToReg(regs, st.freg, st.size, offset)
   857  				default:
   858  					panic("unknown ABI part kind")
   859  				}
   860  			}
   861  		}
   862  	}
   863  
   864  	// Announce that the return values are valid.
   865  	// After this point the runtime can depend on the return values being valid.
   866  	*retValid = true
   867  
   868  	// We have to make sure that the out slice lives at least until
   869  	// the runtime knows the return values are valid. Otherwise, the
   870  	// return values might not be scanned by anyone during a GC.
   871  	// (out would be dead, and the return slots not yet alive.)
   872  	runtime.KeepAlive(out)
   873  
   874  	// runtime.getArgInfo expects to be able to find ctxt on the
   875  	// stack when it finds our caller, makeFuncStub. Make sure it
   876  	// doesn't get garbage collected.
   877  	runtime.KeepAlive(ctxt)
   878  }
   879  
   880  // methodReceiver returns information about the receiver
   881  // described by v. The Value v may or may not have the
   882  // flagMethod bit set, so the kind cached in v.flag should
   883  // not be used.
   884  // The return value rcvrtype gives the method's actual receiver type.
   885  // The return value t gives the method type signature (without the receiver).
   886  // The return value fn is a pointer to the method code.
   887  func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *abi.Type, t *funcType, fn unsafe.Pointer) {
   888  	i := methodIndex
   889  	if v.typ().Kind() == abi.Interface {
   890  		tt := (*interfaceType)(unsafe.Pointer(v.typ()))
   891  		if uint(i) >= uint(len(tt.Methods)) {
   892  			panic("reflect: internal error: invalid method index")
   893  		}
   894  		m := &tt.Methods[i]
   895  		if !tt.nameOff(m.Name).IsExported() {
   896  			panic("reflect: " + op + " of unexported method")
   897  		}
   898  		iface := (*nonEmptyInterface)(v.ptr)
   899  		if iface.itab == nil {
   900  			panic("reflect: " + op + " of method on nil interface value")
   901  		}
   902  		rcvrtype = iface.itab.typ
   903  		fn = unsafe.Pointer(&iface.itab.fun[i])
   904  		t = (*funcType)(unsafe.Pointer(tt.typeOff(m.Typ)))
   905  	} else {
   906  		rcvrtype = v.typ()
   907  		ms := v.typ().ExportedMethods()
   908  		if uint(i) >= uint(len(ms)) {
   909  			panic("reflect: internal error: invalid method index")
   910  		}
   911  		m := ms[i]
   912  		if !nameOffFor(v.typ(), m.Name).IsExported() {
   913  			panic("reflect: " + op + " of unexported method")
   914  		}
   915  		ifn := textOffFor(v.typ(), m.Ifn)
   916  		fn = unsafe.Pointer(&ifn)
   917  		t = (*funcType)(unsafe.Pointer(typeOffFor(v.typ(), m.Mtyp)))
   918  	}
   919  	return
   920  }
   921  
   922  // v is a method receiver. Store at p the word which is used to
   923  // encode that receiver at the start of the argument list.
   924  // Reflect uses the "interface" calling convention for
   925  // methods, which always uses one word to record the receiver.
   926  func storeRcvr(v Value, p unsafe.Pointer) {
   927  	t := v.typ()
   928  	if t.Kind() == abi.Interface {
   929  		// the interface data word becomes the receiver word
   930  		iface := (*nonEmptyInterface)(v.ptr)
   931  		*(*unsafe.Pointer)(p) = iface.word
   932  	} else if v.flag&flagIndir != 0 && !ifaceIndir(t) {
   933  		*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
   934  	} else {
   935  		*(*unsafe.Pointer)(p) = v.ptr
   936  	}
   937  }
   938  
   939  // align returns the result of rounding x up to a multiple of n.
   940  // n must be a power of two.
   941  func align(x, n uintptr) uintptr {
   942  	return (x + n - 1) &^ (n - 1)
   943  }
   944  
   945  // callMethod is the call implementation used by a function returned
   946  // by makeMethodValue (used by v.Method(i).Interface()).
   947  // It is a streamlined version of the usual reflect call: the caller has
   948  // already laid out the argument frame for us, so we don't have
   949  // to deal with individual Values for each argument.
   950  // It is in this file so that it can be next to the two similar functions above.
   951  // The remainder of the makeMethodValue implementation is in makefunc.go.
   952  //
   953  // NOTE: This function must be marked as a "wrapper" in the generated code,
   954  // so that the linker can make it work correctly for panic and recover.
   955  // The gc compilers know to do that for the name "reflect.callMethod".
   956  //
   957  // ctxt is the "closure" generated by makeVethodValue.
   958  // frame is a pointer to the arguments to that closure on the stack.
   959  // retValid points to a boolean which should be set when the results
   960  // section of frame is set.
   961  //
   962  // regs contains the argument values passed in registers and will contain
   963  // the values returned from ctxt.fn in registers.
   964  func callMethod(ctxt *methodValue, frame unsafe.Pointer, retValid *bool, regs *abi.RegArgs) {
   965  	rcvr := ctxt.rcvr
   966  	rcvrType, valueFuncType, methodFn := methodReceiver("call", rcvr, ctxt.method)
   967  
   968  	// There are two ABIs at play here.
   969  	//
   970  	// methodValueCall was invoked with the ABI assuming there was no
   971  	// receiver ("value ABI") and that's what frame and regs are holding.
   972  	//
   973  	// Meanwhile, we need to actually call the method with a receiver, which
   974  	// has its own ABI ("method ABI"). Everything that follows is a translation
   975  	// between the two.
   976  	_, _, valueABI := funcLayout(valueFuncType, nil)
   977  	valueFrame, valueRegs := frame, regs
   978  	methodFrameType, methodFramePool, methodABI := funcLayout(valueFuncType, rcvrType)
   979  
   980  	// Make a new frame that is one word bigger so we can store the receiver.
   981  	// This space is used for both arguments and return values.
   982  	methodFrame := methodFramePool.Get().(unsafe.Pointer)
   983  	var methodRegs abi.RegArgs
   984  
   985  	// Deal with the receiver. It's guaranteed to only be one word in size.
   986  	switch st := methodABI.call.steps[0]; st.kind {
   987  	case abiStepStack:
   988  		// Only copy the receiver to the stack if the ABI says so.
   989  		// Otherwise, it'll be in a register already.
   990  		storeRcvr(rcvr, methodFrame)
   991  	case abiStepPointer:
   992  		// Put the receiver in a register.
   993  		storeRcvr(rcvr, unsafe.Pointer(&methodRegs.Ptrs[st.ireg]))
   994  		fallthrough
   995  	case abiStepIntReg:
   996  		storeRcvr(rcvr, unsafe.Pointer(&methodRegs.Ints[st.ireg]))
   997  	case abiStepFloatReg:
   998  		storeRcvr(rcvr, unsafe.Pointer(&methodRegs.Floats[st.freg]))
   999  	default:
  1000  		panic("unknown ABI parameter kind")
  1001  	}
  1002  
  1003  	// Translate the rest of the arguments.
  1004  	for i, t := range valueFuncType.InSlice() {
  1005  		valueSteps := valueABI.call.stepsForValue(i)
  1006  		methodSteps := methodABI.call.stepsForValue(i + 1)
  1007  
  1008  		// Zero-sized types are trivial: nothing to do.
  1009  		if len(valueSteps) == 0 {
  1010  			if len(methodSteps) != 0 {
  1011  				panic("method ABI and value ABI do not align")
  1012  			}
  1013  			continue
  1014  		}
  1015  
  1016  		// There are four cases to handle in translating each
  1017  		// argument:
  1018  		// 1. Stack -> stack translation.
  1019  		// 2. Stack -> registers translation.
  1020  		// 3. Registers -> stack translation.
  1021  		// 4. Registers -> registers translation.
  1022  
  1023  		// If the value ABI passes the value on the stack,
  1024  		// then the method ABI does too, because it has strictly
  1025  		// fewer arguments. Simply copy between the two.
  1026  		if vStep := valueSteps[0]; vStep.kind == abiStepStack {
  1027  			mStep := methodSteps[0]
  1028  			// Handle stack -> stack translation.
  1029  			if mStep.kind == abiStepStack {
  1030  				if vStep.size != mStep.size {
  1031  					panic("method ABI and value ABI do not align")
  1032  				}
  1033  				typedmemmove(t,
  1034  					add(methodFrame, mStep.stkOff, "precomputed stack offset"),
  1035  					add(valueFrame, vStep.stkOff, "precomputed stack offset"))
  1036  				continue
  1037  			}
  1038  			// Handle stack -> register translation.
  1039  			for _, mStep := range methodSteps {
  1040  				from := add(valueFrame, vStep.stkOff+mStep.offset, "precomputed stack offset")
  1041  				switch mStep.kind {
  1042  				case abiStepPointer:
  1043  					// Do the pointer copy directly so we get a write barrier.
  1044  					methodRegs.Ptrs[mStep.ireg] = *(*unsafe.Pointer)(from)
  1045  					fallthrough // We need to make sure this ends up in Ints, too.
  1046  				case abiStepIntReg:
  1047  					intToReg(&methodRegs, mStep.ireg, mStep.size, from)
  1048  				case abiStepFloatReg:
  1049  					floatToReg(&methodRegs, mStep.freg, mStep.size, from)
  1050  				default:
  1051  					panic("unexpected method step")
  1052  				}
  1053  			}
  1054  			continue
  1055  		}
  1056  		// Handle register -> stack translation.
  1057  		if mStep := methodSteps[0]; mStep.kind == abiStepStack {
  1058  			for _, vStep := range valueSteps {
  1059  				to := add(methodFrame, mStep.stkOff+vStep.offset, "precomputed stack offset")
  1060  				switch vStep.kind {
  1061  				case abiStepPointer:
  1062  					// Do the pointer copy directly so we get a write barrier.
  1063  					*(*unsafe.Pointer)(to) = valueRegs.Ptrs[vStep.ireg]
  1064  				case abiStepIntReg:
  1065  					intFromReg(valueRegs, vStep.ireg, vStep.size, to)
  1066  				case abiStepFloatReg:
  1067  					floatFromReg(valueRegs, vStep.freg, vStep.size, to)
  1068  				default:
  1069  					panic("unexpected value step")
  1070  				}
  1071  			}
  1072  			continue
  1073  		}
  1074  		// Handle register -> register translation.
  1075  		if len(valueSteps) != len(methodSteps) {
  1076  			// Because it's the same type for the value, and it's assigned
  1077  			// to registers both times, it should always take up the same
  1078  			// number of registers for each ABI.
  1079  			panic("method ABI and value ABI don't align")
  1080  		}
  1081  		for i, vStep := range valueSteps {
  1082  			mStep := methodSteps[i]
  1083  			if mStep.kind != vStep.kind {
  1084  				panic("method ABI and value ABI don't align")
  1085  			}
  1086  			switch vStep.kind {
  1087  			case abiStepPointer:
  1088  				// Copy this too, so we get a write barrier.
  1089  				methodRegs.Ptrs[mStep.ireg] = valueRegs.Ptrs[vStep.ireg]
  1090  				fallthrough
  1091  			case abiStepIntReg:
  1092  				methodRegs.Ints[mStep.ireg] = valueRegs.Ints[vStep.ireg]
  1093  			case abiStepFloatReg:
  1094  				methodRegs.Floats[mStep.freg] = valueRegs.Floats[vStep.freg]
  1095  			default:
  1096  				panic("unexpected value step")
  1097  			}
  1098  		}
  1099  	}
  1100  
  1101  	methodFrameSize := methodFrameType.Size()
  1102  	// TODO(mknyszek): Remove this when we no longer have
  1103  	// caller reserved spill space.
  1104  	methodFrameSize = align(methodFrameSize, goarch.PtrSize)
  1105  	methodFrameSize += methodABI.spill
  1106  
  1107  	// Mark pointers in registers for the return path.
  1108  	methodRegs.ReturnIsPtr = methodABI.outRegPtrs
  1109  
  1110  	// Call.
  1111  	// Call copies the arguments from scratch to the stack, calls fn,
  1112  	// and then copies the results back into scratch.
  1113  	call(methodFrameType, methodFn, methodFrame, uint32(methodFrameType.Size()), uint32(methodABI.retOffset), uint32(methodFrameSize), &methodRegs)
  1114  
  1115  	// Copy return values.
  1116  	//
  1117  	// This is somewhat simpler because both ABIs have an identical
  1118  	// return value ABI (the types are identical). As a result, register
  1119  	// results can simply be copied over. Stack-allocated values are laid
  1120  	// out the same, but are at different offsets from the start of the frame
  1121  	// Ignore any changes to args.
  1122  	// Avoid constructing out-of-bounds pointers if there are no return values.
  1123  	// because the arguments may be laid out differently.
  1124  	if valueRegs != nil {
  1125  		*valueRegs = methodRegs
  1126  	}
  1127  	if retSize := methodFrameType.Size() - methodABI.retOffset; retSize > 0 {
  1128  		valueRet := add(valueFrame, valueABI.retOffset, "valueFrame's size > retOffset")
  1129  		methodRet := add(methodFrame, methodABI.retOffset, "methodFrame's size > retOffset")
  1130  		// This copies to the stack. Write barriers are not needed.
  1131  		memmove(valueRet, methodRet, retSize)
  1132  	}
  1133  
  1134  	// Tell the runtime it can now depend on the return values
  1135  	// being properly initialized.
  1136  	*retValid = true
  1137  
  1138  	// Clear the scratch space and put it back in the pool.
  1139  	// This must happen after the statement above, so that the return
  1140  	// values will always be scanned by someone.
  1141  	typedmemclr(methodFrameType, methodFrame)
  1142  	methodFramePool.Put(methodFrame)
  1143  
  1144  	// See the comment in callReflect.
  1145  	runtime.KeepAlive(ctxt)
  1146  
  1147  	// Keep valueRegs alive because it may hold live pointer results.
  1148  	// The caller (methodValueCall) has it as a stack object, which is only
  1149  	// scanned when there is a reference to it.
  1150  	runtime.KeepAlive(valueRegs)
  1151  }
  1152  
  1153  // funcName returns the name of f, for use in error messages.
  1154  func funcName(f func([]Value) []Value) string {
  1155  	pc := *(*uintptr)(unsafe.Pointer(&f))
  1156  	rf := runtime.FuncForPC(pc)
  1157  	if rf != nil {
  1158  		return rf.Name()
  1159  	}
  1160  	return "closure"
  1161  }
  1162  
  1163  // Cap returns v's capacity.
  1164  // It panics if v's Kind is not Array, Chan, Slice or pointer to Array.
  1165  func (v Value) Cap() int {
  1166  	// capNonSlice is split out to keep Cap inlineable for slice kinds.
  1167  	if v.kind() == Slice {
  1168  		return (*unsafeheader.Slice)(v.ptr).Cap
  1169  	}
  1170  	return v.capNonSlice()
  1171  }
  1172  
  1173  func (v Value) capNonSlice() int {
  1174  	k := v.kind()
  1175  	switch k {
  1176  	case Array:
  1177  		return v.typ().Len()
  1178  	case Chan:
  1179  		return chancap(v.pointer())
  1180  	case Ptr:
  1181  		if v.typ().Elem().Kind() == abi.Array {
  1182  			return v.typ().Elem().Len()
  1183  		}
  1184  		panic("reflect: call of reflect.Value.Cap on ptr to non-array Value")
  1185  	}
  1186  	panic(&ValueError{"reflect.Value.Cap", v.kind()})
  1187  }
  1188  
  1189  // Close closes the channel v.
  1190  // It panics if v's Kind is not Chan.
  1191  func (v Value) Close() {
  1192  	v.mustBe(Chan)
  1193  	v.mustBeExported()
  1194  	chanclose(v.pointer())
  1195  }
  1196  
  1197  // CanComplex reports whether Complex can be used without panicking.
  1198  func (v Value) CanComplex() bool {
  1199  	switch v.kind() {
  1200  	case Complex64, Complex128:
  1201  		return true
  1202  	default:
  1203  		return false
  1204  	}
  1205  }
  1206  
  1207  // Complex returns v's underlying value, as a complex128.
  1208  // It panics if v's Kind is not Complex64 or Complex128
  1209  func (v Value) Complex() complex128 {
  1210  	k := v.kind()
  1211  	switch k {
  1212  	case Complex64:
  1213  		return complex128(*(*complex64)(v.ptr))
  1214  	case Complex128:
  1215  		return *(*complex128)(v.ptr)
  1216  	}
  1217  	panic(&ValueError{"reflect.Value.Complex", v.kind()})
  1218  }
  1219  
  1220  // Elem returns the value that the interface v contains
  1221  // or that the pointer v points to.
  1222  // It panics if v's Kind is not Interface or Pointer.
  1223  // It returns the zero Value if v is nil.
  1224  func (v Value) Elem() Value {
  1225  	k := v.kind()
  1226  	switch k {
  1227  	case Interface:
  1228  		var eface any
  1229  		if v.typ().NumMethod() == 0 {
  1230  			eface = *(*any)(v.ptr)
  1231  		} else {
  1232  			eface = (any)(*(*interface {
  1233  				M()
  1234  			})(v.ptr))
  1235  		}
  1236  		x := unpackEface(eface)
  1237  		if x.flag != 0 {
  1238  			x.flag |= v.flag.ro()
  1239  		}
  1240  		return x
  1241  	case Pointer:
  1242  		ptr := v.ptr
  1243  		if v.flag&flagIndir != 0 {
  1244  			if ifaceIndir(v.typ()) {
  1245  				// This is a pointer to a not-in-heap object. ptr points to a uintptr
  1246  				// in the heap. That uintptr is the address of a not-in-heap object.
  1247  				// In general, pointers to not-in-heap objects can be total junk.
  1248  				// But Elem() is asking to dereference it, so the user has asserted
  1249  				// that at least it is a valid pointer (not just an integer stored in
  1250  				// a pointer slot). So let's check, to make sure that it isn't a pointer
  1251  				// that the runtime will crash on if it sees it during GC or write barriers.
  1252  				// Since it is a not-in-heap pointer, all pointers to the heap are
  1253  				// forbidden! That makes the test pretty easy.
  1254  				// See issue 48399.
  1255  				if !verifyNotInHeapPtr(*(*uintptr)(ptr)) {
  1256  					panic("reflect: reflect.Value.Elem on an invalid notinheap pointer")
  1257  				}
  1258  			}
  1259  			ptr = *(*unsafe.Pointer)(ptr)
  1260  		}
  1261  		// The returned value's address is v's value.
  1262  		if ptr == nil {
  1263  			return Value{}
  1264  		}
  1265  		tt := (*ptrType)(unsafe.Pointer(v.typ()))
  1266  		typ := tt.Elem
  1267  		fl := v.flag&flagRO | flagIndir | flagAddr
  1268  		fl |= flag(typ.Kind())
  1269  		return Value{typ, ptr, fl}
  1270  	}
  1271  	panic(&ValueError{"reflect.Value.Elem", v.kind()})
  1272  }
  1273  
  1274  // Field returns the i'th field of the struct v.
  1275  // It panics if v's Kind is not Struct or i is out of range.
  1276  func (v Value) Field(i int) Value {
  1277  	if v.kind() != Struct {
  1278  		panic(&ValueError{"reflect.Value.Field", v.kind()})
  1279  	}
  1280  	tt := (*structType)(unsafe.Pointer(v.typ()))
  1281  	if uint(i) >= uint(len(tt.Fields)) {
  1282  		panic("reflect: Field index out of range")
  1283  	}
  1284  	field := &tt.Fields[i]
  1285  	typ := field.Typ
  1286  
  1287  	// Inherit permission bits from v, but clear flagEmbedRO.
  1288  	fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
  1289  	// Using an unexported field forces flagRO.
  1290  	if !field.Name.IsExported() {
  1291  		if field.Embedded() {
  1292  			fl |= flagEmbedRO
  1293  		} else {
  1294  			fl |= flagStickyRO
  1295  		}
  1296  	}
  1297  	// Either flagIndir is set and v.ptr points at struct,
  1298  	// or flagIndir is not set and v.ptr is the actual struct data.
  1299  	// In the former case, we want v.ptr + offset.
  1300  	// In the latter case, we must have field.offset = 0,
  1301  	// so v.ptr + field.offset is still the correct address.
  1302  	ptr := add(v.ptr, field.Offset, "same as non-reflect &v.field")
  1303  	return Value{typ, ptr, fl}
  1304  }
  1305  
  1306  // FieldByIndex returns the nested field corresponding to index.
  1307  // It panics if evaluation requires stepping through a nil
  1308  // pointer or a field that is not a struct.
  1309  func (v Value) FieldByIndex(index []int) Value {
  1310  	if len(index) == 1 {
  1311  		return v.Field(index[0])
  1312  	}
  1313  	v.mustBe(Struct)
  1314  	for i, x := range index {
  1315  		if i > 0 {
  1316  			if v.Kind() == Pointer && v.typ().Elem().Kind() == abi.Struct {
  1317  				if v.IsNil() {
  1318  					panic("reflect: indirection through nil pointer to embedded struct")
  1319  				}
  1320  				v = v.Elem()
  1321  			}
  1322  		}
  1323  		v = v.Field(x)
  1324  	}
  1325  	return v
  1326  }
  1327  
  1328  // FieldByIndexErr returns the nested field corresponding to index.
  1329  // It returns an error if evaluation requires stepping through a nil
  1330  // pointer, but panics if it must step through a field that
  1331  // is not a struct.
  1332  func (v Value) FieldByIndexErr(index []int) (Value, error) {
  1333  	if len(index) == 1 {
  1334  		return v.Field(index[0]), nil
  1335  	}
  1336  	v.mustBe(Struct)
  1337  	for i, x := range index {
  1338  		if i > 0 {
  1339  			if v.Kind() == Ptr && v.typ().Elem().Kind() == abi.Struct {
  1340  				if v.IsNil() {
  1341  					return Value{}, errors.New("reflect: indirection through nil pointer to embedded struct field " + nameFor(v.typ().Elem()))
  1342  				}
  1343  				v = v.Elem()
  1344  			}
  1345  		}
  1346  		v = v.Field(x)
  1347  	}
  1348  	return v, nil
  1349  }
  1350  
  1351  // FieldByName returns the struct field with the given name.
  1352  // It returns the zero Value if no field was found.
  1353  // It panics if v's Kind is not struct.
  1354  func (v Value) FieldByName(name string) Value {
  1355  	v.mustBe(Struct)
  1356  	if f, ok := toRType(v.typ()).FieldByName(name); ok {
  1357  		return v.FieldByIndex(f.Index)
  1358  	}
  1359  	return Value{}
  1360  }
  1361  
  1362  // FieldByNameFunc returns the struct field with a name
  1363  // that satisfies the match function.
  1364  // It panics if v's Kind is not struct.
  1365  // It returns the zero Value if no field was found.
  1366  func (v Value) FieldByNameFunc(match func(string) bool) Value {
  1367  	if f, ok := toRType(v.typ()).FieldByNameFunc(match); ok {
  1368  		return v.FieldByIndex(f.Index)
  1369  	}
  1370  	return Value{}
  1371  }
  1372  
  1373  // CanFloat reports whether Float can be used without panicking.
  1374  func (v Value) CanFloat() bool {
  1375  	switch v.kind() {
  1376  	case Float32, Float64:
  1377  		return true
  1378  	default:
  1379  		return false
  1380  	}
  1381  }
  1382  
  1383  // Float returns v's underlying value, as a float64.
  1384  // It panics if v's Kind is not Float32 or Float64
  1385  func (v Value) Float() float64 {
  1386  	k := v.kind()
  1387  	switch k {
  1388  	case Float32:
  1389  		return float64(*(*float32)(v.ptr))
  1390  	case Float64:
  1391  		return *(*float64)(v.ptr)
  1392  	}
  1393  	panic(&ValueError{"reflect.Value.Float", v.kind()})
  1394  }
  1395  
  1396  var uint8Type = rtypeOf(uint8(0))
  1397  
  1398  // Index returns v's i'th element.
  1399  // It panics if v's Kind is not Array, Slice, or String or i is out of range.
  1400  func (v Value) Index(i int) Value {
  1401  	switch v.kind() {
  1402  	case Array:
  1403  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  1404  		if uint(i) >= uint(tt.Len) {
  1405  			panic("reflect: array index out of range")
  1406  		}
  1407  		typ := tt.Elem
  1408  		offset := uintptr(i) * typ.Size()
  1409  
  1410  		// Either flagIndir is set and v.ptr points at array,
  1411  		// or flagIndir is not set and v.ptr is the actual array data.
  1412  		// In the former case, we want v.ptr + offset.
  1413  		// In the latter case, we must be doing Index(0), so offset = 0,
  1414  		// so v.ptr + offset is still the correct address.
  1415  		val := add(v.ptr, offset, "same as &v[i], i < tt.len")
  1416  		fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array
  1417  		return Value{typ, val, fl}
  1418  
  1419  	case Slice:
  1420  		// Element flag same as Elem of Pointer.
  1421  		// Addressable, indirect, possibly read-only.
  1422  		s := (*unsafeheader.Slice)(v.ptr)
  1423  		if uint(i) >= uint(s.Len) {
  1424  			panic("reflect: slice index out of range")
  1425  		}
  1426  		tt := (*sliceType)(unsafe.Pointer(v.typ()))
  1427  		typ := tt.Elem
  1428  		val := arrayAt(s.Data, i, typ.Size(), "i < s.Len")
  1429  		fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind())
  1430  		return Value{typ, val, fl}
  1431  
  1432  	case String:
  1433  		s := (*unsafeheader.String)(v.ptr)
  1434  		if uint(i) >= uint(s.Len) {
  1435  			panic("reflect: string index out of range")
  1436  		}
  1437  		p := arrayAt(s.Data, i, 1, "i < s.Len")
  1438  		fl := v.flag.ro() | flag(Uint8) | flagIndir
  1439  		return Value{uint8Type, p, fl}
  1440  	}
  1441  	panic(&ValueError{"reflect.Value.Index", v.kind()})
  1442  }
  1443  
  1444  // CanInt reports whether Int can be used without panicking.
  1445  func (v Value) CanInt() bool {
  1446  	switch v.kind() {
  1447  	case Int, Int8, Int16, Int32, Int64:
  1448  		return true
  1449  	default:
  1450  		return false
  1451  	}
  1452  }
  1453  
  1454  // Int returns v's underlying value, as an int64.
  1455  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
  1456  func (v Value) Int() int64 {
  1457  	k := v.kind()
  1458  	p := v.ptr
  1459  	switch k {
  1460  	case Int:
  1461  		return int64(*(*int)(p))
  1462  	case Int8:
  1463  		return int64(*(*int8)(p))
  1464  	case Int16:
  1465  		return int64(*(*int16)(p))
  1466  	case Int32:
  1467  		return int64(*(*int32)(p))
  1468  	case Int64:
  1469  		return *(*int64)(p)
  1470  	}
  1471  	panic(&ValueError{"reflect.Value.Int", v.kind()})
  1472  }
  1473  
  1474  // CanInterface reports whether Interface can be used without panicking.
  1475  func (v Value) CanInterface() bool {
  1476  	if v.flag == 0 {
  1477  		panic(&ValueError{"reflect.Value.CanInterface", Invalid})
  1478  	}
  1479  	return v.flag&flagRO == 0
  1480  }
  1481  
  1482  // Interface returns v's current value as an interface{}.
  1483  // It is equivalent to:
  1484  //
  1485  //	var i interface{} = (v's underlying value)
  1486  //
  1487  // It panics if the Value was obtained by accessing
  1488  // unexported struct fields.
  1489  func (v Value) Interface() (i any) {
  1490  	return valueInterface(v, true)
  1491  }
  1492  
  1493  func valueInterface(v Value, safe bool) any {
  1494  	if v.flag == 0 {
  1495  		panic(&ValueError{"reflect.Value.Interface", Invalid})
  1496  	}
  1497  	if safe && v.flag&flagRO != 0 {
  1498  		// Do not allow access to unexported values via Interface,
  1499  		// because they might be pointers that should not be
  1500  		// writable or methods or function that should not be callable.
  1501  		panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
  1502  	}
  1503  	if v.flag&flagMethod != 0 {
  1504  		v = makeMethodValue("Interface", v)
  1505  	}
  1506  
  1507  	if v.kind() == Interface {
  1508  		// Special case: return the element inside the interface.
  1509  		// Empty interface has one layout, all interfaces with
  1510  		// methods have a second layout.
  1511  		if v.NumMethod() == 0 {
  1512  			return *(*any)(v.ptr)
  1513  		}
  1514  		return *(*interface {
  1515  			M()
  1516  		})(v.ptr)
  1517  	}
  1518  
  1519  	// TODO: pass safe to packEface so we don't need to copy if safe==true?
  1520  	return packEface(v)
  1521  }
  1522  
  1523  // InterfaceData returns a pair of unspecified uintptr values.
  1524  // It panics if v's Kind is not Interface.
  1525  //
  1526  // In earlier versions of Go, this function returned the interface's
  1527  // value as a uintptr pair. As of Go 1.4, the implementation of
  1528  // interface values precludes any defined use of InterfaceData.
  1529  //
  1530  // Deprecated: The memory representation of interface values is not
  1531  // compatible with InterfaceData.
  1532  func (v Value) InterfaceData() [2]uintptr {
  1533  	v.mustBe(Interface)
  1534  	// The compiler loses track as it converts to uintptr. Force escape.
  1535  	escapes(v.ptr)
  1536  	// We treat this as a read operation, so we allow
  1537  	// it even for unexported data, because the caller
  1538  	// has to import "unsafe" to turn it into something
  1539  	// that can be abused.
  1540  	// Interface value is always bigger than a word; assume flagIndir.
  1541  	return *(*[2]uintptr)(v.ptr)
  1542  }
  1543  
  1544  // IsNil reports whether its argument v is nil. The argument must be
  1545  // a chan, func, interface, map, pointer, or slice value; if it is
  1546  // not, IsNil panics. Note that IsNil is not always equivalent to a
  1547  // regular comparison with nil in Go. For example, if v was created
  1548  // by calling ValueOf with an uninitialized interface variable i,
  1549  // i==nil will be true but v.IsNil will panic as v will be the zero
  1550  // Value.
  1551  func (v Value) IsNil() bool {
  1552  	k := v.kind()
  1553  	switch k {
  1554  	case Chan, Func, Map, Pointer, UnsafePointer:
  1555  		if v.flag&flagMethod != 0 {
  1556  			return false
  1557  		}
  1558  		ptr := v.ptr
  1559  		if v.flag&flagIndir != 0 {
  1560  			ptr = *(*unsafe.Pointer)(ptr)
  1561  		}
  1562  		return ptr == nil
  1563  	case Interface, Slice:
  1564  		// Both interface and slice are nil if first word is 0.
  1565  		// Both are always bigger than a word; assume flagIndir.
  1566  		return *(*unsafe.Pointer)(v.ptr) == nil
  1567  	}
  1568  	panic(&ValueError{"reflect.Value.IsNil", v.kind()})
  1569  }
  1570  
  1571  // IsValid reports whether v represents a value.
  1572  // It returns false if v is the zero Value.
  1573  // If IsValid returns false, all other methods except String panic.
  1574  // Most functions and methods never return an invalid Value.
  1575  // If one does, its documentation states the conditions explicitly.
  1576  func (v Value) IsValid() bool {
  1577  	return v.flag != 0
  1578  }
  1579  
  1580  // IsZero reports whether v is the zero value for its type.
  1581  // It panics if the argument is invalid.
  1582  func (v Value) IsZero() bool {
  1583  	switch v.kind() {
  1584  	case Bool:
  1585  		return !v.Bool()
  1586  	case Int, Int8, Int16, Int32, Int64:
  1587  		return v.Int() == 0
  1588  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  1589  		return v.Uint() == 0
  1590  	case Float32, Float64:
  1591  		return math.Float64bits(v.Float()) == 0
  1592  	case Complex64, Complex128:
  1593  		c := v.Complex()
  1594  		return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
  1595  	case Array:
  1596  		// If the type is comparable, then compare directly with zero.
  1597  		if v.typ().Equal != nil && v.typ().Size() <= maxZero {
  1598  			if v.flag&flagIndir == 0 {
  1599  				return v.ptr == nil
  1600  			}
  1601  			// v.ptr doesn't escape, as Equal functions are compiler generated
  1602  			// and never escape. The escape analysis doesn't know, as it is a
  1603  			// function pointer call.
  1604  			return v.typ().Equal(noescape(v.ptr), unsafe.Pointer(&zeroVal[0]))
  1605  		}
  1606  
  1607  		n := v.Len()
  1608  		for i := 0; i < n; i++ {
  1609  			if !v.Index(i).IsZero() {
  1610  				return false
  1611  			}
  1612  		}
  1613  		return true
  1614  	case Chan, Func, Interface, Map, Pointer, Slice, UnsafePointer:
  1615  		return v.IsNil()
  1616  	case String:
  1617  		return v.Len() == 0
  1618  	case Struct:
  1619  		// If the type is comparable, then compare directly with zero.
  1620  		if v.typ().Equal != nil && v.typ().Size() <= maxZero {
  1621  			if v.flag&flagIndir == 0 {
  1622  				return v.ptr == nil
  1623  			}
  1624  			// See noescape justification above.
  1625  			return v.typ().Equal(noescape(v.ptr), unsafe.Pointer(&zeroVal[0]))
  1626  		}
  1627  
  1628  		n := v.NumField()
  1629  		for i := 0; i < n; i++ {
  1630  			if !v.Field(i).IsZero() {
  1631  				return false
  1632  			}
  1633  		}
  1634  		return true
  1635  	default:
  1636  		// This should never happen, but will act as a safeguard for later,
  1637  		// as a default value doesn't makes sense here.
  1638  		panic(&ValueError{"reflect.Value.IsZero", v.Kind()})
  1639  	}
  1640  }
  1641  
  1642  // SetZero sets v to be the zero value of v's type.
  1643  // It panics if CanSet returns false.
  1644  func (v Value) SetZero() {
  1645  	v.mustBeAssignable()
  1646  	switch v.kind() {
  1647  	case Bool:
  1648  		*(*bool)(v.ptr) = false
  1649  	case Int:
  1650  		*(*int)(v.ptr) = 0
  1651  	case Int8:
  1652  		*(*int8)(v.ptr) = 0
  1653  	case Int16:
  1654  		*(*int16)(v.ptr) = 0
  1655  	case Int32:
  1656  		*(*int32)(v.ptr) = 0
  1657  	case Int64:
  1658  		*(*int64)(v.ptr) = 0
  1659  	case Uint:
  1660  		*(*uint)(v.ptr) = 0
  1661  	case Uint8:
  1662  		*(*uint8)(v.ptr) = 0
  1663  	case Uint16:
  1664  		*(*uint16)(v.ptr) = 0
  1665  	case Uint32:
  1666  		*(*uint32)(v.ptr) = 0
  1667  	case Uint64:
  1668  		*(*uint64)(v.ptr) = 0
  1669  	case Uintptr:
  1670  		*(*uintptr)(v.ptr) = 0
  1671  	case Float32:
  1672  		*(*float32)(v.ptr) = 0
  1673  	case Float64:
  1674  		*(*float64)(v.ptr) = 0
  1675  	case Complex64:
  1676  		*(*complex64)(v.ptr) = 0
  1677  	case Complex128:
  1678  		*(*complex128)(v.ptr) = 0
  1679  	case String:
  1680  		*(*string)(v.ptr) = ""
  1681  	case Slice:
  1682  		*(*unsafeheader.Slice)(v.ptr) = unsafeheader.Slice{}
  1683  	case Interface:
  1684  		*(*[2]unsafe.Pointer)(v.ptr) = [2]unsafe.Pointer{}
  1685  	case Chan, Func, Map, Pointer, UnsafePointer:
  1686  		*(*unsafe.Pointer)(v.ptr) = nil
  1687  	case Array, Struct:
  1688  		typedmemclr(v.typ(), v.ptr)
  1689  	default:
  1690  		// This should never happen, but will act as a safeguard for later,
  1691  		// as a default value doesn't makes sense here.
  1692  		panic(&ValueError{"reflect.Value.SetZero", v.Kind()})
  1693  	}
  1694  }
  1695  
  1696  // Kind returns v's Kind.
  1697  // If v is the zero Value (IsValid returns false), Kind returns Invalid.
  1698  func (v Value) Kind() Kind {
  1699  	return v.kind()
  1700  }
  1701  
  1702  // Len returns v's length.
  1703  // It panics if v's Kind is not Array, Chan, Map, Slice, String, or pointer to Array.
  1704  func (v Value) Len() int {
  1705  	// lenNonSlice is split out to keep Len inlineable for slice kinds.
  1706  	if v.kind() == Slice {
  1707  		return (*unsafeheader.Slice)(v.ptr).Len
  1708  	}
  1709  	return v.lenNonSlice()
  1710  }
  1711  
  1712  func (v Value) lenNonSlice() int {
  1713  	switch k := v.kind(); k {
  1714  	case Array:
  1715  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  1716  		return int(tt.Len)
  1717  	case Chan:
  1718  		return chanlen(v.pointer())
  1719  	case Map:
  1720  		return maplen(v.pointer())
  1721  	case String:
  1722  		// String is bigger than a word; assume flagIndir.
  1723  		return (*unsafeheader.String)(v.ptr).Len
  1724  	case Ptr:
  1725  		if v.typ().Elem().Kind() == abi.Array {
  1726  			return v.typ().Elem().Len()
  1727  		}
  1728  		panic("reflect: call of reflect.Value.Len on ptr to non-array Value")
  1729  	}
  1730  	panic(&ValueError{"reflect.Value.Len", v.kind()})
  1731  }
  1732  
  1733  var stringType = rtypeOf("")
  1734  
  1735  // MapIndex returns the value associated with key in the map v.
  1736  // It panics if v's Kind is not Map.
  1737  // It returns the zero Value if key is not found in the map or if v represents a nil map.
  1738  // As in Go, the key's value must be assignable to the map's key type.
  1739  func (v Value) MapIndex(key Value) Value {
  1740  	v.mustBe(Map)
  1741  	tt := (*mapType)(unsafe.Pointer(v.typ()))
  1742  
  1743  	// Do not require key to be exported, so that DeepEqual
  1744  	// and other programs can use all the keys returned by
  1745  	// MapKeys as arguments to MapIndex. If either the map
  1746  	// or the key is unexported, though, the result will be
  1747  	// considered unexported. This is consistent with the
  1748  	// behavior for structs, which allow read but not write
  1749  	// of unexported fields.
  1750  
  1751  	var e unsafe.Pointer
  1752  	if (tt.Key == stringType || key.kind() == String) && tt.Key == key.typ() && tt.Elem.Size() <= maxValSize {
  1753  		k := *(*string)(key.ptr)
  1754  		e = mapaccess_faststr(v.typ(), v.pointer(), k)
  1755  	} else {
  1756  		key = key.assignTo("reflect.Value.MapIndex", tt.Key, nil)
  1757  		var k unsafe.Pointer
  1758  		if key.flag&flagIndir != 0 {
  1759  			k = key.ptr
  1760  		} else {
  1761  			k = unsafe.Pointer(&key.ptr)
  1762  		}
  1763  		e = mapaccess(v.typ(), v.pointer(), k)
  1764  	}
  1765  	if e == nil {
  1766  		return Value{}
  1767  	}
  1768  	typ := tt.Elem
  1769  	fl := (v.flag | key.flag).ro()
  1770  	fl |= flag(typ.Kind())
  1771  	return copyVal(typ, fl, e)
  1772  }
  1773  
  1774  // MapKeys returns a slice containing all the keys present in the map,
  1775  // in unspecified order.
  1776  // It panics if v's Kind is not Map.
  1777  // It returns an empty slice if v represents a nil map.
  1778  func (v Value) MapKeys() []Value {
  1779  	v.mustBe(Map)
  1780  	tt := (*mapType)(unsafe.Pointer(v.typ()))
  1781  	keyType := tt.Key
  1782  
  1783  	fl := v.flag.ro() | flag(keyType.Kind())
  1784  
  1785  	m := v.pointer()
  1786  	mlen := int(0)
  1787  	if m != nil {
  1788  		mlen = maplen(m)
  1789  	}
  1790  	var it hiter
  1791  	mapiterinit(v.typ(), m, &it)
  1792  	a := make([]Value, mlen)
  1793  	var i int
  1794  	for i = 0; i < len(a); i++ {
  1795  		key := mapiterkey(&it)
  1796  		if key == nil {
  1797  			// Someone deleted an entry from the map since we
  1798  			// called maplen above. It's a data race, but nothing
  1799  			// we can do about it.
  1800  			break
  1801  		}
  1802  		a[i] = copyVal(keyType, fl, key)
  1803  		mapiternext(&it)
  1804  	}
  1805  	return a[:i]
  1806  }
  1807  
  1808  // hiter's structure matches runtime.hiter's structure.
  1809  // Having a clone here allows us to embed a map iterator
  1810  // inside type MapIter so that MapIters can be re-used
  1811  // without doing any allocations.
  1812  type hiter struct {
  1813  	key         unsafe.Pointer
  1814  	elem        unsafe.Pointer
  1815  	t           unsafe.Pointer
  1816  	h           unsafe.Pointer
  1817  	buckets     unsafe.Pointer
  1818  	bptr        unsafe.Pointer
  1819  	overflow    *[]unsafe.Pointer
  1820  	oldoverflow *[]unsafe.Pointer
  1821  	startBucket uintptr
  1822  	offset      uint8
  1823  	wrapped     bool
  1824  	B           uint8
  1825  	i           uint8
  1826  	bucket      uintptr
  1827  	checkBucket uintptr
  1828  }
  1829  
  1830  func (h *hiter) initialized() bool {
  1831  	return h.t != nil
  1832  }
  1833  
  1834  // A MapIter is an iterator for ranging over a map.
  1835  // See Value.MapRange.
  1836  type MapIter struct {
  1837  	m     Value
  1838  	hiter hiter
  1839  }
  1840  
  1841  // Key returns the key of iter's current map entry.
  1842  func (iter *MapIter) Key() Value {
  1843  	if !iter.hiter.initialized() {
  1844  		panic("MapIter.Key called before Next")
  1845  	}
  1846  	iterkey := mapiterkey(&iter.hiter)
  1847  	if iterkey == nil {
  1848  		panic("MapIter.Key called on exhausted iterator")
  1849  	}
  1850  
  1851  	t := (*mapType)(unsafe.Pointer(iter.m.typ()))
  1852  	ktype := t.Key
  1853  	return copyVal(ktype, iter.m.flag.ro()|flag(ktype.Kind()), iterkey)
  1854  }
  1855  
  1856  // SetIterKey assigns to v the key of iter's current map entry.
  1857  // It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value.
  1858  // As in Go, the key must be assignable to v's type and
  1859  // must not be derived from an unexported field.
  1860  func (v Value) SetIterKey(iter *MapIter) {
  1861  	if !iter.hiter.initialized() {
  1862  		panic("reflect: Value.SetIterKey called before Next")
  1863  	}
  1864  	iterkey := mapiterkey(&iter.hiter)
  1865  	if iterkey == nil {
  1866  		panic("reflect: Value.SetIterKey called on exhausted iterator")
  1867  	}
  1868  
  1869  	v.mustBeAssignable()
  1870  	var target unsafe.Pointer
  1871  	if v.kind() == Interface {
  1872  		target = v.ptr
  1873  	}
  1874  
  1875  	t := (*mapType)(unsafe.Pointer(iter.m.typ()))
  1876  	ktype := t.Key
  1877  
  1878  	iter.m.mustBeExported() // do not let unexported m leak
  1879  	key := Value{ktype, iterkey, iter.m.flag | flag(ktype.Kind()) | flagIndir}
  1880  	key = key.assignTo("reflect.MapIter.SetKey", v.typ(), target)
  1881  	typedmemmove(v.typ(), v.ptr, key.ptr)
  1882  }
  1883  
  1884  // Value returns the value of iter's current map entry.
  1885  func (iter *MapIter) Value() Value {
  1886  	if !iter.hiter.initialized() {
  1887  		panic("MapIter.Value called before Next")
  1888  	}
  1889  	iterelem := mapiterelem(&iter.hiter)
  1890  	if iterelem == nil {
  1891  		panic("MapIter.Value called on exhausted iterator")
  1892  	}
  1893  
  1894  	t := (*mapType)(unsafe.Pointer(iter.m.typ()))
  1895  	vtype := t.Elem
  1896  	return copyVal(vtype, iter.m.flag.ro()|flag(vtype.Kind()), iterelem)
  1897  }
  1898  
  1899  // SetIterValue assigns to v the value of iter's current map entry.
  1900  // It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value.
  1901  // As in Go, the value must be assignable to v's type and
  1902  // must not be derived from an unexported field.
  1903  func (v Value) SetIterValue(iter *MapIter) {
  1904  	if !iter.hiter.initialized() {
  1905  		panic("reflect: Value.SetIterValue called before Next")
  1906  	}
  1907  	iterelem := mapiterelem(&iter.hiter)
  1908  	if iterelem == nil {
  1909  		panic("reflect: Value.SetIterValue called on exhausted iterator")
  1910  	}
  1911  
  1912  	v.mustBeAssignable()
  1913  	var target unsafe.Pointer
  1914  	if v.kind() == Interface {
  1915  		target = v.ptr
  1916  	}
  1917  
  1918  	t := (*mapType)(unsafe.Pointer(iter.m.typ()))
  1919  	vtype := t.Elem
  1920  
  1921  	iter.m.mustBeExported() // do not let unexported m leak
  1922  	elem := Value{vtype, iterelem, iter.m.flag | flag(vtype.Kind()) | flagIndir}
  1923  	elem = elem.assignTo("reflect.MapIter.SetValue", v.typ(), target)
  1924  	typedmemmove(v.typ(), v.ptr, elem.ptr)
  1925  }
  1926  
  1927  // Next advances the map iterator and reports whether there is another
  1928  // entry. It returns false when iter is exhausted; subsequent
  1929  // calls to Key, Value, or Next will panic.
  1930  func (iter *MapIter) Next() bool {
  1931  	if !iter.m.IsValid() {
  1932  		panic("MapIter.Next called on an iterator that does not have an associated map Value")
  1933  	}
  1934  	if !iter.hiter.initialized() {
  1935  		mapiterinit(iter.m.typ(), iter.m.pointer(), &iter.hiter)
  1936  	} else {
  1937  		if mapiterkey(&iter.hiter) == nil {
  1938  			panic("MapIter.Next called on exhausted iterator")
  1939  		}
  1940  		mapiternext(&iter.hiter)
  1941  	}
  1942  	return mapiterkey(&iter.hiter) != nil
  1943  }
  1944  
  1945  // Reset modifies iter to iterate over v.
  1946  // It panics if v's Kind is not Map and v is not the zero Value.
  1947  // Reset(Value{}) causes iter to not to refer to any map,
  1948  // which may allow the previously iterated-over map to be garbage collected.
  1949  func (iter *MapIter) Reset(v Value) {
  1950  	if v.IsValid() {
  1951  		v.mustBe(Map)
  1952  	}
  1953  	iter.m = v
  1954  	iter.hiter = hiter{}
  1955  }
  1956  
  1957  // MapRange returns a range iterator for a map.
  1958  // It panics if v's Kind is not Map.
  1959  //
  1960  // Call Next to advance the iterator, and Key/Value to access each entry.
  1961  // Next returns false when the iterator is exhausted.
  1962  // MapRange follows the same iteration semantics as a range statement.
  1963  //
  1964  // Example:
  1965  //
  1966  //	iter := reflect.ValueOf(m).MapRange()
  1967  //	for iter.Next() {
  1968  //		k := iter.Key()
  1969  //		v := iter.Value()
  1970  //		...
  1971  //	}
  1972  func (v Value) MapRange() *MapIter {
  1973  	// This is inlinable to take advantage of "function outlining".
  1974  	// The allocation of MapIter can be stack allocated if the caller
  1975  	// does not allow it to escape.
  1976  	// See https://blog.filippo.io/efficient-go-apis-with-the-inliner/
  1977  	if v.kind() != Map {
  1978  		v.panicNotMap()
  1979  	}
  1980  	return &MapIter{m: v}
  1981  }
  1982  
  1983  // Force slow panicking path not inlined, so it won't add to the
  1984  // inlining budget of the caller.
  1985  // TODO: undo when the inliner is no longer bottom-up only.
  1986  //
  1987  //go:noinline
  1988  func (f flag) panicNotMap() {
  1989  	f.mustBe(Map)
  1990  }
  1991  
  1992  // copyVal returns a Value containing the map key or value at ptr,
  1993  // allocating a new variable as needed.
  1994  func copyVal(typ *abi.Type, fl flag, ptr unsafe.Pointer) Value {
  1995  	if typ.IfaceIndir() {
  1996  		// Copy result so future changes to the map
  1997  		// won't change the underlying value.
  1998  		c := unsafe_New(typ)
  1999  		typedmemmove(typ, c, ptr)
  2000  		return Value{typ, c, fl | flagIndir}
  2001  	}
  2002  	return Value{typ, *(*unsafe.Pointer)(ptr), fl}
  2003  }
  2004  
  2005  // Method returns a function value corresponding to v's i'th method.
  2006  // The arguments to a Call on the returned function should not include
  2007  // a receiver; the returned function will always use v as the receiver.
  2008  // Method panics if i is out of range or if v is a nil interface value.
  2009  func (v Value) Method(i int) Value {
  2010  	if v.typ() == nil {
  2011  		panic(&ValueError{"reflect.Value.Method", Invalid})
  2012  	}
  2013  	if v.flag&flagMethod != 0 || uint(i) >= uint(toRType(v.typ()).NumMethod()) {
  2014  		panic("reflect: Method index out of range")
  2015  	}
  2016  	if v.typ().Kind() == abi.Interface && v.IsNil() {
  2017  		panic("reflect: Method on nil interface value")
  2018  	}
  2019  	fl := v.flag.ro() | (v.flag & flagIndir)
  2020  	fl |= flag(Func)
  2021  	fl |= flag(i)<<flagMethodShift | flagMethod
  2022  	return Value{v.typ(), v.ptr, fl}
  2023  }
  2024  
  2025  // NumMethod returns the number of methods in the value's method set.
  2026  //
  2027  // For a non-interface type, it returns the number of exported methods.
  2028  //
  2029  // For an interface type, it returns the number of exported and unexported methods.
  2030  func (v Value) NumMethod() int {
  2031  	if v.typ() == nil {
  2032  		panic(&ValueError{"reflect.Value.NumMethod", Invalid})
  2033  	}
  2034  	if v.flag&flagMethod != 0 {
  2035  		return 0
  2036  	}
  2037  	return toRType(v.typ()).NumMethod()
  2038  }
  2039  
  2040  // MethodByName returns a function value corresponding to the method
  2041  // of v with the given name.
  2042  // The arguments to a Call on the returned function should not include
  2043  // a receiver; the returned function will always use v as the receiver.
  2044  // It returns the zero Value if no method was found.
  2045  func (v Value) MethodByName(name string) Value {
  2046  	if v.typ() == nil {
  2047  		panic(&ValueError{"reflect.Value.MethodByName", Invalid})
  2048  	}
  2049  	if v.flag&flagMethod != 0 {
  2050  		return Value{}
  2051  	}
  2052  	m, ok := toRType(v.typ()).MethodByName(name)
  2053  	if !ok {
  2054  		return Value{}
  2055  	}
  2056  	return v.Method(m.Index)
  2057  }
  2058  
  2059  // NumField returns the number of fields in the struct v.
  2060  // It panics if v's Kind is not Struct.
  2061  func (v Value) NumField() int {
  2062  	v.mustBe(Struct)
  2063  	tt := (*structType)(unsafe.Pointer(v.typ()))
  2064  	return len(tt.Fields)
  2065  }
  2066  
  2067  // OverflowComplex reports whether the complex128 x cannot be represented by v's type.
  2068  // It panics if v's Kind is not Complex64 or Complex128.
  2069  func (v Value) OverflowComplex(x complex128) bool {
  2070  	k := v.kind()
  2071  	switch k {
  2072  	case Complex64:
  2073  		return overflowFloat32(real(x)) || overflowFloat32(imag(x))
  2074  	case Complex128:
  2075  		return false
  2076  	}
  2077  	panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
  2078  }
  2079  
  2080  // OverflowFloat reports whether the float64 x cannot be represented by v's type.
  2081  // It panics if v's Kind is not Float32 or Float64.
  2082  func (v Value) OverflowFloat(x float64) bool {
  2083  	k := v.kind()
  2084  	switch k {
  2085  	case Float32:
  2086  		return overflowFloat32(x)
  2087  	case Float64:
  2088  		return false
  2089  	}
  2090  	panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
  2091  }
  2092  
  2093  func overflowFloat32(x float64) bool {
  2094  	if x < 0 {
  2095  		x = -x
  2096  	}
  2097  	return math.MaxFloat32 < x && x <= math.MaxFloat64
  2098  }
  2099  
  2100  // OverflowInt reports whether the int64 x cannot be represented by v's type.
  2101  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
  2102  func (v Value) OverflowInt(x int64) bool {
  2103  	k := v.kind()
  2104  	switch k {
  2105  	case Int, Int8, Int16, Int32, Int64:
  2106  		bitSize := v.typ().Size() * 8
  2107  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  2108  		return x != trunc
  2109  	}
  2110  	panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
  2111  }
  2112  
  2113  // OverflowUint reports whether the uint64 x cannot be represented by v's type.
  2114  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  2115  func (v Value) OverflowUint(x uint64) bool {
  2116  	k := v.kind()
  2117  	switch k {
  2118  	case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
  2119  		bitSize := v.typ_.Size() * 8 // ok to use v.typ_ directly as Size doesn't escape
  2120  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  2121  		return x != trunc
  2122  	}
  2123  	panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
  2124  }
  2125  
  2126  //go:nocheckptr
  2127  // This prevents inlining Value.Pointer when -d=checkptr is enabled,
  2128  // which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer())
  2129  // and make an exception.
  2130  
  2131  // Pointer returns v's value as a uintptr.
  2132  // It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.
  2133  //
  2134  // If v's Kind is Func, the returned pointer is an underlying
  2135  // code pointer, but not necessarily enough to identify a
  2136  // single function uniquely. The only guarantee is that the
  2137  // result is zero if and only if v is a nil func Value.
  2138  //
  2139  // If v's Kind is Slice, the returned pointer is to the first
  2140  // element of the slice. If the slice is nil the returned value
  2141  // is 0.  If the slice is empty but non-nil the return value is non-zero.
  2142  //
  2143  // It's preferred to use uintptr(Value.UnsafePointer()) to get the equivalent result.
  2144  func (v Value) Pointer() uintptr {
  2145  	// The compiler loses track as it converts to uintptr. Force escape.
  2146  	escapes(v.ptr)
  2147  
  2148  	k := v.kind()
  2149  	switch k {
  2150  	case Pointer:
  2151  		if v.typ().PtrBytes == 0 {
  2152  			val := *(*uintptr)(v.ptr)
  2153  			// Since it is a not-in-heap pointer, all pointers to the heap are
  2154  			// forbidden! See comment in Value.Elem and issue #48399.
  2155  			if !verifyNotInHeapPtr(val) {
  2156  				panic("reflect: reflect.Value.Pointer on an invalid notinheap pointer")
  2157  			}
  2158  			return val
  2159  		}
  2160  		fallthrough
  2161  	case Chan, Map, UnsafePointer:
  2162  		return uintptr(v.pointer())
  2163  	case Func:
  2164  		if v.flag&flagMethod != 0 {
  2165  			// As the doc comment says, the returned pointer is an
  2166  			// underlying code pointer but not necessarily enough to
  2167  			// identify a single function uniquely. All method expressions
  2168  			// created via reflect have the same underlying code pointer,
  2169  			// so their Pointers are equal. The function used here must
  2170  			// match the one used in makeMethodValue.
  2171  			return methodValueCallCodePtr()
  2172  		}
  2173  		p := v.pointer()
  2174  		// Non-nil func value points at data block.
  2175  		// First word of data block is actual code.
  2176  		if p != nil {
  2177  			p = *(*unsafe.Pointer)(p)
  2178  		}
  2179  		return uintptr(p)
  2180  
  2181  	case Slice:
  2182  		return uintptr((*unsafeheader.Slice)(v.ptr).Data)
  2183  	}
  2184  	panic(&ValueError{"reflect.Value.Pointer", v.kind()})
  2185  }
  2186  
  2187  // Recv receives and returns a value from the channel v.
  2188  // It panics if v's Kind is not Chan.
  2189  // The receive blocks until a value is ready.
  2190  // The boolean value ok is true if the value x corresponds to a send
  2191  // on the channel, false if it is a zero value received because the channel is closed.
  2192  func (v Value) Recv() (x Value, ok bool) {
  2193  	v.mustBe(Chan)
  2194  	v.mustBeExported()
  2195  	return v.recv(false)
  2196  }
  2197  
  2198  // internal recv, possibly non-blocking (nb).
  2199  // v is known to be a channel.
  2200  func (v Value) recv(nb bool) (val Value, ok bool) {
  2201  	tt := (*chanType)(unsafe.Pointer(v.typ()))
  2202  	if ChanDir(tt.Dir)&RecvDir == 0 {
  2203  		panic("reflect: recv on send-only channel")
  2204  	}
  2205  	t := tt.Elem
  2206  	val = Value{t, nil, flag(t.Kind())}
  2207  	var p unsafe.Pointer
  2208  	if ifaceIndir(t) {
  2209  		p = unsafe_New(t)
  2210  		val.ptr = p
  2211  		val.flag |= flagIndir
  2212  	} else {
  2213  		p = unsafe.Pointer(&val.ptr)
  2214  	}
  2215  	selected, ok := chanrecv(v.pointer(), nb, p)
  2216  	if !selected {
  2217  		val = Value{}
  2218  	}
  2219  	return
  2220  }
  2221  
  2222  // Send sends x on the channel v.
  2223  // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
  2224  // As in Go, x's value must be assignable to the channel's element type.
  2225  func (v Value) Send(x Value) {
  2226  	v.mustBe(Chan)
  2227  	v.mustBeExported()
  2228  	v.send(x, false)
  2229  }
  2230  
  2231  // internal send, possibly non-blocking.
  2232  // v is known to be a channel.
  2233  func (v Value) send(x Value, nb bool) (selected bool) {
  2234  	tt := (*chanType)(unsafe.Pointer(v.typ()))
  2235  	if ChanDir(tt.Dir)&SendDir == 0 {
  2236  		panic("reflect: send on recv-only channel")
  2237  	}
  2238  	x.mustBeExported()
  2239  	x = x.assignTo("reflect.Value.Send", tt.Elem, nil)
  2240  	var p unsafe.Pointer
  2241  	if x.flag&flagIndir != 0 {
  2242  		p = x.ptr
  2243  	} else {
  2244  		p = unsafe.Pointer(&x.ptr)
  2245  	}
  2246  	return chansend(v.pointer(), p, nb)
  2247  }
  2248  
  2249  // Set assigns x to the value v.
  2250  // It panics if CanSet returns false.
  2251  // As in Go, x's value must be assignable to v's type and
  2252  // must not be derived from an unexported field.
  2253  func (v Value) Set(x Value) {
  2254  	v.mustBeAssignable()
  2255  	x.mustBeExported() // do not let unexported x leak
  2256  	var target unsafe.Pointer
  2257  	if v.kind() == Interface {
  2258  		target = v.ptr
  2259  	}
  2260  	x = x.assignTo("reflect.Set", v.typ(), target)
  2261  	if x.flag&flagIndir != 0 {
  2262  		if x.ptr == unsafe.Pointer(&zeroVal[0]) {
  2263  			typedmemclr(v.typ(), v.ptr)
  2264  		} else {
  2265  			typedmemmove(v.typ(), v.ptr, x.ptr)
  2266  		}
  2267  	} else {
  2268  		*(*unsafe.Pointer)(v.ptr) = x.ptr
  2269  	}
  2270  }
  2271  
  2272  // SetBool sets v's underlying value.
  2273  // It panics if v's Kind is not Bool or if CanSet() is false.
  2274  func (v Value) SetBool(x bool) {
  2275  	v.mustBeAssignable()
  2276  	v.mustBe(Bool)
  2277  	*(*bool)(v.ptr) = x
  2278  }
  2279  
  2280  // SetBytes sets v's underlying value.
  2281  // It panics if v's underlying value is not a slice of bytes.
  2282  func (v Value) SetBytes(x []byte) {
  2283  	v.mustBeAssignable()
  2284  	v.mustBe(Slice)
  2285  	if toRType(v.typ()).Elem().Kind() != Uint8 { // TODO add Elem method, fix mustBe(Slice) to return slice.
  2286  		panic("reflect.Value.SetBytes of non-byte slice")
  2287  	}
  2288  	*(*[]byte)(v.ptr) = x
  2289  }
  2290  
  2291  // setRunes sets v's underlying value.
  2292  // It panics if v's underlying value is not a slice of runes (int32s).
  2293  func (v Value) setRunes(x []rune) {
  2294  	v.mustBeAssignable()
  2295  	v.mustBe(Slice)
  2296  	if v.typ().Elem().Kind() != abi.Int32 {
  2297  		panic("reflect.Value.setRunes of non-rune slice")
  2298  	}
  2299  	*(*[]rune)(v.ptr) = x
  2300  }
  2301  
  2302  // SetComplex sets v's underlying value to x.
  2303  // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
  2304  func (v Value) SetComplex(x complex128) {
  2305  	v.mustBeAssignable()
  2306  	switch k := v.kind(); k {
  2307  	default:
  2308  		panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
  2309  	case Complex64:
  2310  		*(*complex64)(v.ptr) = complex64(x)
  2311  	case Complex128:
  2312  		*(*complex128)(v.ptr) = x
  2313  	}
  2314  }
  2315  
  2316  // SetFloat sets v's underlying value to x.
  2317  // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
  2318  func (v Value) SetFloat(x float64) {
  2319  	v.mustBeAssignable()
  2320  	switch k := v.kind(); k {
  2321  	default:
  2322  		panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
  2323  	case Float32:
  2324  		*(*float32)(v.ptr) = float32(x)
  2325  	case Float64:
  2326  		*(*float64)(v.ptr) = x
  2327  	}
  2328  }
  2329  
  2330  // SetInt sets v's underlying value to x.
  2331  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
  2332  func (v Value) SetInt(x int64) {
  2333  	v.mustBeAssignable()
  2334  	switch k := v.kind(); k {
  2335  	default:
  2336  		panic(&ValueError{"reflect.Value.SetInt", v.kind()})
  2337  	case Int:
  2338  		*(*int)(v.ptr) = int(x)
  2339  	case Int8:
  2340  		*(*int8)(v.ptr) = int8(x)
  2341  	case Int16:
  2342  		*(*int16)(v.ptr) = int16(x)
  2343  	case Int32:
  2344  		*(*int32)(v.ptr) = int32(x)
  2345  	case Int64:
  2346  		*(*int64)(v.ptr) = x
  2347  	}
  2348  }
  2349  
  2350  // SetLen sets v's length to n.
  2351  // It panics if v's Kind is not Slice or if n is negative or
  2352  // greater than the capacity of the slice.
  2353  func (v Value) SetLen(n int) {
  2354  	v.mustBeAssignable()
  2355  	v.mustBe(Slice)
  2356  	s := (*unsafeheader.Slice)(v.ptr)
  2357  	if uint(n) > uint(s.Cap) {
  2358  		panic("reflect: slice length out of range in SetLen")
  2359  	}
  2360  	s.Len = n
  2361  }
  2362  
  2363  // SetCap sets v's capacity to n.
  2364  // It panics if v's Kind is not Slice or if n is smaller than the length or
  2365  // greater than the capacity of the slice.
  2366  func (v Value) SetCap(n int) {
  2367  	v.mustBeAssignable()
  2368  	v.mustBe(Slice)
  2369  	s := (*unsafeheader.Slice)(v.ptr)
  2370  	if n < s.Len || n > s.Cap {
  2371  		panic("reflect: slice capacity out of range in SetCap")
  2372  	}
  2373  	s.Cap = n
  2374  }
  2375  
  2376  // SetMapIndex sets the element associated with key in the map v to elem.
  2377  // It panics if v's Kind is not Map.
  2378  // If elem is the zero Value, SetMapIndex deletes the key from the map.
  2379  // Otherwise if v holds a nil map, SetMapIndex will panic.
  2380  // As in Go, key's elem must be assignable to the map's key type,
  2381  // and elem's value must be assignable to the map's elem type.
  2382  func (v Value) SetMapIndex(key, elem Value) {
  2383  	v.mustBe(Map)
  2384  	v.mustBeExported()
  2385  	key.mustBeExported()
  2386  	tt := (*mapType)(unsafe.Pointer(v.typ()))
  2387  
  2388  	if (tt.Key == stringType || key.kind() == String) && tt.Key == key.typ() && tt.Elem.Size() <= maxValSize {
  2389  		k := *(*string)(key.ptr)
  2390  		if elem.typ() == nil {
  2391  			mapdelete_faststr(v.typ(), v.pointer(), k)
  2392  			return
  2393  		}
  2394  		elem.mustBeExported()
  2395  		elem = elem.assignTo("reflect.Value.SetMapIndex", tt.Elem, nil)
  2396  		var e unsafe.Pointer
  2397  		if elem.flag&flagIndir != 0 {
  2398  			e = elem.ptr
  2399  		} else {
  2400  			e = unsafe.Pointer(&elem.ptr)
  2401  		}
  2402  		mapassign_faststr(v.typ(), v.pointer(), k, e)
  2403  		return
  2404  	}
  2405  
  2406  	key = key.assignTo("reflect.Value.SetMapIndex", tt.Key, nil)
  2407  	var k unsafe.Pointer
  2408  	if key.flag&flagIndir != 0 {
  2409  		k = key.ptr
  2410  	} else {
  2411  		k = unsafe.Pointer(&key.ptr)
  2412  	}
  2413  	if elem.typ() == nil {
  2414  		mapdelete(v.typ(), v.pointer(), k)
  2415  		return
  2416  	}
  2417  	elem.mustBeExported()
  2418  	elem = elem.assignTo("reflect.Value.SetMapIndex", tt.Elem, nil)
  2419  	var e unsafe.Pointer
  2420  	if elem.flag&flagIndir != 0 {
  2421  		e = elem.ptr
  2422  	} else {
  2423  		e = unsafe.Pointer(&elem.ptr)
  2424  	}
  2425  	mapassign(v.typ(), v.pointer(), k, e)
  2426  }
  2427  
  2428  // SetUint sets v's underlying value to x.
  2429  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
  2430  func (v Value) SetUint(x uint64) {
  2431  	v.mustBeAssignable()
  2432  	switch k := v.kind(); k {
  2433  	default:
  2434  		panic(&ValueError{"reflect.Value.SetUint", v.kind()})
  2435  	case Uint:
  2436  		*(*uint)(v.ptr) = uint(x)
  2437  	case Uint8:
  2438  		*(*uint8)(v.ptr) = uint8(x)
  2439  	case Uint16:
  2440  		*(*uint16)(v.ptr) = uint16(x)
  2441  	case Uint32:
  2442  		*(*uint32)(v.ptr) = uint32(x)
  2443  	case Uint64:
  2444  		*(*uint64)(v.ptr) = x
  2445  	case Uintptr:
  2446  		*(*uintptr)(v.ptr) = uintptr(x)
  2447  	}
  2448  }
  2449  
  2450  // SetPointer sets the [unsafe.Pointer] value v to x.
  2451  // It panics if v's Kind is not UnsafePointer.
  2452  func (v Value) SetPointer(x unsafe.Pointer) {
  2453  	v.mustBeAssignable()
  2454  	v.mustBe(UnsafePointer)
  2455  	*(*unsafe.Pointer)(v.ptr) = x
  2456  }
  2457  
  2458  // SetString sets v's underlying value to x.
  2459  // It panics if v's Kind is not String or if CanSet() is false.
  2460  func (v Value) SetString(x string) {
  2461  	v.mustBeAssignable()
  2462  	v.mustBe(String)
  2463  	*(*string)(v.ptr) = x
  2464  }
  2465  
  2466  // Slice returns v[i:j].
  2467  // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
  2468  // or if the indexes are out of bounds.
  2469  func (v Value) Slice(i, j int) Value {
  2470  	var (
  2471  		cap  int
  2472  		typ  *sliceType
  2473  		base unsafe.Pointer
  2474  	)
  2475  	switch kind := v.kind(); kind {
  2476  	default:
  2477  		panic(&ValueError{"reflect.Value.Slice", v.kind()})
  2478  
  2479  	case Array:
  2480  		if v.flag&flagAddr == 0 {
  2481  			panic("reflect.Value.Slice: slice of unaddressable array")
  2482  		}
  2483  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  2484  		cap = int(tt.Len)
  2485  		typ = (*sliceType)(unsafe.Pointer(tt.Slice))
  2486  		base = v.ptr
  2487  
  2488  	case Slice:
  2489  		typ = (*sliceType)(unsafe.Pointer(v.typ()))
  2490  		s := (*unsafeheader.Slice)(v.ptr)
  2491  		base = s.Data
  2492  		cap = s.Cap
  2493  
  2494  	case String:
  2495  		s := (*unsafeheader.String)(v.ptr)
  2496  		if i < 0 || j < i || j > s.Len {
  2497  			panic("reflect.Value.Slice: string slice index out of bounds")
  2498  		}
  2499  		var t unsafeheader.String
  2500  		if i < s.Len {
  2501  			t = unsafeheader.String{Data: arrayAt(s.Data, i, 1, "i < s.Len"), Len: j - i}
  2502  		}
  2503  		return Value{v.typ(), unsafe.Pointer(&t), v.flag}
  2504  	}
  2505  
  2506  	if i < 0 || j < i || j > cap {
  2507  		panic("reflect.Value.Slice: slice index out of bounds")
  2508  	}
  2509  
  2510  	// Declare slice so that gc can see the base pointer in it.
  2511  	var x []unsafe.Pointer
  2512  
  2513  	// Reinterpret as *unsafeheader.Slice to edit.
  2514  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  2515  	s.Len = j - i
  2516  	s.Cap = cap - i
  2517  	if cap-i > 0 {
  2518  		s.Data = arrayAt(base, i, typ.Elem.Size(), "i < cap")
  2519  	} else {
  2520  		// do not advance pointer, to avoid pointing beyond end of slice
  2521  		s.Data = base
  2522  	}
  2523  
  2524  	fl := v.flag.ro() | flagIndir | flag(Slice)
  2525  	return Value{typ.Common(), unsafe.Pointer(&x), fl}
  2526  }
  2527  
  2528  // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
  2529  // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
  2530  // or if the indexes are out of bounds.
  2531  func (v Value) Slice3(i, j, k int) Value {
  2532  	var (
  2533  		cap  int
  2534  		typ  *sliceType
  2535  		base unsafe.Pointer
  2536  	)
  2537  	switch kind := v.kind(); kind {
  2538  	default:
  2539  		panic(&ValueError{"reflect.Value.Slice3", v.kind()})
  2540  
  2541  	case Array:
  2542  		if v.flag&flagAddr == 0 {
  2543  			panic("reflect.Value.Slice3: slice of unaddressable array")
  2544  		}
  2545  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
  2546  		cap = int(tt.Len)
  2547  		typ = (*sliceType)(unsafe.Pointer(tt.Slice))
  2548  		base = v.ptr
  2549  
  2550  	case Slice:
  2551  		typ = (*sliceType)(unsafe.Pointer(v.typ()))
  2552  		s := (*unsafeheader.Slice)(v.ptr)
  2553  		base = s.Data
  2554  		cap = s.Cap
  2555  	}
  2556  
  2557  	if i < 0 || j < i || k < j || k > cap {
  2558  		panic("reflect.Value.Slice3: slice index out of bounds")
  2559  	}
  2560  
  2561  	// Declare slice so that the garbage collector
  2562  	// can see the base pointer in it.
  2563  	var x []unsafe.Pointer
  2564  
  2565  	// Reinterpret as *unsafeheader.Slice to edit.
  2566  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  2567  	s.Len = j - i
  2568  	s.Cap = k - i
  2569  	if k-i > 0 {
  2570  		s.Data = arrayAt(base, i, typ.Elem.Size(), "i < k <= cap")
  2571  	} else {
  2572  		// do not advance pointer, to avoid pointing beyond end of slice
  2573  		s.Data = base
  2574  	}
  2575  
  2576  	fl := v.flag.ro() | flagIndir | flag(Slice)
  2577  	return Value{typ.Common(), unsafe.Pointer(&x), fl}
  2578  }
  2579  
  2580  // String returns the string v's underlying value, as a string.
  2581  // String is a special case because of Go's String method convention.
  2582  // Unlike the other getters, it does not panic if v's Kind is not String.
  2583  // Instead, it returns a string of the form "<T value>" where T is v's type.
  2584  // The fmt package treats Values specially. It does not call their String
  2585  // method implicitly but instead prints the concrete values they hold.
  2586  func (v Value) String() string {
  2587  	// stringNonString is split out to keep String inlineable for string kinds.
  2588  	if v.kind() == String {
  2589  		return *(*string)(v.ptr)
  2590  	}
  2591  	return v.stringNonString()
  2592  }
  2593  
  2594  func (v Value) stringNonString() string {
  2595  	if v.kind() == Invalid {
  2596  		return "<invalid Value>"
  2597  	}
  2598  	// If you call String on a reflect.Value of other type, it's better to
  2599  	// print something than to panic. Useful in debugging.
  2600  	return "<" + v.Type().String() + " Value>"
  2601  }
  2602  
  2603  // TryRecv attempts to receive a value from the channel v but will not block.
  2604  // It panics if v's Kind is not Chan.
  2605  // If the receive delivers a value, x is the transferred value and ok is true.
  2606  // If the receive cannot finish without blocking, x is the zero Value and ok is false.
  2607  // If the channel is closed, x is the zero value for the channel's element type and ok is false.
  2608  func (v Value) TryRecv() (x Value, ok bool) {
  2609  	v.mustBe(Chan)
  2610  	v.mustBeExported()
  2611  	return v.recv(true)
  2612  }
  2613  
  2614  // TrySend attempts to send x on the channel v but will not block.
  2615  // It panics if v's Kind is not Chan.
  2616  // It reports whether the value was sent.
  2617  // As in Go, x's value must be assignable to the channel's element type.
  2618  func (v Value) TrySend(x Value) bool {
  2619  	v.mustBe(Chan)
  2620  	v.mustBeExported()
  2621  	return v.send(x, true)
  2622  }
  2623  
  2624  // Type returns v's type.
  2625  func (v Value) Type() Type {
  2626  	if v.flag != 0 && v.flag&flagMethod == 0 {
  2627  		return (*rtype)(noescape(unsafe.Pointer(v.typ_))) // inline of toRType(v.typ()), for own inlining in inline test
  2628  	}
  2629  	return v.typeSlow()
  2630  }
  2631  
  2632  func (v Value) typeSlow() Type {
  2633  	if v.flag == 0 {
  2634  		panic(&ValueError{"reflect.Value.Type", Invalid})
  2635  	}
  2636  
  2637  	typ := v.typ()
  2638  	if v.flag&flagMethod == 0 {
  2639  		return toRType(v.typ())
  2640  	}
  2641  
  2642  	// Method value.
  2643  	// v.typ describes the receiver, not the method type.
  2644  	i := int(v.flag) >> flagMethodShift
  2645  	if v.typ().Kind() == abi.Interface {
  2646  		// Method on interface.
  2647  		tt := (*interfaceType)(unsafe.Pointer(typ))
  2648  		if uint(i) >= uint(len(tt.Methods)) {
  2649  			panic("reflect: internal error: invalid method index")
  2650  		}
  2651  		m := &tt.Methods[i]
  2652  		return toRType(typeOffFor(typ, m.Typ))
  2653  	}
  2654  	// Method on concrete type.
  2655  	ms := typ.ExportedMethods()
  2656  	if uint(i) >= uint(len(ms)) {
  2657  		panic("reflect: internal error: invalid method index")
  2658  	}
  2659  	m := ms[i]
  2660  	return toRType(typeOffFor(typ, m.Mtyp))
  2661  }
  2662  
  2663  // CanUint reports whether Uint can be used without panicking.
  2664  func (v Value) CanUint() bool {
  2665  	switch v.kind() {
  2666  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2667  		return true
  2668  	default:
  2669  		return false
  2670  	}
  2671  }
  2672  
  2673  // Uint returns v's underlying value, as a uint64.
  2674  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  2675  func (v Value) Uint() uint64 {
  2676  	k := v.kind()
  2677  	p := v.ptr
  2678  	switch k {
  2679  	case Uint:
  2680  		return uint64(*(*uint)(p))
  2681  	case Uint8:
  2682  		return uint64(*(*uint8)(p))
  2683  	case Uint16:
  2684  		return uint64(*(*uint16)(p))
  2685  	case Uint32:
  2686  		return uint64(*(*uint32)(p))
  2687  	case Uint64:
  2688  		return *(*uint64)(p)
  2689  	case Uintptr:
  2690  		return uint64(*(*uintptr)(p))
  2691  	}
  2692  	panic(&ValueError{"reflect.Value.Uint", v.kind()})
  2693  }
  2694  
  2695  //go:nocheckptr
  2696  // This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled,
  2697  // which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr())
  2698  // and make an exception.
  2699  
  2700  // UnsafeAddr returns a pointer to v's data, as a uintptr.
  2701  // It panics if v is not addressable.
  2702  //
  2703  // It's preferred to use uintptr(Value.Addr().UnsafePointer()) to get the equivalent result.
  2704  func (v Value) UnsafeAddr() uintptr {
  2705  	if v.typ() == nil {
  2706  		panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
  2707  	}
  2708  	if v.flag&flagAddr == 0 {
  2709  		panic("reflect.Value.UnsafeAddr of unaddressable value")
  2710  	}
  2711  	// The compiler loses track as it converts to uintptr. Force escape.
  2712  	escapes(v.ptr)
  2713  	return uintptr(v.ptr)
  2714  }
  2715  
  2716  // UnsafePointer returns v's value as a [unsafe.Pointer].
  2717  // It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.
  2718  //
  2719  // If v's Kind is Func, the returned pointer is an underlying
  2720  // code pointer, but not necessarily enough to identify a
  2721  // single function uniquely. The only guarantee is that the
  2722  // result is zero if and only if v is a nil func Value.
  2723  //
  2724  // If v's Kind is Slice, the returned pointer is to the first
  2725  // element of the slice. If the slice is nil the returned value
  2726  // is nil.  If the slice is empty but non-nil the return value is non-nil.
  2727  func (v Value) UnsafePointer() unsafe.Pointer {
  2728  	k := v.kind()
  2729  	switch k {
  2730  	case Pointer:
  2731  		if v.typ().PtrBytes == 0 {
  2732  			// Since it is a not-in-heap pointer, all pointers to the heap are
  2733  			// forbidden! See comment in Value.Elem and issue #48399.
  2734  			if !verifyNotInHeapPtr(*(*uintptr)(v.ptr)) {
  2735  				panic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer")
  2736  			}
  2737  			return *(*unsafe.Pointer)(v.ptr)
  2738  		}
  2739  		fallthrough
  2740  	case Chan, Map, UnsafePointer:
  2741  		return v.pointer()
  2742  	case Func:
  2743  		if v.flag&flagMethod != 0 {
  2744  			// As the doc comment says, the returned pointer is an
  2745  			// underlying code pointer but not necessarily enough to
  2746  			// identify a single function uniquely. All method expressions
  2747  			// created via reflect have the same underlying code pointer,
  2748  			// so their Pointers are equal. The function used here must
  2749  			// match the one used in makeMethodValue.
  2750  			code := methodValueCallCodePtr()
  2751  			return *(*unsafe.Pointer)(unsafe.Pointer(&code))
  2752  		}
  2753  		p := v.pointer()
  2754  		// Non-nil func value points at data block.
  2755  		// First word of data block is actual code.
  2756  		if p != nil {
  2757  			p = *(*unsafe.Pointer)(p)
  2758  		}
  2759  		return p
  2760  
  2761  	case Slice:
  2762  		return (*unsafeheader.Slice)(v.ptr).Data
  2763  	}
  2764  	panic(&ValueError{"reflect.Value.UnsafePointer", v.kind()})
  2765  }
  2766  
  2767  // StringHeader is the runtime representation of a string.
  2768  // It cannot be used safely or portably and its representation may
  2769  // change in a later release.
  2770  // Moreover, the Data field is not sufficient to guarantee the data
  2771  // it references will not be garbage collected, so programs must keep
  2772  // a separate, correctly typed pointer to the underlying data.
  2773  //
  2774  // Deprecated: Use unsafe.String or unsafe.StringData instead.
  2775  type StringHeader struct {
  2776  	Data uintptr
  2777  	Len  int
  2778  }
  2779  
  2780  // SliceHeader is the runtime representation of a slice.
  2781  // It cannot be used safely or portably and its representation may
  2782  // change in a later release.
  2783  // Moreover, the Data field is not sufficient to guarantee the data
  2784  // it references will not be garbage collected, so programs must keep
  2785  // a separate, correctly typed pointer to the underlying data.
  2786  //
  2787  // Deprecated: Use unsafe.Slice or unsafe.SliceData instead.
  2788  type SliceHeader struct {
  2789  	Data uintptr
  2790  	Len  int
  2791  	Cap  int
  2792  }
  2793  
  2794  func typesMustMatch(what string, t1, t2 Type) {
  2795  	if t1 != t2 {
  2796  		panic(what + ": " + t1.String() + " != " + t2.String())
  2797  	}
  2798  }
  2799  
  2800  // arrayAt returns the i-th element of p,
  2801  // an array whose elements are eltSize bytes wide.
  2802  // The array pointed at by p must have at least i+1 elements:
  2803  // it is invalid (but impossible to check here) to pass i >= len,
  2804  // because then the result will point outside the array.
  2805  // whySafe must explain why i < len. (Passing "i < len" is fine;
  2806  // the benefit is to surface this assumption at the call site.)
  2807  func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
  2808  	return add(p, uintptr(i)*eltSize, "i < len")
  2809  }
  2810  
  2811  // Grow increases the slice's capacity, if necessary, to guarantee space for
  2812  // another n elements. After Grow(n), at least n elements can be appended
  2813  // to the slice without another allocation.
  2814  //
  2815  // It panics if v's Kind is not a Slice or if n is negative or too large to
  2816  // allocate the memory.
  2817  func (v Value) Grow(n int) {
  2818  	v.mustBeAssignable()
  2819  	v.mustBe(Slice)
  2820  	v.grow(n)
  2821  }
  2822  
  2823  // grow is identical to Grow but does not check for assignability.
  2824  func (v Value) grow(n int) {
  2825  	p := (*unsafeheader.Slice)(v.ptr)
  2826  	switch {
  2827  	case n < 0:
  2828  		panic("reflect.Value.Grow: negative len")
  2829  	case p.Len+n < 0:
  2830  		panic("reflect.Value.Grow: slice overflow")
  2831  	case p.Len+n > p.Cap:
  2832  		t := v.typ().Elem()
  2833  		*p = growslice(t, *p, n)
  2834  	}
  2835  }
  2836  
  2837  // extendSlice extends a slice by n elements.
  2838  //
  2839  // Unlike Value.grow, which modifies the slice in place and
  2840  // does not change the length of the slice in place,
  2841  // extendSlice returns a new slice value with the length
  2842  // incremented by the number of specified elements.
  2843  func (v Value) extendSlice(n int) Value {
  2844  	v.mustBeExported()
  2845  	v.mustBe(Slice)
  2846  
  2847  	// Shallow copy the slice header to avoid mutating the source slice.
  2848  	sh := *(*unsafeheader.Slice)(v.ptr)
  2849  	s := &sh
  2850  	v.ptr = unsafe.Pointer(s)
  2851  	v.flag = flagIndir | flag(Slice) // equivalent flag to MakeSlice
  2852  
  2853  	v.grow(n) // fine to treat as assignable since we allocate a new slice header
  2854  	s.Len += n
  2855  	return v
  2856  }
  2857  
  2858  // Clear clears the contents of a map or zeros the contents of a slice.
  2859  //
  2860  // It panics if v's Kind is not Map or Slice.
  2861  func (v Value) Clear() {
  2862  	switch v.Kind() {
  2863  	case Slice:
  2864  		sh := *(*unsafeheader.Slice)(v.ptr)
  2865  		st := (*sliceType)(unsafe.Pointer(v.typ()))
  2866  		typedarrayclear(st.Elem, sh.Data, sh.Len)
  2867  	case Map:
  2868  		mapclear(v.typ(), v.pointer())
  2869  	default:
  2870  		panic(&ValueError{"reflect.Value.Clear", v.Kind()})
  2871  	}
  2872  }
  2873  
  2874  // Append appends the values x to a slice s and returns the resulting slice.
  2875  // As in Go, each x's value must be assignable to the slice's element type.
  2876  func Append(s Value, x ...Value) Value {
  2877  	s.mustBe(Slice)
  2878  	n := s.Len()
  2879  	s = s.extendSlice(len(x))
  2880  	for i, v := range x {
  2881  		s.Index(n + i).Set(v)
  2882  	}
  2883  	return s
  2884  }
  2885  
  2886  // AppendSlice appends a slice t to a slice s and returns the resulting slice.
  2887  // The slices s and t must have the same element type.
  2888  func AppendSlice(s, t Value) Value {
  2889  	s.mustBe(Slice)
  2890  	t.mustBe(Slice)
  2891  	typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
  2892  	ns := s.Len()
  2893  	nt := t.Len()
  2894  	s = s.extendSlice(nt)
  2895  	Copy(s.Slice(ns, ns+nt), t)
  2896  	return s
  2897  }
  2898  
  2899  // Copy copies the contents of src into dst until either
  2900  // dst has been filled or src has been exhausted.
  2901  // It returns the number of elements copied.
  2902  // Dst and src each must have kind Slice or Array, and
  2903  // dst and src must have the same element type.
  2904  //
  2905  // As a special case, src can have kind String if the element type of dst is kind Uint8.
  2906  func Copy(dst, src Value) int {
  2907  	dk := dst.kind()
  2908  	if dk != Array && dk != Slice {
  2909  		panic(&ValueError{"reflect.Copy", dk})
  2910  	}
  2911  	if dk == Array {
  2912  		dst.mustBeAssignable()
  2913  	}
  2914  	dst.mustBeExported()
  2915  
  2916  	sk := src.kind()
  2917  	var stringCopy bool
  2918  	if sk != Array && sk != Slice {
  2919  		stringCopy = sk == String && dst.typ().Elem().Kind() == abi.Uint8
  2920  		if !stringCopy {
  2921  			panic(&ValueError{"reflect.Copy", sk})
  2922  		}
  2923  	}
  2924  	src.mustBeExported()
  2925  
  2926  	de := dst.typ().Elem()
  2927  	if !stringCopy {
  2928  		se := src.typ().Elem()
  2929  		typesMustMatch("reflect.Copy", toType(de), toType(se))
  2930  	}
  2931  
  2932  	var ds, ss unsafeheader.Slice
  2933  	if dk == Array {
  2934  		ds.Data = dst.ptr
  2935  		ds.Len = dst.Len()
  2936  		ds.Cap = ds.Len
  2937  	} else {
  2938  		ds = *(*unsafeheader.Slice)(dst.ptr)
  2939  	}
  2940  	if sk == Array {
  2941  		ss.Data = src.ptr
  2942  		ss.Len = src.Len()
  2943  		ss.Cap = ss.Len
  2944  	} else if sk == Slice {
  2945  		ss = *(*unsafeheader.Slice)(src.ptr)
  2946  	} else {
  2947  		sh := *(*unsafeheader.String)(src.ptr)
  2948  		ss.Data = sh.Data
  2949  		ss.Len = sh.Len
  2950  		ss.Cap = sh.Len
  2951  	}
  2952  
  2953  	return typedslicecopy(de.Common(), ds, ss)
  2954  }
  2955  
  2956  // A runtimeSelect is a single case passed to rselect.
  2957  // This must match ../runtime/select.go:/runtimeSelect
  2958  type runtimeSelect struct {
  2959  	dir SelectDir      // SelectSend, SelectRecv or SelectDefault
  2960  	typ *rtype         // channel type
  2961  	ch  unsafe.Pointer // channel
  2962  	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
  2963  }
  2964  
  2965  // rselect runs a select. It returns the index of the chosen case.
  2966  // If the case was a receive, val is filled in with the received value.
  2967  // The conventional OK bool indicates whether the receive corresponds
  2968  // to a sent value.
  2969  //
  2970  // rselect generally doesn't escape the runtimeSelect slice, except
  2971  // that for the send case the value to send needs to escape. We don't
  2972  // have a way to represent that in the function signature. So we handle
  2973  // that with a forced escape in function Select.
  2974  //
  2975  //go:noescape
  2976  func rselect([]runtimeSelect) (chosen int, recvOK bool)
  2977  
  2978  // A SelectDir describes the communication direction of a select case.
  2979  type SelectDir int
  2980  
  2981  // NOTE: These values must match ../runtime/select.go:/selectDir.
  2982  
  2983  const (
  2984  	_             SelectDir = iota
  2985  	SelectSend              // case Chan <- Send
  2986  	SelectRecv              // case <-Chan:
  2987  	SelectDefault           // default
  2988  )
  2989  
  2990  // A SelectCase describes a single case in a select operation.
  2991  // The kind of case depends on Dir, the communication direction.
  2992  //
  2993  // If Dir is SelectDefault, the case represents a default case.
  2994  // Chan and Send must be zero Values.
  2995  //
  2996  // If Dir is SelectSend, the case represents a send operation.
  2997  // Normally Chan's underlying value must be a channel, and Send's underlying value must be
  2998  // assignable to the channel's element type. As a special case, if Chan is a zero Value,
  2999  // then the case is ignored, and the field Send will also be ignored and may be either zero
  3000  // or non-zero.
  3001  //
  3002  // If Dir is SelectRecv, the case represents a receive operation.
  3003  // Normally Chan's underlying value must be a channel and Send must be a zero Value.
  3004  // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
  3005  // When a receive operation is selected, the received Value is returned by Select.
  3006  type SelectCase struct {
  3007  	Dir  SelectDir // direction of case
  3008  	Chan Value     // channel to use (for send or receive)
  3009  	Send Value     // value to send (for send)
  3010  }
  3011  
  3012  // Select executes a select operation described by the list of cases.
  3013  // Like the Go select statement, it blocks until at least one of the cases
  3014  // can proceed, makes a uniform pseudo-random choice,
  3015  // and then executes that case. It returns the index of the chosen case
  3016  // and, if that case was a receive operation, the value received and a
  3017  // boolean indicating whether the value corresponds to a send on the channel
  3018  // (as opposed to a zero value received because the channel is closed).
  3019  // Select supports a maximum of 65536 cases.
  3020  func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
  3021  	if len(cases) > 65536 {
  3022  		panic("reflect.Select: too many cases (max 65536)")
  3023  	}
  3024  	// NOTE: Do not trust that caller is not modifying cases data underfoot.
  3025  	// The range is safe because the caller cannot modify our copy of the len
  3026  	// and each iteration makes its own copy of the value c.
  3027  	var runcases []runtimeSelect
  3028  	if len(cases) > 4 {
  3029  		// Slice is heap allocated due to runtime dependent capacity.
  3030  		runcases = make([]runtimeSelect, len(cases))
  3031  	} else {
  3032  		// Slice can be stack allocated due to constant capacity.
  3033  		runcases = make([]runtimeSelect, len(cases), 4)
  3034  	}
  3035  
  3036  	haveDefault := false
  3037  	for i, c := range cases {
  3038  		rc := &runcases[i]
  3039  		rc.dir = c.Dir
  3040  		switch c.Dir {
  3041  		default:
  3042  			panic("reflect.Select: invalid Dir")
  3043  
  3044  		case SelectDefault: // default
  3045  			if haveDefault {
  3046  				panic("reflect.Select: multiple default cases")
  3047  			}
  3048  			haveDefault = true
  3049  			if c.Chan.IsValid() {
  3050  				panic("reflect.Select: default case has Chan value")
  3051  			}
  3052  			if c.Send.IsValid() {
  3053  				panic("reflect.Select: default case has Send value")
  3054  			}
  3055  
  3056  		case SelectSend:
  3057  			ch := c.Chan
  3058  			if !ch.IsValid() {
  3059  				break
  3060  			}
  3061  			ch.mustBe(Chan)
  3062  			ch.mustBeExported()
  3063  			tt := (*chanType)(unsafe.Pointer(ch.typ()))
  3064  			if ChanDir(tt.Dir)&SendDir == 0 {
  3065  				panic("reflect.Select: SendDir case using recv-only channel")
  3066  			}
  3067  			rc.ch = ch.pointer()
  3068  			rc.typ = toRType(&tt.Type)
  3069  			v := c.Send
  3070  			if !v.IsValid() {
  3071  				panic("reflect.Select: SendDir case missing Send value")
  3072  			}
  3073  			v.mustBeExported()
  3074  			v = v.assignTo("reflect.Select", tt.Elem, nil)
  3075  			if v.flag&flagIndir != 0 {
  3076  				rc.val = v.ptr
  3077  			} else {
  3078  				rc.val = unsafe.Pointer(&v.ptr)
  3079  			}
  3080  			// The value to send needs to escape. See the comment at rselect for
  3081  			// why we need forced escape.
  3082  			escapes(rc.val)
  3083  
  3084  		case SelectRecv:
  3085  			if c.Send.IsValid() {
  3086  				panic("reflect.Select: RecvDir case has Send value")
  3087  			}
  3088  			ch := c.Chan
  3089  			if !ch.IsValid() {
  3090  				break
  3091  			}
  3092  			ch.mustBe(Chan)
  3093  			ch.mustBeExported()
  3094  			tt := (*chanType)(unsafe.Pointer(ch.typ()))
  3095  			if ChanDir(tt.Dir)&RecvDir == 0 {
  3096  				panic("reflect.Select: RecvDir case using send-only channel")
  3097  			}
  3098  			rc.ch = ch.pointer()
  3099  			rc.typ = toRType(&tt.Type)
  3100  			rc.val = unsafe_New(tt.Elem)
  3101  		}
  3102  	}
  3103  
  3104  	chosen, recvOK = rselect(runcases)
  3105  	if runcases[chosen].dir == SelectRecv {
  3106  		tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
  3107  		t := tt.Elem
  3108  		p := runcases[chosen].val
  3109  		fl := flag(t.Kind())
  3110  		if t.IfaceIndir() {
  3111  			recv = Value{t, p, fl | flagIndir}
  3112  		} else {
  3113  			recv = Value{t, *(*unsafe.Pointer)(p), fl}
  3114  		}
  3115  	}
  3116  	return chosen, recv, recvOK
  3117  }
  3118  
  3119  /*
  3120   * constructors
  3121   */
  3122  
  3123  // implemented in package runtime
  3124  
  3125  //go:noescape
  3126  func unsafe_New(*abi.Type) unsafe.Pointer
  3127  
  3128  //go:noescape
  3129  func unsafe_NewArray(*abi.Type, int) unsafe.Pointer
  3130  
  3131  // MakeSlice creates a new zero-initialized slice value
  3132  // for the specified slice type, length, and capacity.
  3133  func MakeSlice(typ Type, len, cap int) Value {
  3134  	if typ.Kind() != Slice {
  3135  		panic("reflect.MakeSlice of non-slice type")
  3136  	}
  3137  	if len < 0 {
  3138  		panic("reflect.MakeSlice: negative len")
  3139  	}
  3140  	if cap < 0 {
  3141  		panic("reflect.MakeSlice: negative cap")
  3142  	}
  3143  	if len > cap {
  3144  		panic("reflect.MakeSlice: len > cap")
  3145  	}
  3146  
  3147  	s := unsafeheader.Slice{Data: unsafe_NewArray(&(typ.Elem().(*rtype).t), cap), Len: len, Cap: cap}
  3148  	return Value{&typ.(*rtype).t, unsafe.Pointer(&s), flagIndir | flag(Slice)}
  3149  }
  3150  
  3151  // MakeChan creates a new channel with the specified type and buffer size.
  3152  func MakeChan(typ Type, buffer int) Value {
  3153  	if typ.Kind() != Chan {
  3154  		panic("reflect.MakeChan of non-chan type")
  3155  	}
  3156  	if buffer < 0 {
  3157  		panic("reflect.MakeChan: negative buffer size")
  3158  	}
  3159  	if typ.ChanDir() != BothDir {
  3160  		panic("reflect.MakeChan: unidirectional channel type")
  3161  	}
  3162  	t := typ.common()
  3163  	ch := makechan(t, buffer)
  3164  	return Value{t, ch, flag(Chan)}
  3165  }
  3166  
  3167  // MakeMap creates a new map with the specified type.
  3168  func MakeMap(typ Type) Value {
  3169  	return MakeMapWithSize(typ, 0)
  3170  }
  3171  
  3172  // MakeMapWithSize creates a new map with the specified type
  3173  // and initial space for approximately n elements.
  3174  func MakeMapWithSize(typ Type, n int) Value {
  3175  	if typ.Kind() != Map {
  3176  		panic("reflect.MakeMapWithSize of non-map type")
  3177  	}
  3178  	t := typ.common()
  3179  	m := makemap(t, n)
  3180  	return Value{t, m, flag(Map)}
  3181  }
  3182  
  3183  // Indirect returns the value that v points to.
  3184  // If v is a nil pointer, Indirect returns a zero Value.
  3185  // If v is not a pointer, Indirect returns v.
  3186  func Indirect(v Value) Value {
  3187  	if v.Kind() != Pointer {
  3188  		return v
  3189  	}
  3190  	return v.Elem()
  3191  }
  3192  
  3193  // Before Go 1.21, ValueOf always escapes and a Value's content
  3194  // is always heap allocated.
  3195  // Set go121noForceValueEscape to true to avoid the forced escape,
  3196  // allowing Value content to be on the stack.
  3197  // Set go121noForceValueEscape to false for the legacy behavior
  3198  // (for debugging).
  3199  const go121noForceValueEscape = true
  3200  
  3201  // ValueOf returns a new Value initialized to the concrete value
  3202  // stored in the interface i. ValueOf(nil) returns the zero Value.
  3203  func ValueOf(i any) Value {
  3204  	if i == nil {
  3205  		return Value{}
  3206  	}
  3207  
  3208  	if !go121noForceValueEscape {
  3209  		escapes(i)
  3210  	}
  3211  
  3212  	return unpackEface(i)
  3213  }
  3214  
  3215  // Zero returns a Value representing the zero value for the specified type.
  3216  // The result is different from the zero value of the Value struct,
  3217  // which represents no value at all.
  3218  // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
  3219  // The returned value is neither addressable nor settable.
  3220  func Zero(typ Type) Value {
  3221  	if typ == nil {
  3222  		panic("reflect: Zero(nil)")
  3223  	}
  3224  	t := &typ.(*rtype).t
  3225  	fl := flag(t.Kind())
  3226  	if t.IfaceIndir() {
  3227  		var p unsafe.Pointer
  3228  		if t.Size() <= maxZero {
  3229  			p = unsafe.Pointer(&zeroVal[0])
  3230  		} else {
  3231  			p = unsafe_New(t)
  3232  		}
  3233  		return Value{t, p, fl | flagIndir}
  3234  	}
  3235  	return Value{t, nil, fl}
  3236  }
  3237  
  3238  // must match declarations in runtime/map.go.
  3239  const maxZero = 1024
  3240  
  3241  //go:linkname zeroVal runtime.zeroVal
  3242  var zeroVal [maxZero]byte
  3243  
  3244  // New returns a Value representing a pointer to a new zero value
  3245  // for the specified type. That is, the returned Value's Type is PointerTo(typ).
  3246  func New(typ Type) Value {
  3247  	if typ == nil {
  3248  		panic("reflect: New(nil)")
  3249  	}
  3250  	t := &typ.(*rtype).t
  3251  	pt := ptrTo(t)
  3252  	if ifaceIndir(pt) {
  3253  		// This is a pointer to a not-in-heap type.
  3254  		panic("reflect: New of type that may not be allocated in heap (possibly undefined cgo C type)")
  3255  	}
  3256  	ptr := unsafe_New(t)
  3257  	fl := flag(Pointer)
  3258  	return Value{pt, ptr, fl}
  3259  }
  3260  
  3261  // NewAt returns a Value representing a pointer to a value of the
  3262  // specified type, using p as that pointer.
  3263  func NewAt(typ Type, p unsafe.Pointer) Value {
  3264  	fl := flag(Pointer)
  3265  	t := typ.(*rtype)
  3266  	return Value{t.ptrTo(), p, fl}
  3267  }
  3268  
  3269  // assignTo returns a value v that can be assigned directly to dst.
  3270  // It panics if v is not assignable to dst.
  3271  // For a conversion to an interface type, target, if not nil,
  3272  // is a suggested scratch space to use.
  3273  // target must be initialized memory (or nil).
  3274  func (v Value) assignTo(context string, dst *abi.Type, target unsafe.Pointer) Value {
  3275  	if v.flag&flagMethod != 0 {
  3276  		v = makeMethodValue(context, v)
  3277  	}
  3278  
  3279  	switch {
  3280  	case directlyAssignable(dst, v.typ()):
  3281  		// Overwrite type so that they match.
  3282  		// Same memory layout, so no harm done.
  3283  		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
  3284  		fl |= flag(dst.Kind())
  3285  		return Value{dst, v.ptr, fl}
  3286  
  3287  	case implements(dst, v.typ()):
  3288  		if v.Kind() == Interface && v.IsNil() {
  3289  			// A nil ReadWriter passed to nil Reader is OK,
  3290  			// but using ifaceE2I below will panic.
  3291  			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
  3292  			return Value{dst, nil, flag(Interface)}
  3293  		}
  3294  		x := valueInterface(v, false)
  3295  		if target == nil {
  3296  			target = unsafe_New(dst)
  3297  		}
  3298  		if dst.NumMethod() == 0 {
  3299  			*(*any)(target) = x
  3300  		} else {
  3301  			ifaceE2I(dst, x, target)
  3302  		}
  3303  		return Value{dst, target, flagIndir | flag(Interface)}
  3304  	}
  3305  
  3306  	// Failed.
  3307  	panic(context + ": value of type " + stringFor(v.typ()) + " is not assignable to type " + stringFor(dst))
  3308  }
  3309  
  3310  // Convert returns the value v converted to type t.
  3311  // If the usual Go conversion rules do not allow conversion
  3312  // of the value v to type t, or if converting v to type t panics, Convert panics.
  3313  func (v Value) Convert(t Type) Value {
  3314  	if v.flag&flagMethod != 0 {
  3315  		v = makeMethodValue("Convert", v)
  3316  	}
  3317  	op := convertOp(t.common(), v.typ())
  3318  	if op == nil {
  3319  		panic("reflect.Value.Convert: value of type " + stringFor(v.typ()) + " cannot be converted to type " + t.String())
  3320  	}
  3321  	return op(v, t)
  3322  }
  3323  
  3324  // CanConvert reports whether the value v can be converted to type t.
  3325  // If v.CanConvert(t) returns true then v.Convert(t) will not panic.
  3326  func (v Value) CanConvert(t Type) bool {
  3327  	vt := v.Type()
  3328  	if !vt.ConvertibleTo(t) {
  3329  		return false
  3330  	}
  3331  	// Converting from slice to array or to pointer-to-array can panic
  3332  	// depending on the value.
  3333  	switch {
  3334  	case vt.Kind() == Slice && t.Kind() == Array:
  3335  		if t.Len() > v.Len() {
  3336  			return false
  3337  		}
  3338  	case vt.Kind() == Slice && t.Kind() == Pointer && t.Elem().Kind() == Array:
  3339  		n := t.Elem().Len()
  3340  		if n > v.Len() {
  3341  			return false
  3342  		}
  3343  	}
  3344  	return true
  3345  }
  3346  
  3347  // Comparable reports whether the value v is comparable.
  3348  // If the type of v is an interface, this checks the dynamic type.
  3349  // If this reports true then v.Interface() == x will not panic for any x,
  3350  // nor will v.Equal(u) for any Value u.
  3351  func (v Value) Comparable() bool {
  3352  	k := v.Kind()
  3353  	switch k {
  3354  	case Invalid:
  3355  		return false
  3356  
  3357  	case Array:
  3358  		switch v.Type().Elem().Kind() {
  3359  		case Interface, Array, Struct:
  3360  			for i := 0; i < v.Type().Len(); i++ {
  3361  				if !v.Index(i).Comparable() {
  3362  					return false
  3363  				}
  3364  			}
  3365  			return true
  3366  		}
  3367  		return v.Type().Comparable()
  3368  
  3369  	case Interface:
  3370  		return v.Elem().Comparable()
  3371  
  3372  	case Struct:
  3373  		for i := 0; i < v.NumField(); i++ {
  3374  			if !v.Field(i).Comparable() {
  3375  				return false
  3376  			}
  3377  		}
  3378  		return true
  3379  
  3380  	default:
  3381  		return v.Type().Comparable()
  3382  	}
  3383  }
  3384  
  3385  // Equal reports true if v is equal to u.
  3386  // For two invalid values, Equal will report true.
  3387  // For an interface value, Equal will compare the value within the interface.
  3388  // Otherwise, If the values have different types, Equal will report false.
  3389  // Otherwise, for arrays and structs Equal will compare each element in order,
  3390  // and report false if it finds non-equal elements.
  3391  // During all comparisons, if values of the same type are compared,
  3392  // and the type is not comparable, Equal will panic.
  3393  func (v Value) Equal(u Value) bool {
  3394  	if v.Kind() == Interface {
  3395  		v = v.Elem()
  3396  	}
  3397  	if u.Kind() == Interface {
  3398  		u = u.Elem()
  3399  	}
  3400  
  3401  	if !v.IsValid() || !u.IsValid() {
  3402  		return v.IsValid() == u.IsValid()
  3403  	}
  3404  
  3405  	if v.Kind() != u.Kind() || v.Type() != u.Type() {
  3406  		return false
  3407  	}
  3408  
  3409  	// Handle each Kind directly rather than calling valueInterface
  3410  	// to avoid allocating.
  3411  	switch v.Kind() {
  3412  	default:
  3413  		panic("reflect.Value.Equal: invalid Kind")
  3414  	case Bool:
  3415  		return v.Bool() == u.Bool()
  3416  	case Int, Int8, Int16, Int32, Int64:
  3417  		return v.Int() == u.Int()
  3418  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3419  		return v.Uint() == u.Uint()
  3420  	case Float32, Float64:
  3421  		return v.Float() == u.Float()
  3422  	case Complex64, Complex128:
  3423  		return v.Complex() == u.Complex()
  3424  	case String:
  3425  		return v.String() == u.String()
  3426  	case Chan, Pointer, UnsafePointer:
  3427  		return v.Pointer() == u.Pointer()
  3428  	case Array:
  3429  		// u and v have the same type so they have the same length
  3430  		vl := v.Len()
  3431  		if vl == 0 {
  3432  			// panic on [0]func()
  3433  			if !v.Type().Elem().Comparable() {
  3434  				break
  3435  			}
  3436  			return true
  3437  		}
  3438  		for i := 0; i < vl; i++ {
  3439  			if !v.Index(i).Equal(u.Index(i)) {
  3440  				return false
  3441  			}
  3442  		}
  3443  		return true
  3444  	case Struct:
  3445  		// u and v have the same type so they have the same fields
  3446  		nf := v.NumField()
  3447  		for i := 0; i < nf; i++ {
  3448  			if !v.Field(i).Equal(u.Field(i)) {
  3449  				return false
  3450  			}
  3451  		}
  3452  		return true
  3453  	case Func, Map, Slice:
  3454  		break
  3455  	}
  3456  	panic("reflect.Value.Equal: values of type " + v.Type().String() + " are not comparable")
  3457  }
  3458  
  3459  // convertOp returns the function to convert a value of type src
  3460  // to a value of type dst. If the conversion is illegal, convertOp returns nil.
  3461  func convertOp(dst, src *abi.Type) func(Value, Type) Value {
  3462  	switch Kind(src.Kind()) {
  3463  	case Int, Int8, Int16, Int32, Int64:
  3464  		switch Kind(dst.Kind()) {
  3465  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3466  			return cvtInt
  3467  		case Float32, Float64:
  3468  			return cvtIntFloat
  3469  		case String:
  3470  			return cvtIntString
  3471  		}
  3472  
  3473  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3474  		switch Kind(dst.Kind()) {
  3475  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3476  			return cvtUint
  3477  		case Float32, Float64:
  3478  			return cvtUintFloat
  3479  		case String:
  3480  			return cvtUintString
  3481  		}
  3482  
  3483  	case Float32, Float64:
  3484  		switch Kind(dst.Kind()) {
  3485  		case Int, Int8, Int16, Int32, Int64:
  3486  			return cvtFloatInt
  3487  		case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  3488  			return cvtFloatUint
  3489  		case Float32, Float64:
  3490  			return cvtFloat
  3491  		}
  3492  
  3493  	case Complex64, Complex128:
  3494  		switch Kind(dst.Kind()) {
  3495  		case Complex64, Complex128:
  3496  			return cvtComplex
  3497  		}
  3498  
  3499  	case String:
  3500  		if dst.Kind() == abi.Slice && pkgPathFor(dst.Elem()) == "" {
  3501  			switch Kind(dst.Elem().Kind()) {
  3502  			case Uint8:
  3503  				return cvtStringBytes
  3504  			case Int32:
  3505  				return cvtStringRunes
  3506  			}
  3507  		}
  3508  
  3509  	case Slice:
  3510  		if dst.Kind() == abi.String && pkgPathFor(src.Elem()) == "" {
  3511  			switch Kind(src.Elem().Kind()) {
  3512  			case Uint8:
  3513  				return cvtBytesString
  3514  			case Int32:
  3515  				return cvtRunesString
  3516  			}
  3517  		}
  3518  		// "x is a slice, T is a pointer-to-array type,
  3519  		// and the slice and array types have identical element types."
  3520  		if dst.Kind() == abi.Pointer && dst.Elem().Kind() == abi.Array && src.Elem() == dst.Elem().Elem() {
  3521  			return cvtSliceArrayPtr
  3522  		}
  3523  		// "x is a slice, T is an array type,
  3524  		// and the slice and array types have identical element types."
  3525  		if dst.Kind() == abi.Array && src.Elem() == dst.Elem() {
  3526  			return cvtSliceArray
  3527  		}
  3528  
  3529  	case Chan:
  3530  		if dst.Kind() == abi.Chan && specialChannelAssignability(dst, src) {
  3531  			return cvtDirect
  3532  		}
  3533  	}
  3534  
  3535  	// dst and src have same underlying type.
  3536  	if haveIdenticalUnderlyingType(dst, src, false) {
  3537  		return cvtDirect
  3538  	}
  3539  
  3540  	// dst and src are non-defined pointer types with same underlying base type.
  3541  	if dst.Kind() == abi.Pointer && nameFor(dst) == "" &&
  3542  		src.Kind() == abi.Pointer && nameFor(src) == "" &&
  3543  		haveIdenticalUnderlyingType(elem(dst), elem(src), false) {
  3544  		return cvtDirect
  3545  	}
  3546  
  3547  	if implements(dst, src) {
  3548  		if src.Kind() == abi.Interface {
  3549  			return cvtI2I
  3550  		}
  3551  		return cvtT2I
  3552  	}
  3553  
  3554  	return nil
  3555  }
  3556  
  3557  // makeInt returns a Value of type t equal to bits (possibly truncated),
  3558  // where t is a signed or unsigned int type.
  3559  func makeInt(f flag, bits uint64, t Type) Value {
  3560  	typ := t.common()
  3561  	ptr := unsafe_New(typ)
  3562  	switch typ.Size() {
  3563  	case 1:
  3564  		*(*uint8)(ptr) = uint8(bits)
  3565  	case 2:
  3566  		*(*uint16)(ptr) = uint16(bits)
  3567  	case 4:
  3568  		*(*uint32)(ptr) = uint32(bits)
  3569  	case 8:
  3570  		*(*uint64)(ptr) = bits
  3571  	}
  3572  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3573  }
  3574  
  3575  // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
  3576  // where t is a float32 or float64 type.
  3577  func makeFloat(f flag, v float64, t Type) Value {
  3578  	typ := t.common()
  3579  	ptr := unsafe_New(typ)
  3580  	switch typ.Size() {
  3581  	case 4:
  3582  		*(*float32)(ptr) = float32(v)
  3583  	case 8:
  3584  		*(*float64)(ptr) = v
  3585  	}
  3586  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3587  }
  3588  
  3589  // makeFloat32 returns a Value of type t equal to v, where t is a float32 type.
  3590  func makeFloat32(f flag, v float32, t Type) Value {
  3591  	typ := t.common()
  3592  	ptr := unsafe_New(typ)
  3593  	*(*float32)(ptr) = v
  3594  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3595  }
  3596  
  3597  // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
  3598  // where t is a complex64 or complex128 type.
  3599  func makeComplex(f flag, v complex128, t Type) Value {
  3600  	typ := t.common()
  3601  	ptr := unsafe_New(typ)
  3602  	switch typ.Size() {
  3603  	case 8:
  3604  		*(*complex64)(ptr) = complex64(v)
  3605  	case 16:
  3606  		*(*complex128)(ptr) = v
  3607  	}
  3608  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  3609  }
  3610  
  3611  func makeString(f flag, v string, t Type) Value {
  3612  	ret := New(t).Elem()
  3613  	ret.SetString(v)
  3614  	ret.flag = ret.flag&^flagAddr | f
  3615  	return ret
  3616  }
  3617  
  3618  func makeBytes(f flag, v []byte, t Type) Value {
  3619  	ret := New(t).Elem()
  3620  	ret.SetBytes(v)
  3621  	ret.flag = ret.flag&^flagAddr | f
  3622  	return ret
  3623  }
  3624  
  3625  func makeRunes(f flag, v []rune, t Type) Value {
  3626  	ret := New(t).Elem()
  3627  	ret.setRunes(v)
  3628  	ret.flag = ret.flag&^flagAddr | f
  3629  	return ret
  3630  }
  3631  
  3632  // These conversion functions are returned by convertOp
  3633  // for classes of conversions. For example, the first function, cvtInt,
  3634  // takes any value v of signed int type and returns the value converted
  3635  // to type t, where t is any signed or unsigned int type.
  3636  
  3637  // convertOp: intXX -> [u]intXX
  3638  func cvtInt(v Value, t Type) Value {
  3639  	return makeInt(v.flag.ro(), uint64(v.Int()), t)
  3640  }
  3641  
  3642  // convertOp: uintXX -> [u]intXX
  3643  func cvtUint(v Value, t Type) Value {
  3644  	return makeInt(v.flag.ro(), v.Uint(), t)
  3645  }
  3646  
  3647  // convertOp: floatXX -> intXX
  3648  func cvtFloatInt(v Value, t Type) Value {
  3649  	return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
  3650  }
  3651  
  3652  // convertOp: floatXX -> uintXX
  3653  func cvtFloatUint(v Value, t Type) Value {
  3654  	return makeInt(v.flag.ro(), uint64(v.Float()), t)
  3655  }
  3656  
  3657  // convertOp: intXX -> floatXX
  3658  func cvtIntFloat(v Value, t Type) Value {
  3659  	return makeFloat(v.flag.ro(), float64(v.Int()), t)
  3660  }
  3661  
  3662  // convertOp: uintXX -> floatXX
  3663  func cvtUintFloat(v Value, t Type) Value {
  3664  	return makeFloat(v.flag.ro(), float64(v.Uint()), t)
  3665  }
  3666  
  3667  // convertOp: floatXX -> floatXX
  3668  func cvtFloat(v Value, t Type) Value {
  3669  	if v.Type().Kind() == Float32 && t.Kind() == Float32 {
  3670  		// Don't do any conversion if both types have underlying type float32.
  3671  		// This avoids converting to float64 and back, which will
  3672  		// convert a signaling NaN to a quiet NaN. See issue 36400.
  3673  		return makeFloat32(v.flag.ro(), *(*float32)(v.ptr), t)
  3674  	}
  3675  	return makeFloat(v.flag.ro(), v.Float(), t)
  3676  }
  3677  
  3678  // convertOp: complexXX -> complexXX
  3679  func cvtComplex(v Value, t Type) Value {
  3680  	return makeComplex(v.flag.ro(), v.Complex(), t)
  3681  }
  3682  
  3683  // convertOp: intXX -> string
  3684  func cvtIntString(v Value, t Type) Value {
  3685  	s := "\uFFFD"
  3686  	if x := v.Int(); int64(rune(x)) == x {
  3687  		s = string(rune(x))
  3688  	}
  3689  	return makeString(v.flag.ro(), s, t)
  3690  }
  3691  
  3692  // convertOp: uintXX -> string
  3693  func cvtUintString(v Value, t Type) Value {
  3694  	s := "\uFFFD"
  3695  	if x := v.Uint(); uint64(rune(x)) == x {
  3696  		s = string(rune(x))
  3697  	}
  3698  	return makeString(v.flag.ro(), s, t)
  3699  }
  3700  
  3701  // convertOp: []byte -> string
  3702  func cvtBytesString(v Value, t Type) Value {
  3703  	return makeString(v.flag.ro(), string(v.Bytes()), t)
  3704  }
  3705  
  3706  // convertOp: string -> []byte
  3707  func cvtStringBytes(v Value, t Type) Value {
  3708  	return makeBytes(v.flag.ro(), []byte(v.String()), t)
  3709  }
  3710  
  3711  // convertOp: []rune -> string
  3712  func cvtRunesString(v Value, t Type) Value {
  3713  	return makeString(v.flag.ro(), string(v.runes()), t)
  3714  }
  3715  
  3716  // convertOp: string -> []rune
  3717  func cvtStringRunes(v Value, t Type) Value {
  3718  	return makeRunes(v.flag.ro(), []rune(v.String()), t)
  3719  }
  3720  
  3721  // convertOp: []T -> *[N]T
  3722  func cvtSliceArrayPtr(v Value, t Type) Value {
  3723  	n := t.Elem().Len()
  3724  	if n > v.Len() {
  3725  		panic("reflect: cannot convert slice with length " + itoa.Itoa(v.Len()) + " to pointer to array with length " + itoa.Itoa(n))
  3726  	}
  3727  	h := (*unsafeheader.Slice)(v.ptr)
  3728  	return Value{t.common(), h.Data, v.flag&^(flagIndir|flagAddr|flagKindMask) | flag(Pointer)}
  3729  }
  3730  
  3731  // convertOp: []T -> [N]T
  3732  func cvtSliceArray(v Value, t Type) Value {
  3733  	n := t.Len()
  3734  	if n > v.Len() {
  3735  		panic("reflect: cannot convert slice with length " + itoa.Itoa(v.Len()) + " to array with length " + itoa.Itoa(n))
  3736  	}
  3737  	h := (*unsafeheader.Slice)(v.ptr)
  3738  	typ := t.common()
  3739  	ptr := h.Data
  3740  	c := unsafe_New(typ)
  3741  	typedmemmove(typ, c, ptr)
  3742  	ptr = c
  3743  
  3744  	return Value{typ, ptr, v.flag&^(flagAddr|flagKindMask) | flag(Array)}
  3745  }
  3746  
  3747  // convertOp: direct copy
  3748  func cvtDirect(v Value, typ Type) Value {
  3749  	f := v.flag
  3750  	t := typ.common()
  3751  	ptr := v.ptr
  3752  	if f&flagAddr != 0 {
  3753  		// indirect, mutable word - make a copy
  3754  		c := unsafe_New(t)
  3755  		typedmemmove(t, c, ptr)
  3756  		ptr = c
  3757  		f &^= flagAddr
  3758  	}
  3759  	return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
  3760  }
  3761  
  3762  // convertOp: concrete -> interface
  3763  func cvtT2I(v Value, typ Type) Value {
  3764  	target := unsafe_New(typ.common())
  3765  	x := valueInterface(v, false)
  3766  	if typ.NumMethod() == 0 {
  3767  		*(*any)(target) = x
  3768  	} else {
  3769  		ifaceE2I(typ.common(), x, target)
  3770  	}
  3771  	return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
  3772  }
  3773  
  3774  // convertOp: interface -> interface
  3775  func cvtI2I(v Value, typ Type) Value {
  3776  	if v.IsNil() {
  3777  		ret := Zero(typ)
  3778  		ret.flag |= v.flag.ro()
  3779  		return ret
  3780  	}
  3781  	return cvtT2I(v.Elem(), typ)
  3782  }
  3783  
  3784  // implemented in ../runtime
  3785  //
  3786  //go:noescape
  3787  func chancap(ch unsafe.Pointer) int
  3788  
  3789  //go:noescape
  3790  func chanclose(ch unsafe.Pointer)
  3791  
  3792  //go:noescape
  3793  func chanlen(ch unsafe.Pointer) int
  3794  
  3795  // Note: some of the noescape annotations below are technically a lie,
  3796  // but safe in the context of this package. Functions like chansend0
  3797  // and mapassign0 don't escape the referent, but may escape anything
  3798  // the referent points to (they do shallow copies of the referent).
  3799  // We add a 0 to their names and wrap them in functions with the
  3800  // proper escape behavior.
  3801  
  3802  //go:noescape
  3803  func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
  3804  
  3805  //go:noescape
  3806  func chansend0(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
  3807  
  3808  func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool {
  3809  	contentEscapes(val)
  3810  	return chansend0(ch, val, nb)
  3811  }
  3812  
  3813  func makechan(typ *abi.Type, size int) (ch unsafe.Pointer)
  3814  func makemap(t *abi.Type, cap int) (m unsafe.Pointer)
  3815  
  3816  //go:noescape
  3817  func mapaccess(t *abi.Type, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
  3818  
  3819  //go:noescape
  3820  func mapaccess_faststr(t *abi.Type, m unsafe.Pointer, key string) (val unsafe.Pointer)
  3821  
  3822  //go:noescape
  3823  func mapassign0(t *abi.Type, m unsafe.Pointer, key, val unsafe.Pointer)
  3824  
  3825  func mapassign(t *abi.Type, m unsafe.Pointer, key, val unsafe.Pointer) {
  3826  	contentEscapes(key)
  3827  	contentEscapes(val)
  3828  	mapassign0(t, m, key, val)
  3829  }
  3830  
  3831  //go:noescape
  3832  func mapassign_faststr0(t *abi.Type, m unsafe.Pointer, key string, val unsafe.Pointer)
  3833  
  3834  func mapassign_faststr(t *abi.Type, m unsafe.Pointer, key string, val unsafe.Pointer) {
  3835  	contentEscapes((*unsafeheader.String)(unsafe.Pointer(&key)).Data)
  3836  	contentEscapes(val)
  3837  	mapassign_faststr0(t, m, key, val)
  3838  }
  3839  
  3840  //go:noescape
  3841  func mapdelete(t *abi.Type, m unsafe.Pointer, key unsafe.Pointer)
  3842  
  3843  //go:noescape
  3844  func mapdelete_faststr(t *abi.Type, m unsafe.Pointer, key string)
  3845  
  3846  //go:noescape
  3847  func mapiterinit(t *abi.Type, m unsafe.Pointer, it *hiter)
  3848  
  3849  //go:noescape
  3850  func mapiterkey(it *hiter) (key unsafe.Pointer)
  3851  
  3852  //go:noescape
  3853  func mapiterelem(it *hiter) (elem unsafe.Pointer)
  3854  
  3855  //go:noescape
  3856  func mapiternext(it *hiter)
  3857  
  3858  //go:noescape
  3859  func maplen(m unsafe.Pointer) int
  3860  
  3861  func mapclear(t *abi.Type, m unsafe.Pointer)
  3862  
  3863  // call calls fn with "stackArgsSize" bytes of stack arguments laid out
  3864  // at stackArgs and register arguments laid out in regArgs. frameSize is
  3865  // the total amount of stack space that will be reserved by call, so this
  3866  // should include enough space to spill register arguments to the stack in
  3867  // case of preemption.
  3868  //
  3869  // After fn returns, call copies stackArgsSize-stackRetOffset result bytes
  3870  // back into stackArgs+stackRetOffset before returning, for any return
  3871  // values passed on the stack. Register-based return values will be found
  3872  // in the same regArgs structure.
  3873  //
  3874  // regArgs must also be prepared with an appropriate ReturnIsPtr bitmap
  3875  // indicating which registers will contain pointer-valued return values. The
  3876  // purpose of this bitmap is to keep pointers visible to the GC between
  3877  // returning from reflectcall and actually using them.
  3878  //
  3879  // If copying result bytes back from the stack, the caller must pass the
  3880  // argument frame type as stackArgsType, so that call can execute appropriate
  3881  // write barriers during the copy.
  3882  //
  3883  // Arguments passed through to call do not escape. The type is used only in a
  3884  // very limited callee of call, the stackArgs are copied, and regArgs is only
  3885  // used in the call frame.
  3886  //
  3887  //go:noescape
  3888  //go:linkname call runtime.reflectcall
  3889  func call(stackArgsType *abi.Type, f, stackArgs unsafe.Pointer, stackArgsSize, stackRetOffset, frameSize uint32, regArgs *abi.RegArgs)
  3890  
  3891  func ifaceE2I(t *abi.Type, src any, dst unsafe.Pointer)
  3892  
  3893  // memmove copies size bytes to dst from src. No write barriers are used.
  3894  //
  3895  //go:noescape
  3896  func memmove(dst, src unsafe.Pointer, size uintptr)
  3897  
  3898  // typedmemmove copies a value of type t to dst from src.
  3899  //
  3900  //go:noescape
  3901  func typedmemmove(t *abi.Type, dst, src unsafe.Pointer)
  3902  
  3903  // typedmemclr zeros the value at ptr of type t.
  3904  //
  3905  //go:noescape
  3906  func typedmemclr(t *abi.Type, ptr unsafe.Pointer)
  3907  
  3908  // typedmemclrpartial is like typedmemclr but assumes that
  3909  // dst points off bytes into the value and only clears size bytes.
  3910  //
  3911  //go:noescape
  3912  func typedmemclrpartial(t *abi.Type, ptr unsafe.Pointer, off, size uintptr)
  3913  
  3914  // typedslicecopy copies a slice of elemType values from src to dst,
  3915  // returning the number of elements copied.
  3916  //
  3917  //go:noescape
  3918  func typedslicecopy(t *abi.Type, dst, src unsafeheader.Slice) int
  3919  
  3920  // typedarrayclear zeroes the value at ptr of an array of elemType,
  3921  // only clears len elem.
  3922  //
  3923  //go:noescape
  3924  func typedarrayclear(elemType *abi.Type, ptr unsafe.Pointer, len int)
  3925  
  3926  //go:noescape
  3927  func typehash(t *abi.Type, p unsafe.Pointer, h uintptr) uintptr
  3928  
  3929  func verifyNotInHeapPtr(p uintptr) bool
  3930  
  3931  //go:noescape
  3932  func growslice(t *abi.Type, old unsafeheader.Slice, num int) unsafeheader.Slice
  3933  
  3934  // Dummy annotation marking that the value x escapes,
  3935  // for use in cases where the reflect code is so clever that
  3936  // the compiler cannot follow.
  3937  func escapes(x any) {
  3938  	if dummy.b {
  3939  		dummy.x = x
  3940  	}
  3941  }
  3942  
  3943  var dummy struct {
  3944  	b bool
  3945  	x any
  3946  }
  3947  
  3948  // Dummy annotation marking that the content of value x
  3949  // escapes (i.e. modeling roughly heap=*x),
  3950  // for use in cases where the reflect code is so clever that
  3951  // the compiler cannot follow.
  3952  func contentEscapes(x unsafe.Pointer) {
  3953  	if dummy.b {
  3954  		escapes(*(*any)(x)) // the dereference may not always be safe, but never executed
  3955  	}
  3956  }
  3957  
  3958  //go:nosplit
  3959  func noescape(p unsafe.Pointer) unsafe.Pointer {
  3960  	x := uintptr(p)
  3961  	return unsafe.Pointer(x ^ 0)
  3962  }
  3963  

View as plain text