diff --git a/.machine_readable/descriptiles/STATE.deed b/.machine_readable/descriptiles/STATE.deed index 4455a23d..50a6320c 100644 --- a/.machine_readable/descriptiles/STATE.deed +++ b/.machine_readable/descriptiles/STATE.deed @@ -8,6 +8,7 @@ last-updated = "2026-06-21" status = "active" authoritative-status-doc = "docs/CAPABILITY-MATRIX.adoc" drift-flag = "STALE as of 2026-05-23 PM: this file's [components]/[features]/[project-context] still predate landed PRs since 2026-05-19. It MIRRORS, it does not LEAD. Authoritative sources by topic — readiness: docs/CAPABILITY-MATRIX.adoc; spine + AS↔typed-wasm contract: docs/ECOSYSTEM.adoc; coordination ledger / critical path: docs/TECH-DEBT.adoc; test taxonomy + PR-level gates: docs/standards/TESTING.adoc (added 2026-05-23); panic-attack SOP: docs/standards/PANIC-ATTACK.adoc (added 2026-05-23). Gate baseline: CAPABILITY-MATRIX records 260/260 at 2026-05-19 reconstruction; subsequent borrow-checker work has lifted it (#240 → 263, return-escape → 271/274, &mut surface → 278/281). The exact live number for any given commit comes from `dune runtest --force` — do not hard-code it here. (DOC-05, issue #176.)" +session-note-2026-12-01 = "INTERPRETER PARITY #833. lib/interp.ml now runs what the checker accepts: every top-level fn shares one environment cell (self-, forward and mutual recursion, including private fns of imported modules); let mut / const mut bindings are cells (Value.Cell) and assignment resolves its left-hand side to a place (compound operators, array element, record field, tuple component); return unwinds to the enclosing call (Value.EarlyReturn; it used to fall through, a silently wrong value); Some / None / Ok / Err are bound as the preamble constructors the flattener assumes (string::char_at); println writes a String unquoted. affinescript eval type-checks through Typecheck.check_program, as check and compile do. NOT done: eval still skips the borrow checker (COMPLETION-PLAN H6). Anchor: test/test_interp_eval.ml (18 cases, interpreter vs expected vs Bun-ESM). This file MIRRORS; authoritative: docs/SOUNDNESS.adoc." session-note-2026-06-21 = "SESSION: release-binaries pipeline repair + downstream gap triage + onboarding polish. (1) RELEASE — PR #641 (merged b8ba479) fixed .github/workflows/release.yml, which had been shipping v0.2.0 SOURCE-ONLY (regression from v0.1.1). Two bugs, both confirmed from the failed v0.2.0 run 26694097435: (a) immutable releases now forbid adding assets to a PUBLISHED release (linux leg died HTTP 422), and (b) the v0.2.0-added version-bake step used GNU `sed -i` which BSD/macOS sed rejects (extra characters at the end of l command), so both mac legs failed before building. Fix: create the release as a DRAFT, upload all binaries + SHA256SUMS into it, then publish (--draft=false --latest) last so it seals atomically; portable `sed -i.bak`. Compiler verified to build in release mode locally; --version/check/eval/compile work. v0.2.0 is immutable+assetless and cannot be amended, so binaries ship via a fresh v0.2.1 tag — OWNER action: a Claude-Code-web session cannot push v* tags (HTTP 403). Tracked in #646 (incl. downstream quandledb re-pin). (2) WASM cross-module constructor-link task was ALREADY LANDED before this session: #602 / ac98c81 (Closes #138) — register_imported_types in Codegen.gen_imports registers imported public enum constructors into variant_tags via the local gen_decl path; core-Wasm regression test in test_stdlib_aot.ml; verified locally 534/534. Downstream stapeln re-pins to ac98c81 and drops its carried git apply. (3) svalinn-gateway compiler gaps confirmed + filed: #642 (compile has no module search-path / project mode for nested src/**), #643 (float_to_string raises UnboundVariable at core-Wasm compile; wired only in resolve/typecheck/interp/Deno), #644 (empty match-arm body Pat => {} is a parse error). `pub extern fn` was checked and is SUPPORTED — not a gap. (4) ONBOARDING POLISH (this change): added tutorial lesson-01 (the docs/tutorial track previously started at lesson-02), an audience router (developers / maintainers / end-users) in README + NAVIGATION, and this note. Docs consolidation (two overlapping lesson tracks, wiki sync) tracked in #647. Note: guides/lessons/01-hello bare-println example is stale (parse error on current compiler) — folded into #647. This file MIRRORS; authoritative sources unchanged (see drift-flag)." session-note-2026-05-26-publish-104 = "ISSUE #104 CLOSED — FIRST NPM PUBLISH LANDED. @hyperpolymath/affine-vscode@0.1.0 is now on registry.npmjs.org. Owner-action sequence completed today: (1) npm org `hyperpolymath` created on free public-package tier; (2) Granular Access Token generated for scope @hyperpolymath/* with Read+Write, uploaded to repo secret NPM_TOKEN; (3) signed annotated tag affine-vscode-v0.1.0 pushed at origin/main (RSA key 9639451754496E51D6B537CAD119017EBF695AB1); (4) .github/workflows/affine-vscode-publish.yml ran green — `npm publish --access public` succeeded; (5) `npm view @hyperpolymath/affine-vscode` resolves. Downstream consumers (my-lang#66, standards#160) which un-vendored their adapters on 2026-05-21 now have a working `npm install` path; vscode-smoke workflow (skipped per #381 while package was unpublished) will start exercising the live package on its next PR run. Lineage for future @hyperpolymath/* publishes: org+token are reusable; mirror `affine-vscode-publish.yml`'s shape (tag trigger, version-match guard, .npmrc write from secret, npm publish --access public). NPM_TOKEN rotation advised post-publish (token value transited a session transcript during wire-up); see .machine_readable/descriptiles/PLAYBOOK.a2ml [npm-publish] for the runbook." session-note-2026-05-30 = "DOC-16 + DOC-17 — DOC-TRUTHING MONITOR FULLY MECHANICAL (issue #176). Two complementary in-repo guards now enforce the doc-truthing rules that were previously external-bot-only. DOC-16 (PR #476, tools/check-doc-truthing.sh): banner-PRESENCE invariant — fails if any over-claiming doc loses its CAPABILITY-MATRIX banner, if the matrix stops self-declaring primacy / loses its 'What AffineScript is NOT' section, or if STATE.a2ml drops its mirror keys; deliberately does NOT phrase-scan (a naive grep false-positives on the negating banners + future-roadmap text). DOC-17 (PR #475, tools/check-doc-overclaims.sh + tools/doc-overclaims.allow): the phrase-detection complement — a frozen-baseline RATCHET over README + docs/** (excluding CAPABILITY-MATRIX + TECH-DEBT, which quote the rule) that fails any NEW backend-breadth / 'production-ready' / stdlib-% occurrence beyond the 13-line baseline (all current entries legit: future-tense roadmap milestones + dated history snapshots + corrective banners); re-baseline via `--update` / `just doc-overclaims-bless`, diff = audit trail. Both wired into `just check` (guard recipe) + ci.yml build job, both toolchain-free bash (run without OCaml). #475 was originally a superset of #476 (built in parallel, same session); on discovering #476 had merged first, #475 was reworked to drop the duplicated banner check and keep only the unique ratchet, renamed check-doc-truth.sh→check-doc-overclaims.sh to avoid the name clash (DOC-DEDUP-clean). FOLLOW-UP (same day, post-#475-merge): the two near-identically-named guards were consolidated so neither lingers — the ratchet (incl. `--update` mode + tools/doc-overclaims.allow baseline) was folded INTO tools/check-doc-truthing.sh using #476's fail-accumulator/note() structure, and tools/check-doc-overclaims.sh was deleted. A SINGLE toolchain-free guard now enforces both presence invariants (DOC-04/05) and the over-claim ratchet (DOC-08/09) in one run; one CI step; the `guard` recipe runs it; re-baseline via `just doc-truth-bless`. DOC-17 folded into DOC-16 in the ledger. Gate-number policy unchanged (DOC-05): live `dune runtest --force` count never hard-coded. No compiler code touched. Refs #176 / #175." diff --git a/bin/main.ml b/bin/main.ml index 15ee4fca..90546db6 100644 --- a/bin/main.ml +++ b/bin/main.ml @@ -306,17 +306,16 @@ let eval_file face json path = | Error (e, span) -> add (Affinescript.Json_output.of_resolve_error e span) | Ok (resolve_ctx, type_ctx) -> - let type_ctx = { type_ctx with symbols = resolve_ctx.symbols } in - (* Register builtins (print, int_to_string, tea_run, etc.) before type-checking *) - Affinescript.Typecheck.register_builtins type_ctx; - (match List.fold_left (fun acc decl -> - match acc with - | Error _ as e -> e - | Ok () -> Affinescript.Typecheck.check_decl type_ctx decl - ) (Ok ()) prog.prog_decls with + (* The same type-checking entry as `check` and `compile` (#833). `eval` + used to fold [Typecheck.check_decl] itself, without the pass that + pre-registers every top-level signature, so it rejected forward + and mutual references that `compile` accepts. *) + (match Affinescript.Typecheck.check_program + ~import_types:type_ctx.Affinescript.Typecheck.name_types + resolve_ctx.symbols prog with | Error e -> add (Affinescript.Json_output.of_type_error e) - | Ok () -> + | Ok _type_ctx -> (* Stage 1: QTT quantity enforcement *) (match Affinescript.Quantity.check_program_quantities prog with | Error (err, span) -> @@ -354,19 +353,18 @@ let eval_file face json path = (Affinescript.Face.format_resolve_error face e); `Error (false, "Resolution error") | Ok (resolve_ctx, type_ctx) -> - let type_ctx = { type_ctx with symbols = resolve_ctx.symbols } in - (* Register builtins (print, int_to_string, tea_run, etc.) before type-checking *) - Affinescript.Typecheck.register_builtins type_ctx; - (match List.fold_left (fun acc decl -> - match acc with - | Error _ as e -> e - | Ok () -> Affinescript.Typecheck.check_decl type_ctx decl - ) (Ok ()) prog.prog_decls with + (* The same type-checking entry as `check` and `compile` (#833). `eval` + used to fold [Typecheck.check_decl] itself, without the pass that + pre-registers every top-level signature, so it rejected forward + and mutual references that `compile` accepts. *) + (match Affinescript.Typecheck.check_program + ~import_types:type_ctx.Affinescript.Typecheck.name_types + resolve_ctx.symbols prog with | Error e -> Format.eprintf "@[%s@]@." (Affinescript.Face.format_type_error face e); `Error (false, "Type error") - | Ok () -> + | Ok _type_ctx -> (* Stage 1: QTT quantity enforcement *) (match Affinescript.Quantity.check_program_quantities prog with | Error (err, _span) -> diff --git a/docs/COMPLETION-PLAN.adoc b/docs/COMPLETION-PLAN.adoc index 1df1c00b..d265d341 100644 --- a/docs/COMPLETION-PLAN.adoc +++ b/docs/COMPLETION-PLAN.adoc @@ -77,7 +77,7 @@ Results were consistent, but they do not prove CI is green. | No totality gate. | Interpreter (`lib/interp.ml`) -| Early `return` gives a wrong value (`g(5)=2`, expected 1) because of `interp.ml:262`. Local `let mut` reassignment fails at runtime (`value.ml:157`). `2147483647+1` evaluates to `2147483648` in the interpreter but `-2147483648` in compiled WASM. +| Early `return` gives a wrong value (`g(5)=2`, expected 1) because of `interp.ml:262`. Local `let mut` reassignment fails at runtime (`value.ml:157`). (Both fixed 2026-12-01, #833; see H1 and H7 below.) `2147483647+1` evaluates to `2147483648` in the interpreter but `-2147483648` in compiled WASM. | The interpreter is the declared reference semantics, and the Coq models claim to mirror it. | Delimited continuations. The interpreter is the only handler executor, yet it cannot run `return` or `let mut` correctly, so handler programs have no correct execution path today. @@ -201,13 +201,13 @@ 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`). +. H1. Interpreter early `return` has no non-local exit (`lib/interp.ml:262`). *Fixed 2026-12-01 (#833):* `return` unwinds to the enclosing call (`Value.EarlyReturn`). Anchor: `test/test_interp_eval.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. -. H6. `eval` and the REPL skip borrow checking and trait coherence. Only the `eval` borrow-checking gap is RUN. The REPL gap is READ only, because the REPL is not built. -. H7. Interpreter `let mut` reassignment fails at runtime. +. H6. `eval` and the REPL skip borrow checking and trait coherence. Only the `eval` borrow-checking gap is RUN. The REPL gap is READ only, because the REPL is not built. *Narrowed 2026-12-01 (#833):* `eval` now type-checks through `Typecheck.check_program`, as `check` and `compile` do, so it runs trait coherence (RUN: a duplicate impl is rejected). `eval` still does not run the borrow checker. +. H7. Interpreter `let mut` reassignment fails at runtime. *Fixed 2026-12-01 (#833):* a `let mut` / `const mut` binding is a cell (`Value.Cell`), and assignment resolves its left-hand side to a place. The same change fixes self-, forward and mutual recursion in the interpreter and the missing `Some` / `None` / `Ok` / `Err`. Anchor: `test/test_interp_eval.ml`. . H8. `total fn` is accepted without any check. . H9. Integer width diverges: the interpreter uses 63-bit ints, WASM wraps at i32. . H10. `compile` emits a `.wasm` despite typed-wasm L7/L10 violations. @@ -222,7 +222,7 @@ All were observed by RUN unless marked otherwise. The maps confirm that H1–H4 . 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. . 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___` 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. *Round 4 (2026-11-19, #801):* the per-case renaming above still let two modules' public declarations of one name meet when they arrived through other modules' imports (`X` uses `A.f`, `Y` uses `B.f`; the flattened program kept one `f` and Bun ran it for both). Every function and constant of an imported module, public or private, now carries a module-qualified name `__mod___` (length-prefixed as before; `__priv_` is gone), the root keeps its own and its imported names, externs keep their host names, and the flattener and the JS emitters refuse two different top-level bindings of one name. 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`. +. 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 by that change (fixed later, #833). Anchor: `test/test_module_root_flatten.ml`. == 2. Target architecture diff --git a/js/js_api.ml b/js/js_api.ml index b194ba69..b9fe077d 100644 --- a/js/js_api.ml +++ b/js/js_api.ml @@ -72,7 +72,7 @@ let eval_program_string (code : string) : eval_result Js.t = let env_str = List.map (fun (name, value) -> Printf.sprintf "%s = %s" name (Affinescript.Value.show_value value) - ) env + ) (Affinescript.Value.env_values env) |> String.concat "\n" in success_result env_str "Environment" diff --git a/lib/interp.ml b/lib/interp.ml index 96169a83..9198fb2e 100644 --- a/lib/interp.ml +++ b/lib/interp.ml @@ -90,6 +90,13 @@ let rec match_pattern (pat : pattern) (v : value) : (string * value) list result let* bindings = match_pattern pat v in Ok ((id.name, v) :: bindings) +(** Storage named by the left-hand side of an assignment; see + [resolve_place]. *) +type place = { + pl_read : unit -> value result; + pl_write : value -> unit result; +} + (** Evaluate an expression *) let rec eval (env : env) (expr : expr) : value result = match expr with @@ -100,7 +107,7 @@ let rec eval (env : env) (expr : expr) : value result = | ExprLet lb -> let* rhs_val = eval env lb.el_value in let* bindings = match_pattern lb.el_pat rhs_val in - let env' = extend_env_list bindings env in + let env' = bind_let ~mut:lb.el_mut bindings env in begin match lb.el_body with | Some body -> eval env' body | None -> Ok VUnit @@ -124,7 +131,7 @@ let rec eval (env : env) (expr : expr) : value result = Ok (VClosure { cl_params = lam.elam_params; cl_body = lam.elam_body; - cl_env = env; + cl_env = ref env; }) | ExprApp (func, args) -> @@ -260,10 +267,15 @@ let rec eval (env : env) (expr : expr) : value result = eval_block env blk | ExprReturn e_opt -> - begin match e_opt with + (* `return` leaves the enclosing function, not just the enclosing + expression: unwind to [apply_function], which turns [EarlyReturn] back + into the call's result. Before #833 this arm evaluated to its operand + and execution carried on, so `if c { return 1; } 2` yielded 2. *) + let* v = match e_opt with | Some e -> eval env e | None -> Ok VUnit - end + in + Error (EarlyReturn v) | ExprVariant (type_id, variant_id) -> (* Type::Variant syntax - just the variant constructor without payload *) @@ -507,16 +519,29 @@ and eval_stmt (env : env) (stmt : stmt) : env result = | StmtLet sl -> let* rhs_val = eval env sl.sl_value in let* bindings = match_pattern sl.sl_pat rhs_val in - Ok (extend_env_list bindings env) + Ok (bind_let ~mut:sl.sl_mut bindings env) | StmtExpr e -> let* _ = eval env e in Ok env - | StmtAssign (lhs, _op, rhs) -> - let* lhs_val = eval env lhs in - let* rhs_val = eval env rhs in - let* () = assign lhs_val rhs_val in + | StmtAssign (lhs, op, rhs) -> + (* Source order, as the JS backends do: resolve the place (evaluating the + subexpressions of the left-hand side), read it for a compound + operator, evaluate the right-hand side, then write. *) + let* place = resolve_place env lhs in + let* new_val = match op with + | AssignEq -> eval env rhs + | AssignAdd | AssignSub | AssignMul | AssignDiv -> + let* old_val = place.pl_read () in + let* rhs_val = eval env rhs in + let binop = match op with + | AssignAdd -> OpAdd | AssignSub -> OpSub + | AssignMul -> OpMul | AssignDiv | AssignEq -> OpDiv + in + eval_binop binop old_val rhs_val + in + let* () = place.pl_write new_val in Ok env | StmtWhile (cond, body) -> @@ -526,6 +551,97 @@ and eval_stmt (env : env) (stmt : stmt) : env result = let* iter_val = eval env iter in eval_for env pat iter_val body +(** Bind the names of a `let` pattern: in fresh cells for `let mut`, so that + assignment can replace them, and immutably otherwise. *) +and bind_let ~(mut : bool) (bindings : (string * value) list) (env : env) : env = + if mut then extend_env_cells bindings env + else extend_env_list bindings env + +(** Resolve the left-hand side of an assignment to the storage it names. + + - a name bound by `let mut` / `const mut` is its cell; + - `a[i]` is the element of the (shared, mutable) array [a]; + - `r.f` and `t.N` replace one component of the record or tuple held in + the place [r] / [t] (values are immutable, so this writes a new + aggregate back to that place); + - `*p`, and any other expression whose value is a [VMut] reference, + write through the reference. + + Anything else is not assignable and fails loudly. Before #833 the + left-hand side was evaluated to a plain value and then rejected unless + it happened to be a [VMut], so `let mut k = 0; k = k + 1;` could not + run. *) +and resolve_place (env : env) (lhs : expr) : place result = + let through_reference v = + match v with + | VMut r -> Ok { pl_read = (fun () -> Ok !r); + pl_write = (fun v -> r := v; Ok ()) } + | VRef _ -> Error (TypeMismatch "Cannot assign to immutable reference") + | _ -> Error (TypeMismatch "Expected mutable reference") + in + match lhs with + | ExprSpan (e, _) -> resolve_place env e + | ExprVar id -> + let* b = lookup_binding id.name env in + begin match b with + | Cell r -> Ok { pl_read = (fun () -> Ok !r); + pl_write = (fun v -> r := v; Ok ()) } + | Bound (VMut _ | VRef _ as v) -> through_reference v + | Bound _ -> + Error (TypeMismatch + ("Cannot assign to `" ^ id.name ^ "`: it is not declared `mut`")) + end + | ExprIndex (arr, idx_expr) -> + let* arr_val = eval env arr in + let* idx_val = eval env idx_expr in + begin match (arr_val, idx_val) with + | (VArray a, VInt i) -> + Ok { pl_read = (fun () -> get_array_elem i a); + pl_write = (fun v -> set_array_elem i a v) } + | (VArray _, _) -> Error (TypeMismatch "Array index must be integer") + | _ -> Error (TypeMismatch "Expected array") + end + | ExprField (base, field) -> + let* base_place = resolve_place env base in + let fields () = + let* base_val = base_place.pl_read () in + match base_val with + | VRecord fields -> Ok fields + | _ -> Error (TypeMismatch "Expected record") + in + Ok { pl_read = (fun () -> + let* fs = fields () in + get_field field.name fs); + pl_write = (fun v -> + let* fs = fields () in + if List.mem_assoc field.name fs then + base_place.pl_write (VRecord (List.map (fun (n, old) -> + if n = field.name then (n, v) else (n, old)) fs)) + else Error (FieldNotFound field.name)) } + | ExprTupleIndex (base, idx) -> + let* base_place = resolve_place env base in + let elems () = + let* base_val = base_place.pl_read () in + match base_val with + | VTuple elems -> Ok elems + | _ -> Error (TypeMismatch "Expected tuple") + in + Ok { pl_read = (fun () -> + let* es = elems () in + get_tuple_elem idx es); + pl_write = (fun v -> + let* es = elems () in + if idx >= 0 && idx < List.length es then + base_place.pl_write + (VTuple (List.mapi (fun i old -> if i = idx then v else old) es)) + else Error (IndexOutOfBounds (idx, List.length es))) } + | ExprUnary (OpDeref, e) -> + let* v = eval env e in + through_reference v + | _ -> + let* v = eval env lhs in + through_reference v + (** Evaluate while loop *) and eval_while (env : env) (cond : expr) (body : block) : env result = let* cond_val = eval env cond in @@ -575,8 +691,13 @@ and apply_function (func : value) (args : value list) : value result = let bindings = List.map2 (fun param arg -> (param.p_name.name, arg) ) cl.cl_params args in - let env' = extend_env_list bindings cl.cl_env in - eval env' cl.cl_body + (* [cl_env] is read at the call, so a top-level function sees every + declaration of its program, itself included (#833). *) + let env' = extend_env_list bindings !(cl.cl_env) in + begin match eval env' cl.cl_body with + | Error (EarlyReturn v) -> Ok v + | result -> result + end | VBuiltin (_, f) -> f args @@ -605,21 +726,48 @@ let utf8_scalars ~who (s : string) : int list result = let create_initial_env () : env = let builtins = [ + (* -- Preamble constructors (#833) --------------------------------------- + `Some` / `None` / `Ok` / `Err` are the prelude's `Option` and `Result` + constructors. [Module_loader.flatten_imports] does not carry those two + enums into a flattened program, because every non-Wasm backend's + runtime preamble already defines the four constructors + ([Module_loader.preamble_ctors]). The interpreter is such a backend and + had no preamble, so any program that used an imported `Some` — or + called a stdlib function that does, e.g. `string::char_at` — stopped + with `Unbound variable: Some`. The shapes are the ones the flattener + assumes and the ones the builtins below already return (`parse_int`, + `read_file`, …). A program still has to import the names to use them + (the resolver decides that); an enum the program declares itself with + one of these names is bound later and shadows these. *) + ("Some", VBuiltin ("Some", fun args -> + match args with + | [v] -> Ok (VVariant ("Some", Some v)) + | _ -> Error (TypeMismatch "Some expects 1 argument"))); + ("None", VVariant ("None", None)); + ("Ok", VBuiltin ("Ok", fun args -> + match args with + | [v] -> Ok (VVariant ("Ok", Some v)) + | _ -> Error (TypeMismatch "Ok expects 1 argument"))); + ("Err", VBuiltin ("Err", fun args -> + match args with + | [v] -> Ok (VVariant ("Err", Some v)) + | _ -> Error (TypeMismatch "Err expects 1 argument"))); + (* -- Console I/O -------------------------------------------------------- *) ("print", VBuiltin ("print", fun args -> - List.iter (fun v -> print_string (Value.show_value v)) args; + List.iter (fun v -> print_string (display_value v)) args; Ok VUnit )); ("println", VBuiltin ("println", fun args -> - List.iter (fun v -> print_endline (Value.show_value v)) args; + List.iter (fun v -> print_endline (display_value v)) args; Ok VUnit )); ("eprint", VBuiltin ("eprint", fun args -> - List.iter (fun v -> prerr_string (Value.show_value v)) args; + List.iter (fun v -> prerr_string (display_value v)) args; Ok VUnit )); ("eprintln", VBuiltin ("eprintln", fun args -> - List.iter (fun v -> prerr_endline (Value.show_value v)) args; + List.iter (fun v -> prerr_endline (display_value v)) args; Ok VUnit )); @@ -1211,10 +1359,16 @@ let create_initial_env () : env = "tea_run expects a record: {init, update, view, subscriptions}") )); ] in - builtins + extend_env_list builtins empty_env -(** Evaluate a top-level declaration *) -let eval_decl (env : env) (decl : top_level) : env result = +(** Evaluate a top-level declaration. + + [globals] is the environment cell that the functions of one program + share (see [eval_program]). Without it — one declaration at a time, as + in the REPL — a function gets a cell of its own that holds the + environment including itself, so it can at least call itself. *) +let eval_decl ?(globals : env ref option) (env : env) (decl : top_level) + : env result = match decl with | TopFn fd -> (match fd.fd_body with @@ -1227,19 +1381,29 @@ let eval_decl (env : env) (decl : top_level) : env result = Refs #328 root-cause for the interp pattern-match-failure. *) Ok env | FnBlock _ | FnExpr _ -> + let cell = match globals with + | Some g -> g + | None -> ref env + in let closure = VClosure { cl_params = fd.fd_params; cl_body = (match fd.fd_body with | FnBlock blk -> ExprBlock blk | FnExpr e -> e | FnExtern -> assert false (* unreachable: outer match guards *)); - cl_env = env; + cl_env = cell; } in - Ok (extend_env fd.fd_name.name closure env)) + let env' = extend_env fd.fd_name.name closure env in + (* Tie the knot: the closure's environment contains the closure. + With [globals], [eval_program] advances the shared cell. *) + if Option.is_none globals then cell := env'; + Ok env') | TopConst tc -> let* v = eval env tc.tc_value in - Ok (extend_env tc.tc_name.name v env) + (* `const mut` is assignable (#548): give it a cell, like `let mut`. *) + if tc.tc_mut then Ok (extend_env_cells [(tc.tc_name.name, v)] env) + else Ok (extend_env tc.tc_name.name v env) | TopType td -> (* Register enum constructors so they can be used as values / constructor functions. @@ -1297,10 +1461,35 @@ let eval_decl (env : env) (decl : top_level) : env result = ) env ed.ed_ops in Ok env' -(** Evaluate a program *) +(** Evaluate a program. + + Top-level declarations are mutually visible, whatever their order: the + resolver and [Typecheck.check_program] both pre-register every top-level + name (#135 slice 11), and the compiled backends hoist. The interpreter + matches them by giving every top-level function one shared environment + cell, which ends up holding the whole program (#833). Before, a function + captured the environment as it stood *before* its own declaration, so it + could not call itself, a later function, or — once imports are flattened + in front of it — a constructor of an imported enum. + + Two passes. The first binds everything that needs no evaluation + (functions, enum constructors, effect operations). The second evaluates + `const` initialisers in source order, each seeing all functions and the + constants before it; an initialiser that reaches a later constant fails + loudly with [UnboundVariable]. *) let eval_program (prog : program) : env result = - let initial_env = create_initial_env () in - List.fold_left (fun acc decl -> - let* env = acc in - eval_decl env decl - ) (Ok initial_env) prog.prog_decls + let globals = ref (create_initial_env ()) in + let pass keep = + List.fold_left (fun acc decl -> + let* () = acc in + if keep decl then begin + let* env = eval_decl ~globals !globals decl in + globals := env; + Ok () + end else Ok () + ) (Ok ()) prog.prog_decls + in + let is_const = function TopConst _ -> true | _ -> false in + let* () = pass (fun d -> not (is_const d)) in + let* () = pass is_const in + Ok !globals diff --git a/lib/json_output.ml b/lib/json_output.ml index 83112de5..9dde6b4f 100644 --- a/lib/json_output.ml +++ b/lib/json_output.ml @@ -303,6 +303,8 @@ let of_eval_error (e : Value.eval_error) : diagnostic = "E0799", Printf.sprintf "Runtime error: %s" msg | Value.PerformEffect (name, _args) -> "E0710", Printf.sprintf "Unhandled effect: %s" name + | Value.EarlyReturn _ -> + "E0711", "`return` outside a function body" in { severity = Error; diff --git a/lib/module_loader.ml b/lib/module_loader.ml index 217c8e43..6e5150a1 100644 --- a/lib/module_loader.ml +++ b/lib/module_loader.ml @@ -706,9 +706,9 @@ let check_unique (entries : entry list) : unit = is not loaded is skipped, the resolver having reported it. The result is: the imported declarations the root reaches, dependencies - first and each module's in its own order (declarations must precede - their uses: the interpreter binds each function in an environment that - holds only what came before it); then a copy, under its bound name, of + first and each module's in its own order (no consumer depends on that + order any more: since #833 the interpreter binds every top-level function + in one shared environment, as the compiled backends hoist); then a copy, under its bound name, of each function and immutable constant the root imports (not of a function bound as [main]: only the root's own [main] is an entry point, so references to that binding are rewritten to the qualified name); then the root's diff --git a/lib/repl.ml b/lib/repl.ml index 7b6210e3..1e8b9283 100644 --- a/lib/repl.ml +++ b/lib/repl.ml @@ -154,7 +154,7 @@ let process_line (state : state) (input : string) : (state * string) = let scheme = Typecheck.generalize state.type_ctx rhs_ty in let _ = bind_pattern_to_ctx state.type_ctx lb.el_pat scheme in (* Update environment *) - let state' = { state with env = extend_env_list bindings state.env } in + let state' = { state with env = bind_let ~mut:lb.el_mut bindings state.env } in (state', Printf.sprintf "() : Unit") | Error e -> let msg = Printf.sprintf "Pattern match error: %s" diff --git a/lib/value.ml b/lib/value.ml index 2bf654e3..d258587d 100644 --- a/lib/value.ml +++ b/lib/value.ml @@ -27,15 +27,34 @@ type value = | VMut of value ref | VOwn of value ref * bool ref (** Value + moved flag *) -(** Closure: captures environment *) +(** Closure: captures environment. + + [cl_env] is a cell so that a declaration can refer to itself and to + declarations that follow it (#833). A lambda holds a cell of its own that + is never written again. Every top-level function of a program shares one + cell, which [Interp.eval_program] advances as declarations are evaluated; + the function reads it when it is *called*, not when it is declared. *) and closure = { cl_params : param list; cl_body : expr; - cl_env : env; + cl_env : env ref; } -(** Environment: maps names to values *) -and env = (string * value) list +(** How a name is bound. + + [Bound] is an immutable binding. [Cell] is the storage of a `let mut` + local or a `const mut` module binding: reading the name yields the + cell's current content, assigning to the name replaces it, and a closure + that captures the name shares the cell (as a JS `let` does). A cell is + not a value: [lookup_env] always reads through it, so it cannot escape + into a tuple, an argument or a result. The first-class mutable + references are [VRef] / [VMut]. *) +and binding = + | Bound of value + | Cell of value ref + +(** Environment: maps names to bindings *) +and env = (string * binding) list (** Evaluation errors *) and eval_error = @@ -48,6 +67,10 @@ and eval_error = | AffineViolation of string (** Double use of affine value *) | RuntimeError of string | PerformEffect of string * value list (** Effect operation name and arguments *) + | EarlyReturn of value + (** `return e` unwinding to the enclosing function call. Not a failure: + [Interp.apply_function] turns it back into the call's result. It + surfaces as an error only when no function call encloses it. *) and 'a result = ('a, eval_error) Result.t @@ -64,27 +87,46 @@ let show_eval_error (e : eval_error) : string = | AffineViolation msg -> "Affine violation: " ^ msg | RuntimeError msg -> "Runtime error: " ^ msg | PerformEffect (name, _) -> "Unhandled effect: " ^ name + | EarlyReturn _ -> "`return` outside a function body" let pp_eval_error fmt e = Format.pp_print_string fmt (show_eval_error e) (** Empty environment *) let empty_env : env = [] -(** Extend environment with a binding *) +(** Extend environment with an immutable binding *) let extend_env (name : string) (value : value) (env : env) : env = - (name, value) :: env + (name, Bound value) :: env -(** Extend environment with multiple bindings *) +(** Extend environment with multiple immutable bindings *) let extend_env_list (bindings : (string * value) list) (env : env) : env = - bindings @ env + List.map (fun (n, v) -> (n, Bound v)) bindings @ env + +(** Extend environment with multiple mutable bindings, each in a fresh cell + (`let mut`, `const mut`). *) +let extend_env_cells (bindings : (string * value) list) (env : env) : env = + List.map (fun (n, v) -> (n, Cell (ref v))) bindings @ env -(** Look up a variable in the environment *) -let rec lookup_env (name : string) (env : env) : value result = +(** Look up how a name is bound. *) +let rec lookup_binding (name : string) (env : env) : binding result = match env with | [] -> Error (UnboundVariable name) - | (n, v) :: rest -> - if n = name then Ok v - else lookup_env name rest + | (n, b) :: rest -> + if n = name then Ok b + else lookup_binding name rest + +(** Look up a variable's current value, reading through a mutable cell. *) +let lookup_env (name : string) (env : env) : value result = + match lookup_binding name env with + | Ok (Bound v) -> Ok v + | Ok (Cell r) -> Ok !r + | Error e -> Error e + +(** The names of an environment with their current values, innermost + first. *) +let env_values (env : env) : (string * value) list = + List.map (fun (n, b) -> + (n, match b with Bound v -> v | Cell r -> !r)) env (** Check if a value is truthy *) let is_truthy (v : value) : bool = @@ -121,6 +163,14 @@ let rec show_value (v : value) : string = if !moved then "" else "own(" ^ show_value !r ^ ")" +(** What `print` / `println` write for a value: a String is written as its + characters, as every compiled backend does. [show_value] is the debugging + form (a quoted, escaped literal) and is still what `show` returns. *) +let display_value (v : value) : string = + match v with + | VString s -> s + | _ -> show_value v + (** Pretty printer for values *) let pp_value fmt v = Format.pp_print_string fmt (show_value v) diff --git a/test/test_interp_eval.ml b/test/test_interp_eval.ml new file mode 100644 index 00000000..b4594a98 --- /dev/null +++ b/test/test_interp_eval.ml @@ -0,0 +1,416 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(** #833 — the tree-walking interpreter must run every program the type + checker accepts, and agree with the compiled backends on the result. + + Each case below was refused or miscomputed by [Interp] before the fix: + + - a function that calls itself ([Unbound variable: g]); + - a function that calls one declared after it, and mutual recursion; + - a private recursive function inside an imported module; + - `let mut` / `const mut` assignment, compound assignment, and assignment + to an array element, a record field and a tuple component + ([Expected mutable reference]); + - an early `return`, which evaluated its operand and then carried on + (a silently wrong value: `if c { return 1; } 2` yielded 2); + - an imported `Some` / `None` / `Ok` / `Err`, and so `string::char_at` + ([Unbound variable: Some]); + - `println` of a String, which printed a quoted, escaped literal. + + Every program goes through the whole frontend that `check` and `compile` + use (resolve, [Typecheck.check_program], borrow, quantity), so a case can + only pass on a program the language accepts. Its interpreter output is + compared with the expected lines and, when [bun] is installed, with the + output of the same program compiled by the Bun-ESM backend. *) + +open Affinescript + +let fresh_dir tag = + let dir = Filename.concat (Filename.get_temp_dir_name ()) + (Printf.sprintf "as_interp_%s_%d" tag (Unix.getpid ())) in + (try Unix.mkdir dir 0o755 with Unix.Unix_error (Unix.EEXIST, _, _) -> ()); + dir + +let write_file dir rel body = + let oc = open_out (Filename.concat dir rel) in + output_string oc body; + close_out oc + +(** Parse and check [src] as `check` / `compile` do. Returns the program, + its symbols and the loader that holds its imports. Modules in [files] + are written next to it. *) +let frontend ?(files = []) what src = + let dir = fresh_dir "prog" in + List.iter (fun (rel, body) -> write_file dir rel body) files; + let prog = + try Parse_driver.parse_string ~file:("<" ^ what ^ ">") src + with Parse_driver.Parse_error (m, sp) -> + Alcotest.failf "%s: parse error at %s: %s" what (Span.show sp) m + in + let loader = Module_loader.create + { (Module_loader.default_config ()) with current_dir = dir } in + match Resolve.resolve_program_with_loader prog loader with + | Error (e, _) -> + Alcotest.failf "%s: resolve: %s" what (Resolve.show_resolve_error e) + | Ok (rctx, tctx) -> + (match Typecheck.check_program ~import_types:tctx.Typecheck.name_types + rctx.symbols prog with + | Error e -> + Alcotest.failf "%s: typecheck: %s" what (Typecheck.format_type_error e) + | Ok _ -> ()); + (match Borrow.check_program rctx.symbols prog with + | Error e -> + Alcotest.failf "%s: borrow: %s" what (Borrow.show_borrow_error e) + | Ok () -> ()); + (match Quantity.check_program_quantities prog with + | Error _ -> Alcotest.failf "%s: quantity error" what + | Ok () -> ()); + (prog, rctx.symbols, loader) + +let lines_of s = + match List.rev (String.split_on_char '\n' s) with + | "" :: rest -> List.rev rest + | all -> List.rev all + +(** Run [f] with the process's standard output redirected to a file, and + return what was written. The interpreter's `println` writes to the real + stdout, so this is the only way to see it. *) +let capture_stdout f = + let file = Filename.temp_file "as_interp_out" ".txt" in + flush stdout; + let saved = Unix.dup Unix.stdout in + let fd = Unix.openfile file [ Unix.O_WRONLY; Unix.O_TRUNC ] 0o600 in + Unix.dup2 fd Unix.stdout; + Unix.close fd; + let restore () = + flush stdout; + Unix.dup2 saved Unix.stdout; + Unix.close saved + in + let result = try f () with e -> restore (); raise e in + restore (); + let out = In_channel.with_open_bin file In_channel.input_all in + (try Sys.remove file with Sys_error _ -> ()); + (result, out) + +(** Run the program's `main` on the interpreter; return its stdout lines. *) +let interp_lines what (prog, _symbols, loader) = + let flat = Module_loader.flatten_imports loader prog in + let result, out = capture_stdout (fun () -> + match Interp.eval_program flat with + | Error e -> Error ("eval: " ^ Value.show_eval_error e) + | Ok env -> + (match Value.lookup_env "main" env with + | Error _ -> Error "no `main`" + | Ok f -> + (match Interp.apply_function f [] with + | Ok _ -> Ok () + | Error e -> Error ("main: " ^ Value.show_eval_error e)))) + in + match result with + | Ok () -> lines_of out + | Error m -> Alcotest.failf "%s: interpreter: %s" what m + +let bun_available () = Sys.command "bun --version > /dev/null 2>&1" = 0 + +(** Compile the program with the Bun-ESM backend and run it; return its + stdout lines. *) +let bun_lines what (prog, symbols, loader) = + let flat = Module_loader.flatten_imports loader prog in + match Codegen_deno.codegen_bun flat symbols with + | Error e -> Alcotest.failf "%s: Bun-ESM codegen: %s" what e + | Ok js -> + let dir = fresh_dir "bun" in + let file = Filename.concat dir "prog.bun.js" in + write_file dir "prog.bun.js" js; + let ic = Unix.open_process_in ("bun " ^ Filename.quote file ^ " 2>&1") in + let out = In_channel.input_all ic in + let st = Unix.close_process_in ic in + if st <> Unix.WEXITED 0 then + Alcotest.failf "%s: bun exited abnormally:\n%s" what out; + lines_of out + +(** The interpreter prints [expected], and so does Bun-ESM. *) +let agrees ?files what expected src () = + let checked = frontend ?files what src in + Alcotest.(check (list string)) (what ^ ": interpreter") expected + (interp_lines what checked); + if bun_available () then + Alcotest.(check (list string)) (what ^ ": Bun-ESM") expected + (bun_lines what checked) + else + Printf.printf "SKIP %s (Bun-ESM comparison): bun not installed\n%!" what + +(* ---- recursion and declaration order ------------------------------------ *) + +let self_recursion = agrees "self-recursion" [ "6"; "3628800"; "610" ] {| +fn g(x: Int) -> Int { if x <= 0 { 0 } else { g(x - 1) + 2 } } +fn fact(n: Int) -> Int { if n <= 1 { 1 } else { n * fact(n - 1) } } +fn fib(n: Int) -> Int { if n < 2 { return n; } return fib(n - 1) + fib(n - 2); } +pub fn main() -> () { + println(int_to_string(g(3))); + println(int_to_string(fact(10))); + println(int_to_string(fib(15))); +} +|} + +let forward_reference = agrees "forward reference" [ "3" ] {| +pub fn main() -> () { println(int_to_string(helper())); } +fn helper() -> Int { 3 } +|} + +let mutual_recursion = agrees "mutual recursion" [ "even"; "odd" ] {| +fn is_even(n: Int) -> Bool { if n == 0 { true } else { is_odd(n - 1) } } +fn is_odd(n: Int) -> Bool { if n == 0 { false } else { is_even(n - 1) } } +fn say(n: Int) -> () { if is_even(n) { println("even"); } else { println("odd"); } } +pub fn main() -> () { say(10); say(7); } +|} + +(* A constant's initialiser may call a function declared after it; a + function may read a constant declared after it. *) +let const_and_fn_order = agrees "const / fn order" [ "44" ] {| +const mut counter: Int = 0; +const K: Int = base() + 1; +fn bump() -> Int { counter = counter + 1; counter } +fn base() -> Int { 40 } +pub fn main() -> () { bump(); bump(); bump(); println(int_to_string(counter + K)); } +|} + +(* The first shape #833 reports for imports: a private, recursive function + (and a mutually recursive pair) inside an imported module. *) +let imported_recursion = + agrees "recursion in an imported module" [ "8"; "-6" ] + ~files:[ ("recmod.affine", {|module recmod; +fn g(x: Int) -> Int { if x <= 0 { 0 } else { g(x - 1) + 2 } } +fn is_even(n: Int) -> Bool { if n == 0 { true } else { is_odd(n - 1) } } +fn is_odd(n: Int) -> Bool { if n == 0 { false } else { is_even(n - 1) } } +pub fn twice(x: Int) -> Int { if is_even(x) { g(x) } else { 0 - g(x) } } +|}) ] + {| +use recmod::{twice}; +pub fn main() -> () { + println(int_to_string(twice(4))); + println(int_to_string(twice(3))); +} +|} + +(* ---- mutable bindings --------------------------------------------------- *) + +let let_mut_while = agrees "let mut + while" [ "3" ] {| +pub fn main() -> () { + let mut k = 0; + while k < 3 { k = k + 1; } + println(int_to_string(k)); +} +|} + +let let_mut_for = agrees "let mut + for" [ "6"; "2" ] {| +fn count(xs: [Int]) -> Int { + let mut n = 0; + for x in xs { if x > 1 { n = n + 1; } } + n +} +pub fn main() -> () { + let mut s = 0; + for x in [1, 2, 3] { s = s + x; } + println(int_to_string(s)); + println(int_to_string(count([1, 2, 3]))); +} +|} + +(* The operator of a compound assignment was ignored: `a += 5` stored 5. *) +let compound_assignment = agrees "compound assignment" [ "9"; "6" ] {| +pub fn main() -> () { + let mut a = 10; a += 5; a -= 3; a *= 4; a /= 5; + println(int_to_string(a)); + let mut s = 0; + for x in [1, 2, 3] { s += x; } + println(int_to_string(s)); +} +|} + +let aggregate_assignment = + agrees "array / record / tuple assignment" [ "23"; "17"; "9" ] {| +pub fn main() -> () { + let mut a = [1, 2, 3]; + a[1] = 9; + a[2] += 10; + println(int_to_string(a[0] + a[1] + a[2])); + let mut r = #{x: 1, y: 2}; + r.x = 5; + r.y += 10; + println(int_to_string(r.x + r.y)); + let mut t = (1, 2); + t.0 = 7; + println(int_to_string(t.0 + t.1)); +} +|} + +(* A block's `let mut` shadows, and does not disturb, an enclosing one. *) +let shadowed_mut = agrees "shadowed let mut" [ "5"; "1" ] {| +pub fn main() -> () { + let mut n = 1; + { let mut n = 4; n = n + 1; println(int_to_string(n)); }; + println(int_to_string(n)); +} +|} + +(* ---- early return ------------------------------------------------------- *) + +let early_return = agrees "early return" [ "300"; "-1"; "1"; "2"; "2"; "-1" ] {| +fn f(n: Int) -> Int { + let mut i = 0; + while i < 10 { if i == n { return i * 100; } i = i + 1; } + return 0 - 1; +} +fn h(n: Int) -> Int { if n > 0 { return 1; } 2 } +fn find(xs: [Int], want: Int) -> Int { + let mut i = 0; + for x in xs { if x == want { return i; } i = i + 1; } + 0 - 1 +} +pub fn main() -> () { + println(int_to_string(f(3))); + println(int_to_string(f(20))); + println(int_to_string(h(5))); + println(int_to_string(h(0))); + println(int_to_string(find([4, 5, 6], 6))); + println(int_to_string(find([4, 5, 6], 7))); +} +|} + +(* `return` in a lambda leaves the lambda, not the function around it. *) +let return_in_lambda = agrees "return in a lambda" [ "11"; "12" ] {| +fn f(n: Int) -> Int { + let g = |x: Int| -> Int { if x > 0 { return 1; } 2 }; + let a = g(n); + a + 10 +} +pub fn main() -> () { println(int_to_string(f(5))); println(int_to_string(f(0))); } +|} + +(* ---- preamble constructors, println ------------------------------------- *) + +let option_result_ctors = + agrees "imported Some / None / Ok / Err" [ "7"; "none"; "1"; "no" ] {| +use prelude::{Option, Some, None, Result, Ok, Err}; +fn pick(b: Bool) -> Option { if b { Some(7) } else { None } } +fn res(b: Bool) -> Result { if b { Ok(1) } else { Err("no") } } +pub fn main() -> () { + match pick(true) { Some(x) => println(int_to_string(x)), None => println("none") } + match pick(false) { Some(x) => println(int_to_string(x)), None => println("none") } + match res(true) { Ok(x) => println(int_to_string(x)), Err(e) => println(e) } + match res(false) { Ok(x) => println(int_to_string(x)), Err(e) => println(e) } +} +|} + +let string_char_at = agrees "string::char_at" [ "some"; "none" ] {| +use prelude::{Option, Some, None}; +use string::{char_at}; +fn probe(i: Int) -> () { + match char_at("abc", i) { Some(c) => println("some"), None => println("none") } +} +pub fn main() -> () { probe(1); probe(9); } +|} + +let println_raw_string = agrees "println writes the string itself" + [ "plain"; "a \"quoted\" word"; "tab\there" ] {| +pub fn main() -> () { + println("plain"); + println("a \"quoted\" word"); + println("tab\there"); +} +|} + +(* ---- still loud --------------------------------------------------------- *) + +(* The borrow checker rejects an assignment to a binding that is not `mut`. + [Interp] can be handed a program that skipped it; it must then stop, not + invent a cell. *) +let immutable_assignment_fails () = + let prog = Parse_driver.parse_string ~file:"" + "fn main() -> Int { let k = 0; k = k + 1; k }" in + let outcome = + match Interp.eval_program prog with + | Error e -> Error (Value.show_eval_error e) + | Ok env -> + (match Value.lookup_env "main" env with + | Error e -> Error (Value.show_eval_error e) + | Ok f -> + (match Interp.apply_function f [] with + | Ok v -> Ok (Value.show_value v) + | Error e -> Error (Value.show_eval_error e))) + in + Alcotest.(check (result string string)) "assignment to an immutable binding" + (Error "Type mismatch: Cannot assign to `k`: it is not declared `mut`") + outcome + +(* A mutable binding's cell never becomes a value: a copy taken before an + assignment keeps the old content. *) +let cell_does_not_escape = agrees "a read of a let mut is a value" [ "1"; "2" ] {| +pub fn main() -> () { + let mut n = 1; + let before = n; + n = n + 1; + println(int_to_string(before)); + println(int_to_string(n)); +} +|} + +(* ---- the CLI: `eval` uses the checker `compile` uses -------------------- *) + +(* The compiler binary, built next to this test (a dependency in test/dune); + found from the test executable so that the working directory is free. *) +let cli = + Filename.concat (Filename.dirname Sys.executable_name) + (Filename.concat Filename.parent_dir_name (Filename.concat "bin" "main.exe")) + +let run_cli args file = + let ic = Unix.open_process_in + (Printf.sprintf "%s %s %s 2>&1" (Filename.quote cli) args + (Filename.quote file)) in + let out = In_channel.input_all ic in + (lines_of out, Unix.close_process_in ic) + +(* `affinescript eval` folded [Typecheck.check_decl] itself and so rejected + these two with a type error ([Unbound variable: helper]). *) +let cli_eval_forward_and_mutual () = + let dir = fresh_dir "cli" in + write_file dir "fwd.affine" + "pub fn main() -> () { println(int_to_string(helper())); }\n\ + fn helper() -> Int { 3 }\n"; + write_file dir "mutual.affine" + "fn is_even(n: Int) -> Bool { if n == 0 { true } else { is_odd(n - 1) } }\n\ + fn is_odd(n: Int) -> Bool { if n == 0 { false } else { is_even(n - 1) } }\n\ + pub fn main() -> () { if is_even(10) { println(\"even\"); } else { println(\"odd\"); } }\n"; + let check what args file expected = + let lines, st = run_cli args (Filename.concat dir file) in + Alcotest.(check (list string)) what expected lines; + Alcotest.(check bool) (what ^ ": exit 0") true (st = Unix.WEXITED 0) + in + check "eval: forward reference" "eval" "fwd.affine" [ "3" ]; + check "eval: mutual recursion" "eval" "mutual.affine" [ "even" ]; + check "eval --json: mutual recursion" "eval --json" "mutual.affine" + [ "even"; {|{"version":1,"diagnostics":[],"success":true}|} ] + +let tests = [ + Alcotest.test_case "self-recursion" `Quick self_recursion; + Alcotest.test_case "forward reference" `Quick forward_reference; + Alcotest.test_case "mutual recursion" `Quick mutual_recursion; + Alcotest.test_case "const and fn in either order" `Quick const_and_fn_order; + Alcotest.test_case "recursion in an imported module" `Quick imported_recursion; + Alcotest.test_case "let mut in a while loop" `Quick let_mut_while; + Alcotest.test_case "let mut in a for loop" `Quick let_mut_for; + Alcotest.test_case "compound assignment" `Quick compound_assignment; + Alcotest.test_case "array / record / tuple assignment" `Quick aggregate_assignment; + Alcotest.test_case "shadowed let mut" `Quick shadowed_mut; + Alcotest.test_case "a read of a let mut is a value" `Quick cell_does_not_escape; + Alcotest.test_case "early return" `Quick early_return; + Alcotest.test_case "return in a lambda" `Quick return_in_lambda; + Alcotest.test_case "imported Some / None / Ok / Err" `Quick option_result_ctors; + Alcotest.test_case "string::char_at" `Quick string_char_at; + Alcotest.test_case "println writes the string itself" `Quick println_raw_string; + Alcotest.test_case "assignment to an immutable binding fails" `Quick + immutable_assignment_fails; + Alcotest.test_case "CLI eval: forward and mutual references" `Quick + cli_eval_forward_and_mutual; +] diff --git a/test/test_main.ml b/test/test_main.ml index 553f1bca..80e76955 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -33,6 +33,7 @@ let () = ("Module root, decl match, flattening, interp binops, Bun-ESM return-in-arm", Test_module_root_flatten.tests); ("Record update + imported types", Test_records_and_imports.tests); ("Module mut (#548)", Test_module_mut.tests); + ("Interpreter runs what the checker accepts (#833)", Test_interp_eval.tests); ("Int-div on JS-text backend (#478)", Test_int_div_js.tests); ("JS-text backend refuses unprovided builtins (#832)", Test_js_builtin_refusal.tests); ("Bun-ESM let rebinding (#827)", Test_let_rebind_bun.tests); diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 527c5513..2d788c56 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -3,6 +3,7 @@ # Regenerate: tools/check-soundness-ledger.sh --reseal # Format: . FIXTURE = file hash; TEST = the # test's function-body hash; SUITE = whole-file hash. +02aa1c6d9d1f8f141c1d7c5701ad08986a1536eadd02596a7715f0c2e7c65877 suite:test/test_interp_eval.ml 09f299eaf7e9a0d912db441f346438e31ea7157f6f730ab1b6d78ef6d22a76a1 test:test_801_planted_collision_refused 0d3623cf36a67860106d64bb32d30633978bb426d4ddd77ecc2bf6e48e1b7263 fixture:test/e2e/fixtures/borrow_callee_returned_borrow_uam.affine 20e73d88738c8fd075f81a36803554f92fa4ee53f71e33fa6759eae07c6e70f4 suite:test/test_intrinsic_shadow.ml