Source file src/internal/reflectlite/value.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package reflectlite
     6  
     7  import (
     8  	"internal/abi"
     9  	"internal/goarch"
    10  	"internal/unsafeheader"
    11  	"runtime"
    12  	"unsafe"
    13  )
    14  
    15  // Value is the reflection interface to a Go value.
    16  //
    17  // Not all methods apply to all kinds of values. Restrictions,
    18  // if any, are noted in the documentation for each method.
    19  // Use the Kind method to find out the kind of value before
    20  // calling kind-specific methods. Calling a method
    21  // inappropriate to the kind of type causes a run time panic.
    22  //
    23  // The zero Value represents no value.
    24  // Its IsValid method returns false, its Kind method returns Invalid,
    25  // its String method returns "<invalid Value>", and all other methods panic.
    26  // Most functions and methods never return an invalid value.
    27  // If one does, its documentation states the conditions explicitly.
    28  //
    29  // A Value can be used concurrently by multiple goroutines provided that
    30  // the underlying Go value can be used concurrently for the equivalent
    31  // direct operations.
    32  //
    33  // To compare two Values, compare the results of the Interface method.
    34  // Using == on two Values does not compare the underlying values
    35  // they represent.
    36  type Value struct {
    37  	// typ_ holds the type of the value represented by a Value.
    38  	// Access using the typ method to avoid escape of v.
    39  	typ_ *abi.Type
    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  	//
    47  	// The lowest five bits give the Kind of the value, mirroring typ.Kind().
    48  	//
    49  	// The next set of bits are flag bits:
    50  	//	- flagStickyRO: obtained via unexported not embedded field, so read-only
    51  	//	- flagEmbedRO: obtained via unexported embedded field, so read-only
    52  	//	- flagIndir: val holds a pointer to the data
    53  	//	- flagAddr: v.CanAddr is true (implies flagIndir and ptr is non-nil)
    54  	//	- flagMethod: v is a method value.
    55  	// If ifaceIndir(typ), code can assume that flagIndir is set.
    56  	//
    57  	// The remaining 22+ bits give a method number for method values.
    58  	// If flag.kind() != Func, code can assume that flagMethod is unset.
    59  	flag
    60  
    61  	// A method value represents a curried method invocation
    62  	// like r.Read for some receiver r. The typ+val+flag bits describe
    63  	// the receiver r, but the flag's Kind bits say Func (methods are
    64  	// functions), and the top bits of the flag give the method number
    65  	// in r's type's method table.
    66  }
    67  
    68  type flag uintptr
    69  
    70  const (
    71  	flagKindWidth        = 5 // there are 27 kinds
    72  	flagKindMask    flag = 1<<flagKindWidth - 1
    73  	flagStickyRO    flag = 1 << 5
    74  	flagEmbedRO     flag = 1 << 6
    75  	flagIndir       flag = 1 << 7
    76  	flagAddr        flag = 1 << 8
    77  	flagMethod      flag = 1 << 9
    78  	flagMethodShift      = 10
    79  	flagRO          flag = flagStickyRO | flagEmbedRO
    80  )
    81  
    82  func (f flag) kind() Kind {
    83  	return Kind(f & flagKindMask)
    84  }
    85  
    86  func (f flag) ro() flag {
    87  	if f&flagRO != 0 {
    88  		return flagStickyRO
    89  	}
    90  	return 0
    91  }
    92  
    93  func (v Value) typ() *abi.Type {
    94  	// Types are either static (for compiler-created types) or
    95  	// heap-allocated but always reachable (for reflection-created
    96  	// types, held in the central map). So there is no need to
    97  	// escape types. noescape here help avoid unnecessary escape
    98  	// of v.
    99  	return (*abi.Type)(abi.NoEscape(unsafe.Pointer(v.typ_)))
   100  }
   101  
   102  // pointer returns the underlying pointer represented by v.
   103  // v.Kind() must be Pointer, Map, Chan, Func, or UnsafePointer
   104  func (v Value) pointer() unsafe.Pointer {
   105  	if v.typ().Size() != goarch.PtrSize || !v.typ().Pointers() {
   106  		panic("can't call pointer on a non-pointer Value")
   107  	}
   108  	if v.flag&flagIndir != 0 {
   109  		return *(*unsafe.Pointer)(v.ptr)
   110  	}
   111  	return v.ptr
   112  }
   113  
   114  // packEface converts v to the empty interface.
   115  func packEface(v Value) any {
   116  	t := v.typ()
   117  	var i any
   118  	e := (*abi.EmptyInterface)(unsafe.Pointer(&i))
   119  	// First, fill in the data portion of the interface.
   120  	switch {
   121  	case t.IfaceIndir():
   122  		if v.flag&flagIndir == 0 {
   123  			panic("bad indir")
   124  		}
   125  		// Value is indirect, and so is the interface we're making.
   126  		ptr := v.ptr
   127  		if v.flag&flagAddr != 0 {
   128  			c := unsafe_New(t)
   129  			typedmemmove(t, c, ptr)
   130  			ptr = c
   131  		}
   132  		e.Data = ptr
   133  	case v.flag&flagIndir != 0:
   134  		// Value is indirect, but interface is direct. We need
   135  		// to load the data at v.ptr into the interface data word.
   136  		e.Data = *(*unsafe.Pointer)(v.ptr)
   137  	default:
   138  		// Value is direct, and so is the interface.
   139  		e.Data = v.ptr
   140  	}
   141  	// Now, fill in the type portion. We're very careful here not
   142  	// to have any operation between the e.word and e.typ assignments
   143  	// that would let the garbage collector observe the partially-built
   144  	// interface value.
   145  	e.Type = t
   146  	return i
   147  }
   148  
   149  // unpackEface converts the empty interface i to a Value.
   150  func unpackEface(i any) Value {
   151  	e := (*abi.EmptyInterface)(unsafe.Pointer(&i))
   152  	// NOTE: don't read e.word until we know whether it is really a pointer or not.
   153  	t := e.Type
   154  	if t == nil {
   155  		return Value{}
   156  	}
   157  	f := flag(t.Kind())
   158  	if t.IfaceIndir() {
   159  		f |= flagIndir
   160  	}
   161  	return Value{t, e.Data, f}
   162  }
   163  
   164  // A ValueError occurs when a Value method is invoked on
   165  // a Value that does not support it. Such cases are documented
   166  // in the description of each method.
   167  type ValueError struct {
   168  	Method string
   169  	Kind   Kind
   170  }
   171  
   172  func (e *ValueError) Error() string {
   173  	if e.Kind == 0 {
   174  		return "reflect: call of " + e.Method + " on zero Value"
   175  	}
   176  	return "reflect: call of " + e.Method + " on " + e.Kind.String() + " Value"
   177  }
   178  
   179  // methodName returns the name of the calling method,
   180  // assumed to be two stack frames above.
   181  func methodName() string {
   182  	pc, _, _, _ := runtime.Caller(2)
   183  	f := runtime.FuncForPC(pc)
   184  	if f == nil {
   185  		return "unknown method"
   186  	}
   187  	return f.Name()
   188  }
   189  
   190  // mustBeExported panics if f records that the value was obtained using
   191  // an unexported field.
   192  func (f flag) mustBeExported() {
   193  	if f == 0 {
   194  		panic(&ValueError{methodName(), 0})
   195  	}
   196  	if f&flagRO != 0 {
   197  		panic("reflect: " + methodName() + " using value obtained using unexported field")
   198  	}
   199  }
   200  
   201  // mustBeAssignable panics if f records that the value is not assignable,
   202  // which is to say that either it was obtained using an unexported field
   203  // or it is not addressable.
   204  func (f flag) mustBeAssignable() {
   205  	if f == 0 {
   206  		panic(&ValueError{methodName(), abi.Invalid})
   207  	}
   208  	// Assignable if addressable and not read-only.
   209  	if f&flagRO != 0 {
   210  		panic("reflect: " + methodName() + " using value obtained using unexported field")
   211  	}
   212  	if f&flagAddr == 0 {
   213  		panic("reflect: " + methodName() + " using unaddressable value")
   214  	}
   215  }
   216  
   217  // CanSet reports whether the value of v can be changed.
   218  // A Value can be changed only if it is addressable and was not
   219  // obtained by the use of unexported struct fields.
   220  // If CanSet returns false, calling Set or any type-specific
   221  // setter (e.g., SetBool, SetInt) will panic.
   222  func (v Value) CanSet() bool {
   223  	return v.flag&(flagAddr|flagRO) == flagAddr
   224  }
   225  
   226  // Elem returns the value that the interface v contains
   227  // or that the pointer v points to.
   228  // It panics if v's Kind is not Interface or Pointer.
   229  // It returns the zero Value if v is nil.
   230  func (v Value) Elem() Value {
   231  	k := v.kind()
   232  	switch k {
   233  	case abi.Interface:
   234  		var eface any
   235  		if v.typ().NumMethod() == 0 {
   236  			eface = *(*any)(v.ptr)
   237  		} else {
   238  			eface = (any)(*(*interface {
   239  				M()
   240  			})(v.ptr))
   241  		}
   242  		x := unpackEface(eface)
   243  		if x.flag != 0 {
   244  			x.flag |= v.flag.ro()
   245  		}
   246  		return x
   247  	case abi.Pointer:
   248  		ptr := v.ptr
   249  		if v.flag&flagIndir != 0 {
   250  			ptr = *(*unsafe.Pointer)(ptr)
   251  		}
   252  		// The returned value's address is v's value.
   253  		if ptr == nil {
   254  			return Value{}
   255  		}
   256  		tt := (*ptrType)(unsafe.Pointer(v.typ()))
   257  		typ := tt.Elem
   258  		fl := v.flag&flagRO | flagIndir | flagAddr
   259  		fl |= flag(typ.Kind())
   260  		return Value{typ, ptr, fl}
   261  	}
   262  	panic(&ValueError{"reflectlite.Value.Elem", v.kind()})
   263  }
   264  
   265  func valueInterface(v Value) any {
   266  	if v.flag == 0 {
   267  		panic(&ValueError{"reflectlite.Value.Interface", 0})
   268  	}
   269  
   270  	if v.kind() == abi.Interface {
   271  		// Special case: return the element inside the interface.
   272  		// Empty interface has one layout, all interfaces with
   273  		// methods have a second layout.
   274  		if v.numMethod() == 0 {
   275  			return *(*any)(v.ptr)
   276  		}
   277  		return *(*interface {
   278  			M()
   279  		})(v.ptr)
   280  	}
   281  
   282  	return packEface(v)
   283  }
   284  
   285  // IsNil reports whether its argument v is nil. The argument must be
   286  // a chan, func, interface, map, pointer, or slice value; if it is
   287  // not, IsNil panics. Note that IsNil is not always equivalent to a
   288  // regular comparison with nil in Go. For example, if v was created
   289  // by calling ValueOf with an uninitialized interface variable i,
   290  // i==nil will be true but v.IsNil will panic as v will be the zero
   291  // Value.
   292  func (v Value) IsNil() bool {
   293  	k := v.kind()
   294  	switch k {
   295  	case abi.Chan, abi.Func, abi.Map, abi.Pointer, abi.UnsafePointer:
   296  		// if v.flag&flagMethod != 0 {
   297  		// 	return false
   298  		// }
   299  		ptr := v.ptr
   300  		if v.flag&flagIndir != 0 {
   301  			ptr = *(*unsafe.Pointer)(ptr)
   302  		}
   303  		return ptr == nil
   304  	case abi.Interface, abi.Slice:
   305  		// Both interface and slice are nil if first word is 0.
   306  		// Both are always bigger than a word; assume flagIndir.
   307  		return *(*unsafe.Pointer)(v.ptr) == nil
   308  	}
   309  	panic(&ValueError{"reflectlite.Value.IsNil", v.kind()})
   310  }
   311  
   312  // IsValid reports whether v represents a value.
   313  // It returns false if v is the zero Value.
   314  // If IsValid returns false, all other methods except String panic.
   315  // Most functions and methods never return an invalid Value.
   316  // If one does, its documentation states the conditions explicitly.
   317  func (v Value) IsValid() bool {
   318  	return v.flag != 0
   319  }
   320  
   321  // Kind returns v's Kind.
   322  // If v is the zero Value (IsValid returns false), Kind returns Invalid.
   323  func (v Value) Kind() Kind {
   324  	return v.kind()
   325  }
   326  
   327  // implemented in runtime:
   328  
   329  //go:noescape
   330  func chanlen(unsafe.Pointer) int
   331  
   332  //go:noescape
   333  func maplen(unsafe.Pointer) int
   334  
   335  // Len returns v's length.
   336  // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
   337  func (v Value) Len() int {
   338  	k := v.kind()
   339  	switch k {
   340  	case abi.Array:
   341  		tt := (*arrayType)(unsafe.Pointer(v.typ()))
   342  		return int(tt.Len)
   343  	case abi.Chan:
   344  		return chanlen(v.pointer())
   345  	case abi.Map:
   346  		return maplen(v.pointer())
   347  	case abi.Slice:
   348  		// Slice is bigger than a word; assume flagIndir.
   349  		return (*unsafeheader.Slice)(v.ptr).Len
   350  	case abi.String:
   351  		// String is bigger than a word; assume flagIndir.
   352  		return (*unsafeheader.String)(v.ptr).Len
   353  	}
   354  	panic(&ValueError{"reflect.Value.Len", v.kind()})
   355  }
   356  
   357  // NumMethod returns the number of exported methods in the value's method set.
   358  func (v Value) numMethod() int {
   359  	if v.typ() == nil {
   360  		panic(&ValueError{"reflectlite.Value.NumMethod", abi.Invalid})
   361  	}
   362  	return v.typ().NumMethod()
   363  }
   364  
   365  // Set assigns x to the value v.
   366  // It panics if CanSet returns false.
   367  // As in Go, x's value must be assignable to v's type.
   368  func (v Value) Set(x Value) {
   369  	v.mustBeAssignable()
   370  	x.mustBeExported() // do not let unexported x leak
   371  	var target unsafe.Pointer
   372  	if v.kind() == abi.Interface {
   373  		target = v.ptr
   374  	}
   375  	x = x.assignTo("reflectlite.Set", v.typ(), target)
   376  	if x.flag&flagIndir != 0 {
   377  		typedmemmove(v.typ(), v.ptr, x.ptr)
   378  	} else {
   379  		*(*unsafe.Pointer)(v.ptr) = x.ptr
   380  	}
   381  }
   382  
   383  // Type returns v's type.
   384  func (v Value) Type() Type {
   385  	f := v.flag
   386  	if f == 0 {
   387  		panic(&ValueError{"reflectlite.Value.Type", abi.Invalid})
   388  	}
   389  	// Method values not supported.
   390  	return toRType(v.typ())
   391  }
   392  
   393  /*
   394   * constructors
   395   */
   396  
   397  // implemented in package runtime
   398  
   399  //go:noescape
   400  func unsafe_New(*abi.Type) unsafe.Pointer
   401  
   402  // ValueOf returns a new Value initialized to the concrete value
   403  // stored in the interface i. ValueOf(nil) returns the zero Value.
   404  func ValueOf(i any) Value {
   405  	if i == nil {
   406  		return Value{}
   407  	}
   408  	return unpackEface(i)
   409  }
   410  
   411  // assignTo returns a value v that can be assigned directly to typ.
   412  // It panics if v is not assignable to typ.
   413  // For a conversion to an interface type, target is a suggested scratch space to use.
   414  func (v Value) assignTo(context string, dst *abi.Type, target unsafe.Pointer) Value {
   415  	// if v.flag&flagMethod != 0 {
   416  	// 	v = makeMethodValue(context, v)
   417  	// }
   418  
   419  	switch {
   420  	case directlyAssignable(dst, v.typ()):
   421  		// Overwrite type so that they match.
   422  		// Same memory layout, so no harm done.
   423  		fl := v.flag&(flagAddr|flagIndir) | v.flag.ro()
   424  		fl |= flag(dst.Kind())
   425  		return Value{dst, v.ptr, fl}
   426  
   427  	case implements(dst, v.typ()):
   428  		if target == nil {
   429  			target = unsafe_New(dst)
   430  		}
   431  		if v.Kind() == abi.Interface && v.IsNil() {
   432  			// A nil ReadWriter passed to nil Reader is OK,
   433  			// but using ifaceE2I below will panic.
   434  			// Avoid the panic by returning a nil dst (e.g., Reader) explicitly.
   435  			return Value{dst, nil, flag(abi.Interface)}
   436  		}
   437  		x := valueInterface(v)
   438  		if dst.NumMethod() == 0 {
   439  			*(*any)(target) = x
   440  		} else {
   441  			ifaceE2I(dst, x, target)
   442  		}
   443  		return Value{dst, target, flagIndir | flag(abi.Interface)}
   444  	}
   445  
   446  	// Failed.
   447  	panic(context + ": value of type " + toRType(v.typ()).String() + " is not assignable to type " + toRType(dst).String())
   448  }
   449  
   450  // arrayAt returns the i-th element of p,
   451  // an array whose elements are eltSize bytes wide.
   452  // The array pointed at by p must have at least i+1 elements:
   453  // it is invalid (but impossible to check here) to pass i >= len,
   454  // because then the result will point outside the array.
   455  // whySafe must explain why i < len. (Passing "i < len" is fine;
   456  // the benefit is to surface this assumption at the call site.)
   457  func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer {
   458  	return add(p, uintptr(i)*eltSize, "i < len")
   459  }
   460  
   461  func ifaceE2I(t *abi.Type, src any, dst unsafe.Pointer)
   462  
   463  // typedmemmove copies a value of type t to dst from src.
   464  //
   465  //go:noescape
   466  func typedmemmove(t *abi.Type, dst, src unsafe.Pointer)
   467  
   468  // Dummy annotation marking that the value x escapes,
   469  // for use in cases where the reflect code is so clever that
   470  // the compiler cannot follow.
   471  func escapes(x any) {
   472  	if dummy.b {
   473  		dummy.x = x
   474  	}
   475  }
   476  
   477  var dummy struct {
   478  	b bool
   479  	x any
   480  }
   481  

View as plain text