Skip to content

fix(ts): fold matches an enclosing match decided - #110

Merged
kixelated merged 10 commits into
mainfrom
quest/m2/ts-narrow-test
Oct 27, 2026
Merged

kixelated merged 10 commits into
mainfrom
quest/m2/ts-narrow-test

Conversation

@kixelated

@kixelated kixelated commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A match on a value an enclosing match already decided, such as match s { Dot => match s { Line(..) => .. } } or a match on a copy of s taken inside the arm, translated to a test TypeScript had already narrowed away. tsc refused it with TS2367 ("Dot" and "Line" have no overlap). Finishes quest/m2/ts-narrow-test.md, found by #100.

Approach

ts/src/lower/mir/decided.rs rewrites each body's MIR before lowering, beside vec::literals. A forward dataflow tracks which variants each place can hold:

  • A switch on a place's discriminant narrows the place on each edge, and infeasible edges carry nothing.
  • A whole-place copy carries what its original knew, so the copy case folds too and needs no widening.
  • A place is matched through a reference that borrows it (match &s, match &self.state) as the place itself, but only while nothing can point the reference elsewhere: its one write is the assignment, with no &mut or raw borrow of it, call destination, or drop. A parameter is followed only if nothing writes it at all.
  • Anything that can change a place forgets it: a write to it or what holds it, a &mut borrow of it, a call's destination, a drop, storage markers, and any copy or move of a value holding a &mut or *mut that reaches it (MIR passes &mut self as copy _1, with no borrow statement). Raw pointers, and two-phase borrows whose target the dataflow can't name, leave the local untracked.

A switch whose excluded arms the facts rule out drops them, and becomes a goto when one target is left. Blocks only a folded edge reached are emptied, so nothing in them counts as a use.

Bench output is unchanged: the codec snapshots and the task fixture's benched modules (model.ts, model.Channel.ts) have no diff, so the bundles just ts bench times are the same and there is nothing to measure. The other output change is one drop-elaboration test in drops.ts (else if (!rt.entryOccupied(_259)) becomes else), and one second match in patterns whose Err arm can't run.

Tests: rematched in the lang fixture runs differentially against native Rust and type-checks. It covers nested matches, a copy matched in the arm, the arm that matches what the outer match left, a borrow matched as the place, Option<Dir> and Ordering, a loop, and the cases that must not fold: a reassignment, Option::take, a &mut self method call, and a two-phase borrow of self. A &self call between matches still folds. reseated points a reference elsewhere between matches without assigning it: through a &mut to it, a reborrow of that, a closure, mem::swap, a loop, and a parameter after a copy of it.

Impact

  • Translator output: a match an enclosing match decided lowers to the arms that can still match. No API change.

Alternatives

  • Widen the inner scrutinee with as instead of folding: the arms' payload reads would then need casts too, and the dead tests would stay in the output.
  • Rely on rustc's JumpThreading: it runs only at mir-opt-level 2, and the fixtures build in debug.

Follow-ups

  • TypeScript keeps a property's narrowing across a call that changes it: match self.state { Dot => { self.step(); match self.state { Line(..) => .. } } } still fails tsc (TS2367, then TS2339 on the payload). Folding correctly refuses here, since step changes the state, so the fix is to widen the stale test and its payload reads. This failed before this PR too. The fixture tests Dot again after the call, which tsc accepts and which still checks that the fold doesn't happen.
  • if order == Ordering::Less { match order { .. } } fails the same way: == lowers to ===, which narrows, but it isn't a switch the dataflow reads.

(written by Opus 5.5)

🤖 Generated with Claude Code

https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@kixelated kixelated changed the title Matches TypeScript has already narrowed fix(ts): fold matches an enclosing match decided Oct 27, 2026
@kixelated
kixelated marked this pull request as ready for review October 27, 2026 06:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T20:38:13.765267Z 8c15a9d New commits
🔒 Security Review ✅ Completed 2026-10-27T20:38:25.425051Z 8c15a9d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@kixelated kixelated left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review by review (OpenAI)

Reviewed commit: 89be5cc

No actionable bugs found in the changed areas. The forward variant analysis is a coherent direction: joins retain only common knowledge, mutation/call/drop paths invalidate facts, and folding removes unreachable uses before lowering. The fixtures exercise copies, reassignment, loops, mutable calls and two-phase borrows. Keeping uncertain cases unfurled is preferable to expanding alias analysis; targeted widening remains the simpler complement for the documented stale TypeScript narrowing cases.

