Source file src/reflect/value.go

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

View as plain text