Skip to content

fix(interp): run what the checker accepts — recursion, let mut, return, preamble ctors (#833) - #843

Merged
hyperpolymath merged 4 commits into
mainfrom
fix/833-interp-recursion-mut
Dec 1, 2026
Merged

hyperpolymath merged 4 commits into
mainfrom
fix/833-interp-recursion-mut

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

Closes #833

What was broken, and why

affinescript eval (the tree-walking interpreter in lib/interp.ml) is the oracle the compiled backends are compared against. It refused or miscomputed programs the checker accepts. Reproduced on main 4248912.

Program eval before Cause
A function that calls itself Unbound variable: g TopFn built its closure with the environment as it stood before the function's own name was bound.
A private recursive function in an imported module Unbound variable: __mod_6recmod__g The same.
main calls a function declared after it; mutual recursion Type error, Unbound variable: helper eval folded Typecheck.check_decl itself, without the signature pre-registration in Typecheck.check_program. The interpreter had the same define-before-use limit underneath.
let mut k = 0; k = k + 1; Expected mutable reference StmtLet ignored sl_mut; StmtAssign evaluated its left-hand side to a plain value and rejected it.
if c { return 1; } 2 prints 2 (silently wrong) ExprReturn evaluated its operand and execution carried on. Not in the issue; found while testing while with return.
string::char_at, or any imported Some / None / Ok / Err Unbound variable: Some Module_loader.flatten_imports does not carry the prelude's Option / 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)) prints "2" with quotes println used Value.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; eval was the outlier.

So no language rule changes here and no ADR is needed. eval now calls Typecheck.check_program.

The fix

  • Recursion. closure.cl_env is an env ref. Every top-level function of a program shares one cell, read when the function is called. eval_program binds functions, enum constructors and effect operations first, then evaluates const initialisers in source order. One closure per function; nothing is duplicated. eval_decl on its own (REPL shape) ties a per-function knot, so self-recursion still works there.
  • Mutable bindings. env maps a name to a binding: Bound of value or Cell of value ref. let mut and const mut bind a Cell. lookup_env always 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-mut binding stays a loud error.
  • Early return. return raises Value.EarlyReturn, which apply_function turns back into the call's result. It leaves loops, and in a lambda it leaves only the lambda.
  • Preamble constructors. Some / None / Ok / Err are 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 / print write 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 4248912 and pass with this change:

[OK]  0   self-recursion.
[OK]  1   forward reference.
[OK]  2   mutual recursion.
[OK]  3   const and fn in either order.
[OK]  4   recursion in an imported module.
[OK]  5   let mut in a while loop.
[OK]  6   let mut in a for loop.
[OK]  7   compound assignment.
[OK]  8   array / record / tuple assignment.
[OK]  9   shadowed let mut.
[OK] 10   a read of a let mut is a value.
[OK] 11   early return.
[OK] 12   return in a lambda.
[OK] 13   imported Some / None / Ok / Err.
[OK] 14   string::char_at.
[OK] 15   println writes the string itself.
[OK] 16   assignment to an immutable binding fails.
[OK] 17   CLI eval: forward and mutual references.
Test Successful in 0.166s. 18 tests run.

Regression runs (local)

Gate Result
dune build clean
dune runtest --force, main suite Test Successful … 690 tests run (672 before, plus these 18)
xfail pin XFAIL-OK test_resume_nontail_xfail (unchanged; no pin flipped)
tools/run_codegen_wasm_tests.sh passed (48 harnesses)
tools/run_codegen_deno_tests.sh passed (42 harnesses)
tools/run_codegen_bun_tests.sh passed (8 harnesses)
just guard scripts (extension-ts, doc-truthing, deed-gates, soundness-ledger, capability-anchors) all OK
tools/run_face_transformer_tests.sh, tools/ci/governance-standalone.sh pass

Not run locally, stated plainly:

  • tools/res-to-affine walker tests (32) fail in my container with tree-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: ocamlformat is not installed here, so the recipe skips, as it does by design.
  • just itself is not installed; I ran the recipes' commands directly.

Soundness ledger

lib/interp.ml is a soundness path. docs/SOUNDNESS.adoc gets a #833 row (fixed, anchored to test/test_interp_eval.ml), :ground-truth-sha: advances to 4248912, and tools/soundness-anchors.sha256 is resealed. docs/COMPLETION-PLAN.adoc: H1 (early return) and H7 (let mut) marked fixed; H6 narrowed.

For the owner

  1. eval still skips the borrow checker (COMPLETION-PLAN H6). check and compile reject let k = 0; k = k + 1; with a borrow error; eval reaches the interpreter, which now stops with Cannot assign to `k`: it is not declared `mut` . Adding Borrow.check_program to eval is a two-arm change. I left it out because it changes what eval accepts and the issue did not ask for it.
  2. eval now runs trait coherence, as a consequence of using check_program. A duplicate impl is rejected with the tracking: CORE-04 traits residual — associated-type substitution, where-clause supertraits, coherence checking #559 message; before, eval rejected every trait program with Trait 'Greet' not found.
  3. Record and tuple field assignment writes a new aggregate back to the place; Bun-ESM mutates the shared object. The two agree unless the aggregate is aliased, which the borrow checker should prevent. Not tested under aliasing.
  4. PR feat(strings): backend-independent UTF-8 octet count and code-point view #829 is still open, so step 5 of the brief (run stdlib utf8 fit on the interpreter, update its Bun-only note) is not done. Both PRs touch lib/interp.ml (different regions), docs/SOUNDNESS.adoc, test/dune, test/test_main.ml; whichever lands second needs a rebase and a reseal.
  5. tools/run_codegen_bun_tests.sh leaves an untracked tests/codegen-bun/deno-removed.json behind. Not from this change; not committed.

Commits are unsigned, for the owner to re-sign.


Generated by Claude Code

…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
@gitnotebooks

gitnotebooks Bot commented Dec 1, 2026

Copy link
Copy Markdown

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
hyperpolymath enabled auto-merge (squash) December 1, 2026 19:17
Repository owner deleted a comment from chatgpt-codex-connector Bot Dec 1, 2026
Repository owner deleted a comment from coderabbitai Bot Dec 1, 2026
Repository owner deleted a comment from chatgpt-codex-connector Bot Dec 1, 2026
Repository owner deleted a comment from coderabbitai Bot Dec 1, 2026
Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 32bd0fb1-e536-4208-ba4f-e1c0ad20d18e
Commits

Reviewing files that changed from the base of the PR and between ff3f08d and cb33fcd.

Files selected for processing: 12

  • .machine_readable/descriptiles/STATE.deed
  • bin/main.ml
  • docs/COMPLETION-PLAN.adoc
  • js/js_api.ml
  • lib/interp.ml
  • lib/json_output.ml
  • lib/module_loader.ml
  • lib/repl.ml
  • lib/value.ml
  • test/test_interp_eval.ml
  • test/test_main.ml
  • tools/soundness-anchors.sha256
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@hyperpolymath
hyperpolymath merged commit 220d6f1 into main Dec 1, 2026
14 of 15 checks passed
@hyperpolymath
hyperpolymath deleted the fix/833-interp-recursion-mut branch December 1, 2026 19:43
@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

eval: self-recursion, forward/mutual references and let mut fail on well-typed programs (interp diverges from compile)

2 participants