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

View as plain text