Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 25 additions & 15 deletions bin/main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -173,25 +173,23 @@ let parse_file (face : Affinescript.Face.face) path =
Affinescript.Span.pp_short span msg;
`Error (false, "Parse error")

(** Build a loader rooted at the source file's directory. The historical
CLI used the process CWD as [current_dir], so compiling `src/Main.affine`
could not find a sibling `src/Helper.affine` even though the module
loader already supported relative sibling paths (#642). *)
(** Build the loader for a source file: rooted at its package root when its
`module` declaration matches its directories, with its own directory
still searchable (#642). See [Module_loader.config_for_file]. *)
let loader_config_for_file ?prog path =
let absolute_path =
if Filename.is_relative path then Filename.concat (Sys.getcwd ()) path
else path
in
let config = Affinescript.Module_loader.default_config () in
let mod_path =
Option.bind prog (fun (p : Affinescript.Ast.program) ->
Option.map (List.map (fun (id : Affinescript.Ast.ident) -> id.name))
p.prog_module)
in
{ config with
current_dir =
Affinescript.Module_loader.module_root_dir
~file_dir:(Filename.dirname absolute_path) mod_path }
Affinescript.Module_loader.config_for_file ~file_path:path mod_path

(* Auto-call `main` only when the root program declares it
(Module_loader.declares_main). *)
let lookup_root_main (prog : Affinescript.Ast.program) env =
if Affinescript.Module_loader.declares_main prog
then Affinescript.Value.lookup_env "main" env
else Error (Affinescript.Value.UnboundVariable "main")

(** Type-check a file. With [--json], emits a structured diagnostic
report on stderr. *)
Expand Down Expand Up @@ -328,7 +326,7 @@ let eval_file face json path =
(Affinescript.Module_loader.flatten_imports loader prog) with
| Ok env ->
(* Auto-call main() if defined — entry point for TEA apps and scripts *)
(match Affinescript.Value.lookup_env "main" env with
(match lookup_root_main prog env with
| Ok main_fn ->
(match Affinescript.Interp.apply_function main_fn [] with
| Ok _ -> ()
Expand All @@ -341,6 +339,8 @@ let eval_file face json path =
add (Affinescript.Json_output.of_lexer_error msg pos path)
| Affinescript.Parse_driver.Parse_error (msg, span) ->
add (Affinescript.Json_output.of_parse_error msg span)
| Affinescript.Module_loader.Flatten_error e ->
add (Affinescript.Json_output.of_flatten_error e path)
end;
json_finish (List.rev !diags)
end else begin
Expand Down Expand Up @@ -378,7 +378,7 @@ let eval_file face json path =
(Affinescript.Module_loader.flatten_imports loader prog) with
| Ok env ->
(* Auto-call main() if defined — entry point for TEA apps and scripts *)
(match Affinescript.Value.lookup_env "main" env with
(match lookup_root_main prog env with
| Ok main_fn ->
(match Affinescript.Interp.apply_function main_fn [] with
| Ok _ -> `Ok ()
Expand All @@ -402,6 +402,10 @@ let eval_file face json path =
Format.eprintf "@[<v>%a: parse error: %s@]@."
Affinescript.Span.pp_short span msg;
`Error (false, "Parse error")
| Affinescript.Module_loader.Flatten_error e ->
Format.eprintf "@[<v>%s: %s@]@." path
(Affinescript.Module_loader.flatten_error_message e);
`Error (false, "Import error")
end

