Source file src/reflect/value.go

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

View as plain text