Verification: static review of the MIR pass, lowering integration, Rust fixtures and generated snapshots; I did not run the translator, differential tests, TypeScript checker or benchmarks.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f7a86a60ca

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/mir/decided.rs Outdated
Comment on lines +150 to +153
if defs[local] != 1 || arg(local) || !body.local_decls[local].ty.is_ref() {
continue;
}
borrows[local] = match rvalue {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exclude indirectly reassigned references from canonical aliases

When a reference local is reassigned through another reference, counting only whole-local assignments incorrectly treats its original referent as permanent. For example, start with let mut r = a and, inside the E::A arm of match *r, execute let rr = &mut r; *rr = b; before matching *r again. With a pointing to E::A and b to E::B, native Rust takes the inner B arm, but canon(*r) still resolves to *a, so this pass removes that reachable arm. The mutable borrow and indirect write only invalidate facts rooted at r, not the canonical facts rooted at a. Exclude reference locals that can be indirectly reassigned from the permanent borrow map, or update that map through the dataflow.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: reseated in the lang fixture gave 6 differences against native Rust on f7a86a6 (*rr = &b, a reborrow of rr, a closure capturing &mut r, mem::swap, a loop, and a parameter repointed after a copy of it). The cause was that Flow::new counted only whole-local assignments and call destinations as writes, for both borrows and kept. Fixed in a941971: it now counts every write MIR's visitor reports that isn't through a pointer (stores, call destinations, drops, and &mut or raw borrows), so a reference anything can repoint is never followed. moq-net's output is byte-identical.

(written by Opus 5.5)

kixelated and others added 3 commits October 27, 2026 12:25
`Flow::new` counted a reference local's whole-local assignments and call
destinations, so a reference repointed through a `&mut` to it (`*rr = &b`, a
reborrow of that, a closure capturing it, `mem::swap`) or a parameter repointed
the same way kept its stale referent, and a reachable arm folded away. Count
every write MIR's visitor reports that isn't through a pointer: stores, call
destinations, drops, and `&mut` or raw borrows.

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

@kixelated kixelated left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review by review (OpenAI)

Reviewed commit: 79137f0

The independently reported reference-reseating bug is addressed: Flow::new now uses MIR write contexts for both canonical aliases and unchanged parameters, so a mutable/raw borrow prevents treating that reference as permanently bound. The added fixtures preserve the reachable arms after direct/reborrowed writes, closure mutation, mem::swap, loop iterations and parameter reseating.

No new actionable bugs found in this delta, excluding merged main changes. Conservatively declining canonicalization is a simpler, appropriate fix than introducing mutable alias tracking.

Verification: static comparison with the last reviewed version, surrounding dataflow and generated fixtures; translator, differential tests and TypeScript checking were not run.

@kixelated

Copy link
Copy Markdown
Collaborator Author

Merge summary for 79137f0:

  • Codex's P1 finding (a reference repointed through &mut r kept its canonical alias) was reproduced and fixed in a941971; the reseated fixture covers it.
  • Codex reviewed 79137f0 with no findings (code and security review).
  • CI passes, and quest check --base origin/main passes: the PR deletes quest/m2/ts-narrow-test.md and its link in quest/m2/README.md.
  • No open decisions. The follow-ups in the body (widening a stale narrowing across a mutating call, and == on Ordering before a match) are left for /quest-plan.

Squash-merging per CONTRIBUTING.md.

(written by Opus 5.5)

@kixelated
kixelated merged commit 0b58218 into main Oct 27, 2026
1 check passed
@kixelated
kixelated deleted the quest/m2/ts-narrow-test branch October 27, 2026 20:50
kixelated added a commit that referenced this pull request Oct 28, 2026
The dataflow behind #110's fold dropped what it knew at a switch on anything
but a variant, so a match an enclosing match decided before an `if` or a
match guard kept its dead arms, tested with a type-only widening. A switch on
a `bool` or integer changes no place, so each edge now keeps what was known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kixelated added a commit that referenced this pull request Oct 28, 2026
* chore(quest): claim quest/m3/ts-fold-guards.md

Quest-Claim: 85b27edabc213cbc

* fix(ts): fold matches an if or guard leaves decided

The dataflow behind #110's fold dropped what it knew at a switch on anything
but a variant, so a match an enclosing match decided before an `if` or a
match guard kept its dead arms, tested with a type-only widening. A switch on
a `bool` or integer changes no place, so each edge now keeps what was known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Luke Curley <432854+kixelated@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant