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