Skip to content

fix(ts): widen tests TypeScript narrowed stale - #118

Merged
kixelated merged 19 commits into
mainfrom
fix/ts-stale-narrow
Oct 27, 2026
Merged

kixelated merged 19 commits into
mainfrom
fix/ts-stale-narrow

Conversation

@kixelated

@kixelated kixelated commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

tsc rejected the translation where TypeScript still held a narrowing the lowering didn't account for:

  • A match after a call that changes the place: match self.state { Dot => { self.step(); match self.state { Line(_, to) => .. } } }. TypeScript keeps a property's narrowing across a call, so the inner test gave TS2367 ("Dot" and "Line" have no overlap) and its payload read TS2339.
  • A match after a library call's test: if order == Ordering::Less { match order { Equal => .. } }. == lowers to ===, which narrows. if r.is_ok() { match r { .. Err(e) => e } } (.ok) and if flow.is_break() { match flow { .. } } failed the same way.
  • A library call's test after an assignment: let mut o = Less; if .. { o = Greater } if o == Equal { .. } gave TS2367 (-1 | 1 and 0), since fix(ts): output tsc accepts for payload writes and variants in sight #100's widening of what a place is assigned covered only places a switch tests.

All of these fail on main and on #110. Found by #110.

Approach

One mechanism in decided.rs, beside #110's fold: the same forward dataflow now also follows what TypeScript narrowed each place to.

  • A switch's edge narrows the place to the variants it sends that way, unless its test is widened.
  • A library call whose bool a switch branches on (one that resolves outside the crate, as PartialEq::eq of an Ordering or Result::is_ok) narrows the enums it reads by shared reference or copy, and what they hold, to something the dataflow can't name.
  • Only an assignment TypeScript sees undoes a narrowing: a write to the place's own path. A call, a &mut, a drop, or a write through a reference forgets what Rust knows but keeps TypeScript's narrowing.

Where a switch tests a variant TypeScript narrowed the place away from, the lowering casts each read of the place in its tests to the place's whole type ((self.state as Shape.Shape).tag === "Line"). That narrows nothing, so the dataflow reruns with it until no new switch widens. A payload read where TypeScript may not have narrowed the place to that variant casts through the whole type to the variant (((self.state as Shape.Shape) as { tag: "Line"; .. })._1), for unions, Result, ControlFlow, Option, and Poll. A map's Entry is one class for either variant, which TypeScript narrows nothing by, so its payload reads need none. Places a library call's test reads count as tested for #100's widening of what they're assigned.

Output: only type syntax changes.

Tests (lang fixture, differential against native Rust, type-checked, no new op): Machine::run now reads Line's payload after step(). Filled::run matches an Option<Shape> field, fills it through &mut self, and matches it again, from None and from Some(Dot). rematched covers == on an Ordering, Result::is_ok, ControlFlow::is_break, and an assigned Ordering compared with ==, and an Option<hash_map::Entry> tested by is_some() and matched on both variants.

Impact

  • Translator output: tests and payload reads TypeScript narrowed stale get type-only casts. No JS changes.
  • No public API change.

Alternatives

  • Cast at each call site that can change a place: it misses library-call tests and writes through references, and the brief asked for one mechanism.
  • Fold the library-call cases instead, by reading == and is_ok as switches in fix(ts): fold matches an enclosing match decided #110's dataflow: it needs each library call's meaning, and a user's PartialEq can mean anything.
  • Widen every test and payload read of a place once any of them is stale: a simpler lowering, but more casts, and the dataflow is the same.

Choices made without the maintainer

  • A library call counts as a test when its result is switched on and it resolves outside the crate. That over-approximates: rt.eqOption(Dir.eq$PartialEq)(d, ..) narrows nothing but widens a later match on d. Over-approximating only adds casts.
  • After a library call's test, the narrowing is unknown, so it lasts past the if until an assignment TypeScript sees. Knowing which variant == Less names would take const-evaluating the operand.
  • Option::take counts as a change TypeScript doesn't see, so fix(ts): fold matches an enclosing match decided #110's held case gains one cast.
  • A write through a &mut to a reference counts as a change TypeScript doesn't see, though the lowering writes it as an assignment to the reference (r = b), so fix(ts): fold matches an enclosing match decided #110's reseated cases gain one cast each. Over-approximating only adds casts.

