Skip to main content

Crate bynk_ts

Crate bynk_ts 

Source
Expand description

The TypeScript tree and printer (phase 7 of the compiler trajectory, design/bynk-compiler-trajectory.md). Emission produces nodes (TsProgram/TsStmt); printer::print is the only code in the compiler that writes a character (R7.3). The crate also holds the PredKind → check-condition mapping (pred_condition_and_message) and the one TypeScript string escaper (escape_ts_literal), shared by the emitter, the checker’s wire defaults and the language server (crate-hygiene A2).

Invariant: this crate depends on bynk-syntax only (for bynk_syntax::span::Span, reused unchanged rather than redefined — bynk-emit’s own TypeRef/Ir machinery is not visible here, and never will be: a function taking one would not compile, the dependency isn’t present, by design). cargo tree -p bynk-ts shows bynk-syntax and nothing else. Matches the same load-bearing shape bynk_driver::render’s own module doc states for itself (bynk-driver/src/render.rs).

What exists here today (P7.5, #1307 → P7.8, #1313). The reference’s own §7.1 sketch names four tree enums (TsStmt/TsExpr/TsType/ TsDecl) with real variants (Const, Let, Binary, Named, Class, …), but only as a variant-name list, not a field-level design. P7.5 built only TsStmt’s Verbatim escape hatch (VerbatimOrigin- tagged text, Q2, design/tracks/the-typescript-tree.md §3.2). P7.8 (#1313) adds the rest — TsExpr/TsType/TsDecl, plus real TsStmt kinds — but not the sketch’s full variant list: only what bynk-emit/src/emitter/events_fanout.rs (Arc C’s real next file — P7.8’s own accepted proposal corrected the track doc’s stale schedule, design/tracks/the-typescript-tree.md §6/§9) concretely needs, grounded against that file’s own real shape. bynk-emit still builds no TsProgram beyond Verbatim — Arc C’s own first slice is what starts converting real emission into real nodes, file by file; this crate exists so that conversion has somewhere to land, following R10.3’s own “carve prospectively, at the moment the dependency appears” precedent (bynk-strip’s own carve is the control case cited for this).

Structs§

ExportedName
One name a statement exports (TsStmt::exported_names).
ModuleExports
#2036: what a module exports, for namespace_member_uses’ members.
NamespaceMemberUse
#2036: a member a module names through one of its namespace imports: handlers.Batch in type position, handlers.__deserialise_Batch(…) in value position.
Printed
The result of printing a TsProgram: the emitted text, and its source map — None when no checkpoint resolved, either because no statement carried a span or every span fell outside source_text (SourceMapBuilder::to_v3’s own “nothing resolves” case).
SourceMapBuilder
Accumulates source-map checkpoints during emission. Lives behind a RefCell on bynk-emit’s LowerCtx so the deep lowering chain and the declaration loop can both record without fighting the borrow checker. A sub-builder (one per spliced body) records against its local buffer, then is merged into the module builder at the splice offset.
TsClassCtor
A class’s own constructor.
TsClassField
One class field.
TsClassMethod
One class method.
TsDeclarator
One declarator of a TsStmtKind::LetList: name, name!: T, name: T or name: T = init (1A.35a part B). definite prints the ! assertion, which TypeScript allows only with a type and no initialiser.
TsParam
One function/method/constructor parameter.
TsProgram
A whole generated TypeScript module, as an ordered sequence of top-level statements. Vec<TsStmt>, plain — no richer container yet (P7.6’s own Artefacts { docs: BTreeMap<PathBuf, Document> } is where a project’s documents get keyed; this is one document’s own tree).
TsStmt
One statement — a Verbatim-tagged escape hatch (still constructible only via TsStmt::verbatim, per #1307’s Decision D — the verbatim_sites probe needs exactly one string to line-scan for), or, from this slice, a real structured kind. The real kinds have no such sealing: they’re normal typed constructors, not a “wrap opaque text” escape hatch, so the verbatim_sites concern that motivates verbatim’s own single-constructor discipline doesn’t apply to them.
TsSwitchCase
One case/default arm of a TsStmtKind::Switch. empty labels is the default: case — every real default in workers_entry.rs prints its body directly under default: with no { } block, while every real non-default case (regardless of test) always prints a { }-blocked body.
Violation
One construct verbatim_violations found, and the line it was on.

Enums§

TsArrowBody
TsExpr::Arrow’s own body shape (#1435, Arc E slice 1) — see that field’s own doc for why this is a widened field rather than a second TsExpr variant. Expr is every real site before this slice (and the overwhelming majority after it): the arrow’s body is one expression, printed with no surrounding braces. Block is serialisation.rs’s own Float non-finite guard, the first real statement-bodied arrow anywhere in this tree — printed as a real braced block, reusing this crate’s own printer’s existing compact-statement-list renderer (render_compact_stmts, the same one TsStmtKind::InlineBlock already shares with render_branch’s own same-line if/else) rather than a third copy of that “one physical line, semicolon-separated” logic. Every real Block site today is exactly this one-line IIFE shape (an arrow with no other real use of a genuinely multi-line block body has been found); a future multi-line block-bodied arrow is a real, separate gap this variant does not yet cover.
TsBinaryOp
?? (events_fanout.rs’s env ?? {}), plus three more real operators #1321 (workers.rs) grounds: ||/&& (the Bearer-header presence checks, __authz === null || !__authz.startsWith(...) / __authz !== null && __authz.startsWith(...)) and ===/!== (pervasive throughout the file’s own tagged-result and header checks). #1323 (workers_entry.rs) grounds one more: > (the request-body- ceiling guard’s own Number(__contentLength) > <cap> — the one real site anywhere in bynk-emit that needs a relational, not equality, comparison). Not the full JS/TS operator table (Decision B’s own “extend narrowly” posture) — see the printer’s own binary_precedence (bynk-ts/src/printer/precedence.rs, private) for why a nested Binary operand’s parenthesisation needed to become precedence-aware once more than one operator existed. Arc C, step (11) (#1388) grounds one more: + (string concatenation) — the ICU-formatting cluster’s own dominant structural pattern, every literal/placeholder segment in a message template joins this way. Real JS/TS precedence (binds tighter than every comparison/logical operator this table already has) and real left-associativity ("a" + "b" + "c" needs no parens, the same way a same-operator ||/&& chain already prints flat) both matter here, not just the operator symbol itself.
TsBindingName
A binding’s own name, in either of the two shapes events_fanout.rs itself uses: a plain identifier (const subs = ...), or an object-destructuring pattern (const { events } = ...) — naming only the destructured properties themselves ({ a, b }), not the renamed ({ a: renamed }) or nested ({ a: { b } }) forms, since nothing in the grounding file needs either.
TsDecl
A top-level declaration. Import, Export, Interface, ConstDecl, and Class were events_fanout.rs’s own grounding (P7.8’s own note: “not the sketch’s Function/TypeAlias — unused in the grounding file”). #1321 (workers.rs) needed both after all — a real gap the accepted proposal’s own Framing didn’t name (its own “no other gap surfaced” checked TsStmt/TsExpr/TsType shapes, not TsDecl ones): compose.ts’s own export function compose(env: Env, …) { … } is a top-level function declaration, and (when the Worker has agents or publishes events) a type DurableObjectNamespace = { … }; fallback alias sits alongside it. Named explicitly as a deviation from the accepted proposal’s own catalogue, not silently added — both are mechanical, direct TsDecl siblings of ConstDecl/Class already here, the same “small, grounded, same class of gap” this track’s own history repeatedly found and closed (P7.8’s Assign/Continue/ TryCatch, Arc C slice 1’s Comment).
TsExpr
An expression. Only the shapes events_fanout.rs concretely uses (Decision B) — not the reference sketch’s full TsExpr list (Arrow, Cond, TemplateLit, Spread are all unused in the grounding file and deliberately not built here). Arc C slice 3 (#1321, workers.rs) adds Arrow, OptionalMember/OptionalIndex (Decision A, gaps 3/4) — this slice’s own real, grounded needs.
TsLit
A literal — the three kinds events_fanout.rs uses (a string, a number, null), plus Bool (#1323’s own real gap: workers_entry.rs’s CorsPolicy.credentials/SecurityPolicy.nosniff object-literal fields are real booleans, e.g. credentials: true, nosniff: false — nothing before this slice’s own grounding ever built one).
TsMappedModifier
The modifier on a TsType::Mapped type’s readonly.
TsObjectEntry
One entry of a TsExpr::Object literal. Only Prop existed before #1321 (events_fanout.rs’s own grounding never needed the other three) — workers.rs’s own dominant shape (Decision A, gap 1) is a literal object whose entries are shorthand async methods (every on call/on http/… wrapper attaches this way), its local capability-deps object mixes bare shorthand names with explicit key: value pairs, and three real sites spread another object into one (gap 2, folded in here rather than as its own top-level TsExpr variant — a spread only ever appears as an object- or array-literal entry in this file, never as a standalone expression, so scoping it to entry position is the narrower correct change).
TsType
A type-position node. Named (extended with type arguments — a real gap the reference sketch left unaddressed: Record<string, Array<{...}>>/Promise<Response> both need one, and a bare Named with no type-argument slot cannot represent either), Array (extended with a readonly modifier — P7.9’s own real gap: every List/Query element type bynk-emit’s ts_type_ref*/ts_ty families build is readonly T[], not plain T[]), Object, and Fn (P7.9’s own second real gap — the query-thunk wrapper (() => readonly T[]) and a real parametered function type (a0: T0, …) => Ret both need one) — not the sketch’s Union/Intersection/Literal/TypeParam/Readonly (still unused; readonly here is a modifier on Array, not the sketch’s own separate Readonly wrapper variant).
TsTypeMember
One member of a TsType::Object structural type — a property (Prop) or a method signature (Method, #1323’s own real gap: ack(): void, retry(): void, waitUntil(promise: Promise<unknown>): void — no body, a type-position sibling to TsObjectEntry::Method, which does carry one). Method’s own parameters reuse TsParam directly (not a bare Vec<TsType> the way TsType::Fn’s anonymous, positionally-numbered parameters do) — waitUntil’s own real parameter has a real name (promise) the printed text must show, unlike Fn’s callers, none of which have one to show.
TsUnaryOp
!x (events_fanout.rs’s !Array.isArray(subs), !binding) and typeof x (#1321, workers.rs’s own secret-probe idiom: typeof __secret !== "string") — the two unary operators real content uses, not the full JS/TS table.
VerbatimOrigin
Which family of residual, not-yet-converted emission a TsStmt::verbatim statement came from. A closed enum, deliberately — “makes the ratchet a compile-time construct, not a grep” (Q2’s own settling text). Named file-by-file as Arc C actually needs them (ast_importers’s own five-file floor is the precedent for how this track names residue), not pre-populated for the whole ~19-slice Arc C schedule up front.

Functions§

decimal_range_condition
The Decimal range check as printed text — for bynk-emit’s lower.rs, which still assembles its refinement guard from text.
decimal_signed_coef
#2622: a coefficient as a signed bigint literal body: no leading zeros (007n is not valid TypeScript) and no negative zero.
escape_ts_literal
Escapes a string for embedding in a TypeScript double-quoted string literal. The one definition: the printer’s TsLit::Str, bynk-emit’s escape_ts_string and bynk-check’s wire defaults all splice into generated TypeScript and must never disagree.
expr_contains_await
Whether expr contains an await, at any depth. A TsExpr::VerbatimExpr or TsExpr::RawUsing is foreign text, so it is searched as text; an Ident is an identifier path, so it never awaits.
module_exports
#2036: the names program exports. Structured exports are read with TsStmt::exported_names; opaque text line by line, as unbound_names reads its declarations: a line starting export and then a declaration keyword or a { … } list. Over-reporting an export can only hide a defect.
namespace_member_uses
#2036: every member program names through a namespace import (import * as ns, import type * as ns), sorted and deduplicated. A member the target module does not export is a TS2694/TS2339 that tsc would report (Namespace 'handlers' has no exported member), which unbound_names cannot see: the namespace itself is bound. Checking it needs the target module too, so a caller pairs this with module_exports. Opaque text is not searched for uses.
pred_condition_and_message
#661 (Decision D)/#70 review: the one PredKind → runtime-check mapping, shared by the owner-side check (emit::emit_pred_check, over a value binding) and the boundary-side inline check (serialisation::emit_inline_pred_check, over a json binding) — the two used to hand-roll this mapping independently, pinned identical only by a comment, so amending one (e.g. the Matches regex’s ^(?:…)$ anchoring) could silently drift from the other. receiver is the bound name the generated condition reads (value or json); the returned message is the same either side of the boundary by construction.
pred_condition_and_message_for
pred_condition_and_message knowing the receiver’s base type: a Decimal is an object, so its numeric predicates are not recv > 0.
pred_condition_and_message_over
pred_condition_and_message_for over a receiver that is itself an expression (a field read, an indexed element, a temporary), not just a name.
print
Print program to TypeScript text. source_name/source_text register the .bynk source every statement’s own span is measured against — today always exactly one, since nothing spans two files yet; output_file names the generated file in the source map’s own file field. Every statement’s own span is recorded as a checkpoint, at any depth (1A.15; before that only a top-level statement’s was, R7.4’s original scope) — except inside an arrow body, which carries none yet.
print_class_method
Print a single TsClassMethod on its own, at depth — the class-method sibling of print_object_entry’s own “one fragment, not a whole document” entry point. depth means the class’s own depth (matching print_object_entry’s own convention exactly), so the method itself lands at depth + 1, its own body at depth + 2. #1359’s own real need: emit_provider’s own class wrapper stays hand-written text (each method’s own body needs a per-method source-map sub-builder/ merge, and the wrapper’s own real spacing — no blank line between methods — genuinely differs from TsDecl::Class’s own “one blank line before each method” policy, events_fanout.rs’s real convention, #1317), so each real method prints through here directly into that still-hand-written wrapper. Deliberately no automatic blank-line insertion of its own — the same “caller controls spacing” contract print_object_entry already established.
print_class_method_and_merge
print_class_method’s own sibling (#1477): identical rendering, but merges any of method.body’s own direct-child nested_maps into map as they print, at the real print-time offset — no reverse-engineering the offset from the returned text afterward, the way bynk-emit’s own emit_class_method_and_merge_source_map (emitter/emit.rs) has to today. Kept as a separate function, not an added parameter on print_class_method itself, so every existing caller’s own call sites are untouched — this is a strict addition.
print_expr
Print a single TsExpr on its own — the expression-level sibling of print_type’s own “one fragment, not a whole document” entry point. Arc C, step (11) (#1388) need: emit_icu_placeholder’s own Select arm stays one opaque, hand-built block-bodied IIFE (at the time, TsExpr:: Arrow had no block-body variant at all, and extending it for that one site was rejected as disproportionate) — its own arm VALUES, emit_sub_message’s now-real TsExpr results, still need stringifying back into that opaque host text. #1435 (Arc E slice 1) later added TsArrowBody::Block for a genuinely different real site (serialisation.rs’s Float guard); emit_icu_placeholder’s own Select arm was not reconverted along with it — out of that slice’s own scope — so this call site’s opaque text stays exactly as it was. No source-map/buffer machinery, matching print_type/print_stmt’s own scope exactly.
print_multi_source
#1486’s own multi-source sibling of print(): a test/integration module’s own aggregate map spans one source per fragment file a case’s body was spliced in from (emit_test_module/emit_integration_module, project/tests_emit.rs), not the single .bynk file print’s own signature assumes — see TsStmt::nested_map_source_id’s own doc for why a per-statement source selector needs a caller that can register more than one source in the first place. Takes the caller’s own already- built map directly (rather than a (name, text) list built fresh here) so a caller can keep registering sources incrementally as it discovers them — emit_test_module’s own per-case loop, one add_source call per case, exactly as it already did before this function existed — and get each call’s own returned id back immediately, to set on that case’s own top-level statement’s nested_map_source_id, instead of having to pre-compute the full source list up front. Every statement’s own nested_map_source_id selects which of map’s already-registered sources (by id) its own nested_map merges against; a statement with no span of its own (this whole module’s own shape — an aggregate with no single “primary” source of its own) never records a top-level checkpoint, so map’s own id-0 source (if any) needs no special “primary” meaning here the way print()’s single source does.
print_object_entry
Print a single TsObjectEntry on its own, at depth — the object-entry sibling of print_stmt’s own “one fragment, not a whole document” entry point, depth meaning the SAME thing it does for this crate’s own internal multi-line-object renderer: the object’s own depth, so the entry itself lands one level deeper, matching an object built by that renderer exactly. #1337’s own real need: emit_attached_methods (a shared helper spliced into emit_refined_type/emit_record_type/ emit_sum_type’s own still-unconverted &mut String buffers) now returns Vec<TsObjectEntry> instead of writing text directly — each caller renders the returned entries one at a time through this, the same P7.9/#1333 “keep the caller’s own signature, print just the fragment” pattern applied to an object-entry-shaped fragment instead of a whole statement or type.
print_stmt
Print a single TsStmt on its own, at depth — the statement-level sibling of print_type’s own “one fragment, not a whole document” entry point. bynk-emit‘s own #1333 need (emit_doc_block, a shared helper spliced into ~14 still-unconverted callers’ own buffers) wants one statement’s own printed text at a caller-supplied depth, not a whole TsProgram — no source-map/buffer machinery, matching print_type’s own scope exactly, and reusing render_stmt’s own exhaustive per-kind dispatch (this module’s own private renderer) rather than a second copy. Review of #1402: a TsStmtKind::Raw nested inside a Switch case’s own body (emit_stub_rhs’s own ReturnsEach dispatch, Arc C slice 33, tests_emit.rs slice C) carries the identical “no indent of its own, pre-indented at a fixed absolute depth” hazard render_class_method’s and render_multiline_object_entry’s own debug_assert!s already guard — stmt_contains_raw already recurses into Switch cases, so the same check applies here, this fragment entry point’s own first Raw-bearing Switch caller. A bare Raw passed directly as stmt itself is exempt (not a false negative — render_stmt’s own Raw arm never reads depth at all, so calling print_stmt on a bare Raw is safe at any depth, the established print_stmt_renders_raw_text_verbatim_with_no_ added_indent_or_punctuation contract below): only a Raw nested inside a depth-using wrapper (like this Switch case) is the real hazard.
print_stmt_and_merge
print_stmt’s own sibling (#1477), the TsDecl::Function-body counterpart to print_class_method_and_merge: identical rendering, but merges any nested_map stmt carries — on stmt itself, or on anything nested inside it (a function’s body, a class’s constructor/ methods, …) — into map as it prints, at the real print-time offset — the same offset bynk-emit’s own emit_free_fn (emitter/emit.rs) used to recover by exact arithmetic over the returned text, guarded by a debug_assert!, before #1480 converted it to set nested_map directly instead. Kept separate from print_stmt itself so every existing caller’s own call sites are untouched. source_id is map’s own registered source this statement’s content belongs to (see this crate’s own private MergeTarget’s own doc for why this can’t just be hardcoded).
print_stmt_with_spans
print_stmt, also reporting where each statement that carries a TsStmt::span starts in the printed text (back-half paydown 1A.11, Decision C of #3712). The offset is a byte offset into the returned text, at the start of the statement’s own line, so before its indentation; an inline if/else branch (no braces, same line as its if) starts after the space that separates it. The statement itself, then every statement nested in it, is reported in the order printed; a statement with no span is not reported.
print_type
Print a single TsType on its own — the real callers this closes R7.2 for (bynk-emit’s ts_type_ref*/ts_ty families, P7.9, #1315) each want one type fragment to interpolate into a larger, still-hand-built line (a field’s own type annotation, a parameter list, …), not a whole TsProgram. No source-map/buffer machinery — print() owns that for a whole document; this is the printer’s other, narrower entry point, sharing the same internal recursion rather than a second copy.
raw_statement_texts
1B.5e: the text of every opaque statement (TsStmt::raw, raw_using, a Verbatim) in stmts, at any depth — inside a function body, a try, a switch case or an object method, not only at the top level. A producer that reads a tree for the names it uses asks for this to check what the tree cannot see: a shallow raw_text() over the top-level statements alone misses a nested one.
text_idents
1A.39b (Decision D): every TsExpr::Ident of program that is not an identifier path ([A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*) and every TsBindingName::Ident that is not an identifier, sorted and deduplicated. Such a text is expression text or a name built from it held in a variable-like node: it hides what it uses from unbound_names and from the printer’s precedence. Member chains (globalThis.Number, this.state) pass: they print as they read and their head is what the closure sees.
type_only_value_uses
#2045: every name program uses as a value that only a type-only import binds (import { type Status } then Status.Active): a TS1361 (cannot be used as a value because it was imported using 'import type'). Opaque text is not searched for uses, as in unbound_names.
unbound_names
Every name program uses, in type or value position, that it does not bind, sorted and deduplicated.
unbound_names_in
unbound_names_providing over a module’s statements as a slice, for a caller that holds them before it has a TsProgram (an emitter deriving a module’s own header from the body it just built).
unbound_names_providing
unbound_names for a module whose imports provided knows: a name that provided accepts is never hidden by the global tables.
value_imports
#2045: each (specifier, name) a structured named import brings in as a value: every entry of an import { … } but its type X ones, none of an import type { … }. Namespace and opaque-text imports are not reported.
verbatim_violations
Scan text (a Verbatim statement’s own wrapped TypeScript) for every line matching one of the six banned constructs. Order of the checks within a line matters only for which construct label a line already matching two patterns gets — real emitted lines don’t do that in practice, so the first match wins and the rest of that line isn’t checked further.