Black Lives Matter. Support the Equal Justice Initiative.

Source file src/reflect/value.go

Documentation: reflect

     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  	"internal/unsafeheader"
     9  	"math"
    10  	"runtime"
    11  	"unsafe"
    12  )
    13  
    14  const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const
    15  
    16  // Value is the reflection interface to a Go value.
    17  //
    18  // Not all methods apply to all kinds of values. Restrictions,
    19  // if any, are noted in the documentation for each method.
    20  // Use the Kind method to find out the kind of value before
    21  // calling kind-specific methods. Calling a method
    22  // inappropriate to the kind of type causes a run time panic.
    23  //
    24  // The zero Value represents no value.
    25  // Its IsValid method returns false, its Kind method returns Invalid,
    26  // its String method returns "<invalid Value>", and all other methods panic.
    27  // Most functions and methods never return an invalid value.
    28  // If one does, its documentation states the conditions explicitly.
    29  //
    30  // A Value can be used concurrently by multiple goroutines provided that
    31  // the underlying Go value can be used concurrently for the equivalent
    32  // direct operations.
    33  //
    34  // To compare two Values, compare the results of the Interface method.
    35  // Using == on two Values does not compare the underlying values
    36  // they represent.
    37  type Value struct {
    38  	// typ holds the type of the value represented by a Value.
    39  	typ *rtype
    40  
    41  	// Pointer-valued data or, if flagIndir is set, pointer to data.
    42  	// Valid when either flagIndir is set or typ.pointers() is true.
    43  	ptr unsafe.Pointer
    44  
    45  	// flag holds metadata about the value.
    46  	// The lowest bits are flag bits:
    47  	//	- flagStickyRO: obtained via unexported not embedded field, so read-only
    48  	//	- flagEmbedRO: obtained via unexported embedded field, so read-only
    49  	//	- flagIndir: val holds a pointer to the data
    50  	//	- flagAddr: v.CanAddr is true (implies flagIndir)
    51  	//	- flagMethod: v is a method value.
    52  	// The next five bits give the Kind of the value.
    53  	// This repeats typ.Kind() except for method values.
    54  	// The remaining 23+ bits give a method number for method values.
    55  	// If flag.kind() != Func, code can assume that flagMethod is unset.
    56  	// If ifaceIndir(typ), code can assume that flagIndir is set.
    57  	flag
    58  
    59  	// A method value represents a curried method invocation
    60  	// like r.Read for some receiver r. The typ+val+flag bits describe
    61  	// the receiver r, but the flag's Kind bits say Func (methods are
    62  	// functions), and the top bits of the flag give the method number
    63  	// in r's type's method table.
    64  }
    65  
    66  type flag uintptr
    67  
    68  const (
    69  	flagKindWidth        = 5 // there are 27 kinds
    70  	flagKindMask    flag = 1<<flagKindWidth - 1
    71  	flagStickyRO    flag = 1 << 5
    72  	flagEmbedRO     flag = 1 << 6
    73  	flagIndir       flag = 1 << 7
    74  	flagAddr        flag = 1 << 8
    75  	flagMethod      flag = 1 << 9
    76  	flagMethodShift      = 10
    77  	flagRO          flag = flagStickyRO | flagEmbedRO
    78  )
    79  
    80  func (f flag) kind() Kind {
    81  	return Kind(f & flagKindMask)
    82  }
    83  
    84  func (f flag) ro() flag {
    85  	if f&flagRO != 0 {
    86  		return flagStickyRO
    87  	}
    88  	return 0
    89  }
    90  
    91  // pointer returns the underlying pointer represented by v.
    92  // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
    93  // if v.Kind() == Ptr, the base type must not be go:notinheap.
    94  func (v Value) pointer() unsafe.Pointer {
    95  	if v.typ.size != ptrSize || !v.typ.pointers() {
    96  		panic("can't call pointer on a non-pointer Value")
    97  	}
    98  	if v.flag&flagIndir != 0 {
    99  		return *(*unsafe.Pointer)(v.ptr)
   100  	}
   101  	return v.ptr
   102  }
   103  
   104  // packEface converts v to the empty interface.
   105  func packEface(v Value) interface{} {
   106  	t := v.typ
   107  	var i interface{}
   108  	e := (*emptyInterface)(unsafe.Pointer(&i))
   109  	// First, fill in the data portion of the interface.
   110  	switch {
   111  	case ifaceIndir(t):
   112  		if v.flag&flagIndir == 0 {
   113  			panic("bad indir")
   114  		}
   115  		// Value is indirect, and so is the interface we're making.
   116  		ptr := v.ptr
   117  		if v.flag&flagAddr != 0 {
   118  			// TODO: pass safe boolean from valueInterface so
   119  			// we don't need to copy if safe==true?
   120  			c := unsafe_New(t)
   121  			typedmemmove(t, c, ptr)
   122  			ptr = c
   123  		}
   124  		e.word = ptr
   125  	case v.flag&flagIndir != 0:
   126  		// Value is indirect, but interface is direct. We need
   127  		// to load the data at v.ptr into the interface data word.
   128  		e.word = *(*unsafe.Pointer)(v.ptr)
   129  	default:
   130  		// Value is direct, and so is the interface.
   131  		e.word = v.ptr
   132  	}
   133  	// Now, fill in the type portion. We're very careful here not
   134  	// to have any operation between the e.word and e.typ assignments
   135  	// that would let the garbage collector observe the partially-built
   136  	// interface value.
   137  	e.typ = t
   138  	return i
   139  }
   140  
   141  // unpackEface converts the empty interface i to a Value.
   142  func unpackEface(i interface{}) Value {
   143  	e := (*emptyInterface)(unsafe.Pointer(&i))
   144  	// NOTE: don't read e.word until we know whether it is really a pointer or not.
   145  	t := e.typ
   146  	if t == nil {
   147  		return Value{}
   148  	}
   149  	f := flag(t.Kind())
   150  	if ifaceIndir(t) {
   151  		f |= flagIndir
   152  	}
   153  	return Value{t, e.word, f}
   154  }
   155  
   156  // A ValueError occurs when a Value method is invoked on
   157  // a Value that does not support it. Such cases are documented
   158  // in the description of each method.
   159  type ValueError struct {
   160  	Method string
   161  	Kind   Kind
   162  }
   163  
   164  func (e *ValueError) Error() string {
   165  	if e.Kind == 0 {
   166  		return "reflect: call of " + e.Method + " on zero Value"
   167  	}
   168  	return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
   169  }
   170  
   171  // methodName returns the name of the calling method,
   172  // assumed to be two stack frames above.
   173  func methodName() string {
   174  	pc, _, _, _ := runtime.Caller(2)
   175  	f := runtime.FuncForPC(pc)
   176  	if f == nil {
   177  		return "unknown method"
   178  	}
   179  	return f.Name()
   180  }
   181  
   182  // methodNameSkip is like methodName, but skips another stack frame.
   183  // This is a separate function so that reflect.flag.mustBe will be inlined.
   184  func methodNameSkip() string {
   185  	pc, _, _, _ := runtime.Caller(3)
   186  	f := runtime.FuncForPC(pc)
   187  	if f == nil {
   188  		return "unknown method"
   189  	}
   190  	return f.Name()
   191  }
   192  
   193  // emptyInterface is the header for an interface{} value.
   194  type emptyInterface struct {
   195  	typ  *rtype
   196  	word unsafe.Pointer
   197  }
   198  
   199  // nonEmptyInterface is the header for an interface value with methods.
   200  type nonEmptyInterface struct {
   201  	// see ../runtime/iface.go:/Itab
   202  	itab *struct {
   203  		ityp *rtype // static interface type
   204  		typ  *rtype // dynamic concrete type
   205  		hash uint32 // copy of typ.hash
   206  		_    [4]byte
   207  		fun  [100000]unsafe.Pointer // method table
   208  	}
   209  	word unsafe.Pointer
   210  }
   211  
   212  // mustBe panics if f's kind is not expected.
   213  // Making this a method on flag instead of on Value
   214  // (and embedding flag in Value) means that we can write
   215  // the very clear v.mustBe(Bool) and have it compile into
   216  // v.flag.mustBe(Bool), which will only bother to copy the
   217  // single important word for the receiver.
   218  func (f flag) mustBe(expected Kind) {
   219  	// TODO(mvdan): use f.kind() again once mid-stack inlining gets better
   220  	if Kind(f&flagKindMask) != expected {
   221  		panic(&ValueError{methodName(), f.kind()})
   222  	}
   223  }
   224  
   225  // mustBeExported panics if f records that the value was obtained using
   226  // an unexported field.
   227  func (f flag) mustBeExported() {
   228  	if f == 0 || f&flagRO != 0 {
   229  		f.mustBeExportedSlow()
   230  	}
   231  }
   232  
   233  func (f flag) mustBeExportedSlow() {
   234  	if f == 0 {
   235  		panic(&ValueError{methodNameSkip(), Invalid})
   236  	}
   237  	if f&flagRO != 0 {
   238  		panic("reflect: " + methodNameSkip() + " using value obtained using unexported field")
   239  	}
   240  }
   241  
   242  // mustBeAssignable panics if f records that the value is not assignable,
   243  // which is to say that either it was obtained using an unexported field
   244  // or it is not addressable.
   245  func (f flag) mustBeAssignable() {
   246  	if f&flagRO != 0 || f&flagAddr == 0 {
   247  		f.mustBeAssignableSlow()
   248  	}
   249  }
   250  
   251  func (f flag) mustBeAssignableSlow() {
   252  	if f == 0 {
   253  		panic(&ValueError{methodNameSkip(), Invalid})
   254  	}
   255  	// Assignable if addressable and not read-only.
   256  	if f&flagRO != 0 {
   257  		panic("reflect: " + methodNameSkip() + " using value obtained using unexported field")
   258  	}
   259  	if f&flagAddr == 0 {
   260  		panic("reflect: " + methodNameSkip() + " using unaddressable value")
   261  	}
   262  }
   263  
   264  // Addr returns a pointer value representing the address of v.
   265  // It panics if CanAddr() returns false.
   266  // Addr is typically used to obtain a pointer to a struct field
   267  // or slice element in order to call a method that requires a
   268  // pointer receiver.
   269  func (v Value) Addr() Value {
   270  	if v.flag&flagAddr == 0 {
   271  		panic("reflect.Value.Addr of unaddressable value")
   272  	}
   273  	// Preserve flagRO instead of using v.flag.ro() so that
   274  	// v.Addr().Elem() is equivalent to v (#32772)
   275  	fl := v.flag & flagRO
   276  	return Value{v.typ.ptrTo(), v.ptr, fl | flag(Ptr)}
   277  }
   278  
   279  // Bool returns v's underlying value.
   280  // It panics if v's kind is not Bool.
   281  func (v Value) Bool() bool {
   282  	v.mustBe(Bool)
   283  	return *(*bool)(v.ptr)
   284  }
   285  
   286  // Bytes returns v's underlying value.
   287  // It panics if v's underlying value is not a slice of bytes.
   288  func (v Value) Bytes() []byte {
   289  	v.mustBe(Slice)
   290  	if v.typ.Elem().Kind() != Uint8 {
   291  		panic("reflect.Value.Bytes of non-byte slice")
   292  	}
   293  	// Slice is always bigger than a word; assume flagIndir.
   294  	return *(*[]byte)(v.ptr)
   295  }
   296  
   297  // runes returns v's underlying value.
   298  // It panics if v's underlying value is not a slice of runes (int32s).
   299  func (v Value) runes() []rune {
   300  	v.mustBe(Slice)
   301  	if v.typ.Elem().Kind() != Int32 {
   302  		panic("reflect.Value.Bytes of non-rune slice")
   303  	}
   304  	// Slice is always bigger than a word; assume flagIndir.
   305  	return *(*[]rune)(v.ptr)
   306  }
   307  
   308  // CanAddr reports whether the value's address can be obtained with Addr.
   309  // Such values are called addressable. A value is addressable if it is
   310  // an element of a slice, an element of an addressable array,
   311  // a field of an addressable struct, or the result of dereferencing a pointer.
   312  // If CanAddr returns false, calling Addr will panic.
   313  func (v Value) CanAddr() bool {
   314  	return v.flag&flagAddr != 0
   315  }
   316  
   317  // CanSet reports whether the value of v can be changed.
   318  // A Value can be changed only if it is addressable and was not
   319  // obtained by the use of unexported struct fields.
   320  // If CanSet returns false, calling Set or any type-specific
   321  // setter (e.g., SetBool, SetInt) will panic.
   322  func (v Value) CanSet() bool {
   323  	return v.flag&(flagAddr|flagRO) == flagAddr
   324  }
   325  
   326  // Call calls the function v with the input arguments in.
   327  // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
   328  // Call panics if v's Kind is not Func.
   329  // It returns the output results as Values.
   330  // As in Go, each input argument must be assignable to the
   331  // type of the function's corresponding input parameter.
   332  // If v is a variadic function, Call creates the variadic slice parameter
   333  // itself, copying in the corresponding values.
   334  func (v Value) Call(in []Value) []Value {
   335  	v.mustBe(Func)
   336  	v.mustBeExported()
   337  	return v.call("Call", in)
   338  }
   339  
   340  // CallSlice calls the variadic function v with the input arguments in,
   341  // assigning the slice in[len(in)-1] to v's final variadic argument.
   342  // For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...).
   343  // CallSlice panics if v's Kind is not Func or if v is not variadic.
   344  // It returns the output results as Values.
   345  // As in Go, each input argument must be assignable to the
   346  // type of the function's corresponding input parameter.
   347  func (v Value) CallSlice(in []Value) []Value {
   348  	v.mustBe(Func)
   349  	v.mustBeExported()
   350  	return v.call("CallSlice", in)
   351  }
   352  
   353  var callGC bool // for testing; see TestCallMethodJump
   354  
   355  func (v Value) call(op string, in []Value) []Value {
   356  	// Get function pointer, type.
   357  	t := (*funcType)(unsafe.Pointer(v.typ))
   358  	var (
   359  		fn       unsafe.Pointer
   360  		rcvr     Value
   361  		rcvrtype *rtype
   362  	)
   363  	if v.flag&flagMethod != 0 {
   364  		rcvr = v
   365  		rcvrtype, t, fn = methodReceiver(op, v, int(v.flag)>>flagMethodShift)
   366  	} else if v.flag&flagIndir != 0 {
   367  		fn = *(*unsafe.Pointer)(v.ptr)
   368  	} else {
   369  		fn = v.ptr
   370  	}
   371  
   372  	if fn == nil {
   373  		panic("reflect.Value.Call: call of nil function")
   374  	}
   375  
   376  	isSlice := op == "CallSlice"
   377  	n := t.NumIn()
   378  	if isSlice {
   379  		if !t.IsVariadic() {
   380  			panic("reflect: CallSlice of non-variadic function")
   381  		}
   382  		if len(in) < n {
   383  			panic("reflect: CallSlice with too few input arguments")
   384  		}
   385  		if len(in) > n {
   386  			panic("reflect: CallSlice with too many input arguments")
   387  		}
   388  	} else {
   389  		if t.IsVariadic() {
   390  			n--
   391  		}
   392  		if len(in) < n {
   393  			panic("reflect: Call with too few input arguments")
   394  		}
   395  		if !t.IsVariadic() && len(in) > n {
   396  			panic("reflect: Call with too many input arguments")
   397  		}
   398  	}
   399  	for _, x := range in {
   400  		if x.Kind() == Invalid {
   401  			panic("reflect: " + op + " using zero Value argument")
   402  		}
   403  	}
   404  	for i := 0; i < n; i++ {
   405  		if xt, targ := in[i].Type(), t.In(i); !xt.AssignableTo(targ) {
   406  			panic("reflect: " + op + " using " + xt.String() + " as type " + targ.String())
   407  		}
   408  	}
   409  	if !isSlice && t.IsVariadic() {
   410  		// prepare slice for remaining values
   411  		m := len(in) - n
   412  		slice := MakeSlice(t.In(n), m, m)
   413  		elem := t.In(n).Elem()
   414  		for i := 0; i < m; i++ {
   415  			x := in[n+i]
   416  			if xt := x.Type(); !xt.AssignableTo(elem) {
   417  				panic("reflect: cannot use " + xt.String() + " as type " + elem.String() + " in " + op)
   418  			}
   419  			slice.Index(i).Set(x)
   420  		}
   421  		origIn := in
   422  		in = make([]Value, n+1)
   423  		copy(in[:n], origIn)
   424  		in[n] = slice
   425  	}
   426  
   427  	nin := len(in)
   428  	if nin != t.NumIn() {
   429  		panic("reflect.Value.Call: wrong argument count")
   430  	}
   431  	nout := t.NumOut()
   432  
   433  	// Compute frame type.
   434  	frametype, _, retOffset, _, framePool := funcLayout(t, rcvrtype)
   435  
   436  	// Allocate a chunk of memory for frame.
   437  	var args unsafe.Pointer
   438  	if nout == 0 {
   439  		args = framePool.Get().(unsafe.Pointer)
   440  	} else {
   441  		// Can't use pool if the function has return values.
   442  		// We will leak pointer to args in ret, so its lifetime is not scoped.
   443  		args = unsafe_New(frametype)
   444  	}
   445  	off := uintptr(0)
   446  
   447  	// Copy inputs into args.
   448  	if rcvrtype != nil {
   449  		storeRcvr(rcvr, args)
   450  		off = ptrSize
   451  	}
   452  	for i, v := range in {
   453  		v.mustBeExported()
   454  		targ := t.In(i).(*rtype)
   455  		a := uintptr(targ.align)
   456  		off = (off + a - 1) &^ (a - 1)
   457  		n := targ.size
   458  		if n == 0 {
   459  			// Not safe to compute args+off pointing at 0 bytes,
   460  			// because that might point beyond the end of the frame,
   461  			// but we still need to call assignTo to check assignability.
   462  			v.assignTo("reflect.Value.Call", targ, nil)
   463  			continue
   464  		}
   465  		addr := add(args, off, "n > 0")
   466  		v = v.assignTo("reflect.Value.Call", targ, addr)
   467  		if v.flag&flagIndir != 0 {
   468  			typedmemmove(targ, addr, v.ptr)
   469  		} else {
   470  			*(*unsafe.Pointer)(addr) = v.ptr
   471  		}
   472  		off += n
   473  	}
   474  
   475  	// Call.
   476  	call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
   477  
   478  	// For testing; see TestCallMethodJump.
   479  	if callGC {
   480  		runtime.GC()
   481  	}
   482  
   483  	var ret []Value
   484  	if nout == 0 {
   485  		typedmemclr(frametype, args)
   486  		framePool.Put(args)
   487  	} else {
   488  		// Zero the now unused input area of args,
   489  		// because the Values returned by this function contain pointers to the args object,
   490  		// and will thus keep the args object alive indefinitely.
   491  		typedmemclrpartial(frametype, args, 0, retOffset)
   492  
   493  		// Wrap Values around return values in args.
   494  		ret = make([]Value, nout)
   495  		off = retOffset
   496  		for i := 0; i < nout; i++ {
   497  			tv := t.Out(i)
   498  			a := uintptr(tv.Align())
   499  			off = (off + a - 1) &^ (a - 1)
   500  			if tv.Size() != 0 {
   501  				fl := flagIndir | flag(tv.Kind())
   502  				ret[i] = Value{tv.common(), add(args, off, "tv.Size() != 0"), fl}
   503  				// Note: this does introduce false sharing between results -
   504  				// if any result is live, they are all live.
   505  				// (And the space for the args is live as well, but as we've
   506  				// cleared that space it isn't as big a deal.)
   507  			} else {
   508  				// For zero-sized return value, args+off may point to the next object.
   509  				// In this case, return the zero value instead.
   510  				ret[i] = Zero(tv)
   511  			}
   512  			off += tv.Size()
   513  		}
   514  	}
   515  
   516  	return ret
   517  }
   518  
   519  // callReflect is the call implementation used by a function
   520  // returned by MakeFunc. In many ways it is the opposite of the
   521  // method Value.call above. The method above converts a call using Values
   522  // into a call of a function with a concrete argument frame, while
   523  // callReflect converts a call of a function with a concrete argument
   524  // frame into a call using Values.
   525  // It is in this file so that it can be next to the call method above.
   526  // The remainder of the MakeFunc implementation is in makefunc.go.
   527  //
   528  // NOTE: This function must be marked as a "wrapper" in the generated code,
   529  // so that the linker can make it work correctly for panic and recover.
   530  // The gc compilers know to do that for the name "reflect.callReflect".
   531  //
   532  // ctxt is the "closure" generated by MakeFunc.
   533  // frame is a pointer to the arguments to that closure on the stack.
   534  // retValid points to a boolean which should be set when the results
   535  // section of frame is set.
   536  func callReflect(ctxt *makeFuncImpl, frame unsafe.Pointer, retValid *bool) {
   537  	ftyp := ctxt.ftyp
   538  	f := ctxt.fn
   539  
   540  	// Copy argument frame into Values.
   541  	ptr := frame
   542  	off := uintptr(0)
   543  	in := make([]Value, 0, int(ftyp.inCount))
   544  	for _, typ := range ftyp.in() {
   545  		off += -off & uintptr(typ.align-1)
   546  		v := Value{typ, nil, flag(typ.Kind())}
   547  		if ifaceIndir(typ) {
   548  			// value cannot be inlined in interface data.
   549  			// Must make a copy, because f might keep a reference to it,
   550  			// and we cannot let f keep a reference to the stack frame
   551  			// after this function returns, not even a read-only reference.
   552  			v.ptr = unsafe_New(typ)
   553  			if typ.size > 0 {
   554  				typedmemmove(typ, v.ptr, add(ptr, off, "typ.size > 0"))
   555  			}
   556  			v.flag |= flagIndir
   557  		} else {
   558  			v.ptr = *(*unsafe.Pointer)(add(ptr, off, "1-ptr"))
   559  		}
   560  		in = append(in, v)
   561  		off += typ.size
   562  	}
   563  
   564  	// Call underlying function.
   565  	out := f(in)
   566  	numOut := ftyp.NumOut()
   567  	if len(out) != numOut {
   568  		panic("reflect: wrong return count from function created by MakeFunc")
   569  	}
   570  
   571  	// Copy results back into argument frame.
   572  	if numOut > 0 {
   573  		off += -off & (ptrSize - 1)
   574  		for i, typ := range ftyp.out() {
   575  			v := out[i]
   576  			if v.typ == nil {
   577  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   578  					" returned zero Value")
   579  			}
   580  			if v.flag&flagRO != 0 {
   581  				panic("reflect: function created by MakeFunc using " + funcName(f) +
   582  					" returned value obtained from unexported field")
   583  			}
   584  			off += -off & uintptr(typ.align-1)
   585  			if typ.size == 0 {
   586  				continue
   587  			}
   588  			addr := add(ptr, off, "typ.size > 0")
   589  
   590  			// Convert v to type typ if v is assignable to a variable
   591  			// of type t in the language spec.
   592  			// See issue 28761.
   593  			if typ.Kind() == Interface {
   594  				// We must clear the destination before calling assignTo,
   595  				// in case assignTo writes (with memory barriers) to the
   596  				// target location used as scratch space. See issue 39541.
   597  				*(*uintptr)(addr) = 0
   598  				*(*uintptr)(add(addr, ptrSize, "typ.size == 2*ptrSize")) = 0
   599  			}
   600  			v = v.assignTo("reflect.MakeFunc", typ, addr)
   601  
   602  			// We are writing to stack. No write barrier.
   603  			if v.flag&flagIndir != 0 {
   604  				memmove(addr, v.ptr, typ.size)
   605  			} else {
   606  				*(*uintptr)(addr) = uintptr(v.ptr)
   607  			}
   608  			off += typ.size
   609  		}
   610  	}
   611  
   612  	// Announce that the return values are valid.
   613  	// After this point the runtime can depend on the return values being valid.
   614  	*retValid = true
   615  
   616  	// We have to make sure that the out slice lives at least until
   617  	// the runtime knows the return values are valid. Otherwise, the
   618  	// return values might not be scanned by anyone during a GC.
   619  	// (out would be dead, and the return slots not yet alive.)
   620  	runtime.KeepAlive(out)
   621  
   622  	// runtime.getArgInfo expects to be able to find ctxt on the
   623  	// stack when it finds our caller, makeFuncStub. Make sure it
   624  	// doesn't get garbage collected.
   625  	runtime.KeepAlive(ctxt)
   626  }
   627  
   628  // methodReceiver returns information about the receiver
   629  // described by v. The Value v may or may not have the
   630  // flagMethod bit set, so the kind cached in v.flag should
   631  // not be used.
   632  // The return value rcvrtype gives the method's actual receiver type.
   633  // The return value t gives the method type signature (without the receiver).
   634  // The return value fn is a pointer to the method code.
   635  func methodReceiver(op string, v Value, methodIndex int) (rcvrtype *rtype, t *funcType, fn unsafe.Pointer) {
   636  	i := methodIndex
   637  	if v.typ.Kind() == Interface {
   638  		tt := (*interfaceType)(unsafe.Pointer(v.typ))
   639  		if uint(i) >= uint(len(tt.methods)) {
   640  			panic("reflect: internal error: invalid method index")
   641  		}
   642  		m := &tt.methods[i]
   643  		if !tt.nameOff(m.name).isExported() {
   644  			panic("reflect: " + op + " of unexported method")
   645  		}
   646  		iface := (*nonEmptyInterface)(v.ptr)
   647  		if iface.itab == nil {
   648  			panic("reflect: " + op + " of method on nil interface value")
   649  		}
   650  		rcvrtype = iface.itab.typ
   651  		fn = unsafe.Pointer(&iface.itab.fun[i])
   652  		t = (*funcType)(unsafe.Pointer(tt.typeOff(m.typ)))
   653  	} else {
   654  		rcvrtype = v.typ
   655  		ms := v.typ.exportedMethods()
   656  		if uint(i) >= uint(len(ms)) {
   657  			panic("reflect: internal error: invalid method index")
   658  		}
   659  		m := ms[i]
   660  		if !v.typ.nameOff(m.name).isExported() {
   661  			panic("reflect: " + op + " of unexported method")
   662  		}
   663  		ifn := v.typ.textOff(m.ifn)
   664  		fn = unsafe.Pointer(&ifn)
   665  		t = (*funcType)(unsafe.Pointer(v.typ.typeOff(m.mtyp)))
   666  	}
   667  	return
   668  }
   669  
   670  // v is a method receiver. Store at p the word which is used to
   671  // encode that receiver at the start of the argument list.
   672  // Reflect uses the "interface" calling convention for
   673  // methods, which always uses one word to record the receiver.
   674  func storeRcvr(v Value, p unsafe.Pointer) {
   675  	t := v.typ
   676  	if t.Kind() == Interface {
   677  		// the interface data word becomes the receiver word
   678  		iface := (*nonEmptyInterface)(v.ptr)
   679  		*(*unsafe.Pointer)(p) = iface.word
   680  	} else if v.flag&flagIndir != 0 && !ifaceIndir(t) {
   681  		*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(v.ptr)
   682  	} else {
   683  		*(*unsafe.Pointer)(p) = v.ptr
   684  	}
   685  }
   686  
   687  // align returns the result of rounding x up to a multiple of n.
   688  // n must be a power of two.
   689  func align(x, n uintptr) uintptr {
   690  	return (x + n - 1) &^ (n - 1)
   691  }
   692  
   693  // callMethod is the call implementation used by a function returned
   694  // by makeMethodValue (used by v.Method(i).Interface()).
   695  // It is a streamlined version of the usual reflect call: the caller has
   696  // already laid out the argument frame for us, so we don't have
   697  // to deal with individual Values for each argument.
   698  // It is in this file so that it can be next to the two similar functions above.
   699  // The remainder of the makeMethodValue implementation is in makefunc.go.
   700  //
   701  // NOTE: This function must be marked as a "wrapper" in the generated code,
   702  // so that the linker can make it work correctly for panic and recover.
   703  // The gc compilers know to do that for the name "reflect.callMethod".
   704  //
   705  // ctxt is the "closure" generated by makeVethodValue.
   706  // frame is a pointer to the arguments to that closure on the stack.
   707  // retValid points to a boolean which should be set when the results
   708  // section of frame is set.
   709  func callMethod(ctxt *methodValue, frame unsafe.Pointer, retValid *bool) {
   710  	rcvr := ctxt.rcvr
   711  	rcvrtype, t, fn := methodReceiver("call", rcvr, ctxt.method)
   712  	frametype, argSize, retOffset, _, framePool := funcLayout(t, rcvrtype)
   713  
   714  	// Make a new frame that is one word bigger so we can store the receiver.
   715  	// This space is used for both arguments and return values.
   716  	scratch := framePool.Get().(unsafe.Pointer)
   717  
   718  	// Copy in receiver and rest of args.
   719  	storeRcvr(rcvr, scratch)
   720  	// Align the first arg. The alignment can't be larger than ptrSize.
   721  	argOffset := uintptr(ptrSize)
   722  	if len(t.in()) > 0 {
   723  		argOffset = align(argOffset, uintptr(t.in()[0].align))
   724  	}
   725  	// Avoid constructing out-of-bounds pointers if there are no args.
   726  	if argSize-argOffset > 0 {
   727  		typedmemmovepartial(frametype, add(scratch, argOffset, "argSize > argOffset"), frame, argOffset, argSize-argOffset)
   728  	}
   729  
   730  	// Call.
   731  	// Call copies the arguments from scratch to the stack, calls fn,
   732  	// and then copies the results back into scratch.
   733  	call(frametype, fn, scratch, uint32(frametype.size), uint32(retOffset))
   734  
   735  	// Copy return values.
   736  	// Ignore any changes to args and just copy return values.
   737  	// Avoid constructing out-of-bounds pointers if there are no return values.
   738  	if frametype.size-retOffset > 0 {
   739  		callerRetOffset := retOffset - argOffset
   740  		// This copies to the stack. Write barriers are not needed.
   741  		memmove(add(frame, callerRetOffset, "frametype.size > retOffset"),
   742  			add(scratch, retOffset, "frametype.size > retOffset"),
   743  			frametype.size-retOffset)
   744  	}
   745  
   746  	// Tell the runtime it can now depend on the return values
   747  	// being properly initialized.
   748  	*retValid = true
   749  
   750  	// Clear the scratch space and put it back in the pool.
   751  	// This must happen after the statement above, so that the return
   752  	// values will always be scanned by someone.
   753  	typedmemclr(frametype, scratch)
   754  	framePool.Put(scratch)
   755  
   756  	// See the comment in callReflect.
   757  	runtime.KeepAlive(ctxt)
   758  }
   759  
   760  // funcName returns the name of f, for use in error messages.
   761  func funcName(f func([]Value) []Value) string {
   762  	pc := *(*uintptr)(unsafe.Pointer(&f))
   763  	rf := runtime.FuncForPC(pc)
   764  	if rf != nil {
   765  		return rf.Name()
   766  	}
   767  	return "closure"
   768  }
   769  
   770  // Cap returns v's capacity.
   771  // It panics if v's Kind is not Array, Chan, or Slice.
   772  func (v Value) Cap() int {
   773  	k := v.kind()
   774  	switch k {
   775  	case Array:
   776  		return v.typ.Len()
   777  	case Chan:
   778  		return chancap(v.pointer())
   779  	case Slice:
   780  		// Slice is always bigger than a word; assume flagIndir.
   781  		return (*unsafeheader.Slice)(v.ptr).Cap
   782  	}
   783  	panic(&ValueError{"reflect.Value.Cap", v.kind()})
   784  }
   785  
   786  // Close closes the channel v.
   787  // It panics if v's Kind is not Chan.
   788  func (v Value) Close() {
   789  	v.mustBe(Chan)
   790  	v.mustBeExported()
   791  	chanclose(v.pointer())
   792  }
   793  
   794  // Complex returns v's underlying value, as a complex128.
   795  // It panics if v's Kind is not Complex64 or Complex128
   796  func (v Value) Complex() complex128 {
   797  	k := v.kind()
   798  	switch k {
   799  	case Complex64:
   800  		return complex128(*(*complex64)(v.ptr))
   801  	case Complex128:
   802  		return *(*complex128)(v.ptr)
   803  	}
   804  	panic(&ValueError{"reflect.Value.Complex", v.kind()})
   805  }
   806  
   807  // Elem returns the value that the interface v contains
   808  // or that the pointer v points to.
   809  // It panics if v's Kind is not Interface or Ptr.
   810  // It returns the zero Value if v is nil.
   811  func (v Value) Elem() Value {
   812  	k := v.kind()
   813  	switch k {
   814  	case Interface:
   815  		var eface interface{}
   816  		if v.typ.NumMethod() == 0 {
   817  			eface = *(*interface{})(v.ptr)
   818  		} else {
   819  			eface = (interface{})(*(*interface {
   820  				M()
   821  			})(v.ptr))
   822  		}
   823  		x := unpackEface(eface)
   824  		if x.flag != 0 {
   825  			x.flag |= v.flag.ro()
   826  		}
   827  		return x
   828  	case Ptr:
   829  		ptr := v.ptr
   830  		if v.flag&flagIndir != 0 {
   831  			ptr = *(*unsafe.Pointer)(ptr)
   832  		}
   833  		// The returned value's address is v's value.
   834  		if ptr == nil {
   835  			return Value{}
   836  		}
   837  		tt := (*ptrType)(unsafe.Pointer(v.typ))
   838  		typ := tt.elem
   839  		fl := v.flag&flagRO | flagIndir | flagAddr
   840  		fl |= flag(typ.Kind())
   841  		return Value{typ, ptr, fl}
   842  	}
   843  	panic(&ValueError{"reflect.Value.Elem", v.kind()})
   844  }
   845  
   846  // Field returns the i'th field of the struct v.
   847  // It panics if v's Kind is not Struct or i is out of range.
   848  func (v Value) Field(i int) Value {
   849  	if v.kind() != Struct {
   850  		panic(&ValueError{"reflect.Value.Field", v.kind()})
   851  	}
   852  	tt := (*structType)(unsafe.Pointer(v.typ))
   853  	if uint(i) >= uint(len(tt.fields)) {
   854  		panic("reflect: Field index out of range")
   855  	}
   856  	field := &tt.fields[i]
   857  	typ := field.typ
   858  
   859  	// Inherit permission bits from v, but clear flagEmbedRO.
   860  	fl := v.flag&(flagStickyRO|flagIndir|flagAddr) | flag(typ.Kind())
   861  	// Using an unexported field forces flagRO.
   862  	if !field.name.isExported() {
   863  		if field.embedded() {
   864  			fl |= flagEmbedRO
   865  		} else {
   866  			fl |= flagStickyRO
   867  		}
   868  	}
   869  	// Either flagIndir is set and v.ptr points at struct,
   870  	// or flagIndir is not set and v.ptr is the actual struct data.
   871  	// In the former case, we want v.ptr + offset.
   872  	// In the latter case, we must have field.offset = 0,
   873  	// so v.ptr + field.offset is still the correct address.
   874  	ptr := add(v.ptr, field.offset(), "same as non-reflect &v.field")
   875  	return Value{typ, ptr, fl}
   876  }
   877  
   878  // FieldByIndex returns the nested field corresponding to index.
   879  // It panics if v's Kind is not struct.
   880  func (v Value) FieldByIndex(index []int) Value {
   881  	if len(index) == 1 {
   882  		return v.Field(index[0])
   883  	}
   884  	v.mustBe(Struct)
   885  	for i, x := range index {
   886  		if i > 0 {
   887  			if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
   888  				if v.IsNil() {
   889  					panic("reflect: indirection through nil pointer to embedded struct")
   890  				}
   891  				v = v.Elem()
   892  			}
   893  		}
   894  		v = v.Field(x)
   895  	}
   896  	return v
   897  }
   898  
   899  // FieldByName returns the struct field with the given name.
   900  // It returns the zero Value if no field was found.
   901  // It panics if v's Kind is not struct.
   902  func (v Value) FieldByName(name string) Value {
   903  	v.mustBe(Struct)
   904  	if f, ok := v.typ.FieldByName(name); ok {
   905  		return v.FieldByIndex(f.Index)
   906  	}
   907  	return Value{}
   908  }
   909  
   910  // FieldByNameFunc returns the struct field with a name
   911  // that satisfies the match function.
   912  // It panics if v's Kind is not struct.
   913  // It returns the zero Value if no field was found.
   914  func (v Value) FieldByNameFunc(match func(string) bool) Value {
   915  	if f, ok := v.typ.FieldByNameFunc(match); ok {
   916  		return v.FieldByIndex(f.Index)
   917  	}
   918  	return Value{}
   919  }
   920  
   921  // Float returns v's underlying value, as a float64.
   922  // It panics if v's Kind is not Float32 or Float64
   923  func (v Value) Float() float64 {
   924  	k := v.kind()
   925  	switch k {
   926  	case Float32:
   927  		return float64(*(*float32)(v.ptr))
   928  	case Float64:
   929  		return *(*float64)(v.ptr)
   930  	}
   931  	panic(&ValueError{"reflect.Value.Float", v.kind()})
   932  }
   933  
   934  var uint8Type = TypeOf(uint8(0)).(*rtype)
   935  
   936  // Index returns v's i'th element.
   937  // It panics if v's Kind is not Array, Slice, or String or i is out of range.
   938  func (v Value) Index(i int) Value {
   939  	switch v.kind() {
   940  	case Array:
   941  		tt := (*arrayType)(unsafe.Pointer(v.typ))
   942  		if uint(i) >= uint(tt.len) {
   943  			panic("reflect: array index out of range")
   944  		}
   945  		typ := tt.elem
   946  		offset := uintptr(i) * typ.size
   947  
   948  		// Either flagIndir is set and v.ptr points at array,
   949  		// or flagIndir is not set and v.ptr is the actual array data.
   950  		// In the former case, we want v.ptr + offset.
   951  		// In the latter case, we must be doing Index(0), so offset = 0,
   952  		// so v.ptr + offset is still the correct address.
   953  		val := add(v.ptr, offset, "same as &v[i], i < tt.len")
   954  		fl := v.flag&(flagIndir|flagAddr) | v.flag.ro() | flag(typ.Kind()) // bits same as overall array
   955  		return Value{typ, val, fl}
   956  
   957  	case Slice:
   958  		// Element flag same as Elem of Ptr.
   959  		// Addressable, indirect, possibly read-only.
   960  		s := (*unsafeheader.Slice)(v.ptr)
   961  		if uint(i) >= uint(s.Len) {
   962  			panic("reflect: slice index out of range")
   963  		}
   964  		tt := (*sliceType)(unsafe.Pointer(v.typ))
   965  		typ := tt.elem
   966  		val := arrayAt(s.Data, i, typ.size, "i < s.Len")
   967  		fl := flagAddr | flagIndir | v.flag.ro() | flag(typ.Kind())
   968  		return Value{typ, val, fl}
   969  
   970  	case String:
   971  		s := (*unsafeheader.String)(v.ptr)
   972  		if uint(i) >= uint(s.Len) {
   973  			panic("reflect: string index out of range")
   974  		}
   975  		p := arrayAt(s.Data, i, 1, "i < s.Len")
   976  		fl := v.flag.ro() | flag(Uint8) | flagIndir
   977  		return Value{uint8Type, p, fl}
   978  	}
   979  	panic(&ValueError{"reflect.Value.Index", v.kind()})
   980  }
   981  
   982  // Int returns v's underlying value, as an int64.
   983  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
   984  func (v Value) Int() int64 {
   985  	k := v.kind()
   986  	p := v.ptr
   987  	switch k {
   988  	case Int:
   989  		return int64(*(*int)(p))
   990  	case Int8:
   991  		return int64(*(*int8)(p))
   992  	case Int16:
   993  		return int64(*(*int16)(p))
   994  	case Int32:
   995  		return int64(*(*int32)(p))
   996  	case Int64:
   997  		return *(*int64)(p)
   998  	}
   999  	panic(&ValueError{"reflect.Value.Int", v.kind()})
  1000  }
  1001  
  1002  // CanInterface reports whether Interface can be used without panicking.
  1003  func (v Value) CanInterface() bool {
  1004  	if v.flag == 0 {
  1005  		panic(&ValueError{"reflect.Value.CanInterface", Invalid})
  1006  	}
  1007  	return v.flag&flagRO == 0
  1008  }
  1009  
  1010  // Interface returns v's current value as an interface{}.
  1011  // It is equivalent to:
  1012  //	var i interface{} = (v's underlying value)
  1013  // It panics if the Value was obtained by accessing
  1014  // unexported struct fields.
  1015  func (v Value) Interface() (i interface{}) {
  1016  	return valueInterface(v, true)
  1017  }
  1018  
  1019  func valueInterface(v Value, safe bool) interface{} {
  1020  	if v.flag == 0 {
  1021  		panic(&ValueError{"reflect.Value.Interface", Invalid})
  1022  	}
  1023  	if safe && v.flag&flagRO != 0 {
  1024  		// Do not allow access to unexported values via Interface,
  1025  		// because they might be pointers that should not be
  1026  		// writable or methods or function that should not be callable.
  1027  		panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
  1028  	}
  1029  	if v.flag&flagMethod != 0 {
  1030  		v = makeMethodValue("Interface", v)
  1031  	}
  1032  
  1033  	if v.kind() == Interface {
  1034  		// Special case: return the element inside the interface.
  1035  		// Empty interface has one layout, all interfaces with
  1036  		// methods have a second layout.
  1037  		if v.NumMethod() == 0 {
  1038  			return *(*interface{})(v.ptr)
  1039  		}
  1040  		return *(*interface {
  1041  			M()
  1042  		})(v.ptr)
  1043  	}
  1044  
  1045  	// TODO: pass safe to packEface so we don't need to copy if safe==true?
  1046  	return packEface(v)
  1047  }
  1048  
  1049  // InterfaceData returns the interface v's value as a uintptr pair.
  1050  // It panics if v's Kind is not Interface.
  1051  func (v Value) InterfaceData() [2]uintptr {
  1052  	// TODO: deprecate this
  1053  	v.mustBe(Interface)
  1054  	// We treat this as a read operation, so we allow
  1055  	// it even for unexported data, because the caller
  1056  	// has to import "unsafe" to turn it into something
  1057  	// that can be abused.
  1058  	// Interface value is always bigger than a word; assume flagIndir.
  1059  	return *(*[2]uintptr)(v.ptr)
  1060  }
  1061  
  1062  // IsNil reports whether its argument v is nil. The argument must be
  1063  // a chan, func, interface, map, pointer, or slice value; if it is
  1064  // not, IsNil panics. Note that IsNil is not always equivalent to a
  1065  // regular comparison with nil in Go. For example, if v was created
  1066  // by calling ValueOf with an uninitialized interface variable i,
  1067  // i==nil will be true but v.IsNil will panic as v will be the zero
  1068  // Value.
  1069  func (v Value) IsNil() bool {
  1070  	k := v.kind()
  1071  	switch k {
  1072  	case Chan, Func, Map, Ptr, UnsafePointer:
  1073  		if v.flag&flagMethod != 0 {
  1074  			return false
  1075  		}
  1076  		ptr := v.ptr
  1077  		if v.flag&flagIndir != 0 {
  1078  			ptr = *(*unsafe.Pointer)(ptr)
  1079  		}
  1080  		return ptr == nil
  1081  	case Interface, Slice:
  1082  		// Both interface and slice are nil if first word is 0.
  1083  		// Both are always bigger than a word; assume flagIndir.
  1084  		return *(*unsafe.Pointer)(v.ptr) == nil
  1085  	}
  1086  	panic(&ValueError{"reflect.Value.IsNil", v.kind()})
  1087  }
  1088  
  1089  // IsValid reports whether v represents a value.
  1090  // It returns false if v is the zero Value.
  1091  // If IsValid returns false, all other methods except String panic.
  1092  // Most functions and methods never return an invalid Value.
  1093  // If one does, its documentation states the conditions explicitly.
  1094  func (v Value) IsValid() bool {
  1095  	return v.flag != 0
  1096  }
  1097  
  1098  // IsZero reports whether v is the zero value for its type.
  1099  // It panics if the argument is invalid.
  1100  func (v Value) IsZero() bool {
  1101  	switch v.kind() {
  1102  	case Bool:
  1103  		return !v.Bool()
  1104  	case Int, Int8, Int16, Int32, Int64:
  1105  		return v.Int() == 0
  1106  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  1107  		return v.Uint() == 0
  1108  	case Float32, Float64:
  1109  		return math.Float64bits(v.Float()) == 0
  1110  	case Complex64, Complex128:
  1111  		c := v.Complex()
  1112  		return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
  1113  	case Array:
  1114  		for i := 0; i < v.Len(); i++ {
  1115  			if !v.Index(i).IsZero() {
  1116  				return false
  1117  			}
  1118  		}
  1119  		return true
  1120  	case Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer:
  1121  		return v.IsNil()
  1122  	case String:
  1123  		return v.Len() == 0
  1124  	case Struct:
  1125  		for i := 0; i < v.NumField(); i++ {
  1126  			if !v.Field(i).IsZero() {
  1127  				return false
  1128  			}
  1129  		}
  1130  		return true
  1131  	default:
  1132  		// This should never happens, but will act as a safeguard for
  1133  		// later, as a default value doesn't makes sense here.
  1134  		panic(&ValueError{"reflect.Value.IsZero", v.Kind()})
  1135  	}
  1136  }
  1137  
  1138  // Kind returns v's Kind.
  1139  // If v is the zero Value (IsValid returns false), Kind returns Invalid.
  1140  func (v Value) Kind() Kind {
  1141  	return v.kind()
  1142  }
  1143  
  1144  // Len returns v's length.
  1145  // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
  1146  func (v Value) Len() int {
  1147  	k := v.kind()
  1148  	switch k {
  1149  	case Array:
  1150  		tt := (*arrayType)(unsafe.Pointer(v.typ))
  1151  		return int(tt.len)
  1152  	case Chan:
  1153  		return chanlen(v.pointer())
  1154  	case Map:
  1155  		return maplen(v.pointer())
  1156  	case Slice:
  1157  		// Slice is bigger than a word; assume flagIndir.
  1158  		return (*unsafeheader.Slice)(v.ptr).Len
  1159  	case String:
  1160  		// String is bigger than a word; assume flagIndir.
  1161  		return (*unsafeheader.String)(v.ptr).Len
  1162  	}
  1163  	panic(&ValueError{"reflect.Value.Len", v.kind()})
  1164  }
  1165  
  1166  // MapIndex returns the value associated with key in the map v.
  1167  // It panics if v's Kind is not Map.
  1168  // It returns the zero Value if key is not found in the map or if v represents a nil map.
  1169  // As in Go, the key's value must be assignable to the map's key type.
  1170  func (v Value) MapIndex(key Value) Value {
  1171  	v.mustBe(Map)
  1172  	tt := (*mapType)(unsafe.Pointer(v.typ))
  1173  
  1174  	// Do not require key to be exported, so that DeepEqual
  1175  	// and other programs can use all the keys returned by
  1176  	// MapKeys as arguments to MapIndex. If either the map
  1177  	// or the key is unexported, though, the result will be
  1178  	// considered unexported. This is consistent with the
  1179  	// behavior for structs, which allow read but not write
  1180  	// of unexported fields.
  1181  	key = key.assignTo("reflect.Value.MapIndex", tt.key, nil)
  1182  
  1183  	var k unsafe.Pointer
  1184  	if key.flag&flagIndir != 0 {
  1185  		k = key.ptr
  1186  	} else {
  1187  		k = unsafe.Pointer(&key.ptr)
  1188  	}
  1189  	e := mapaccess(v.typ, v.pointer(), k)
  1190  	if e == nil {
  1191  		return Value{}
  1192  	}
  1193  	typ := tt.elem
  1194  	fl := (v.flag | key.flag).ro()
  1195  	fl |= flag(typ.Kind())
  1196  	return copyVal(typ, fl, e)
  1197  }
  1198  
  1199  // MapKeys returns a slice containing all the keys present in the map,
  1200  // in unspecified order.
  1201  // It panics if v's Kind is not Map.
  1202  // It returns an empty slice if v represents a nil map.
  1203  func (v Value) MapKeys() []Value {
  1204  	v.mustBe(Map)
  1205  	tt := (*mapType)(unsafe.Pointer(v.typ))
  1206  	keyType := tt.key
  1207  
  1208  	fl := v.flag.ro() | flag(keyType.Kind())
  1209  
  1210  	m := v.pointer()
  1211  	mlen := int(0)
  1212  	if m != nil {
  1213  		mlen = maplen(m)
  1214  	}
  1215  	it := mapiterinit(v.typ, m)
  1216  	a := make([]Value, mlen)
  1217  	var i int
  1218  	for i = 0; i < len(a); i++ {
  1219  		key := mapiterkey(it)
  1220  		if key == nil {
  1221  			// Someone deleted an entry from the map since we
  1222  			// called maplen above. It's a data race, but nothing
  1223  			// we can do about it.
  1224  			break
  1225  		}
  1226  		a[i] = copyVal(keyType, fl, key)
  1227  		mapiternext(it)
  1228  	}
  1229  	return a[:i]
  1230  }
  1231  
  1232  // A MapIter is an iterator for ranging over a map.
  1233  // See Value.MapRange.
  1234  type MapIter struct {
  1235  	m  Value
  1236  	it unsafe.Pointer
  1237  }
  1238  
  1239  // Key returns the key of the iterator's current map entry.
  1240  func (it *MapIter) Key() Value {
  1241  	if it.it == nil {
  1242  		panic("MapIter.Key called before Next")
  1243  	}
  1244  	if mapiterkey(it.it) == nil {
  1245  		panic("MapIter.Key called on exhausted iterator")
  1246  	}
  1247  
  1248  	t := (*mapType)(unsafe.Pointer(it.m.typ))
  1249  	ktype := t.key
  1250  	return copyVal(ktype, it.m.flag.ro()|flag(ktype.Kind()), mapiterkey(it.it))
  1251  }
  1252  
  1253  // Value returns the value of the iterator's current map entry.
  1254  func (it *MapIter) Value() Value {
  1255  	if it.it == nil {
  1256  		panic("MapIter.Value called before Next")
  1257  	}
  1258  	if mapiterkey(it.it) == nil {
  1259  		panic("MapIter.Value called on exhausted iterator")
  1260  	}
  1261  
  1262  	t := (*mapType)(unsafe.Pointer(it.m.typ))
  1263  	vtype := t.elem
  1264  	return copyVal(vtype, it.m.flag.ro()|flag(vtype.Kind()), mapiterelem(it.it))
  1265  }
  1266  
  1267  // Next advances the map iterator and reports whether there is another
  1268  // entry. It returns false when the iterator is exhausted; subsequent
  1269  // calls to Key, Value, or Next will panic.
  1270  func (it *MapIter) Next() bool {
  1271  	if it.it == nil {
  1272  		it.it = mapiterinit(it.m.typ, it.m.pointer())
  1273  	} else {
  1274  		if mapiterkey(it.it) == nil {
  1275  			panic("MapIter.Next called on exhausted iterator")
  1276  		}
  1277  		mapiternext(it.it)
  1278  	}
  1279  	return mapiterkey(it.it) != nil
  1280  }
  1281  
  1282  // MapRange returns a range iterator for a map.
  1283  // It panics if v's Kind is not Map.
  1284  //
  1285  // Call Next to advance the iterator, and Key/Value to access each entry.
  1286  // Next returns false when the iterator is exhausted.
  1287  // MapRange follows the same iteration semantics as a range statement.
  1288  //
  1289  // Example:
  1290  //
  1291  //	iter := reflect.ValueOf(m).MapRange()
  1292  // 	for iter.Next() {
  1293  //		k := iter.Key()
  1294  //		v := iter.Value()
  1295  //		...
  1296  //	}
  1297  //
  1298  func (v Value) MapRange() *MapIter {
  1299  	v.mustBe(Map)
  1300  	return &MapIter{m: v}
  1301  }
  1302  
  1303  // copyVal returns a Value containing the map key or value at ptr,
  1304  // allocating a new variable as needed.
  1305  func copyVal(typ *rtype, fl flag, ptr unsafe.Pointer) Value {
  1306  	if ifaceIndir(typ) {
  1307  		// Copy result so future changes to the map
  1308  		// won't change the underlying value.
  1309  		c := unsafe_New(typ)
  1310  		typedmemmove(typ, c, ptr)
  1311  		return Value{typ, c, fl | flagIndir}
  1312  	}
  1313  	return Value{typ, *(*unsafe.Pointer)(ptr), fl}
  1314  }
  1315  
  1316  // Method returns a function value corresponding to v's i'th method.
  1317  // The arguments to a Call on the returned function should not include
  1318  // a receiver; the returned function will always use v as the receiver.
  1319  // Method panics if i is out of range or if v is a nil interface value.
  1320  func (v Value) Method(i int) Value {
  1321  	if v.typ == nil {
  1322  		panic(&ValueError{"reflect.Value.Method", Invalid})
  1323  	}
  1324  	if v.flag&flagMethod != 0 || uint(i) >= uint(v.typ.NumMethod()) {
  1325  		panic("reflect: Method index out of range")
  1326  	}
  1327  	if v.typ.Kind() == Interface && v.IsNil() {
  1328  		panic("reflect: Method on nil interface value")
  1329  	}
  1330  	fl := v.flag.ro() | (v.flag & flagIndir)
  1331  	fl |= flag(Func)
  1332  	fl |= flag(i)<<flagMethodShift | flagMethod
  1333  	return Value{v.typ, v.ptr, fl}
  1334  }
  1335  
  1336  // NumMethod returns the number of exported methods in the value's method set.
  1337  func (v Value) NumMethod() int {
  1338  	if v.typ == nil {
  1339  		panic(&ValueError{"reflect.Value.NumMethod", Invalid})
  1340  	}
  1341  	if v.flag&flagMethod != 0 {
  1342  		return 0
  1343  	}
  1344  	return v.typ.NumMethod()
  1345  }
  1346  
  1347  // MethodByName returns a function value corresponding to the method
  1348  // of v with the given name.
  1349  // The arguments to a Call on the returned function should not include
  1350  // a receiver; the returned function will always use v as the receiver.
  1351  // It returns the zero Value if no method was found.
  1352  func (v Value) MethodByName(name string) Value {
  1353  	if v.typ == nil {
  1354  		panic(&ValueError{"reflect.Value.MethodByName", Invalid})
  1355  	}
  1356  	if v.flag&flagMethod != 0 {
  1357  		return Value{}
  1358  	}
  1359  	m, ok := v.typ.MethodByName(name)
  1360  	if !ok {
  1361  		return Value{}
  1362  	}
  1363  	return v.Method(m.Index)
  1364  }
  1365  
  1366  // NumField returns the number of fields in the struct v.
  1367  // It panics if v's Kind is not Struct.
  1368  func (v Value) NumField() int {
  1369  	v.mustBe(Struct)
  1370  	tt := (*structType)(unsafe.Pointer(v.typ))
  1371  	return len(tt.fields)
  1372  }
  1373  
  1374  // OverflowComplex reports whether the complex128 x cannot be represented by v's type.
  1375  // It panics if v's Kind is not Complex64 or Complex128.
  1376  func (v Value) OverflowComplex(x complex128) bool {
  1377  	k := v.kind()
  1378  	switch k {
  1379  	case Complex64:
  1380  		return overflowFloat32(real(x)) || overflowFloat32(imag(x))
  1381  	case Complex128:
  1382  		return false
  1383  	}
  1384  	panic(&ValueError{"reflect.Value.OverflowComplex", v.kind()})
  1385  }
  1386  
  1387  // OverflowFloat reports whether the float64 x cannot be represented by v's type.
  1388  // It panics if v's Kind is not Float32 or Float64.
  1389  func (v Value) OverflowFloat(x float64) bool {
  1390  	k := v.kind()
  1391  	switch k {
  1392  	case Float32:
  1393  		return overflowFloat32(x)
  1394  	case Float64:
  1395  		return false
  1396  	}
  1397  	panic(&ValueError{"reflect.Value.OverflowFloat", v.kind()})
  1398  }
  1399  
  1400  func overflowFloat32(x float64) bool {
  1401  	if x < 0 {
  1402  		x = -x
  1403  	}
  1404  	return math.MaxFloat32 < x && x <= math.MaxFloat64
  1405  }
  1406  
  1407  // OverflowInt reports whether the int64 x cannot be represented by v's type.
  1408  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
  1409  func (v Value) OverflowInt(x int64) bool {
  1410  	k := v.kind()
  1411  	switch k {
  1412  	case Int, Int8, Int16, Int32, Int64:
  1413  		bitSize := v.typ.size * 8
  1414  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1415  		return x != trunc
  1416  	}
  1417  	panic(&ValueError{"reflect.Value.OverflowInt", v.kind()})
  1418  }
  1419  
  1420  // OverflowUint reports whether the uint64 x cannot be represented by v's type.
  1421  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  1422  func (v Value) OverflowUint(x uint64) bool {
  1423  	k := v.kind()
  1424  	switch k {
  1425  	case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
  1426  		bitSize := v.typ.size * 8
  1427  		trunc := (x << (64 - bitSize)) >> (64 - bitSize)
  1428  		return x != trunc
  1429  	}
  1430  	panic(&ValueError{"reflect.Value.OverflowUint", v.kind()})
  1431  }
  1432  
  1433  //go:nocheckptr
  1434  // This prevents inlining Value.Pointer when -d=checkptr is enabled,
  1435  // which ensures cmd/compile can recognize unsafe.Pointer(v.Pointer())
  1436  // and make an exception.
  1437  
  1438  // Pointer returns v's value as a uintptr.
  1439  // It returns uintptr instead of unsafe.Pointer so that
  1440  // code using reflect cannot obtain unsafe.Pointers
  1441  // without importing the unsafe package explicitly.
  1442  // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
  1443  //
  1444  // If v's Kind is Func, the returned pointer is an underlying
  1445  // code pointer, but not necessarily enough to identify a
  1446  // single function uniquely. The only guarantee is that the
  1447  // result is zero if and only if v is a nil func Value.
  1448  //
  1449  // If v's Kind is Slice, the returned pointer is to the first
  1450  // element of the slice. If the slice is nil the returned value
  1451  // is 0.  If the slice is empty but non-nil the return value is non-zero.
  1452  func (v Value) Pointer() uintptr {
  1453  	// TODO: deprecate
  1454  	k := v.kind()
  1455  	switch k {
  1456  	case Ptr:
  1457  		if v.typ.ptrdata == 0 {
  1458  			// Handle pointers to go:notinheap types directly,
  1459  			// so we never materialize such pointers as an
  1460  			// unsafe.Pointer. (Such pointers are always indirect.)
  1461  			// See issue 42076.
  1462  			return *(*uintptr)(v.ptr)
  1463  		}
  1464  		fallthrough
  1465  	case Chan, Map, UnsafePointer:
  1466  		return uintptr(v.pointer())
  1467  	case Func:
  1468  		if v.flag&flagMethod != 0 {
  1469  			// As the doc comment says, the returned pointer is an
  1470  			// underlying code pointer but not necessarily enough to
  1471  			// identify a single function uniquely. All method expressions
  1472  			// created via reflect have the same underlying code pointer,
  1473  			// so their Pointers are equal. The function used here must
  1474  			// match the one used in makeMethodValue.
  1475  			f := methodValueCall
  1476  			return **(**uintptr)(unsafe.Pointer(&f))
  1477  		}
  1478  		p := v.pointer()
  1479  		// Non-nil func value points at data block.
  1480  		// First word of data block is actual code.
  1481  		if p != nil {
  1482  			p = *(*unsafe.Pointer)(p)
  1483  		}
  1484  		return uintptr(p)
  1485  
  1486  	case Slice:
  1487  		return (*SliceHeader)(v.ptr).Data
  1488  	}
  1489  	panic(&ValueError{"reflect.Value.Pointer", v.kind()})
  1490  }
  1491  
  1492  // Recv receives and returns a value from the channel v.
  1493  // It panics if v's Kind is not Chan.
  1494  // The receive blocks until a value is ready.
  1495  // The boolean value ok is true if the value x corresponds to a send
  1496  // on the channel, false if it is a zero value received because the channel is closed.
  1497  func (v Value) Recv() (x Value, ok bool) {
  1498  	v.mustBe(Chan)
  1499  	v.mustBeExported()
  1500  	return v.recv(false)
  1501  }
  1502  
  1503  // internal recv, possibly non-blocking (nb).
  1504  // v is known to be a channel.
  1505  func (v Value) recv(nb bool) (val Value, ok bool) {
  1506  	tt := (*chanType)(unsafe.Pointer(v.typ))
  1507  	if ChanDir(tt.dir)&RecvDir == 0 {
  1508  		panic("reflect: recv on send-only channel")
  1509  	}
  1510  	t := tt.elem
  1511  	val = Value{t, nil, flag(t.Kind())}
  1512  	var p unsafe.Pointer
  1513  	if ifaceIndir(t) {
  1514  		p = unsafe_New(t)
  1515  		val.ptr = p
  1516  		val.flag |= flagIndir
  1517  	} else {
  1518  		p = unsafe.Pointer(&val.ptr)
  1519  	}
  1520  	selected, ok := chanrecv(v.pointer(), nb, p)
  1521  	if !selected {
  1522  		val = Value{}
  1523  	}
  1524  	return
  1525  }
  1526  
  1527  // Send sends x on the channel v.
  1528  // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
  1529  // As in Go, x's value must be assignable to the channel's element type.
  1530  func (v Value) Send(x Value) {
  1531  	v.mustBe(Chan)
  1532  	v.mustBeExported()
  1533  	v.send(x, false)
  1534  }
  1535  
  1536  // internal send, possibly non-blocking.
  1537  // v is known to be a channel.
  1538  func (v Value) send(x Value, nb bool) (selected bool) {
  1539  	tt := (*chanType)(unsafe.Pointer(v.typ))
  1540  	if ChanDir(tt.dir)&SendDir == 0 {
  1541  		panic("reflect: send on recv-only channel")
  1542  	}
  1543  	x.mustBeExported()
  1544  	x = x.assignTo("reflect.Value.Send", tt.elem, nil)
  1545  	var p unsafe.Pointer
  1546  	if x.flag&flagIndir != 0 {
  1547  		p = x.ptr
  1548  	} else {
  1549  		p = unsafe.Pointer(&x.ptr)
  1550  	}
  1551  	return chansend(v.pointer(), p, nb)
  1552  }
  1553  
  1554  // Set assigns x to the value v.
  1555  // It panics if CanSet returns false.
  1556  // As in Go, x's value must be assignable to v's type.
  1557  func (v Value) Set(x Value) {
  1558  	v.mustBeAssignable()
  1559  	x.mustBeExported() // do not let unexported x leak
  1560  	var target unsafe.Pointer
  1561  	if v.kind() == Interface {
  1562  		target = v.ptr
  1563  	}
  1564  	x = x.assignTo("reflect.Set", v.typ, target)
  1565  	if x.flag&flagIndir != 0 {
  1566  		typedmemmove(v.typ, v.ptr, x.ptr)
  1567  	} else {
  1568  		*(*unsafe.Pointer)(v.ptr) = x.ptr
  1569  	}
  1570  }
  1571  
  1572  // SetBool sets v's underlying value.
  1573  // It panics if v's Kind is not Bool or if CanSet() is false.
  1574  func (v Value) SetBool(x bool) {
  1575  	v.mustBeAssignable()
  1576  	v.mustBe(Bool)
  1577  	*(*bool)(v.ptr) = x
  1578  }
  1579  
  1580  // SetBytes sets v's underlying value.
  1581  // It panics if v's underlying value is not a slice of bytes.
  1582  func (v Value) SetBytes(x []byte) {
  1583  	v.mustBeAssignable()
  1584  	v.mustBe(Slice)
  1585  	if v.typ.Elem().Kind() != Uint8 {
  1586  		panic("reflect.Value.SetBytes of non-byte slice")
  1587  	}
  1588  	*(*[]byte)(v.ptr) = x
  1589  }
  1590  
  1591  // setRunes sets v's underlying value.
  1592  // It panics if v's underlying value is not a slice of runes (int32s).
  1593  func (v Value) setRunes(x []rune) {
  1594  	v.mustBeAssignable()
  1595  	v.mustBe(Slice)
  1596  	if v.typ.Elem().Kind() != Int32 {
  1597  		panic("reflect.Value.setRunes of non-rune slice")
  1598  	}
  1599  	*(*[]rune)(v.ptr) = x
  1600  }
  1601  
  1602  // SetComplex sets v's underlying value to x.
  1603  // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
  1604  func (v Value) SetComplex(x complex128) {
  1605  	v.mustBeAssignable()
  1606  	switch k := v.kind(); k {
  1607  	default:
  1608  		panic(&ValueError{"reflect.Value.SetComplex", v.kind()})
  1609  	case Complex64:
  1610  		*(*complex64)(v.ptr) = complex64(x)
  1611  	case Complex128:
  1612  		*(*complex128)(v.ptr) = x
  1613  	}
  1614  }
  1615  
  1616  // SetFloat sets v's underlying value to x.
  1617  // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
  1618  func (v Value) SetFloat(x float64) {
  1619  	v.mustBeAssignable()
  1620  	switch k := v.kind(); k {
  1621  	default:
  1622  		panic(&ValueError{"reflect.Value.SetFloat", v.kind()})
  1623  	case Float32:
  1624  		*(*float32)(v.ptr) = float32(x)
  1625  	case Float64:
  1626  		*(*float64)(v.ptr) = x
  1627  	}
  1628  }
  1629  
  1630  // SetInt sets v's underlying value to x.
  1631  // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
  1632  func (v Value) SetInt(x int64) {
  1633  	v.mustBeAssignable()
  1634  	switch k := v.kind(); k {
  1635  	default:
  1636  		panic(&ValueError{"reflect.Value.SetInt", v.kind()})
  1637  	case Int:
  1638  		*(*int)(v.ptr) = int(x)
  1639  	case Int8:
  1640  		*(*int8)(v.ptr) = int8(x)
  1641  	case Int16:
  1642  		*(*int16)(v.ptr) = int16(x)
  1643  	case Int32:
  1644  		*(*int32)(v.ptr) = int32(x)
  1645  	case Int64:
  1646  		*(*int64)(v.ptr) = x
  1647  	}
  1648  }
  1649  
  1650  // SetLen sets v's length to n.
  1651  // It panics if v's Kind is not Slice or if n is negative or
  1652  // greater than the capacity of the slice.
  1653  func (v Value) SetLen(n int) {
  1654  	v.mustBeAssignable()
  1655  	v.mustBe(Slice)
  1656  	s := (*unsafeheader.Slice)(v.ptr)
  1657  	if uint(n) > uint(s.Cap) {
  1658  		panic("reflect: slice length out of range in SetLen")
  1659  	}
  1660  	s.Len = n
  1661  }
  1662  
  1663  // SetCap sets v's capacity to n.
  1664  // It panics if v's Kind is not Slice or if n is smaller than the length or
  1665  // greater than the capacity of the slice.
  1666  func (v Value) SetCap(n int) {
  1667  	v.mustBeAssignable()
  1668  	v.mustBe(Slice)
  1669  	s := (*unsafeheader.Slice)(v.ptr)
  1670  	if n < s.Len || n > s.Cap {
  1671  		panic("reflect: slice capacity out of range in SetCap")
  1672  	}
  1673  	s.Cap = n
  1674  }
  1675  
  1676  // SetMapIndex sets the element associated with key in the map v to elem.
  1677  // It panics if v's Kind is not Map.
  1678  // If elem is the zero Value, SetMapIndex deletes the key from the map.
  1679  // Otherwise if v holds a nil map, SetMapIndex will panic.
  1680  // As in Go, key's elem must be assignable to the map's key type,
  1681  // and elem's value must be assignable to the map's elem type.
  1682  func (v Value) SetMapIndex(key, elem Value) {
  1683  	v.mustBe(Map)
  1684  	v.mustBeExported()
  1685  	key.mustBeExported()
  1686  	tt := (*mapType)(unsafe.Pointer(v.typ))
  1687  	key = key.assignTo("reflect.Value.SetMapIndex", tt.key, nil)
  1688  	var k unsafe.Pointer
  1689  	if key.flag&flagIndir != 0 {
  1690  		k = key.ptr
  1691  	} else {
  1692  		k = unsafe.Pointer(&key.ptr)
  1693  	}
  1694  	if elem.typ == nil {
  1695  		mapdelete(v.typ, v.pointer(), k)
  1696  		return
  1697  	}
  1698  	elem.mustBeExported()
  1699  	elem = elem.assignTo("reflect.Value.SetMapIndex", tt.elem, nil)
  1700  	var e unsafe.Pointer
  1701  	if elem.flag&flagIndir != 0 {
  1702  		e = elem.ptr
  1703  	} else {
  1704  		e = unsafe.Pointer(&elem.ptr)
  1705  	}
  1706  	mapassign(v.typ, v.pointer(), k, e)
  1707  }
  1708  
  1709  // SetUint sets v's underlying value to x.
  1710  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
  1711  func (v Value) SetUint(x uint64) {
  1712  	v.mustBeAssignable()
  1713  	switch k := v.kind(); k {
  1714  	default:
  1715  		panic(&ValueError{"reflect.Value.SetUint", v.kind()})
  1716  	case Uint:
  1717  		*(*uint)(v.ptr) = uint(x)
  1718  	case Uint8:
  1719  		*(*uint8)(v.ptr) = uint8(x)
  1720  	case Uint16:
  1721  		*(*uint16)(v.ptr) = uint16(x)
  1722  	case Uint32:
  1723  		*(*uint32)(v.ptr) = uint32(x)
  1724  	case Uint64:
  1725  		*(*uint64)(v.ptr) = x
  1726  	case Uintptr:
  1727  		*(*uintptr)(v.ptr) = uintptr(x)
  1728  	}
  1729  }
  1730  
  1731  // SetPointer sets the unsafe.Pointer value v to x.
  1732  // It panics if v's Kind is not UnsafePointer.
  1733  func (v Value) SetPointer(x unsafe.Pointer) {
  1734  	v.mustBeAssignable()
  1735  	v.mustBe(UnsafePointer)
  1736  	*(*unsafe.Pointer)(v.ptr) = x
  1737  }
  1738  
  1739  // SetString sets v's underlying value to x.
  1740  // It panics if v's Kind is not String or if CanSet() is false.
  1741  func (v Value) SetString(x string) {
  1742  	v.mustBeAssignable()
  1743  	v.mustBe(String)
  1744  	*(*string)(v.ptr) = x
  1745  }
  1746  
  1747  // Slice returns v[i:j].
  1748  // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
  1749  // or if the indexes are out of bounds.
  1750  func (v Value) Slice(i, j int) Value {
  1751  	var (
  1752  		cap  int
  1753  		typ  *sliceType
  1754  		base unsafe.Pointer
  1755  	)
  1756  	switch kind := v.kind(); kind {
  1757  	default:
  1758  		panic(&ValueError{"reflect.Value.Slice", v.kind()})
  1759  
  1760  	case Array:
  1761  		if v.flag&flagAddr == 0 {
  1762  			panic("reflect.Value.Slice: slice of unaddressable array")
  1763  		}
  1764  		tt := (*arrayType)(unsafe.Pointer(v.typ))
  1765  		cap = int(tt.len)
  1766  		typ = (*sliceType)(unsafe.Pointer(tt.slice))
  1767  		base = v.ptr
  1768  
  1769  	case Slice:
  1770  		typ = (*sliceType)(unsafe.Pointer(v.typ))
  1771  		s := (*unsafeheader.Slice)(v.ptr)
  1772  		base = s.Data
  1773  		cap = s.Cap
  1774  
  1775  	case String:
  1776  		s := (*unsafeheader.String)(v.ptr)
  1777  		if i < 0 || j < i || j > s.Len {
  1778  			panic("reflect.Value.Slice: string slice index out of bounds")
  1779  		}
  1780  		var t unsafeheader.String
  1781  		if i < s.Len {
  1782  			t = unsafeheader.String{Data: arrayAt(s.Data, i, 1, "i < s.Len"), Len: j - i}
  1783  		}
  1784  		return Value{v.typ, unsafe.Pointer(&t), v.flag}
  1785  	}
  1786  
  1787  	if i < 0 || j < i || j > cap {
  1788  		panic("reflect.Value.Slice: slice index out of bounds")
  1789  	}
  1790  
  1791  	// Declare slice so that gc can see the base pointer in it.
  1792  	var x []unsafe.Pointer
  1793  
  1794  	// Reinterpret as *unsafeheader.Slice to edit.
  1795  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  1796  	s.Len = j - i
  1797  	s.Cap = cap - i
  1798  	if cap-i > 0 {
  1799  		s.Data = arrayAt(base, i, typ.elem.Size(), "i < cap")
  1800  	} else {
  1801  		// do not advance pointer, to avoid pointing beyond end of slice
  1802  		s.Data = base
  1803  	}
  1804  
  1805  	fl := v.flag.ro() | flagIndir | flag(Slice)
  1806  	return Value{typ.common(), unsafe.Pointer(&x), fl}
  1807  }
  1808  
  1809  // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
  1810  // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
  1811  // or if the indexes are out of bounds.
  1812  func (v Value) Slice3(i, j, k int) Value {
  1813  	var (
  1814  		cap  int
  1815  		typ  *sliceType
  1816  		base unsafe.Pointer
  1817  	)
  1818  	switch kind := v.kind(); kind {
  1819  	default:
  1820  		panic(&ValueError{"reflect.Value.Slice3", v.kind()})
  1821  
  1822  	case Array:
  1823  		if v.flag&flagAddr == 0 {
  1824  			panic("reflect.Value.Slice3: slice of unaddressable array")
  1825  		}
  1826  		tt := (*arrayType)(unsafe.Pointer(v.typ))
  1827  		cap = int(tt.len)
  1828  		typ = (*sliceType)(unsafe.Pointer(tt.slice))
  1829  		base = v.ptr
  1830  
  1831  	case Slice:
  1832  		typ = (*sliceType)(unsafe.Pointer(v.typ))
  1833  		s := (*unsafeheader.Slice)(v.ptr)
  1834  		base = s.Data
  1835  		cap = s.Cap
  1836  	}
  1837  
  1838  	if i < 0 || j < i || k < j || k > cap {
  1839  		panic("reflect.Value.Slice3: slice index out of bounds")
  1840  	}
  1841  
  1842  	// Declare slice so that the garbage collector
  1843  	// can see the base pointer in it.
  1844  	var x []unsafe.Pointer
  1845  
  1846  	// Reinterpret as *unsafeheader.Slice to edit.
  1847  	s := (*unsafeheader.Slice)(unsafe.Pointer(&x))
  1848  	s.Len = j - i
  1849  	s.Cap = k - i
  1850  	if k-i > 0 {
  1851  		s.Data = arrayAt(base, i, typ.elem.Size(), "i < k <= cap")
  1852  	} else {
  1853  		// do not advance pointer, to avoid pointing beyond end of slice
  1854  		s.Data = base
  1855  	}
  1856  
  1857  	fl := v.flag.ro() | flagIndir | flag(Slice)
  1858  	return Value{typ.common(), unsafe.Pointer(&x), fl}
  1859  }
  1860  
  1861  // String returns the string v's underlying value, as a string.
  1862  // String is a special case because of Go's String method convention.
  1863  // Unlike the other getters, it does not panic if v's Kind is not String.
  1864  // Instead, it returns a string of the form "<T value>" where T is v's type.
  1865  // The fmt package treats Values specially. It does not call their String
  1866  // method implicitly but instead prints the concrete values they hold.
  1867  func (v Value) String() string {
  1868  	switch k := v.kind(); k {
  1869  	case Invalid:
  1870  		return "<invalid Value>"
  1871  	case String:
  1872  		return *(*string)(v.ptr)
  1873  	}
  1874  	// If you call String on a reflect.Value of other type, it's better to
  1875  	// print something than to panic. Useful in debugging.
  1876  	return "<" + v.Type().String() + " Value>"
  1877  }
  1878  
  1879  // TryRecv attempts to receive a value from the channel v but will not block.
  1880  // It panics if v's Kind is not Chan.
  1881  // If the receive delivers a value, x is the transferred value and ok is true.
  1882  // If the receive cannot finish without blocking, x is the zero Value and ok is false.
  1883  // If the channel is closed, x is the zero value for the channel's element type and ok is false.
  1884  func (v Value) TryRecv() (x Value, ok bool) {
  1885  	v.mustBe(Chan)
  1886  	v.mustBeExported()
  1887  	return v.recv(true)
  1888  }
  1889  
  1890  // TrySend attempts to send x on the channel v but will not block.
  1891  // It panics if v's Kind is not Chan.
  1892  // It reports whether the value was sent.
  1893  // As in Go, x's value must be assignable to the channel's element type.
  1894  func (v Value) TrySend(x Value) bool {
  1895  	v.mustBe(Chan)
  1896  	v.mustBeExported()
  1897  	return v.send(x, true)
  1898  }
  1899  
  1900  // Type returns v's type.
  1901  func (v Value) Type() Type {
  1902  	f := v.flag
  1903  	if f == 0 {
  1904  		panic(&ValueError{"reflect.Value.Type", Invalid})
  1905  	}
  1906  	if f&flagMethod == 0 {
  1907  		// Easy case
  1908  		return v.typ
  1909  	}
  1910  
  1911  	// Method value.
  1912  	// v.typ describes the receiver, not the method type.
  1913  	i := int(v.flag) >> flagMethodShift
  1914  	if v.typ.Kind() == Interface {
  1915  		// Method on interface.
  1916  		tt := (*interfaceType)(unsafe.Pointer(v.typ))
  1917  		if uint(i) >= uint(len(tt.methods)) {
  1918  			panic("reflect: internal error: invalid method index")
  1919  		}
  1920  		m := &tt.methods[i]
  1921  		return v.typ.typeOff(m.typ)
  1922  	}
  1923  	// Method on concrete type.
  1924  	ms := v.typ.exportedMethods()
  1925  	if uint(i) >= uint(len(ms)) {
  1926  		panic("reflect: internal error: invalid method index")
  1927  	}
  1928  	m := ms[i]
  1929  	return v.typ.typeOff(m.mtyp)
  1930  }
  1931  
  1932  // Uint returns v's underlying value, as a uint64.
  1933  // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
  1934  func (v Value) Uint() uint64 {
  1935  	k := v.kind()
  1936  	p := v.ptr
  1937  	switch k {
  1938  	case Uint:
  1939  		return uint64(*(*uint)(p))
  1940  	case Uint8:
  1941  		return uint64(*(*uint8)(p))
  1942  	case Uint16:
  1943  		return uint64(*(*uint16)(p))
  1944  	case Uint32:
  1945  		return uint64(*(*uint32)(p))
  1946  	case Uint64:
  1947  		return *(*uint64)(p)
  1948  	case Uintptr:
  1949  		return uint64(*(*uintptr)(p))
  1950  	}
  1951  	panic(&ValueError{"reflect.Value.Uint", v.kind()})
  1952  }
  1953  
  1954  //go:nocheckptr
  1955  // This prevents inlining Value.UnsafeAddr when -d=checkptr is enabled,
  1956  // which ensures cmd/compile can recognize unsafe.Pointer(v.UnsafeAddr())
  1957  // and make an exception.
  1958  
  1959  // UnsafeAddr returns a pointer to v's data.
  1960  // It is for advanced clients that also import the "unsafe" package.
  1961  // It panics if v is not addressable.
  1962  func (v Value) UnsafeAddr() uintptr {
  1963  	// TODO: deprecate
  1964  	if v.typ == nil {
  1965  		panic(&ValueError{"reflect.Value.UnsafeAddr", Invalid})
  1966  	}
  1967  	if v.flag&flagAddr == 0 {
  1968  		panic("reflect.Value.UnsafeAddr of unaddressable value")
  1969  	}
  1970  	return uintptr(v.ptr)
  1971  }
  1972  
  1973  // StringHeader is the runtime representation of a string.
  1974  // It cannot be used safely or portably and its representation may
  1975  // change in a later release.
  1976  // Moreover, the Data field is not sufficient to guarantee the data
  1977  // it references will not be garbage collected, so programs must keep
  1978  // a separate, correctly typed pointer to the underlying data.
  1979  type StringHeader struct {
  1980  	Data uintptr
  1981  	Len  int
  1982  }
  1983  
  1984  // SliceHeader is the runtime representation of a slice.
  1985  // It cannot be used safely or portably and its representation may
  1986  // change in a later release.
  1987  // Moreover, the Data field is not sufficient to guarantee the data
  1988  // it references will not be garbage collected, so programs must keep
  1989  // a separate, correctly typed pointer to the underlying data.
  1990  type SliceHeader struct {
  1991  	Data uintptr
  1992  	Len  int
  1993  	Cap  int
  1994  }
  1995  
  1996  func typesMustMatch(what string, t1, t2 Type) {
  1997  	if t1 != t2 {
  1998  		panic(what + ": " + t1.String() + " != " + t2.String())
  1999  	}
  2000  }
  2001  
  2002  // arrayAt returns the i-th element of p,
  2003  // an array whose elements are eltSize bytes wide.
  2004  // The array pointed at by p must have at least i+1 elements:
  2005  // it is invalid (but impossible to check here) to pass i >= len,
  2006  // because then the result will point outside the array.
  2007  // whySafe must explain why i < len. (Passing "i < len" is fine;
  2008  // the benefit is to surface this assumption at the call site.)
  2009  func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
  2010  	return add(p, uintptr(i)*eltSize, "i < len")
  2011  }
  2012  
  2013  // grow grows the slice s so that it can hold extra more values, allocating
  2014  // more capacity if needed. It also returns the old and new slice lengths.
  2015  func grow(s Value, extra int) (Value, int, int) {
  2016  	i0 := s.Len()
  2017  	i1 := i0 + extra
  2018  	if i1 < i0 {
  2019  		panic("reflect.Append: slice overflow")
  2020  	}
  2021  	m := s.Cap()
  2022  	if i1 <= m {
  2023  		return s.Slice(0, i1), i0, i1
  2024  	}
  2025  	if m == 0 {
  2026  		m = extra
  2027  	} else {
  2028  		for m < i1 {
  2029  			if i0 < 1024 {
  2030  				m += m
  2031  			} else {
  2032  				m += m / 4
  2033  			}
  2034  		}
  2035  	}
  2036  	t := MakeSlice(s.Type(), i1, m)
  2037  	Copy(t, s)
  2038  	return t, i0, i1
  2039  }
  2040  
  2041  // Append appends the values x to a slice s and returns the resulting slice.
  2042  // As in Go, each x's value must be assignable to the slice's element type.
  2043  func Append(s Value, x ...Value) Value {
  2044  	s.mustBe(Slice)
  2045  	s, i0, i1 := grow(s, len(x))
  2046  	for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
  2047  		s.Index(i).Set(x[j])
  2048  	}
  2049  	return s
  2050  }
  2051  
  2052  // AppendSlice appends a slice t to a slice s and returns the resulting slice.
  2053  // The slices s and t must have the same element type.
  2054  func AppendSlice(s, t Value) Value {
  2055  	s.mustBe(Slice)
  2056  	t.mustBe(Slice)
  2057  	typesMustMatch("reflect.AppendSlice", s.Type().Elem(), t.Type().Elem())
  2058  	s, i0, i1 := grow(s, t.Len())
  2059  	Copy(s.Slice(i0, i1), t)
  2060  	return s
  2061  }
  2062  
  2063  // Copy copies the contents of src into dst until either
  2064  // dst has been filled or src has been exhausted.
  2065  // It returns the number of elements copied.
  2066  // Dst and src each must have kind Slice or Array, and
  2067  // dst and src must have the same element type.
  2068  //
  2069  // As a special case, src can have kind String if the element type of dst is kind Uint8.
  2070  func Copy(dst, src Value) int {
  2071  	dk := dst.kind()
  2072  	if dk != Array && dk != Slice {
  2073  		panic(&ValueError{"reflect.Copy", dk})
  2074  	}
  2075  	if dk == Array {
  2076  		dst.mustBeAssignable()
  2077  	}
  2078  	dst.mustBeExported()
  2079  
  2080  	sk := src.kind()
  2081  	var stringCopy bool
  2082  	if sk != Array && sk != Slice {
  2083  		stringCopy = sk == String && dst.typ.Elem().Kind() == Uint8
  2084  		if !stringCopy {
  2085  			panic(&ValueError{"reflect.Copy", sk})
  2086  		}
  2087  	}
  2088  	src.mustBeExported()
  2089  
  2090  	de := dst.typ.Elem()
  2091  	if !stringCopy {
  2092  		se := src.typ.Elem()
  2093  		typesMustMatch("reflect.Copy", de, se)
  2094  	}
  2095  
  2096  	var ds, ss unsafeheader.Slice
  2097  	if dk == Array {
  2098  		ds.Data = dst.ptr
  2099  		ds.Len = dst.Len()
  2100  		ds.Cap = ds.Len
  2101  	} else {
  2102  		ds = *(*unsafeheader.Slice)(dst.ptr)
  2103  	}
  2104  	if sk == Array {
  2105  		ss.Data = src.ptr
  2106  		ss.Len = src.Len()
  2107  		ss.Cap = ss.Len
  2108  	} else if sk == Slice {
  2109  		ss = *(*unsafeheader.Slice)(src.ptr)
  2110  	} else {
  2111  		sh := *(*unsafeheader.String)(src.ptr)
  2112  		ss.Data = sh.Data
  2113  		ss.Len = sh.Len
  2114  		ss.Cap = sh.Len
  2115  	}
  2116  
  2117  	return typedslicecopy(de.common(), ds, ss)
  2118  }
  2119  
  2120  // A runtimeSelect is a single case passed to rselect.
  2121  // This must match ../runtime/select.go:/runtimeSelect
  2122  type runtimeSelect struct {
  2123  	dir SelectDir      // SelectSend, SelectRecv or SelectDefault
  2124  	typ *rtype         // channel type
  2125  	ch  unsafe.Pointer // channel
  2126  	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
  2127  }
  2128  
  2129  // rselect runs a select. It returns the index of the chosen case.
  2130  // If the case was a receive, val is filled in with the received value.
  2131  // The conventional OK bool indicates whether the receive corresponds
  2132  // to a sent value.
  2133  //go:noescape
  2134  func rselect([]runtimeSelect) (chosen int, recvOK bool)
  2135  
  2136  // A SelectDir describes the communication direction of a select case.
  2137  type SelectDir int
  2138  
  2139  // NOTE: These values must match ../runtime/select.go:/selectDir.
  2140  
  2141  const (
  2142  	_             SelectDir = iota
  2143  	SelectSend              // case Chan <- Send
  2144  	SelectRecv              // case <-Chan:
  2145  	SelectDefault           // default
  2146  )
  2147  
  2148  // A SelectCase describes a single case in a select operation.
  2149  // The kind of case depends on Dir, the communication direction.
  2150  //
  2151  // If Dir is SelectDefault, the case represents a default case.
  2152  // Chan and Send must be zero Values.
  2153  //
  2154  // If Dir is SelectSend, the case represents a send operation.
  2155  // Normally Chan's underlying value must be a channel, and Send's underlying value must be
  2156  // assignable to the channel's element type. As a special case, if Chan is a zero Value,
  2157  // then the case is ignored, and the field Send will also be ignored and may be either zero
  2158  // or non-zero.
  2159  //
  2160  // If Dir is SelectRecv, the case represents a receive operation.
  2161  // Normally Chan's underlying value must be a channel and Send must be a zero Value.
  2162  // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
  2163  // When a receive operation is selected, the received Value is returned by Select.
  2164  //
  2165  type SelectCase struct {
  2166  	Dir  SelectDir // direction of case
  2167  	Chan Value     // channel to use (for send or receive)
  2168  	Send Value     // value to send (for send)
  2169  }
  2170  
  2171  // Select executes a select operation described by the list of cases.
  2172  // Like the Go select statement, it blocks until at least one of the cases
  2173  // can proceed, makes a uniform pseudo-random choice,
  2174  // and then executes that case. It returns the index of the chosen case
  2175  // and, if that case was a receive operation, the value received and a
  2176  // boolean indicating whether the value corresponds to a send on the channel
  2177  // (as opposed to a zero value received because the channel is closed).
  2178  // Select supports a maximum of 65536 cases.
  2179  func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool) {
  2180  	if len(cases) > 65536 {
  2181  		panic("reflect.Select: too many cases (max 65536)")
  2182  	}
  2183  	// NOTE: Do not trust that caller is not modifying cases data underfoot.
  2184  	// The range is safe because the caller cannot modify our copy of the len
  2185  	// and each iteration makes its own copy of the value c.
  2186  	var runcases []runtimeSelect
  2187  	if len(cases) > 4 {
  2188  		// Slice is heap allocated due to runtime dependent capacity.
  2189  		runcases = make([]runtimeSelect, len(cases))
  2190  	} else {
  2191  		// Slice can be stack allocated due to constant capacity.
  2192  		runcases = make([]runtimeSelect, len(cases), 4)
  2193  	}
  2194  
  2195  	haveDefault := false
  2196  	for i, c := range cases {
  2197  		rc := &runcases[i]
  2198  		rc.dir = c.Dir
  2199  		switch c.Dir {
  2200  		default:
  2201  			panic("reflect.Select: invalid Dir")
  2202  
  2203  		case SelectDefault: // default
  2204  			if haveDefault {
  2205  				panic("reflect.Select: multiple default cases")
  2206  			}
  2207  			haveDefault = true
  2208  			if c.Chan.IsValid() {
  2209  				panic("reflect.Select: default case has Chan value")
  2210  			}
  2211  			if c.Send.IsValid() {
  2212  				panic("reflect.Select: default case has Send value")
  2213  			}
  2214  
  2215  		case SelectSend:
  2216  			ch := c.Chan
  2217  			if !ch.IsValid() {
  2218  				break
  2219  			}
  2220  			ch.mustBe(Chan)
  2221  			ch.mustBeExported()
  2222  			tt := (*chanType)(unsafe.Pointer(ch.typ))
  2223  			if ChanDir(tt.dir)&SendDir == 0 {
  2224  				panic("reflect.Select: SendDir case using recv-only channel")
  2225  			}
  2226  			rc.ch = ch.pointer()
  2227  			rc.typ = &tt.rtype
  2228  			v := c.Send
  2229  			if !v.IsValid() {
  2230  				panic("reflect.Select: SendDir case missing Send value")
  2231  			}
  2232  			v.mustBeExported()
  2233  			v = v.assignTo("reflect.Select", tt.elem, nil)
  2234  			if v.flag&flagIndir != 0 {
  2235  				rc.val = v.ptr
  2236  			} else {
  2237  				rc.val = unsafe.Pointer(&v.ptr)
  2238  			}
  2239  
  2240  		case SelectRecv:
  2241  			if c.Send.IsValid() {
  2242  				panic("reflect.Select: RecvDir case has Send value")
  2243  			}
  2244  			ch := c.Chan
  2245  			if !ch.IsValid() {
  2246  				break
  2247  			}
  2248  			ch.mustBe(Chan)
  2249  			ch.mustBeExported()
  2250  			tt := (*chanType)(unsafe.Pointer(ch.typ))
  2251  			if ChanDir(tt.dir)&RecvDir == 0 {
  2252  				panic("reflect.Select: RecvDir case using send-only channel")
  2253  			}
  2254  			rc.ch = ch.pointer()
  2255  			rc.typ = &tt.rtype
  2256  			rc.val = unsafe_New(tt.elem)
  2257  		}
  2258  	}
  2259  
  2260  	chosen, recvOK = rselect(runcases)
  2261  	if runcases[chosen].dir == SelectRecv {
  2262  		tt := (*chanType)(unsafe.Pointer(runcases[chosen].typ))
  2263  		t := tt.elem
  2264  		p := runcases[chosen].val
  2265  		fl := flag(t.Kind())
  2266  		if ifaceIndir(t) {
  2267  			recv = Value{t, p, fl | flagIndir}
  2268  		} else {
  2269  			recv = Value{t, *(*unsafe.Pointer)(p), fl}
  2270  		}
  2271  	}
  2272  	return chosen, recv, recvOK
  2273  }
  2274  
  2275  /*
  2276   * constructors
  2277   */
  2278  
  2279  // implemented in package runtime
  2280  func unsafe_New(*rtype) unsafe.Pointer
  2281  func unsafe_NewArray(*rtype, int) unsafe.Pointer
  2282  
  2283  // MakeSlice creates a new zero-initialized slice value
  2284  // for the specified slice type, length, and capacity.
  2285  func MakeSlice(typ Type, len, cap int) Value {
  2286  	if typ.Kind() != Slice {
  2287  		panic("reflect.MakeSlice of non-slice type")
  2288  	}
  2289  	if len < 0 {
  2290  		panic("reflect.MakeSlice: negative len")
  2291  	}
  2292  	if cap < 0 {
  2293  		panic("reflect.MakeSlice: negative cap")
  2294  	}
  2295  	if len > cap {
  2296  		panic("reflect.MakeSlice: len > cap")
  2297  	}
  2298  
  2299  	s := unsafeheader.Slice{Data: unsafe_NewArray(typ.Elem().(*rtype), cap), Len: len, Cap: cap}
  2300  	return Value{typ.(*rtype), unsafe.Pointer(&s), flagIndir | flag(Slice)}
  2301  }
  2302  
  2303  // MakeChan creates a new channel with the specified type and buffer size.
  2304  func MakeChan(typ Type, buffer int) Value {
  2305  	if typ.Kind() != Chan {
  2306  		panic("reflect.MakeChan of non-chan type")
  2307  	}
  2308  	if buffer < 0 {
  2309  		panic("reflect.MakeChan: negative buffer size")
  2310  	}
  2311  	if typ.ChanDir() != BothDir {
  2312  		panic("reflect.MakeChan: unidirectional channel type")
  2313  	}
  2314  	t := typ.(*rtype)
  2315  	ch := makechan(t, buffer)
  2316  	return Value{t, ch, flag(Chan)}
  2317  }
  2318  
  2319  // MakeMap creates a new map with the specified type.
  2320  func MakeMap(typ Type) Value {
  2321  	return MakeMapWithSize(typ, 0)
  2322  }
  2323  
  2324  // MakeMapWithSize creates a new map with the specified type
  2325  // and initial space for approximately n elements.
  2326  func MakeMapWithSize(typ Type, n int) Value {
  2327  	if typ.Kind() != Map {
  2328  		panic("reflect.MakeMapWithSize of non-map type")
  2329  	}
  2330  	t := typ.(*rtype)
  2331  	m := makemap(t, n)
  2332  	return Value{t, m, flag(Map)}
  2333  }
  2334  
  2335  // Indirect returns the value that v points to.
  2336  // If v is a nil pointer, Indirect returns a zero Value.
  2337  // If v is not a pointer, Indirect returns v.
  2338  func Indirect(v Value) Value {
  2339  	if v.Kind() != Ptr {
  2340  		return v
  2341  	}
  2342  	return v.Elem()
  2343  }
  2344  
  2345  // ValueOf returns a new Value initialized to the concrete value
  2346  // stored in the interface i. ValueOf(nil) returns the zero Value.
  2347  func ValueOf(i interface{}) Value {
  2348  	if i == nil {
  2349  		return Value{}
  2350  	}
  2351  
  2352  	// TODO: Maybe allow contents of a Value to live on the stack.
  2353  	// For now we make the contents always escape to the heap. It
  2354  	// makes life easier in a few places (see chanrecv/mapassign
  2355  	// comment below).
  2356  	escapes(i)
  2357  
  2358  	return unpackEface(i)
  2359  }
  2360  
  2361  // Zero returns a Value representing the zero value for the specified type.
  2362  // The result is different from the zero value of the Value struct,
  2363  // which represents no value at all.
  2364  // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
  2365  // The returned value is neither addressable nor settable.
  2366  func Zero(typ Type) Value {
  2367  	if typ == nil {
  2368  		panic("reflect: Zero(nil)")
  2369  	}
  2370  	t := typ.(*rtype)
  2371  	fl := flag(t.Kind())
  2372  	if ifaceIndir(t) {
  2373  		return Value{t, unsafe_New(t), fl | flagIndir}
  2374  	}
  2375  	return Value{t, nil, fl}
  2376  }
  2377  
  2378  // New returns a Value representing a pointer to a new zero value
  2379  // for the specified type. That is, the returned Value's Type is PtrTo(typ).
  2380  func New(typ Type) Value {
  2381  	if typ == nil {
  2382  		panic("reflect: New(nil)")
  2383  	}
  2384  	t := typ.(*rtype)
  2385  	ptr := unsafe_New(t)
  2386  	fl := flag(Ptr)
  2387  	return Value{t.ptrTo(), ptr, fl}
  2388  }
  2389  
  2390  // NewAt returns a Value representing a pointer to a value of the
  2391  // specified type, using p as that pointer.
  2392  func NewAt(typ Type, p unsafe.Pointer) Value {
  2393  	fl := flag(Ptr)
  2394  	t := typ.(*rtype)
  2395  	return Value{t.ptrTo(), p, fl}
  2396  }
  2397  
  2398  // assignTo returns a value v that can be assigned directly to typ.
  2399  // It panics if v is not assignable to typ.
  2400  // For a conversion to an interface type, target is a suggested scratch space to use.
  2401  // target must be initialized memory (or nil).
  2402  func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value {
  2403  	if v.flag&flagMethod != 0 {
  2404  		v = makeMethodValue(context, v)
  2405  	}
  2406  
  2407  	switch {
  2408  	case directlyAssignable(dst, v.typ):
  2409  		// Overwrite type so that they match.
  2410  		// Same memory layout, so no harm done.
  2411  		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
  2412  		fl |= flag(dst.Kind())
  2413  		return Value{dst, v.ptr, fl}
  2414  
  2415  	case implements(dst, v.typ):
  2416  		if target == nil {
  2417  			target = unsafe_New(dst)
  2418  		}
  2419  		if v.Kind() == Interface && v.IsNil() {
  2420  			// A nil ReadWriter passed to nil Reader is OK,
  2421  			// but using ifaceE2I below will panic.
  2422  			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
  2423  			return Value{dst, nil, flag(Interface)}
  2424  		}
  2425  		x := valueInterface(v, false)
  2426  		if dst.NumMethod() == 0 {
  2427  			*(*interface{})(target) = x
  2428  		} else {
  2429  			ifaceE2I(dst, x, target)
  2430  		}
  2431  		return Value{dst, target, flagIndir | flag(Interface)}
  2432  	}
  2433  
  2434  	// Failed.
  2435  	panic(context + ": value of type " + v.typ.String() + " is not assignable to type " + dst.String())
  2436  }
  2437  
  2438  // Convert returns the value v converted to type t.
  2439  // If the usual Go conversion rules do not allow conversion
  2440  // of the value v to type t, Convert panics.
  2441  func (v Value) Convert(t Type) Value {
  2442  	if v.flag&flagMethod != 0 {
  2443  		v = makeMethodValue("Convert", v)
  2444  	}
  2445  	op := convertOp(t.common(), v.typ)
  2446  	if op == nil {
  2447  		panic("reflect.Value.Convert: value of type " + v.typ.String() + " cannot be converted to type " + t.String())
  2448  	}
  2449  	return op(v, t)
  2450  }
  2451  
  2452  // convertOp returns the function to convert a value of type src
  2453  // to a value of type dst. If the conversion is illegal, convertOp returns nil.
  2454  func convertOp(dst, src *rtype) func(Value, Type) Value {
  2455  	switch src.Kind() {
  2456  	case Int, Int8, Int16, Int32, Int64:
  2457  		switch dst.Kind() {
  2458  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2459  			return cvtInt
  2460  		case Float32, Float64:
  2461  			return cvtIntFloat
  2462  		case String:
  2463  			return cvtIntString
  2464  		}
  2465  
  2466  	case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2467  		switch dst.Kind() {
  2468  		case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2469  			return cvtUint
  2470  		case Float32, Float64:
  2471  			return cvtUintFloat
  2472  		case String:
  2473  			return cvtUintString
  2474  		}
  2475  
  2476  	case Float32, Float64:
  2477  		switch dst.Kind() {
  2478  		case Int, Int8, Int16, Int32, Int64:
  2479  			return cvtFloatInt
  2480  		case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  2481  			return cvtFloatUint
  2482  		case Float32, Float64:
  2483  			return cvtFloat
  2484  		}
  2485  
  2486  	case Complex64, Complex128:
  2487  		switch dst.Kind() {
  2488  		case Complex64, Complex128:
  2489  			return cvtComplex
  2490  		}
  2491  
  2492  	case String:
  2493  		if dst.Kind() == Slice && dst.Elem().PkgPath() == "" {
  2494  			switch dst.Elem().Kind() {
  2495  			case Uint8:
  2496  				return cvtStringBytes
  2497  			case Int32:
  2498  				return cvtStringRunes
  2499  			}
  2500  		}
  2501  
  2502  	case Slice:
  2503  		if dst.Kind() == String && src.Elem().PkgPath() == "" {
  2504  			switch src.Elem().Kind() {
  2505  			case Uint8:
  2506  				return cvtBytesString
  2507  			case Int32:
  2508  				return cvtRunesString
  2509  			}
  2510  		}
  2511  
  2512  	case Chan:
  2513  		if dst.Kind() == Chan && specialChannelAssignability(dst, src) {
  2514  			return cvtDirect
  2515  		}
  2516  	}
  2517  
  2518  	// dst and src have same underlying type.
  2519  	if haveIdenticalUnderlyingType(dst, src, false) {
  2520  		return cvtDirect
  2521  	}
  2522  
  2523  	// dst and src are non-defined pointer types with same underlying base type.
  2524  	if dst.Kind() == Ptr && dst.Name() == "" &&
  2525  		src.Kind() == Ptr && src.Name() == "" &&
  2526  		haveIdenticalUnderlyingType(dst.Elem().common(), src.Elem().common(), false) {
  2527  		return cvtDirect
  2528  	}
  2529  
  2530  	if implements(dst, src) {
  2531  		if src.Kind() == Interface {
  2532  			return cvtI2I
  2533  		}
  2534  		return cvtT2I
  2535  	}
  2536  
  2537  	return nil
  2538  }
  2539  
  2540  // makeInt returns a Value of type t equal to bits (possibly truncated),
  2541  // where t is a signed or unsigned int type.
  2542  func makeInt(f flag, bits uint64, t Type) Value {
  2543  	typ := t.common()
  2544  	ptr := unsafe_New(typ)
  2545  	switch typ.size {
  2546  	case 1:
  2547  		*(*uint8)(ptr) = uint8(bits)
  2548  	case 2:
  2549  		*(*uint16)(ptr) = uint16(bits)
  2550  	case 4:
  2551  		*(*uint32)(ptr) = uint32(bits)
  2552  	case 8:
  2553  		*(*uint64)(ptr) = bits
  2554  	}
  2555  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2556  }
  2557  
  2558  // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
  2559  // where t is a float32 or float64 type.
  2560  func makeFloat(f flag, v float64, t Type) Value {
  2561  	typ := t.common()
  2562  	ptr := unsafe_New(typ)
  2563  	switch typ.size {
  2564  	case 4:
  2565  		*(*float32)(ptr) = float32(v)
  2566  	case 8:
  2567  		*(*float64)(ptr) = v
  2568  	}
  2569  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2570  }
  2571  
  2572  // makeFloat returns a Value of type t equal to v, where t is a float32 type.
  2573  func makeFloat32(f flag, v float32, t Type) Value {
  2574  	typ := t.common()
  2575  	ptr := unsafe_New(typ)
  2576  	*(*float32)(ptr) = v
  2577  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2578  }
  2579  
  2580  // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
  2581  // where t is a complex64 or complex128 type.
  2582  func makeComplex(f flag, v complex128, t Type) Value {
  2583  	typ := t.common()
  2584  	ptr := unsafe_New(typ)
  2585  	switch typ.size {
  2586  	case 8:
  2587  		*(*complex64)(ptr) = complex64(v)
  2588  	case 16:
  2589  		*(*complex128)(ptr) = v
  2590  	}
  2591  	return Value{typ, ptr, f | flagIndir | flag(typ.Kind())}
  2592  }
  2593  
  2594  func makeString(f flag, v string, t Type) Value {
  2595  	ret := New(t).Elem()
  2596  	ret.SetString(v)
  2597  	ret.flag = ret.flag&^flagAddr | f
  2598  	return ret
  2599  }
  2600  
  2601  func makeBytes(f flag, v []byte, t Type) Value {
  2602  	ret := New(t).Elem()
  2603  	ret.SetBytes(v)
  2604  	ret.flag = ret.flag&^flagAddr | f
  2605  	return ret
  2606  }
  2607  
  2608  func makeRunes(f flag, v []rune, t Type) Value {
  2609  	ret := New(t).Elem()
  2610  	ret.setRunes(v)
  2611  	ret.flag = ret.flag&^flagAddr | f
  2612  	return ret
  2613  }
  2614  
  2615  // These conversion functions are returned by convertOp
  2616  // for classes of conversions. For example, the first function, cvtInt,
  2617  // takes any value v of signed int type and returns the value converted
  2618  // to type t, where t is any signed or unsigned int type.
  2619  
  2620  // convertOp: intXX -> [u]intXX
  2621  func cvtInt(v Value, t Type) Value {
  2622  	return makeInt(v.flag.ro(), uint64(v.Int()), t)
  2623  }
  2624  
  2625  // convertOp: uintXX -> [u]intXX
  2626  func cvtUint(v Value, t Type) Value {
  2627  	return makeInt(v.flag.ro(), v.Uint(), t)
  2628  }
  2629  
  2630  // convertOp: floatXX -> intXX
  2631  func cvtFloatInt(v Value, t Type) Value {
  2632  	return makeInt(v.flag.ro(), uint64(int64(v.Float())), t)
  2633  }
  2634  
  2635  // convertOp: floatXX -> uintXX
  2636  func cvtFloatUint(v Value, t Type) Value {
  2637  	return makeInt(v.flag.ro(), uint64(v.Float()), t)
  2638  }
  2639  
  2640  // convertOp: intXX -> floatXX
  2641  func cvtIntFloat(v Value, t Type) Value {
  2642  	return makeFloat(v.flag.ro(), float64(v.Int()), t)
  2643  }
  2644  
  2645  // convertOp: uintXX -> floatXX
  2646  func cvtUintFloat(v Value, t Type) Value {
  2647  	return makeFloat(v.flag.ro(), float64(v.Uint()), t)
  2648  }
  2649  
  2650  // convertOp: floatXX -> floatXX
  2651  func cvtFloat(v Value, t Type) Value {
  2652  	if v.Type().Kind() == Float32 && t.Kind() == Float32 {
  2653  		// Don't do any conversion if both types have underlying type float32.
  2654  		// This avoids converting to float64 and back, which will
  2655  		// convert a signaling NaN to a quiet NaN. See issue 36400.
  2656  		return makeFloat32(v.flag.ro(), *(*float32)(v.ptr), t)
  2657  	}
  2658  	return makeFloat(v.flag.ro(), v.Float(), t)
  2659  }
  2660  
  2661  // convertOp: complexXX -> complexXX
  2662  func cvtComplex(v Value, t Type) Value {
  2663  	return makeComplex(v.flag.ro(), v.Complex(), t)
  2664  }
  2665  
  2666  // convertOp: intXX -> string
  2667  func cvtIntString(v Value, t Type) Value {
  2668  	return makeString(v.flag.ro(), string(rune(v.Int())), t)
  2669  }
  2670  
  2671  // convertOp: uintXX -> string
  2672  func cvtUintString(v Value, t Type) Value {
  2673  	return makeString(v.flag.ro(), string(rune(v.Uint())), t)
  2674  }
  2675  
  2676  // convertOp: []byte -> string
  2677  func cvtBytesString(v Value, t Type) Value {
  2678  	return makeString(v.flag.ro(), string(v.Bytes()), t)
  2679  }
  2680  
  2681  // convertOp: string -> []byte
  2682  func cvtStringBytes(v Value, t Type) Value {
  2683  	return makeBytes(v.flag.ro(), []byte(v.String()), t)
  2684  }
  2685  
  2686  // convertOp: []rune -> string
  2687  func cvtRunesString(v Value, t Type) Value {
  2688  	return makeString(v.flag.ro(), string(v.runes()), t)
  2689  }
  2690  
  2691  // convertOp: string -> []rune
  2692  func cvtStringRunes(v Value, t Type) Value {
  2693  	return makeRunes(v.flag.ro(), []rune(v.String()), t)
  2694  }
  2695  
  2696  // convertOp: direct copy
  2697  func cvtDirect(v Value, typ Type) Value {
  2698  	f := v.flag
  2699  	t := typ.common()
  2700  	ptr := v.ptr
  2701  	if f&flagAddr != 0 {
  2702  		// indirect, mutable word - make a copy
  2703  		c := unsafe_New(t)
  2704  		typedmemmove(t, c, ptr)
  2705  		ptr = c
  2706  		f &^= flagAddr
  2707  	}
  2708  	return Value{t, ptr, v.flag.ro() | f} // v.flag.ro()|f == f?
  2709  }
  2710  
  2711  // convertOp: concrete -> interface
  2712  func cvtT2I(v Value, typ Type) Value {
  2713  	target := unsafe_New(typ.common())
  2714  	x := valueInterface(v, false)
  2715  	if typ.NumMethod() == 0 {
  2716  		*(*interface{})(target) = x
  2717  	} else {
  2718  		ifaceE2I(typ.(*rtype), x, target)
  2719  	}
  2720  	return Value{typ.common(), target, v.flag.ro() | flagIndir | flag(Interface)}
  2721  }
  2722  
  2723  // convertOp: interface -> interface
  2724  func cvtI2I(v Value, typ Type) Value {
  2725  	if v.IsNil() {
  2726  		ret := Zero(typ)
  2727  		ret.flag |= v.flag.ro()
  2728  		return ret
  2729  	}
  2730  	return cvtT2I(v.Elem(), typ)
  2731  }
  2732  
  2733  // implemented in ../runtime
  2734  func chancap(ch unsafe.Pointer) int
  2735  func chanclose(ch unsafe.Pointer)
  2736  func chanlen(ch unsafe.Pointer) int
  2737  
  2738  // Note: some of the noescape annotations below are technically a lie,
  2739  // but safe in the context of this package. Functions like chansend
  2740  // and mapassign don't escape the referent, but may escape anything
  2741  // the referent points to (they do shallow copies of the referent).
  2742  // It is safe in this package because the referent may only point
  2743  // to something a Value may point to, and that is always in the heap
  2744  // (due to the escapes() call in ValueOf).
  2745  
  2746  //go:noescape
  2747  func chanrecv(ch unsafe.Pointer, nb bool, val unsafe.Pointer) (selected, received bool)
  2748  
  2749  //go:noescape
  2750  func chansend(ch unsafe.Pointer, val unsafe.Pointer, nb bool) bool
  2751  
  2752  func makechan(typ *rtype, size int) (ch unsafe.Pointer)
  2753  func makemap(t *rtype, cap int) (m unsafe.Pointer)
  2754  
  2755  //go:noescape
  2756  func mapaccess(t *rtype, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer)
  2757  
  2758  //go:noescape
  2759  func mapassign(t *rtype, m unsafe.Pointer, key, val unsafe.Pointer)
  2760  
  2761  //go:noescape
  2762  func mapdelete(t *rtype, m unsafe.Pointer, key unsafe.Pointer)
  2763  
  2764  // m escapes into the return value, but the caller of mapiterinit
  2765  // doesn't let the return value escape.
  2766  //go:noescape
  2767  func mapiterinit(t *rtype, m unsafe.Pointer) unsafe.Pointer
  2768  
  2769  //go:noescape
  2770  func mapiterkey(it unsafe.Pointer) (key unsafe.Pointer)
  2771  
  2772  //go:noescape
  2773  func mapiterelem(it unsafe.Pointer) (elem unsafe.Pointer)
  2774  
  2775  //go:noescape
  2776  func mapiternext(it unsafe.Pointer)
  2777  
  2778  //go:noescape
  2779  func maplen(m unsafe.Pointer) int
  2780  
  2781  // call calls fn with a copy of the n argument bytes pointed at by arg.
  2782  // After fn returns, reflectcall copies n-retoffset result bytes
  2783  // back into arg+retoffset before returning. If copying result bytes back,
  2784  // the caller must pass the argument frame type as argtype, so that
  2785  // call can execute appropriate write barriers during the copy.
  2786  //
  2787  //go:linkname call runtime.reflectcall
  2788  func call(argtype *rtype, fn, arg unsafe.Pointer, n uint32, retoffset uint32)
  2789  
  2790  func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer)
  2791  
  2792  // memmove copies size bytes to dst from src. No write barriers are used.
  2793  //go:noescape
  2794  func memmove(dst, src unsafe.Pointer, size uintptr)
  2795  
  2796  // typedmemmove copies a value of type t to dst from src.
  2797  //go:noescape
  2798  func typedmemmove(t *rtype, dst, src unsafe.Pointer)
  2799  
  2800  // typedmemmovepartial is like typedmemmove but assumes that
  2801  // dst and src point off bytes into the value and only copies size bytes.
  2802  //go:noescape
  2803  func typedmemmovepartial(t *rtype, dst, src unsafe.Pointer, off, size uintptr)
  2804  
  2805  // typedmemclr zeros the value at ptr of type t.
  2806  //go:noescape
  2807  func typedmemclr(t *rtype, ptr unsafe.Pointer)
  2808  
  2809  // typedmemclrpartial is like typedmemclr but assumes that
  2810  // dst points off bytes into the value and only clears size bytes.
  2811  //go:noescape
  2812  func typedmemclrpartial(t *rtype, ptr unsafe.Pointer, off, size uintptr)
  2813  
  2814  // typedslicecopy copies a slice of elemType values from src to dst,
  2815  // returning the number of elements copied.
  2816  //go:noescape
  2817  func typedslicecopy(elemType *rtype, dst, src unsafeheader.Slice) int
  2818  
  2819  //go:noescape
  2820  func typehash(t *rtype, p unsafe.Pointer, h uintptr) uintptr
  2821  
  2822  // Dummy annotation marking that the value x escapes,
  2823  // for use in cases where the reflect code is so clever that
  2824  // the compiler cannot follow.
  2825  func escapes(x interface{}) {
  2826  	if dummy.b {
  2827  		dummy.x = x
  2828  	}
  2829  }
  2830  
  2831  var dummy struct {
  2832  	b bool
  2833  	x interface{}
  2834  }
  2835  

View as plain text