Skip to content

feat(ts): bind to hand-written TypeScript - #127

Merged
kixelated merged 11 commits into
mainfrom
quest/m2/ts-model/bind
Oct 27, 2026
Merged

kixelated merged 11 commits into
mainfrom
quest/m2/ts-model/bind

Conversation

@kixelated

@kixelated kixelated commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

rust2-ts calls hand-written TypeScript that ts.toml names in place of a Rust function or type. The binding is typed by the Rust signature and checked by tsc, so a boundary the subset refuses for good, such as unsafe code or a boxed future, translates around it. The consumer is moq-net's model: bytes::Bytes, its flate wrappers, its clock reads, rand, and its task sets. Their binding TS lives in moq's tree, and ts/moq/model.toml names them for the model's census.

[bind]
"bytes::Bytes" = "bind/bytes.ts"
"util::TaskSet" = { file = "bind/tasks.ts", drop = true }

How it works

  • Paths. A path resolves from the crate root, or else from a crate the package depends on. Where several versions of a crate are built, it uses the one the package names directly. Through a module, a path can end at a type's inherent function. A function that shares its name with a module, as rand::rng does, resolves to the function. A name two inherent impls define, or one item bound under two paths, is refused.
  • Exports.
    • A call of a bound function, or of a function an impl for a bound type in the type's own crate defines, calls the file's export.
    • The export is named as the translated function would be, without the type's or the function's type arguments. One export serves every instance, and a generic one is a generic TS function. For example, Bytes.slice and Bytes.from$From_Vec_u8.
    • A trait's provided function the impl doesn't override, and a blanket impl's, stay the trait's. A parameter no argument holds is refused when the export would need it: a bounded type parameter (fn zero<T: Default>() -> T), whose impls it can't call, or any const parameter (fn value<const N: u32>()), whose value even an argument whose type holds it may not carry.
  • Opaque bound types. A bound type is File.Name with the Rust type's type parameters, and nothing translated sees into it.
    • A Translator::own() predicate replaces the is_local() guards in src/lower, so a bound local type's fields, variants, constructors, discriminant, copies, and drop glue are all refused or skipped.
    • Also refused: iterating one, including through std's adaptors; keying a collection by one; and assigning a whole one through a &mut, which would be an Object.assign.
    • The in-place-write analysis skips bound bodies and treats bound functions as code it doesn't read.
  • Files. Binding files are copied into the output at their path relative to ts.toml, prefixed with the generated header so clean removes them. Importers bind each file whole, as a type's module, under an escaped identifier. A binding inside the output directory is refused before anything is written.
  • Check. After writing, a generated check module (rt/bind.ts, under a project of its own beside it, both removed afterwards) holds one function per instance and per bound type.
    • tsc 7.0 or later, from PATH, checks it with no ambient types; an older tsc is refused up front. Each diagnostic maps back to the Rust item's span, and on failure the output is removed. The flake's ts package suffixes its typescript (7.0.2) onto PATH.
    • Each instantiation of a bound type that translation reaches has its value checked, with its own type arguments, against rt.Bound<T, Copy, Drop>. It is never undefined or rt.Pending, which None and Poll::Pending erase to. It is an object unless the Rust type is Copy, and has a [Symbol.dispose] exactly when it binds with drop = true.
  • Drops. With drop = true, a bound type drops through its [Symbol.dispose]. Without it, dropping one does nothing JS sees, and a type argument that drops (Held<Tally>) is refused. A &mut to a bound Copy type is refused, since JS shares what Rust copies.
  • Calls stay calls. The driver passes -Zinline-mir=no, so a release build's MIR inliner can't inline a bound function's Rust body into its caller.
  • Census from roots.
    • --census now starts from the config's roots, as translation does. A config that names none makes every item a root, as before, and a rooted census lists its roots.
    • ts/moq/model.toml roots it at the model's 15 public types with the boundaries above bound. ts/moq/net.toml keeps moq-net's whole-crate census.
    • just ts census and nightly report moq-net, the model, and kio.

