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