generic_closure_result.mx raw

   1  /*
   2  A func literal inside a GENERIC body returns its result, natively AND on wasm.
   3  
   4  The literal's signature was resolved without the enclosing instantiation's type
   5  arguments, so `func(x T) (y T)` came out params=[nil] results=[nil] and the CALL
   6  was emitted as a VOID indirect call:
   7  
   8  - natively the result was silently DISCARDED - `v = g(v)` left v unchanged, so an
   9    identity closure looked correct and the bug hid behind that. A closure that
  10    returns something else exposes it immediately.
  11  - on wasm the same signature produced
  12    `call_indirect (type (i32,i32)->nil)` against a closure value stored void, and
  13    the program trapped with "null function or function signature mismatch"
  14    (recorded in the wasm section of the work log as the generic-literal trap).
  15  
  16  `replace` is the shape that fails both ways before the fix and passes after:
  17  it IGNORES its first argument and returns its second, so a discarded result is
  18  observable, and the wasm call has a real i32 result.
  19  
  20  The closure takes both values as PARAMETERS on purpose: a closure that captured
  21  `w` from the enclosing scope is a language-restriction violation for user code
  22  (`closure captures outer variable(s) [w]`), and the suite compiles fixtures from
  23  a path where that rule applies - unlike a build inside the tree, which does not
  24  enforce it. Capture-free is what a user fixture must be.
  25  */
  26  package main
  27  
  28  func replace[T comparable](v T, w T, n int32) (r T) {
  29  	g := func(x T, y T) (z T) {
  30  		return y
  31  	}
  32  	for i := int32(0); i < n; i++ {
  33  		v = g(v, w)
  34  	}
  35  	return v
  36  }
  37  
  38  func identity[T comparable](v T, n int32) (r T) {
  39  	g := func(x T) (y T) {
  40  		return x
  41  	}
  42  	for i := int32(0); i < n; i++ {
  43  		v = g(v)
  44  	}
  45  	return v
  46  }
  47  
  48  func main() {
  49  	// Termination: a batch program must still be stoppable, so the entry
  50  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  51  	select {
  52  	case <-shutdown:
  53  		return
  54  	default:
  55  	}
  56  
  57  	if replace(int32(1), int32(9), 1) != 9 {
  58  		panic("replace int32")
  59  	}
  60  	if replace("a", "b", 2) != "b" {
  61  		panic("replace string")
  62  	}
  63  	if identity(int32(7), 3) != 7 {
  64  		panic("identity int32")
  65  	}
  66  	if identity("hi", 1) != "hi" {
  67  		panic("identity string")
  68  	}
  69  	println("generic closure result ok")
  70  }
  71