shift_compare_context.mx raw

   1  /*
   2  A non-constant shift whose left operand is an untyped constant takes the type of
   3  the operand it is compared against, so `u == 1<<(n-1)` with u uint64 shifts at 64
   4  bits.
   5  
   6  stage4 used to require the sibling's width to EQUAL the shift's own, so a 32-bit
   7  default shift stayed 32 bits against a uint64 sibling: 1<<61 evaluated to 0,
   8  `uint64(0) == 1<<61` was true, and `dfrac > 1<<(extra-1)` in strconv's ryu
   9  rounding was true for every exact value. That made stage4 format 1.0 as "2e+00"
  10  and 0.1 as "2.0001e-01" while legacy formatted them correctly, and it also moved
  11  ParseFloat's results.
  12  */
  13  package main
  14  
  15  import (
  16  	"strconv"
  17  )
  18  
  19  func main() {
  20  	// Termination: a batch program must still be stoppable, so the entry
  21  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  22  	select {
  23  	case <-shutdown:
  24  		return
  25  	default:
  26  	}
  27  
  28  	var s uint32 = 62
  29  	var zero uint64 = 0
  30  
  31  	// Widening context: the shift must run at 64 bits.
  32  	if zero == 1<<(s-1) {
  33  		panic("uint64(0) == 1<<61; the shift ran at 32 bits")
  34  	}
  35  	if 1<<(s-1) == zero {
  36  		panic("1<<61 == uint64(0); the shift ran at 32 bits")
  37  	}
  38  	var one uint64 = 1
  39  	if zero == one<<(s-1) {
  40  		panic("uint64(0) == uint64(1)<<61")
  41  	}
  42  	half := uint64(1) << (s - 1)
  43  	if half != 2305843009213693952 {
  44  		panic("1<<61 != 2^61")
  45  	}
  46  	if zero == half {
  47  		panic("uint64(0) == 1<<61 stored in a uint64")
  48  	}
  49  
  50  	// Signed 64-bit sibling.
  51  	var izero int64 = 0
  52  	if izero == 1<<(s-2) {
  53  		panic("int64(0) == 1<<60; the shift ran at 32 bits")
  54  	}
  55  
  56  	// Equal-width contexts keep working.
  57  	var w uint32 = 4
  58  	if !(w == 1<<2) {
  59  		panic("uint32(4) != 1<<2")
  60  	}
  61  	var b byte = 128
  62  	if !(b == 1<<7) {
  63  		panic("byte(128) != 1<<7")
  64  	}
  65  
  66  	// The rounding that exposed it: exact values must not round up.
  67  	if got := strconv.FormatFloat(1, 'e', 0, 64); got != "1e+00" {
  68  		panic("FormatFloat(1, 'e', 0) = " | got)
  69  	}
  70  	if got := strconv.FormatFloat(1.5, 'e', 1, 64); got != "1.5e+00" {
  71  		panic("FormatFloat(1.5, 'e', 1) = " | got)
  72  	}
  73  	if got := strconv.FormatFloat(0.1, 'e', 4, 64); got != "1.0000e-01" {
  74  		panic("FormatFloat(0.1, 'e', 4) = " | got)
  75  	}
  76  	if got := strconv.FormatFloat(0.5, 'e', 0, 64); got != "5e-01" {
  77  		panic("FormatFloat(0.5, 'e', 0) = " | got)
  78  	}
  79  	println("shift comparison context ok")
  80  }
  81