unsafe_typeof.mx raw

   1  /*
   2  unsafe.TypeOf accepts ANY operand, and that is the design - not the hole that
   3  unsafe.Pointer had.
   4  
   5  The objective's unsafe item named two builtins. `unsafe.Pointer(x)` was the bug:
   6  declared `__any->ptr`, it accepted a struct or slice value and silently made it a
   7  pointer, which is why six sites in src/net produced invalid IR instead of a
   8  compile error; that is now a checked conversion (round 103,
   9  reject_unsafe_ptr_nonpointer). `unsafe.TypeOf(x)` is the opposite case: returning
  10  the compiler's OWN descriptor for whatever x is IS its purpose, the operand is
  11  never converted, and comparing two of those pointers is how a program asks "are
  12  these the same type" without reflection. Restricting it would remove the ability,
  13  not a hole.
  14  
  15  This fixture pins the semantics so a future widening of the unsafe checks cannot
  16  quietly break them: same type compares equal, different types do not, and that
  17  holds across basic widths, struct shapes, composite kinds and two local types in
  18  one function (which round 107 made distinct types).
  19  */
  20  package main
  21  
  22  import (
  23  	"unsafe"
  24  )
  25  
  26  type alpha struct {
  27  	x int32
  28  }
  29  
  30  type beta struct {
  31  	y []byte
  32  }
  33  
  34  func main() {
  35  	// Termination: a batch program must still be stoppable, so the entry
  36  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  37  	select {
  38  	case <-shutdown:
  39  		return
  40  	default:
  41  	}
  42  
  43  	var a int64 = 1
  44  	var b int64 = 2
  45  	var c int32 = 3
  46  	if unsafe.TypeOf(a) != unsafe.TypeOf(b) {
  47  		panic("two int64 values have different descriptors")
  48  	}
  49  	if unsafe.TypeOf(a) == unsafe.TypeOf(c) {
  50  		panic("int64 and int32 share a descriptor")
  51  	}
  52  	var x alpha
  53  	var y beta
  54  	if unsafe.TypeOf(x) == unsafe.TypeOf(y) {
  55  		panic("two different struct types share a descriptor")
  56  	}
  57  	var s []byte = "s"
  58  	var p *alpha = &x
  59  	if unsafe.TypeOf(s) == unsafe.TypeOf(p) {
  60  		panic("a slice and a pointer share a descriptor")
  61  	}
  62  	type localOne struct{ n int32 }
  63  	type localTwo struct{ m int32 }
  64  	var l1 localOne
  65  	var l2 localTwo
  66  	if unsafe.TypeOf(l1) == unsafe.TypeOf(l2) {
  67  		panic("two local types share a descriptor")
  68  	}
  69  	println("unsafe.TypeOf ok")
  70  }
  71