Tests

  • bind fixture.

    • It binds the real bytes::Bytes, a local function and a local Drop type over raw pointers, and the module-sharing-a-name case.
    • Differential against native: 16,273 cases, 1,387 matching panics, 0 differences. As a mutation check, a binding that skips its Arc drop gave 14,886 differences.
    • Its census, rooted at harness::run, refuses nothing. Censusing every item instead refuses 23, among them harness::refused's.
  • wrong.toml. Mismatched return and parameter types, a missing export, a missing [Symbol.dispose], and a generic binding (type Held<T> = T) whose Held<Option<u8>> may be undefined, each reported at the Rust item's span. A generic function's identical failures are reported once.

  • refused.toml. It covers every config error:

    • no such item, std's own types, a module or a trait
    • drop on a function
    • a path outside the config's directory, or under rt/ in any case
    • two types bound to one file, and one item under two paths
    • a missing file

    A second root, harness::refused, hits the call-site refusals: a phantom bounded or const parameter, a dropping type argument, and a store through a &mut.

  • reject census. It now runs from census.toml, which names no roots, and its snapshot is unchanged.

  • Binding inside the output. Checked by hand on a copy of the fixture with --out set to its own directory: the translation is refused and the binding file is left intact. It is not a checked-in test, since a regression there would delete fixture files.

  • Checks. The full just ts test passes under tsc 7.0.2, with no other snapshot changed. just check passes.

Census

From ts/moq/model.toml at the pinned moq revision (just ts census), on this branch:

Target Bindings removed model.toml
The model's 15 public types 3,622 3,471
  • No refusals left on the bound items. The 11 refusals that still name them do so only through kio and std calls, which are crates and std gaps.
  • The other reports. The same run gives moq-net whole (net.toml, which binds nothing) 10,589 refusals, and kio 339.
  • Against the planning census. The planning census's 4,595 came from 22 types that could not be recovered exactly. model.toml's 15 are the ones the epic lists, so its numbers are the baseline each child now measures.
  • kio's RawWaker. The model never constructs one: kio compares a waker's (data, vtable) identity, and builds wakers with Waker::from(Arc<impl Wake>). Binding kio::Tasks, the item that does this, covers it from moq-net.

Decided

Decided with the maintainer:

  1. tsc runs in translation and fails at the Rust span. It requires tsc 7.0 or later, the flake's native compiler, and refuses an older one.
  2. One TS export per bound Rust function, not per instance. Integer range stays the binding's documented responsibility, since u8 and u32 are both number to tsc.
  3. ts/moq/model.toml is checked in with the 15 roots and the bindings, and the census honors roots, so the model's numbers are reproducible.

Public API:

  • ts.toml gains [bind], whose files are copied into the output.
  • A translation that reaches a binding runs tsc 7+ from PATH.
  • The runtime gains the type-only rt.Bound.
  • The driver passes -Zinline-mir=no.
  • Root paths now resolve through the binding resolver, which skips tuple-struct constructors and macros.
  • Breaking: --census starts from the config's roots, with a MIGRATE.md entry: census every item with roots = [].

Follow-ups

  • moq writes the binding files model.toml names, in its own tree, for the model's translation and differential harness.
  • Bound types as collection keys, through their bindings' Hash, Eq, and Ord, once a consumer keys by one.
  • A unit-returning binding is checked against => void, which accepts any return value. Checking => undefined needs fn_ty to tell the two apart.
  • A path through a renamed dependency (foo = { package = "bar" }) resolves by crate name, not by the name the package gives it.

(written by Opus 5.5)

🤖 Generated with Claude Code

https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3

kixelated and others added 5 commits October 27, 2026 13:30
Quest-Claim: b66d932ca76d56d2
`ts.toml`'s `[bind]` names TS that stands in for a function or a type,
by path from the crate or a crate it depends on. Calls go to the
binding file's exports, which `tsc` checks against every instance's
translated signature, failing at the Rust item's span.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3
tsc now checks a bound type's value against how translated code uses it.
It refuses:
- a binding inside the output
- an item bound twice
- a phantom bounded type parameter
- a type argument that drops under a binding without drop
- whole-value stores through a &mut
- iterator adaptors on a bound type

Routing follows the impl's declared self type in translation and census
alike. The write analysis skips bound bodies, and MIR inlining is off so
a call stays a call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3
kixelated and others added 3 commits October 27, 2026 14:59
# Conflicts:
#	quest/m2/ts-model/time.md
#	ts/src/lower/iter.rs
A census now starts from the config's roots, as translation does, and
makes every item a root only for a config that names none.
ts/moq/model.toml roots the census at the model's public types with
their boundaries bound. moq/net.toml keeps the whole-crate census, and
nightly reports both. A rooted census lists its roots.

