Skip to content

fix(typecheck): end a block's let bindings with the block - #826

Merged
hyperpolymath merged 5 commits into
mainfrom
claude/gifted-lamport-k0mc5l-block-scope
Dec 1, 2026
Merged

hyperpolymath merged 5 commits into
mainfrom
claude/gifted-lamport-k0mc5l-block-scope

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

A type-checker soundness hole found while answering review on #798.

The hole

synth_block never removed a block-local binding's type from name_types. The binding therefore replaced the type of any outer binding with the same name for the rest of the function. The resolver scopes blocks correctly, so only the types were wrong:

pub fn unsound(c: Bool) -> Int {
  let x = "s";
  if c { let x = 1; }
  x + 1
}

On main (ee211d3) this type-checks, and unsound(false) returns the string "s1" on Bun-ESM; it also compiles to Wasm. The converse (an outer Int shadowed by a block-local String) is wrongly rejected.

The fix

synth_block now saves the types of the names its lets bind and restores them when the block ends, through Fun.protect.

Evidence

  • test/test_block_scope.ml adds 6 cases: the unsound program for if, bare and while blocks; the converse; a builtin shadowed inside a block; and the inner binding staying in scope. Five fail without the change. The sixth passes either way.
  • dune build @test/runtest: 662 tests pass.
  • Bun-ESM: 8 harnesses. Legacy codegen-deno corpus: 42 harnesses. Wasm: 48 harnesses. All pass.

Not in this PR

On Bun-ESM, let x = x + 1 in a nested block reads the inner const x before it is initialised. JavaScript's temporal dead zone (TDZ) for const makes that a ReferenceError. The fix is to rename the inner binding in codegen. It is pre-existing and separate from this hole; it will follow in its own PR.


Generated by Claude Code

synth_block left a block-local binding's type in name_types, so it
replaced the type of an outer binding of the same name for the rest of
the function. The resolver already scoped blocks; the type checker did
not. So

    let x = "s";
    if c { let x = 1; }
    x + 1

type-checked as an Int, and a function declared `-> Int` returned the
string "s1" at run time on Bun-ESM and Wasm. The converse (an outer Int
shadowed by a block-local String) was wrongly rejected.

synth_block now saves the types of the names its lets bind and restores
them when the block ends, on every path.

test/test_block_scope.ml plants the unsound program for if, bare and
while blocks, and the converse; five of its six cases fail without this
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK
@gitnotebooks

gitnotebooks Bot commented Nov 30, 2026

Copy link
Copy Markdown

Adds the #826 row (fixed, anchored by test/test_block_scope.ml),
reseals tools/soundness-anchors.sha256 and moves the ground-truth stamp
to ee211d3, the main commit this fix was verified against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

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 42 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: be3dc8af-c488-4c16-9c10-45cc9cef3858
Commits

Reviewing files that changed from the base of the PR and between c33da4f and 1473469.

Files selected for processing: 5

  • docs/SOUNDNESS.adoc
  • lib/typecheck.ml
  • test/test_block_scope.ml
  • test/test_main.ml
  • tools/soundness-anchors.sha256

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Names declared inside a block no longer affect the type of a same-named variable after the block. This applies to conditional, loop and standalone blocks, including when the inner name shadows a built-in.
  • Tests
    • Added coverage for block-scoped bindings, restored outer types and use of inner bindings within their block.

The type checker now restores prior bindings for names declared inside a block. New tests cover shadowing in several block forms and use of bindings within and after a block.

Changes: Block-scoped type bindings

Layer / File(s) Summary
Restore block-local bindings
lib/typecheck.ml
synth_block saves and restores prior bindings for block-level StmtLet names, including when checking raises or returns an error. Statement and result-type checking is moved to synth_block_body.
Block-scope tests and soundness ledger
test/test_block_scope.ml, test/test_main.ml, tools/soundness-anchors.sha256
New tests check shadowing in if, bare, and while blocks, restoration of outer types, builtin visibility after a block, and use of an inner binding within its block. The runner registers the tests, and the ledger adds a suite digest.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Merge Risk: Minimal · previous review c33da

