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