github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/reflect/value.go (about)

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