Source file src/reflect/value.go

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

View as plain text