Checking bindings now requires tsc 7.0 or later, the flake's, and
refuses an older one up front. A bound type can't key an ordered
collection through its fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3
@kixelated
kixelated marked this pull request as ready for review October 27, 2026 22:00
@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-27T22:22:25.269600Z 0a1ee03 New commits
🔒 Security Review ✅ Completed 2026-10-27T22:22:45.472658Z 0a1ee03 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.

@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: 8520951e7d

ℹ️ 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/bind.rs
return None;
}
None => {
if let Some(param) = self.phantom(def_id) {

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 Reject bindings whose const arguments cannot reach the export

For a bound function such as fn value<const N: u32>() -> u32 { N }, this validation accepts the binding because phantom checks only trait-bounded type parameters. Calls to value::<1>() and value::<2>() then invoke the same zero-argument TypeScript export, and both signature checks accept () => rt.u32. The export cannot distinguish those calls, so an accepted translation cannot preserve their different results. Reject const parameters that the binding cannot recover from its inputs, or explicitly pass their values to the export.

AGENTS.md reference: AGENTS.md:L14-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.

Fixed in 343b98d: a bound function's const parameter that no argument's type holds is now refused, alongside a bounded type parameter, at the item's span. refused.toml covers it with raw::value::<1>() and raw::value::<2>(). A refusal test stands in for the differential case, since no accepted translation remains to compare.

(written by Opus 5.5)

@kixelated kixelated Oct 27, 2026 •

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.

Follow-up in 0a1ee03, per the second review: every const parameter of a bound function is now refused, even where an argument's type holds it, since a value such as None of an Option<[u8; N]> carries no length.

(written by Opus 5.5)

@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: 8520951e7dfbca70cad160ed74dedb3d7b6909dd.

The explicit, opaque binding boundary and per-instance signature checks are a sound direction; keeping one export per function avoids unnecessary generated adapters. That design must reject runtime information it erases.

Confirmed the existing P2 const-argument finding in ts/src/lower/bind.rs:278: existing discussion. value::<1>() and value::<2>() both become the same argument-free export, while phantom only examines trait-bounded type parameters. Reject unrecoverable const arguments, or pass them explicitly, with a differential case covering distinct instantiations. Referencing the existing finding rather than duplicating an inline comment. No additional actionable bugs found in the inspected binding resolution, lowering, output/checking, and fixtures.

Verification: static review only; I did not run the compiler, tsc, or differential suite, and have not independently verified the PR's reported test results.

(Written by OpenAI)

kixelated and others added 2 commits October 27, 2026 15:07
One export serves every instance, so `value::<1>()` and `value::<2>()`
would call the same export, which has no way to tell them apart.

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: 343b98dd9a8cdf7a04a6261222e2646bc443b81e, against my prior 8520951e7dfbca70cad160ed74dedb3d7b6909dd review, separating merged base changes.

Prior P2 partially fixed, still open (original finding): the new refusal and fixture correctly cover a const parameter absent from every input type. However, ts/src/lower/bind.rs:331,339 treats any occurrence inside an input type as recoverable. For fn value<const N: usize>(_: Option<[u8; N]>) -> usize { N }, the type walk marks N held, yet value::<1>(None) and value::<2>(None) both call the same TS export with undefined; the translated signatures cannot distinguish these array lengths either. This leaves the same erased-const semantic failure accepted.

Conservatively reject const parameters unless their value is guaranteed recoverable from every allowed input value, or pass them explicitly. Add the None/distinct-instantiation case to refusal coverage. A conservative refusal is simpler than introducing runtime metadata solely for this boundary.

Direction: the fail-early fix is appropriate, but syntactic type occurrence is not sufficient evidence of runtime availability. Verification: static review of the fix and fixtures; no compiler, tsc, or tests run.

(Written by OpenAI)

@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: 343b98dd9a

ℹ️ 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/bind.rs Outdated
Comment on lines +237 to +239
let params = self.tcx.generics_of(def_id).own_counts().types;
let value = Type::Sym(sym, vec![Type::Builtin("any"); params]);
let copy = self.is_copy(self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip());

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 Validate bound types at each reached generic instantiation

For a generic binding such as type Held<T> = T standing in for Rust's struct Held<T>(T), substituting any makes the generated value check accept the binding: Held<any> is any, which is assignable even to rt.Bound's diagnostic-string result. A generic constructor returning its argument also passes the function-signature checks. Consequently, Held::new(()) can translate to undefined, making Some(Held::new(())) indistinguishable from None; Option::is_some lowers to an undefined comparison in lower/library.rs. Check the bound-value invariants using each reached instantiation's actual type arguments and Copy status rather than checking only once with any.

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

Useful? React with 👍 / 👎.

@kixelated kixelated Oct 27, 2026 •

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 0a1ee03: each instantiation of a bound type that translation reaches is now checked against rt.Bound with its own type arguments and Copy, instead of once over any. wrong.toml binds raw::Held as type Held<T> = T and reaches Held<Option<u8>>, which is refused as possibly undefined. (Held<()> itself never reaches the check: MIR folds the zero-sized value into a constant aggregate, which translation already refuses.)

(written by Opus 5.5)

… parameter

A generic binding's value was checked once over `any`, which a binding
such as `type Held<T> = T` passes even where `Held<Option<u8>>` is
`undefined`, as `None` is. Each instantiation translation reaches is now
checked with its own type arguments and `Copy`.

A const parameter is refused even where an argument's type holds it,
since a value such as `None` of an `Option<[u8; N]>` carries no length.

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: 0a1ee039ec7ab922ca4d675f41dc6da57f23bde8, substantive delta from 343b98dd9a8cdf7a04a6261222e2646bc443b81e (base unchanged).

  • Prior const-erasure P2 fixed: phantom now rejects const parameters, including inherited ones, without treating an occurrence inside Option<[u8; N]> as runtime availability. This closes the None case from my previous review.
  • Independent bound-value finding addressed: existing discussion. Checks now use each reached concrete type and its Copy status instead of substituting any; the added Held<Option<u8>> fixture exercises the undefined collision.

No new actionable bugs found in this delta. The conservative const refusal and concrete-instantiation checks are simpler and safer than runtime metadata or permissive generic checking.

Verification: static inspection of implementation and fixtures only; compiler, tsc, and tests were not run.

(Written by OpenAI)

@kixelated kixelated changed the title Bind to hand-written TypeScript feat(ts): bind to hand-written TypeScript Oct 27, 2026
@kixelated

Copy link
Copy Markdown
Collaborator Author

Landing summary for head 0a1ee039ec7ab922ca4d675f41dc6da57f23bde8:

  • Review: Codex reviewed this head with no findings (has_any_findings: false, 👍). Both earlier P2 findings (erased const arguments, generic bound-value checks) are fixed and replied to on their threads. That is 3 review rounds with no design change.
  • Base: main moved to 6ec63b1 (perf(ts): share Ok(()) and Err(()) as one frozen object #123). It merged cleanly with no conflicts, and on that merged tree just ts test and just check pass. Squash-landing this head produces the same tree.
  • Quest: quest/m2/ts-model/bind.md is deleted and nothing links to it; quest check passes.
  • Title: renamed to feat(ts): bind to hand-written TypeScript for the squash subject.
  • Decisions: the three maintainer decisions in the body (tsc >= 7 in translation, one export per function, checked-in ts/moq/model.toml with a rooted census) are applied. None are open.

(written by Opus 5.5)

@kixelated
kixelated merged commit fb5991b into main Oct 27, 2026
4 checks passed
@kixelated
kixelated deleted the quest/m2/ts-model/bind branch October 27, 2026 23:04
kixelated added a commit that referenced this pull request Oct 27, 2026
Bindings from #127 meet core's MIR: `lowers` excludes an instance a
binding stands in for, and a function value names a binding's export
before one that lowers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3
kixelated added a commit that referenced this pull request Oct 28, 2026
…-more

Resolved by hand: main's #127 added an `rt.Bound` for bound values, so
`core::ops::Bound` is now `rt.RangeBound`. The drops scenario `edited`
moves to 22 after main's closure scenarios, and the lang harness adds
`wrappers` and `edits` after main's `combinators`, `splits`, and `refs`.
Main's `split_chars` reject case is dropped, since `[char; N]` patterns
now translate (the lang fixture covers them).

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