(** Generate the AffineScript TEA bridge Wasm module.
Expand Down Expand Up @@ -749,6 +753,8 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
add (Affinescript.Json_output.of_lexer_error msg pos path)
| Affinescript.Parse_driver.Parse_error (msg, span) ->
add (Affinescript.Json_output.of_parse_error msg span)
| Affinescript.Module_loader.Flatten_error e ->
add (Affinescript.Json_output.of_flatten_error e path)
end;
json_finish (List.rev !diags)
end else begin
Expand Down Expand Up @@ -1002,6 +1008,10 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
Format.eprintf "@[<v>%a: parse error: %s@]@."
Affinescript.Span.pp_short span msg;
`Error (false, "Parse error")
| Affinescript.Module_loader.Flatten_error e ->
Format.eprintf "@[<v>%s: %s@]@." path
(Affinescript.Module_loader.flatten_error_message e);
`Error (false, "Import error")
end

(** Format a file. Only canonical face is supported — non-canonical face
Expand Down
8 changes: 4 additions & 4 deletions docs/COMPLETION-PLAN.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ Results were consistent, but they do not prove CI is green.
All were observed by RUN unless marked otherwise. The maps confirm that H1–H4 and H9 are absent from `docs/SOUNDNESS.adoc`. H5–H8, H10, H12 and H13 were not checked against the ledger. H11 already has a drafted issue (`issues-drafts/06`, referenced from the AFFIRMATION). H14, H15 and H19 belong to typed-wasm, not the AffineScript ledger.

. H1. Interpreter early `return` has no non-local exit (`lib/interp.ml:262`).
. H2. Bun-ESM `return` in expression position is lowered as an IIFE (`lib/codegen_deno.ml:1575`). *Narrowed 2026-11-09:* `let` initializers and function and lambda tails are now lowered to statements, so the `return` leaves the function; a match used as an argument or operand with a `return` in an arm is refused loudly. Anchor: `test/test_module_root_flatten.ml`.
. H2. Bun-ESM `return` in expression position is lowered as an IIFE (`lib/codegen_deno.ml:1575`). *Narrowed 2026-11-09:* `let` initializers and function and lambda tails are now lowered to statements, so the `return` leaves the function; a match used as an argument or operand with a `return` in an arm is refused loudly. *Round 2 (2026-11-16):* match arms and guards are lowered as a labelled block, so a guard sees the arm's bindings and a `return` in an arm leaves the function; `let _ = e` still evaluates `e`; a `return` in an `if` condition, a scrutinee or a guard is refused loudly. Anchor: `test/test_module_root_flatten.ml`.
. H3. The JS-text backend drops block returns (`lib/js_codegen.ml`). The Lua backend emits invalid code.
. H4. Non-exhaustive match compiles to "return 0" on core WASM.
. H5. Effect rows are not checked against performed operations or callee rows.
Expand All @@ -220,9 +220,9 @@ All were observed by RUN unless marked otherwise. The maps confirm that H1–H4
. H17. The lexer accepts the bad escape `\q`, and an empty `match` parses (conformance invalid cases 010 and 011).
. H18. The interpreter fails when dereferencing refs returned through calls ("Expected reference type"). The session lead reproduced this on two #554 fixtures.
. 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.
. H20 (found and fixed 2026-11-09, checking and running metadatastician/kyq). 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. Anchor: `test/test_module_root_flatten.ml`.
. H21 (found and fixed 2026-11-09). `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. Anchor: `test/test_module_root_flatten.ml`.
. H22 (found and fixed 2026-11-09). 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`.
. 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`.
. 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`.
. 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`.

== 2. Target architecture

Expand Down
142 changes: 140 additions & 2 deletions lib/ast.ml
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,16 @@ let rec expr_contains_return (e : expr) : bool =
|| List.exists (fun arm ->
(match arm.ma_guard with Some g -> expr_contains_return g | None -> false)
|| expr_contains_return arm.ma_body) em_arms
(* Aggregates: `[return 1]`, `(x, return y)`, `#{ f: return z }` and
projections of them return just as directly. *)
| ExprTuple es | ExprArray es -> List.exists expr_contains_return es
| ExprRecord { er_fields; er_spread } ->
List.exists (fun (_, e) ->
match e with Some e -> expr_contains_return e | None -> false) er_fields
|| (match er_spread with Some e -> expr_contains_return e | None -> false)
| ExprField (e, _) | ExprTupleIndex (e, _) -> expr_contains_return e
| ExprIndex (a, b) | ExprStringConcat (a, b) ->
expr_contains_return a || expr_contains_return b
| _ -> false

and block_contains_return (blk : block) : bool =
Expand Down Expand Up @@ -566,6 +576,127 @@ let rec pattern_binders (pat : pattern) : string list =
| PatOr (p1, p2) -> pattern_binders p1 @ pattern_binders p2
| PatAs (id, pat) -> id.name :: pattern_binders pat

(** Rename free occurrences of variables: [ren] maps old names to new ones.
Capture-avoiding in the usual way: a binder (let, match arm, lambda
parameter, block `let`, `for` pattern, handler pattern) removes the
names it binds from [ren] for its scope, so a local that shadows a
renamed top-level name keeps referring to the local. A record
shorthand field `#{ x }` whose variable is renamed becomes
`#{ x: x' }`. Used by import flattening to give each module's private
helpers module-specific names. *)
let without_names (ren : (string * string) list) (names : string list) =
List.filter (fun (old, _) -> not (List.mem old names)) ren

let rec rename_free (ren : (string * string) list) (e : expr) : expr =
if ren = [] then e
else
let r = rename_free ren in
let ro = Option.map r in
match e with
| ExprLit _ | ExprBreak _ | ExprContinue _ | ExprVariant _ -> e
| ExprVar id ->
(match List.assoc_opt id.name ren with
| Some n -> ExprVar { id with name = n }
| None -> e)
| ExprLet lb ->
let inner = without_names ren (pattern_binders lb.el_pat) in
ExprLet { lb with el_value = r lb.el_value;
el_body = Option.map (rename_free inner) lb.el_body }
| ExprIf ei ->
ExprIf { ei_cond = r ei.ei_cond; ei_then = r ei.ei_then;
ei_else = ro ei.ei_else }
| ExprMatch m ->
ExprMatch { em_scrutinee = r m.em_scrutinee;
em_arms = List.map (rename_arm ren) m.em_arms }
| ExprLambda lam ->
let inner =
without_names ren (List.map (fun (p : param) -> p.p_name.name)
lam.elam_params) in
ExprLambda { lam with elam_body = rename_free inner lam.elam_body }
| ExprApp (f, args) -> ExprApp (r f, List.map r args)
| ExprField (x, f) -> ExprField (r x, f)
| ExprTupleIndex (x, i) -> ExprTupleIndex (r x, i)
| ExprIndex (a, b) -> ExprIndex (r a, r b)
| ExprTuple es -> ExprTuple (List.map r es)
| ExprArray es -> ExprArray (List.map r es)
| ExprRecord rc ->
let field ((n : ident), eo) =
match eo with
| Some x -> (n, Some (r x))
| None ->
(match List.assoc_opt n.name ren with
| Some nn -> (n, Some (ExprVar { n with name = nn }))
| None -> (n, None))
in
ExprRecord { er_fields = List.map field rc.er_fields;
er_spread = ro rc.er_spread }
| ExprRowRestrict (x, f) -> ExprRowRestrict (r x, f)
| ExprBinary (a, op, b) -> ExprBinary (r a, op, r b)
| ExprStringConcat (a, b) -> ExprStringConcat (r a, r b)
| ExprStringEq (a, b, neg) -> ExprStringEq (r a, r b, neg)
| ExprStringRel (a, b, op) -> ExprStringRel (r a, r b, op)
| ExprFloatBinary (a, op, b) -> ExprFloatBinary (r a, op, r b)
| ExprFloatArray es -> ExprFloatArray (List.map r es)
| ExprFloatIndex (a, b) -> ExprFloatIndex (r a, r b)
| ExprCellTuple cs -> ExprCellTuple (List.map (fun (x, f) -> (r x, f)) cs)
| ExprCellTupleIndex (x, i, f) -> ExprCellTupleIndex (r x, i, f)
| ExprCellRecord fs ->
ExprCellRecord (List.map (fun (n, x, f) -> (n, r x, f)) fs)
| ExprCellField (x, i, f) -> ExprCellField (r x, i, f)
| ExprUnary (op, x) -> ExprUnary (op, r x)
| ExprBlock b -> ExprBlock (rename_block ren b)
| ExprReturn eo -> ExprReturn (ro eo)
| ExprTry t ->
ExprTry { et_body = rename_block ren t.et_body;
et_catch = Option.map (List.map (rename_arm ren)) t.et_catch;
et_finally = Option.map (rename_block ren) t.et_finally }
| ExprHandle h ->
let handler = function
| HandlerReturn (p, x) ->
HandlerReturn (p, rename_free (without_names ren (pattern_binders p)) x)
| HandlerOp (op, ps, x) ->
HandlerOp (op, ps,
rename_free
(without_names ren (List.concat_map pattern_binders ps)) x)
in
ExprHandle { eh_body = r h.eh_body;
eh_handlers = List.map handler h.eh_handlers }
| ExprResume eo -> ExprResume (ro eo)
| ExprUnsafe ops ->
ExprUnsafe (List.map (function
| UnsafeRead x -> UnsafeRead (r x)
| UnsafeWrite (a, b) -> UnsafeWrite (r a, r b)
| UnsafeOffset (a, b) -> UnsafeOffset (r a, r b)
| UnsafeTransmute (t1, t2, x) -> UnsafeTransmute (t1, t2, r x)
| UnsafeForget x -> UnsafeForget (r x)) ops)
| ExprSpan (x, sp) -> ExprSpan (r x, sp)

and rename_arm ren (arm : match_arm) : match_arm =
let inner = without_names ren (pattern_binders arm.ma_pat) in
{ arm with ma_guard = Option.map (rename_free inner) arm.ma_guard;
ma_body = rename_free inner arm.ma_body }

and rename_block ren (blk : block) : block =
if ren = [] then blk
else
let rec go ren acc = function
| [] -> (List.rev acc, ren)
| StmtLet sl :: rest ->
let s = StmtLet { sl with sl_value = rename_free ren sl.sl_value } in
go (without_names ren (pattern_binders sl.sl_pat)) (s :: acc) rest
| StmtExpr x :: rest -> go ren (StmtExpr (rename_free ren x) :: acc) rest
| StmtAssign (a, op, b) :: rest ->
go ren (StmtAssign (rename_free ren a, op, rename_free ren b) :: acc) rest
| StmtWhile (c, b) :: rest ->
go ren (StmtWhile (rename_free ren c, rename_block ren b) :: acc) rest
| StmtFor (p, it, b) :: rest ->
let s = StmtFor (p, rename_free ren it,
rename_block (without_names ren (pattern_binders p)) b) in
go ren (s :: acc) rest
in
let stmts, ren_after = go ren [] blk.blk_stmts in
{ blk_stmts = stmts; blk_expr = Option.map (rename_free ren_after) blk.blk_expr }

(** Free variables of an expression.

Returns the names used in [expr] but not bound within it; [bound_vars]
Expand Down Expand Up @@ -659,11 +790,18 @@ let rec find_free_vars (bound_vars : string list) (expr : expr) : string list =
| ExprTuple exprs | ExprArray exprs ->
List.concat (List.map (find_free_vars bound_vars) exprs)
| ExprRecord r ->
List.concat (List.map (fun (_, e_opt) ->
(* A shorthand field `#{ x }` reads the variable `x`, and a spread
`..base` reads `base`: both are free uses, which import flattening
needs to carry the helper or constant they name. *)
List.concat (List.map (fun ((name : ident), e_opt) ->
match e_opt with
| Some e -> find_free_vars bound_vars e
| None -> []
| None ->
if List.mem name.name bound_vars then [] else [name.name]
) r.er_fields)
@ (match r.er_spread with
| Some e -> find_free_vars bound_vars e
| None -> [])
| ExprField (e, _) -> find_free_vars bound_vars e
| ExprTupleIndex (e, _) -> find_free_vars bound_vars e
| ExprIndex (e1, e2) ->
Expand Down
Loading
Loading