switch_default_first.mx raw

   1  // Regression: a default clause written before the cases swallowed the switch.
   2  //
   3  // The SSA builder emitted the default clause's body where it stood, as an
   4  // unconditional jump, so every case after it was dead. crypto/aes.NewCipher
   5  // validates its key with
   6  //
   7  //	switch k {
   8  //	default:
   9  //		return nil, KeySizeError(k)
  10  //	case 16, 24, 32:
  11  //		break
  12  //	}
  13  //
  14  // and rejected a valid 32-byte AES-256 key ("crypto/aes: invalid key size
  15  // 32"), which trapped the signer worker on addIdentity.
  16  //
  17  // Reproduces: switch with default first, and a tagless switch with default.
  18  // Fixed in: _mxc_stage4 ssa_builder buildSwitch (default evaluated last).
  19  
  20  package main
  21  
  22  func classify(n int32) (s string) {
  23  	switch n {
  24  	default:
  25  		return "other"
  26  	case 1, 2, 3:
  27  		break
  28  	}
  29  	return "small"
  30  }
  31  
  32  func tagless(n int32) (s string) {
  33  	switch {
  34  	default:
  35  		return "none"
  36  	case n == 1:
  37  		return "one"
  38  	case n == 2, n == 3:
  39  		return "few"
  40  	}
  41  }
  42  
  43  func main() {
  44  	if classify(1) != "small" || classify(3) != "small" {
  45  		panic("case after default did not match")
  46  	}
  47  	if classify(9) != "other" {
  48  		panic("default did not run")
  49  	}
  50  	if tagless(1) != "one" || tagless(3) != "few" {
  51  		panic("tagless case after default did not match")
  52  	}
  53  	if tagless(9) != "none" {
  54  		panic("tagless default did not run")
  55  	}
  56  	println("ok")
  57  }
  58