diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index fff88671..02984227 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -115,6 +115,10 @@ pure-extern semantics (Closes #332) (#338) ==== Fixed +* WASM: a block ending in a Unit call with no `;` (`println("Hi")`) now +compiles to the same code as the statement form (`println("Hi");`). +Faces keep whichever form the author wrote, so greet in all six faces +now gives byte-identical wasm instead of two classes (Closes #601) * Bun-ESM: every module carried the whole runtime (~300 host helpers), including a `document.body.innerHTML` setter that add-on linters flag. Only the helpers a module reaches are emitted now, in their original order diff --git a/lib/codegen.ml b/lib/codegen.ml index bcba5b27..53921072 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -36,6 +36,10 @@ type context = { fn_ret_types : (string * value_type) list; (** Float wall: function name -> wasm result value type, so a call site `let x = f(...)` can infer whether x is f64. *) + unit_fns : string list; + (** Top-level functions, externs and effect operations declared to return + Unit. A block whose tail is a call to one emits the same code as the + statement form `f(..);` (#601); see [expr_is_unit]. *) loop_depth : int; (** current loop nesting depth *) func_indices : (string * int) list; (** Top-level name environment shared by functions and constants. @@ -173,6 +177,7 @@ let create_context () : context = { next_local = 0; local_types = []; fn_ret_types = []; + unit_fns = []; loop_depth = 0; func_indices = []; lambda_funcs = []; @@ -267,6 +272,40 @@ let lookup_local (ctx : context) (name : string) : int result = | Some idx -> Ok idx | None -> Error (UnboundVariable name) +(** A declared return type that is Unit: omitted, `()` or `Unit`. *) +let rec ret_ty_is_unit : type_expr option -> bool = function + | None | Some (TyTuple []) -> true + | Some (TyCon id) -> id.name = "Unit" + | Some (TyOwn t | TyRef (_, t) | TyMut (_, t)) -> ret_ty_is_unit (Some t) + | Some _ -> false + +(** Names of the program's top-level functions, externs and effect + operations declared to return Unit (#601). *) +let unit_fn_names (prog : program) : string list = + List.concat_map + (function + | TopFn fd when ret_ty_is_unit fd.fd_ret_ty -> [ fd.fd_name.name ] + | TopExternFn { ef_name; ef_ret_ty; _ } when ret_ty_is_unit ef_ret_ty -> + [ ef_name.name ] + | TopEffect ed -> + List.filter_map + (fun (op : effect_op_decl) -> + if ret_ty_is_unit op.eod_ret_ty then Some op.eod_name.name else None) + ed.ed_ops + | _ -> []) + prog.prog_decls + +(** Is [e] provably Unit-valued? Conservative: a [false] keeps the tail + value as emitted. A call whose callee name is a local (a closure) is + not the top-level declaration of that name. *) +let rec expr_is_unit (ctx : context) (e : expr) : bool = + match e with + | ExprSpan (e, _) -> expr_is_unit ctx e + | ExprLit (LitUnit _) -> true + | ExprApp (ExprVar id, _) -> + List.mem id.name ctx.unit_fns && not (List.mem_assoc id.name ctx.locals) + | _ -> false + (** Generate code to bind a pattern to the value on the WASM stack. Assumes the RHS value is already on the stack. Returns instructions that consume the stack value and bind locals. *) @@ -2468,6 +2507,13 @@ and gen_block (ctx : context) (blk : block) : (context * instr list) result = Ok (c', codes @ code) ) (Ok (ctx, [])) blk.blk_stmts in match blk.blk_expr with + | Some e when expr_is_unit ctx' e -> + (* A Unit tail `{ ..; f(x) }` emits exactly what the statement form + `{ ..; f(x); }` does, so the two spellings (which faces choose + differently) compile to identical bytes (#601). The block's value + is the canonical unit 0 either way, whatever [f] leaves behind. *) + let* (ctx_final, expr_code) = gen_expr ctx' e in + Ok (ctx_final, stmt_codes @ expr_code @ [Drop] @ [I32Const 0l]) | Some e -> let* (ctx_final, expr_code) = gen_expr ctx' e in Ok (ctx_final, stmt_codes @ expr_code) @@ -3783,7 +3829,7 @@ let generate_module ?loader (prog : program) : wasm_module result = | Some l -> l | None -> Module_loader.create (Module_loader.default_config ()) in - let ctx = create_context () in + let ctx = { (create_context ()) with unit_fns = unit_fn_names prog } in (* Add WASI fd_write import at index 0 *) let (fd_write_import, fd_write_type) = Wasi_runtime.create_fd_write_import () in diff --git a/test/test_main.ml b/test/test_main.ml index 71a665c0..fc123f75 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -35,6 +35,7 @@ let () = ("Int-div on JS-text backend (#478)", Test_int_div_js.tests); ("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests); ("Bun integer block scope", Test_int_scope_bun.tests); + ("Same cube: faces compile alike (#601)", Test_same_cube.tests); ("ESM runtime pruning", Test_runtime_prune.tests); ("Stdlib algebraic laws (batch 1)", Test_stdlib_laws.tests); ("Solo CESK (VM M1, ADR-0025)", Test_solo_cesk.tests); diff --git a/test/test_same_cube.ml b/test/test_same_cube.ml new file mode 100644 index 00000000..1e441b19 --- /dev/null +++ b/test/test_same_cube.ml @@ -0,0 +1,81 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 hyperpolymath *) + +(** Same cube (#601): one program written in every face compiles to + byte-identical core-WASM. + + The faces keep a block's trailing call as their author wrote it: a + statement `println("Hello");` (canonical, jaffa) or a tail expression + `println("Hello")` (rattle, pseudo, lucid, and cafe written without a + `;`). For a Unit-returning call the WASM emitter now gives both forms + the same code, so the faces cannot split into two wasm classes. *) + +open Affinescript + +let effect_io = "effect IO {\n fn println(s: String) -> ();\n}\n\n" + +(* (face, parser, source) for the one-call greet program. *) +let greet = + [ ("canonical", Parse_driver.parse_file, + effect_io ^ "fn main() -{IO}-> () {\n println(\"Hello\");\n}\n"); + ("rattle", Python_face.parse_file_python, + "effect IO:\n fn println(s: String) -> ();\n\n\ + def main() -{IO}-> ():\n println(\"Hello\")\n"); + ("jaffa", Js_face.parse_file_js, + effect_io ^ "function main() -{IO}-> () {\n println(\"Hello\");\n}\n"); + ("cafe", Cafe_face.parse_file_cafe, + effect_io ^ "fn main() -{IO}-> () {\n println(\"Hello\")\n}\n"); + ("pseudo", Pseudocode_face.parse_file_pseudocode, + effect_io ^ "function main() -{IO}-> () do\n output \"Hello\"\nend\n"); + ("lucid", Lucid_face.parse_file_lucid, + effect_io ^ "main :: -{IO}-> ()\nmain () = println(\"Hello\")\n") ] + +let read_all path = + let ic = open_in_bin path in + let s = really_input_string ic (in_channel_length ic) in + close_in ic; s + +let with_tmp suffix contents f = + let path = Filename.temp_file "same_cube" suffix in + Fun.protect ~finally:(fun () -> try Sys.remove path with Sys_error _ -> ()) + (fun () -> + let oc = open_out_bin path in + output_string oc contents; close_out oc; + f path) + +let wasm_bytes_of_prog prog = + match Codegen.generate_module (Opt.fold_constants_program prog) with + | Error e -> Alcotest.failf "codegen: %s" (Codegen.show_codegen_error e) + | Ok m -> + with_tmp ".wasm" "" (fun out -> + Wasm_encode.write_module_to_file out m; + read_all out) + +let wasm_of (face, parse, src) = + with_tmp ".affine" src (fun path -> + match parse path with + | prog -> wasm_bytes_of_prog prog + | exception e -> Alcotest.failf "%s face did not parse: %s" face (Printexc.to_string e)) + +let test_greet_one_class () = + let reference = wasm_of (List.hd greet) in + List.iter + (fun ((face, _, _) as g) -> + if not (String.equal (wasm_of g) reference) then + Alcotest.failf "the %s face compiles greet to different wasm than canonical" face) + (List.tl greet) + +(* A value-returning tail is not Unit: it keeps its value, so its wasm + differs from the statement form (which would not type-check as Int). *) +let test_value_tail_untouched () = + let src tail = + "fn k() -> Int { 7 }\n\npub fn f() -> Int {\n " ^ tail ^ "\n}\n" in + let a = wasm_of ("canonical", Parse_driver.parse_file, src "k()") in + let b = wasm_of ("canonical", Parse_driver.parse_file, src "k();") in + Alcotest.(check bool) "an Int tail is not dropped" false (String.equal a b) + +let tests = [ + Alcotest.test_case "greet: six faces, one wasm" `Quick test_greet_one_class; + Alcotest.test_case "a value-returning tail keeps its value" `Quick + test_value_tail_untouched; +]