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

View as plain text