Repository navigation
fix(interp): run what the checker accepts — recursion, let mut, return, preamble ctors (#833) - #843
Merged
Merged
Conversation
…n, preamble ctors (#833) The tree-walking interpreter is the oracle the compiled backends are compared against, and it refused or miscomputed well-typed programs. Recursion and declaration order. A top-level 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 private helper of an imported module. Every top-level function of a program now shares one environment cell, read when the function is called; eval_program binds functions, enum constructors and effect operations first, then evaluates const initialisers in source order. This matches the resolver's and Typecheck.check_program's pre-registration of top-level names (#135 slice 11) and the hoisting of the compiled backends. Mutable bindings. `let mut` / `const mut` now bind a cell (Value.Cell), which lookup_env always reads through, so a cell cannot escape as a value. Assignment resolves its left-hand side to a place: a mutable name, an array element, a record field, a tuple component, or a reference. Compound operators are applied (the arm used to ignore them). Assigning to a binding that is not `mut` stays a loud error. Early return. `return e` evaluated e and carried on, so `if c { return 1; } 2` yielded 2 — a silently wrong value. It now unwinds to the enclosing call (Value.EarlyReturn), including from loops and from a lambda. Preamble constructors. Module_loader.flatten_imports does not carry the prelude's Option / Result because every non-Wasm backend's preamble defines Some / None / Ok / Err. The interpreter had no preamble, so any imported use of them, and so string::char_at, stopped with `Unbound variable: Some`. They are now in the initial environment. println / print write a String as its characters, as every compiled backend does, not as a quoted, escaped literal. CLI. `affinescript eval` folded Typecheck.check_decl itself, without the signature pre-registration, and so rejected forward and mutual references that `check` and `compile` accept. It now calls Typecheck.check_program. As a consequence it also runs trait coherence. It still does not run the borrow checker (COMPLETION-PLAN H6); that is left for an owner decision. Tests: test/test_interp_eval.ml, 18 cases. Each program passes the full frontend, then its interpreter output is compared with the expected lines and with the Bun-ESM output of the same program. All 18 fail on 4248912. docs/SOUNDNESS.adoc: #833 row, stamp advanced to 4248912, anchors resealed. docs/COMPLETION-PLAN.adoc: H1 and H7 fixed, H6 narrowed. Closes #833 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDgaiMn26BfqukYvBwf
|
Review these changes at https://app.gitnotebooks.com/hyperpolymath/affinescript/pull/843 |
This was referenced Dec 1, 2026
hyperpolymath
marked this pull request as ready for review
December 1, 2026 18:33
hyperpolymath
enabled auto-merge (squash)
December 1, 2026 18:36
hyperpolymath
disabled auto-merge
December 1, 2026 19:00
Conflicts: docs/SOUNDNESS.adoc (both sides appended a ledger row; both kept, #836 then #833) and test/dune (both sides added a dependency; both kept). Ledger stamp advanced to 70180a1 and anchors resealed after re-running dune runtest --force and the three codegen harnesses on the merged tree. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDgaiMn26BfqukYvBwf
hyperpolymath
enabled auto-merge (squash)
December 1, 2026 19:17
Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
hyperpolymath
disabled auto-merge
December 1, 2026 19:43
Contributor
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 49 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
|
This was referenced Dec 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Closes #833
What was broken, and why
affinescript eval(the tree-walking interpreter inlib/interp.ml) is the oracle the compiled backends are compared against. It refused or miscomputed programs the checker accepts. Reproduced onmain4248912.evalbeforeUnbound variable: gTopFnbuilt its closure with the environment as it stood before the function's own name was bound.Unbound variable: __mod_6recmod__gmaincalls a function declared after it; mutual recursionUnbound variable: helperevalfoldedTypecheck.check_declitself, without the signature pre-registration inTypecheck.check_program. The interpreter had the same define-before-use limit underneath.let mut k = 0; k = k + 1;Expected mutable referenceStmtLetignoredsl_mut;StmtAssignevaluated its left-hand side to a plain value and rejected it.if c { return 1; } 22(silently wrong)ExprReturnevaluated its operand and execution carried on. Not in the issue; found while testingwhilewithreturn.string::char_at, or any importedSome/None/Ok/ErrUnbound variable: SomeModule_loader.flatten_importsdoes not carry the prelude'sOption/Result, because every non-Wasm backend's runtime preamble defines the four constructors (preamble_ctors). The interpreter had no preamble.println(int_to_string(2))"2"with quotesprintlnusedValue.show_value, the debugging form.Language rule on forward references
AffineScript is not define-before-use at top level. This was already decided and tested;
evalwas the outlier.lib/resolve.mlpre_register_decl: two-pass resolution "so that forward references between top-level declarations resolve" (issue stdlib: make every stdlib/*.affine compile through resolve→typecheck→codegen #135 slice 11).lib/typecheck.mlcheck_program: "Forward pass: register all types, effects, traits, impls, and function signatures so that mutually recursive declarations resolve."test/test_e2e.ml:test_forward_reference,test_mutual_recursion(stdlib: make every stdlib/*.affine compile through resolve→typecheck→codegen #135 sl11).checkandcompileboth go throughcheck_program. Bun-ESM and core wasm run these programs.So no language rule changes here and no ADR is needed.
evalnow callsTypecheck.check_program.The fix
closure.cl_envis anenv ref. Every top-level function of a program shares one cell, read when the function is called.eval_programbinds functions, enum constructors and effect operations first, then evaluatesconstinitialisers in source order. One closure per function; nothing is duplicated.eval_declon its own (REPL shape) ties a per-function knot, so self-recursion still works there.envmaps a name to abinding:Bound of valueorCell of value ref.let mutandconst mutbind aCell.lookup_envalways reads through a cell, so a cell cannot escape as a value: this is a property of the type, not a convention. Assignment resolves its left-hand side to a place (mutable name,a[i],r.f,t.N,*p). Compound operators are applied; the old arm ignored them. Assigning to a non-mutbinding stays a loud error.returnraisesValue.EarlyReturn, whichapply_functionturns back into the call's result. It leaves loops, and in a lambda it leaves only the lambda.Some/None/Ok/Errare in the interpreter's initial environment, in the shapes the flattener assumes and the builtins already return. Importing them is still required (the resolver decides that).println/printwrite a String as its characters.Tests
test/test_interp_eval.ml, 18 cases. Each program goes through the full frontend (resolve,check_program, borrow, quantity). Its interpreter output is then compared with the expected lines and with the Bun-ESM output of the same program. One case drives the CLI binary (eval,eval --json).All 18 fail on
4248912and pass with this change:Regression runs (local)
dune builddune runtest --force, main suiteTest Successful … 690 tests run(672 before, plus these 18)XFAIL-OK test_resume_nontail_xfail(unchanged; no pin flipped)tools/run_codegen_wasm_tests.shtools/run_codegen_deno_tests.shtools/run_codegen_bun_tests.shjust guardscripts (extension-ts, doc-truthing, deed-gates, soundness-ledger, capability-anchors)tools/run_face_transformer_tests.sh,tools/ci/governance-standalone.shNot run locally, stated plainly:
tools/res-to-affinewalker tests (32) fail in my container withtree-sitter CLI not on PATH. They fail the same way without this change; installing the CLI was not permitted in the session. CI installs it.just lint:ocamlformatis not installed here, so the recipe skips, as it does by design.justitself is not installed; I ran the recipes' commands directly.Soundness ledger
lib/interp.mlis a soundness path.docs/SOUNDNESS.adocgets a#833row (fixed, anchored totest/test_interp_eval.ml),:ground-truth-sha:advances to4248912, andtools/soundness-anchors.sha256is resealed.docs/COMPLETION-PLAN.adoc: H1 (early return) and H7 (let mut) marked fixed; H6 narrowed.For the owner
evalstill skips the borrow checker (COMPLETION-PLAN H6).checkandcompilerejectlet k = 0; k = k + 1;with a borrow error;evalreaches the interpreter, which now stops withCannot assign to `k`: it is not declared `mut`. AddingBorrow.check_programtoevalis a two-arm change. I left it out because it changes whatevalaccepts and the issue did not ask for it.evalnow runs trait coherence, as a consequence of usingcheck_program. A duplicate impl is rejected with the tracking: CORE-04 traits residual — associated-type substitution, where-clause supertraits, coherence checking #559 message; before,evalrejected every trait program withTrait 'Greet' not found.stdlib utf8 fiton the interpreter, update its Bun-only note) is not done. Both PRs touchlib/interp.ml(different regions),docs/SOUNDNESS.adoc,test/dune,test/test_main.ml; whichever lands second needs a rebase and a reseal.tools/run_codegen_bun_tests.shleaves an untrackedtests/codegen-bun/deno-removed.jsonbehind. Not from this change; not committed.Commits are unsigned, for the owner to re-sign.
Generated by Claude Code