This change fixes block-local shadowing in the type checker so an inner binding no longer replaces an outer binding's type. Tests cover the main cases. No merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: block-local let bindings should stop affecting outer bindings when the block ends. It matches the changeset, which snapshots and restores name types in synth_block, an…
Description check Passed The description explains the soundness hole, gives a reproducer, describes the fix via synth_block saving and restoring name types with Fun.protect, and lists the new tests and verification runs. It a…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: block-local let bindings should stop affecting outer bindings when the block ends. It matches the changeset, which snapshots and restores name types in synth_block, and the fix(typecheck) prefix fits a type-checker fix. The title is short and specific.

Full details: Description check

Explanation

The description explains the soundness hole, gives a reproducer, describes the fix via synth_block saving and restoring name types with Fun.protect, and lists the new tests and verification runs. It also notes a separate TDZ issue that is out of scope. It is directly related to the changeset.

  • 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

Recent review info

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: c6c3a275-184f-419e-b482-3c0c027a7ccf
Commits

Reviewing files that changed from the base of the PR and between 5ff584e and c33da4f.

Files selected for processing: 1

  • tools/soundness-anchors.sha256

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Recent review details

Context from checks skipped due to timeout: 7

  • GitHub Check: CodeRabbit
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: coverage-visibility
  • GitHub Check: bench-visibility
  • GitHub Check: build
  • GitHub Check: lint
  • GitHub Check: analyze (actions, none)

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 30, 2026
Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
The merge of main (c33da4f) kept #838's row and dropped #826's, while
tools/soundness-anchors.sha256 still pinned test/test_block_scope.ml, so
the soundness-ledger gate failed (property 3). Both rows now stand; the
gate passes and the manifest needs no reseal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDiosfvobXq67wbduuK
coderabbitai[bot]
coderabbitai Bot previously approved these changes Dec 1, 2026
@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

@hyperpolymath
hyperpolymath merged commit 4248912 into main Dec 1, 2026
19 checks passed
@hyperpolymath
hyperpolymath deleted the claude/gifted-lamport-k0mc5l-block-scope branch December 1, 2026 17:58
hyperpolymath added a commit that referenced this pull request Dec 1, 2026
…bles (#827)

Two Bun-ESM miscompiles on `main`, found while answering review on #798.
They are separate from the type-checker hole in #826.

## 1. A `let` that reads or shadows an enclosing name

A JS `const x` is in its temporal dead zone (TDZ) for its whole block,
so the old emission failed in two ways:

| Source | Emitted on `main` | Result |
|---|---|---|
| `let y = { let x = x + 1; x };` | `const x = (x + 1)` in the block |
`ReferenceError` |
| `pub fn p(x: Int) -> Int { let x = x + 1; x }` | `function p(x) {
const x = (x + 1); … }` | `SyntaxError`: **the whole module fails to
load** |

**Fix.** A `let` binder is emitted under a fresh `name$N` when its
initializer mentions the name, or when it shadows a name already bound
in the function. `$` cannot occur in a source identifier, so fresh names
never collide.

References resolve through a scoped rename table in `resolve_var`.
Binders that keep their own name clear the rename for their scope:
parameters, lambda parameters, match arms and loops. Destructuring and
punned record patterns are renamed the same way.

## 2. An Int-typed lambda parameter

```affine
pub fn lambda_int(s: String) -> Int {
  let f = fn(len: String -> Int) => len(s) / 2;
  f(fn(t: String) => 5)
}
```

This returned `2.5` on `main`: a function declared `-> Int` returned a
non-integer. CodeRabbit left this open on #798. Lambda parameters are
now seeded the way function parameters are. An untyped or non-Int
parameter also stops a same-named outer `Int` from truncating.

## Evidence

- `tests/codegen-bun/let_rebind` has 7 cases. On `main` its module fails
to load (`"x" was originally declared here`).
- `dune build @test/runtest`: 662 tests pass. Bun-ESM: 9 harnesses.
Legacy codegen-deno corpus: 42. Wasm: 48. All pass.
- `tools/check-soundness-ledger.sh` passes. A ledger row follows in the
next commit.

---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Co-authored-by: Claude <noreply@anthropic.com>
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.

2 participants