Follow-ups

  • fix(ts): fold matches an enclosing match decided #110's dataflow forgets what it knows at a switch on anything but a variant, such as an if or a match guard, so a match decided before an if doesn't fold. This PR keeps that (folding more would change JS) but carries TypeScript's narrowing through, so those tests now widen instead of failing.

The quest was unplanned work. It is added and deleted here (quest/m2/ts-stale-narrow.md).

(written by Opus 5.5)

🤖 Generated with Claude Code

https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@kixelated
kixelated marked this pull request as ready for review October 27, 2026 10:40
@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-27T21:51:25.290896Z 92efb3c New commits
🔒 Security Review ✅ Completed 2026-10-27T21:52:01.469520Z 92efb3c 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: 13cf40e

No actionable bugs found in the two-commit delta above #110 (89be5ccffab0b4280d965999016e2f0dee6d56fb). Separating Rust variant knowledge from TypeScript's persistent narrowing, then applying whole-type/variant casts, is a sound direction. Reusing the existing dataflow is preferable to scattered call-site exceptions; conservatively treating library predicates as unknown narrowing keeps the extra complexity justified without requiring their semantics.

Inspected visible-write invalidation, joins and widened-test iteration, payload casts, and the method-mutation/nested Option/library-predicate fixtures. Verification was static source and generated-output inspection only; I did not run translation, tsc, differential tests, benchmarks, or independently verify the claimed byte-identical JavaScript.

kixelated and others added 2 commits October 27, 2026 10:12
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 and others added 4 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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
# Conflicts:
#	ts/fixtures/lang/expected/shapes.Machine.ts
#	ts/fixtures/lang/expected/shapes.ts
#	ts/fixtures/lang/src/shapes.rs
#	ts/src/lower/mir/decided.rs

@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: 144e90f916

ℹ️ 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/place.rs
Comment on lines +289 to +293
let Some(variant) = self.variant_ty(ty, variant, span) else {
return self.err(
span,
format!("a payload of `{ty}` read where TypeScript narrowed it to another variant"),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve support for stale collection-entry payload reads

For an Option<hash_map::Entry<...>> or Option<btree_map::Entry<...>> parameter, checking is_some() before matching Some(Entry::Occupied(e)) now reaches this error. The library-call analysis marks the option's narrowing unknown, and Facts::narrowing propagates that unknown state to its nested entry, so the entry's payload read is marked stale. However, variant_ty has no Std::Entry case and returns None. Entry matching was already supported by variant_test and field, which represent both entry variants as the entry itself. Handle that representation here rather than rejecting previously supported Rust because of a conservative narrowing fact.

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.

Fixed in 29f9d30: rt.Entry is one class for either variant and rt.entryOccupied returns a plain boolean, so TypeScript narrows nothing by an entry test and a stale payload read now passes the entry through uncast. rematched covers it with an Option<hash_map::Entry> tested by is_some() and matched on both variants.

(written by Opus 5.5)

`rt.Entry` is one class for either variant, so TypeScript narrows nothing
by its test and a stale payload read needs no cast. It errored instead.

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

@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: 29f9d30

No actionable bugs found in the Entry fix since the equivalent main/stack updates. The independent stale collection-entry payload finding is addressed by place.rs:289–292: passing through the shared rt.Entry representation matches existing field lowering and its non-narrowing boolean predicate, for both hash-map and B-tree entries. This targeted exception is simpler than inventing variant-specific Entry casts. The new fixture exercises occupied and vacant paths after Option::is_some().

Verification: static inspection of the change, generated fixture, library mapping and runtime representation only; translation, TypeScript checking and differential tests were not run.

@kixelated

Copy link
Copy Markdown
Collaborator Author

Merge summary:

(written by Opus 5.5)

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