Skip to content

Commit 974f08a

Browse files
committed
fix: guard int tracking, swallowed returns, import name hygiene (#797 review)
Four findings from the CodeRabbit review of #797, each verified and pinned by a test that fails without its fix. Bun-ESM backend: - A match arm's guard is emitted before its body, and a tail-position block runs in its own scope of integer tracking (`with_int_scope`), so a `let n = 0.5` in an arm's body no longer turns the guard's `n / 2` into float division. - `gen_tail_to` refuses a `return` in a form it emits as an expression (`[{ return 7; 0 }]`), where the IIFE would have swallowed it. Module flattening: - A public declaration carried only for its module's own callers (the original of an aliased import, or a helper only a selected function calls) gets an internal name, with its references rewritten. With `use A::{helper as ah, api}` and `use B::{helper as bh}`, both `helper`s were emitted under `helper` and `api` called B's. - Internal names length-prefix each module path component, so `A_B.C` and `A.B_C` no longer give the same name. - Aliasing a mutable module binding (`const mut`) is refused: the alias would be a second, separate copy. - Both errors are a structured `Flatten_error`, reported by `eval` and `compile` as a diagnostic (E0206 with `--json`), instead of an uncaught `Failure`. Tests: five new cases in test/test_module_root_flatten.ml. Reverting each fix (the int scoping, the fallback refusal, the internal names, the injective encoding, the mutable-alias refusal) makes its test fail. Full suite: no failures beyond the 33 walker-* tests that need tree-sitter (same on main). kyq parser and lint drivers: 0 failures under Bun. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01P4yFkxW5Heb8p2YW7ZYs9F
1 parent 4ee0e22 commit 974f08a

6 files changed

Lines changed: 285 additions & 54 deletions

File tree

‎bin/main.ml‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,8 @@ let eval_file face json path =
339339
add (Affinescript.Json_output.of_lexer_error msg pos path)
340340
| Affinescript.Parse_driver.Parse_error (msg, span) ->
341341
add (Affinescript.Json_output.of_parse_error msg span)
342+
| Affinescript.Module_loader.Flatten_error e ->
343+
add (Affinescript.Json_output.of_flatten_error e path)
342344
end;
343345
json_finish (List.rev !diags)
344346
end else begin
@@ -400,6 +402,10 @@ let eval_file face json path =
400402
Format.eprintf "@[<v>%a: parse error: %s@]@."
401403
Affinescript.Span.pp_short span msg;
402404
`Error (false, "Parse error")
405+
| Affinescript.Module_loader.Flatten_error e ->
406+
Format.eprintf "@[<v>%s: %s@]@." path
407+
(Affinescript.Module_loader.flatten_error_message e);
408+
`Error (false, "Import error")
403409
end
404410

405411
(** Generate the AffineScript TEA bridge Wasm module.
@@ -747,6 +753,8 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
747753
add (Affinescript.Json_output.of_lexer_error msg pos path)
748754
| Affinescript.Parse_driver.Parse_error (msg, span) ->
749755
add (Affinescript.Json_output.of_parse_error msg span)
756+
| Affinescript.Module_loader.Flatten_error e ->
757+
add (Affinescript.Json_output.of_flatten_error e path)
750758
end;
751759
json_finish (List.rev !diags)
752760
end else begin
@@ -1000,6 +1008,10 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
10001008
Format.eprintf "@[<v>%a: parse error: %s@]@."
10011009
Affinescript.Span.pp_short span msg;
10021010
`Error (false, "Parse error")
1011+
| Affinescript.Module_loader.Flatten_error e ->
1012+
Format.eprintf "@[<v>%s: %s@]@." path
1013+
(Affinescript.Module_loader.flatten_error_message e);
1014+
`Error (false, "Import error")
10031015
end
10041016

10051017
(** Format a file. Only canonical face is supported — non-canonical face

‎docs/COMPLETION-PLAN.adoc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ All were observed by RUN unless marked otherwise. The maps confirm that H1–H4
221221
. H18. The interpreter fails when dereferencing refs returned through calls ("Expected reference type"). The session lead reproduced this on two #554 fixtures.
222222
. H19 (typed-wasm). No L5 index guard: `get_player_hp(0,150)` reads an adjacent region. `where` constraints are discarded. Malformed `session` blocks are silently ignored.
223223
. H23 (found and fixed 2026-11-09, checking and running metadatastician/kyq; numbered H20 in #788, renumbered because #787 assigned H20–H22). A module file found for `A.B` that declares `module A;` was accepted as `A.B`, so `use A.Nonexistent::*` type-checked and imported `A`'s exports; it is now a `ModuleDeclMismatch` load error. *Round 2 (2026-11-16):* a nested candidate (`dir/A/B.affine`) is now searched in every directory before any parent-module fallback, and a module whose load fails is no longer left marked as loading (which reported a later import of it as a cycle). Anchor: `test/test_module_root_flatten.ml`.
224-
. H24 (found and fixed 2026-11-09; numbered H21 in #788). `eval` ran the unflattened program, so no imported function was bound at run time; flattening also emitted a selected function before the private helpers it calls and carried no helpers for glob or plain imports. `eval` now flattens, every import kind carries its helpers, and they are emitted in the imported module's declaration order. *Round 2 (2026-11-16):* two modules with a same-named private helper no longer collide: every private helper carried into a flattened program is renamed `__priv_<Module>__<name>` with a capture-avoiding substitution, and an aliased import emits the original before the alias. Only the root program's `main` is run. Anchor: `test/test_module_root_flatten.ml`.
224+
. H24 (found and fixed 2026-11-09; numbered H21 in #788). `eval` ran the unflattened program, so no imported function was bound at run time; flattening also emitted a selected function before the private helpers it calls and carried no helpers for glob or plain imports. `eval` now flattens, every import kind carries its helpers, and they are emitted in the imported module's declaration order. *Round 2 (2026-11-16):* two modules with a same-named private helper no longer collide: every private helper carried into a flattened program is renamed `__priv_<Module>__<name>` with a capture-avoiding substitution (the module path is length-prefixed, so `A_B.C` and `A.B_C` cannot share a name), and an aliased import emits the original before the alias. *Round 3 (2026-11-16):* a public declaration carried only for the module's own callers (the original of an alias, or a helper only a selected function calls) gets an internal name too, so two modules' `helper`s cannot replace one another; aliasing a mutable binding, which would make a second copy, and an unresolvable name collision are structured flattening errors (diagnostic E0206), not exceptions. Only the root program's `main` is run. Anchor: `test/test_module_root_flatten.ml`.
225225
. H25 (found and fixed 2026-11-09; numbered H22 in #788). The interpreter had no `++` on arrays and no `==`/`!=` beyond Int, Float, String and Bool, though the checker accepts them; it now uses the structural `Value.value_eq`. H7 (`let mut`) is unchanged. Anchor: `test/test_module_root_flatten.ml`.
226226

227227
== 2. Target architecture

‎lib/codegen_deno.ml‎

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1897,14 +1897,17 @@ and gen_tail_to ctx (sink : string -> string) e =
18971897
| ExprSpan (inner, _) -> gen_tail_to ctx sink inner
18981898
| ExprReturn _ -> gen_stmt_expr ctx e
18991899
| ExprBlock blk ->
1900-
let b = Buffer.create 64 in
1901-
List.iter (fun s ->
1902-
Buffer.add_string b (gen_stmt ctx s);
1903-
Buffer.add_char b ' ') blk.blk_stmts;
1904-
(match blk.blk_expr with
1905-
| Some tail -> Buffer.add_string b (gen_tail_to ctx sink tail)
1906-
| None -> Buffer.add_string b (sink "Unit"));
1907-
"{ " ^ Buffer.contents b ^ " }"
1900+
(* The block is a JS block scope: its `let`s must not change the
1901+
integer tracking of the code after it (a guard, a later arm). *)
1902+
with_int_scope ctx (fun () ->
1903+
let b = Buffer.create 64 in
1904+
List.iter (fun s ->
1905+
Buffer.add_string b (gen_stmt ctx s);
1906+
Buffer.add_char b ' ') blk.blk_stmts;
1907+
(match blk.blk_expr with
1908+
| Some tail -> Buffer.add_string b (gen_tail_to ctx sink tail)
1909+
| None -> Buffer.add_string b (sink "Unit"));
1910+
"{ " ^ Buffer.contents b ^ " }")
19081911
| ExprIf { ei_cond; ei_then; ei_else } ->
19091912
(* The condition is emitted as an expression, where a `return` would
19101913
leave an IIFE instead of the function. *)
@@ -1935,17 +1938,40 @@ and gen_tail_to ctx (sink : string -> string) e =
19351938
let arm_js arm =
19361939
let cond = gen_pattern_test sv arm.ma_pat in
19371940
let binds = gen_pattern_bindings sv arm.ma_pat in
1938-
let body = gen_tail_to ctx sink arm.ma_body ^ " break " ^ label ^ ";" in
1939-
let guarded = match arm.ma_guard with
1941+
(* The guard is emitted before the body, against the integer
1942+
tracking the guard actually runs under. *)
1943+
let guard = Option.map (gen_expr ctx) arm.ma_guard in
1944+
let body =
1945+
with_int_scope ctx (fun () -> gen_tail_to ctx sink arm.ma_body)
1946+
^ " break " ^ label ^ ";"
1947+
in
1948+
let guarded = match guard with
19401949
| None -> body
1941-
| Some g -> "if (" ^ gen_expr ctx g ^ ") { " ^ body ^ " }"
1950+
| Some g -> "if (" ^ g ^ ") { " ^ body ^ " }"
19421951
in
19431952
"if (" ^ cond ^ ") { " ^ binds ^ guarded ^ " }"
19441953
in
19451954
label ^ ": { const " ^ sv ^ " = " ^ gen_expr ctx em_scrutinee ^ "; "
19461955
^ String.concat " " (List.map arm_js em_arms)
19471956
^ " throw new Error(\"non-exhaustive match\"); }"
1948-
| other -> sink (gen_expr ctx other)
1957+
| other ->
1958+
(* Any other form is emitted as an expression, where a nested block
1959+
becomes an IIFE and a `return` in it would leave only the IIFE
1960+
(`[{ return 7; 0 }]`). Refuse it rather than drop the return. *)
1961+
if expr_contains_return other then refuse_return "this expression";
1962+
sink (gen_expr ctx other)
1963+
1964+
(* Run [f] in a nested scope of [ctx]'s integer tracking: bindings it records
1965+
are dropped afterwards, so they cannot leak into the code that follows. *)
1966+
and with_int_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f ->
1967+
let saved = Hashtbl.copy ctx.int_vars in
1968+
let restore () =
1969+
Hashtbl.reset ctx.int_vars;
1970+
Hashtbl.iter (Hashtbl.replace ctx.int_vars) saved
1971+
in
1972+
match f () with
1973+
| v -> restore (); v
1974+
| exception e -> restore (); raise e
19491975

19501976
(* Fail loudly where a `return` would otherwise be compiled into an IIFE and
19511977
leave it instead of the enclosing function. *)

‎lib/json_output.ml‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,20 @@ let of_parse_error (msg : string) (span : Span.t) : diagnostic =
136136
labels = [];
137137
}
138138

139+
(** Convert an import-flattening error to a diagnostic. It names no source
140+
position, so it is placed at the start of the root file. *)
141+
let of_flatten_error (e : Module_loader.flatten_error) (file : string)
142+
: diagnostic =
143+
let start = { Span.line = 1; col = 1; offset = 0 } in
144+
{
145+
severity = Error;
146+
code = "E0206";
147+
message = Module_loader.flatten_error_message e;
148+
span = Span.make ~file ~start_pos:start ~end_pos:start;
149+
help = Some "import the binding under its own name, or rename one of them";
150+
labels = [];
151+
}
152+
139153
(** Convert a resolve error to a diagnostic.
140154
141155
[Resolve.resolve_error] variants carry [Ast.ident] values which

‎lib/module_loader.ml‎

Lines changed: 125 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@ type load_error =
2121
would bind [A]'s exports under a name that does not exist. *)
2222
[@@deriving show]
2323

24+
(** Why the declarations of a program's imports cannot be flattened into one
25+
program. Raised as {!Flatten_error} by {!flatten_imports}; the CLI reports
26+
it as a diagnostic. *)
27+
type flatten_error =
28+
| ImportCollision of string * string list * string list
29+
(** One flattened name, carried by two different modules' declarations. *)
30+
| MutableAlias of string * string * string list
31+
(** A mutable module binding, the alias it was imported under, and its
32+
module. An alias is a second declaration, so it would be a second,
33+
separate copy of the binding. *)
34+
[@@deriving show]
35+
36+
exception Flatten_error of flatten_error
37+
2438
(** Helper for Result bind *)
2539
let ( let* ) = Result.bind
2640

@@ -369,7 +383,53 @@ let clear_cache (loader : t) : unit =
369383
module's code would call another module's helper. Underscores keep the
370384
name valid in every backend's target language. *)
371385
let qualified_private_name (mod_path : string list) (name : string) : string =
372-
"__priv_" ^ String.concat "_" mod_path ^ "__" ^ name
386+
(* Each path component is prefixed by its length, so the encoding is
387+
injective: joining with `_` made `A_B.C` and `A.B_C` the same. *)
388+
"__priv_"
389+
^ String.concat ""
390+
(List.map (fun c -> string_of_int (String.length c) ^ c) mod_path)
391+
^ "__" ^ name
392+
393+
(** The diagnostic text of a {!flatten_error}. *)
394+
let flatten_error_message = function
395+
| ImportCollision (name, a, b) ->
396+
Printf.sprintf
397+
"cannot flatten imports: `%s` is defined in both %s and %s" name
398+
(String.concat "::" a) (String.concat "::" b)
399+
| MutableAlias (name, alias, m) ->
400+
Printf.sprintf
401+
"cannot import the mutable binding `%s` from %s as `%s`: an alias would \
402+
be a separate copy of it; import it under its own name" name
403+
(String.concat "::" m) alias
404+
405+
(** Rename, by [ren] (old name to new), a top-level function or constant's
406+
own name and the free references to the renamed names in its body; a
407+
parameter that shadows a renamed name is left alone. *)
408+
let rename_top_level (ren : (string * string) list) (decl : top_level)
409+
: top_level =
410+
if ren = [] then decl
411+
else
412+
let rename_ident (id : ident) =
413+
match List.assoc_opt id.name ren with
414+
| Some n -> { id with name = n }
415+
| None -> id
416+
in
417+
match decl with
418+
| TopFn fd ->
419+
let inner =
420+
without_names ren
421+
(List.map (fun (p : param) -> p.p_name.name) fd.fd_params)
422+
in
423+
let body = match fd.fd_body with
424+
| FnExpr e -> FnExpr (rename_free inner e)
425+
| FnBlock b -> FnBlock (rename_block inner b)
426+
| FnExtern -> FnExtern
427+
in
428+
TopFn { fd with fd_name = rename_ident fd.fd_name; fd_body = body }
429+
| TopConst c ->
430+
TopConst { c with tc_name = rename_ident c.tc_name;
431+
tc_value = rename_free ren c.tc_value }
432+
| other -> other
373433

374434
(** Give [prog]'s own private functions and constants (those of [own], the
375435
module's unflattened declarations) their {!qualified_private_name}, and
@@ -390,28 +450,7 @@ let qualify_private (mod_path : string list) (own : top_level list)
390450
in
391451
if ren = [] then prog
392452
else
393-
let rename_ident (id : ident) =
394-
match List.assoc_opt id.name ren with
395-
| Some n -> { id with name = n }
396-
| None -> id
397-
in
398-
let rename_decl = function
399-
| TopFn fd ->
400-
let inner =
401-
without_names ren
402-
(List.map (fun (p : param) -> p.p_name.name) fd.fd_params)
403-
in
404-
let body = match fd.fd_body with
405-
| FnExpr e -> FnExpr (rename_free inner e)
406-
| FnBlock b -> FnBlock (rename_block inner b)
407-
| FnExtern -> FnExtern
408-
in
409-
TopFn { fd with fd_name = rename_ident fd.fd_name; fd_body = body }
410-
| TopConst c ->
411-
TopConst { c with tc_name = rename_ident c.tc_name;
412-
tc_value = rename_free ren c.tc_value }
413-
| other -> other
414-
in
453+
let rename_decl = rename_top_level ren in
415454
let is_own d = List.exists (fun o -> o == d) own in
416455
{ prog with
417456
prog_decls =
@@ -503,11 +542,7 @@ let rec flatten_imports_from
503542
make the other module call the wrong function. (Public
504543
collisions are rejected by the resolver; #743's last-wins rule
505544
still applies to them.) *)
506-
failwith
507-
(Printf.sprintf
508-
"cannot flatten imports: `%s` is defined in both %s and %s, \
509-
and at least one is a private helper"
510-
name (show_module_path other) (show_module_path origin))
545+
raise (Flatten_error (ImportCollision (name, other, origin)))
511546
| _ -> ());
512547
if not (Hashtbl.mem imported_by_name name) then
513548
imported_order := name :: !imported_order;
@@ -674,13 +709,29 @@ let rec flatten_imports_from
674709
the bodies present. *)
675710
close_over public_decls
676711
| ImportList (_, items) ->
677-
(* The name a directly-named item is imported under (alias
678-
honoured). *)
679-
let bound_name_of target =
680-
match List.find_opt (fun item -> item.ii_name.name = target) items with
681-
| Some { ii_alias = Some a; _ } -> a.name
682-
| _ -> target
712+
(* Every alias an item is imported under. *)
713+
let aliases_of target =
714+
List.filter_map (fun item ->
715+
match item.ii_alias with
716+
| Some a when item.ii_name.name = target -> Some a.name
717+
| _ -> None) items
718+
in
719+
(* Names the importer binds under their own name. *)
720+
let exposed =
721+
List.filter_map (fun item ->
722+
match item.ii_alias with
723+
| None -> Some item.ii_name.name
724+
| Some _ -> None) items
683725
in
726+
(* An alias is a second declaration: for a mutable binding that
727+
would be a second, separate copy. *)
728+
List.iter (fun item ->
729+
match item.ii_alias,
730+
List.assoc_opt item.ii_name.name public_decls with
731+
| Some a, Some (`Const (TopConst { tc_mut = true; _ })) ->
732+
raise (Flatten_error
733+
(MutableAlias (item.ii_name.name, a.name, mod_path)))
734+
| _ -> ()) items;
684735
let rename_decl bound_name found =
685736
match found with
686737
| `Fn fd ->
@@ -707,14 +758,47 @@ let rec flatten_imports_from
707758
) items
708759
in
709760
let closed = close_over direct in
710-
(* An aliased item (`use M::{helper as h, api}`) is carried under
711-
its alias for the importer, and also under its own name when
712-
it is renamed, because the module's other declarations (`api`)
713-
still call it by that name. *)
761+
(* This module's own public functions and immutable constants that
762+
the closure carries but the importer does not bind under their
763+
own name (`helper` in `use M::{helper as h, api}`, or a public
764+
helper only `api` calls) get an internal name, with the
765+
references to them rewritten. Left under their own name, two
766+
modules' `helper`s would replace one another and `api` would
767+
call the other module's (CodeRabbit on #797). A mutable binding
768+
keeps its name: it may be imported under that name elsewhere,
769+
and a renamed copy would be separate storage. *)
770+
let hidden =
771+
List.filter_map (function
772+
| TopFn fd
773+
when (fd.fd_vis = Public || fd.fd_vis = PubCrate)
774+
&& fd.fd_body <> FnExtern
775+
&& not (List.mem fd.fd_name.name exposed)
776+
&& List.mem_assoc fd.fd_name.name closed ->
777+
Some (fd.fd_name.name,
778+
qualified_private_name mod_path fd.fd_name.name)
779+
| TopConst { tc_vis = (Public | PubCrate); tc_mut = false;
780+
tc_name; _ }
781+
when not (List.mem tc_name.name exposed)
782+
&& List.mem_assoc tc_name.name closed ->
783+
Some (tc_name.name,
784+
qualified_private_name mod_path tc_name.name)
785+
| _ -> None) lm0.mod_program.prog_decls
786+
in
787+
let internalise = function
788+
| `Fn fd ->
789+
(match rename_top_level hidden (TopFn fd) with
790+
| TopFn fd' -> `Fn fd'
791+
| _ -> `Fn fd)
792+
| `Const d -> `Const (rename_top_level hidden d)
793+
| `Type _ as t -> t
794+
in
795+
(* An aliased item (`use M::{helper as h, api}`) is bound under its
796+
alias for the importer; the original stays, under its internal
797+
name, because the module's other declarations (`api`) call it. *)
714798
List.concat_map (fun (n, dk) ->
715-
let b = bound_name_of n in
716-
if b = n then [ (n, dk) ]
717-
else [ (n, dk); (b, rename_decl b dk) ])
799+
let dk = internalise dk in
800+
let n' = Option.value (List.assoc_opt n hidden) ~default:n in
801+
(n', dk) :: List.map (fun b -> (b, rename_decl b dk)) (aliases_of n))
718802
closed
719803
in
720804
(* Public enums the importer names directly. A constructor in the

0 commit comments

Comments
 (0)