bynk_ts/printer/fragment.rs
1use super::MergeTarget;
2use super::decl::render_class_method;
3use super::expr::render_expr;
4use super::multiline::render_multiline_object_entry;
5use super::stmt::render_stmt;
6use super::types::render_type;
7#[cfg(doc)]
8use crate::program::{TsArrowBody, TsDecl, TsProgram};
9use crate::program::{TsClassMethod, TsExpr, TsObjectEntry, TsStmt, TsStmtKind, TsType};
10use crate::source_map::SourceMapBuilder;
11use bynk_syntax::span::Span;
12
13/// Print a single [`TsType`] on its own — the real callers this closes R7.2
14/// for (`bynk-emit`'s `ts_type_ref*`/`ts_ty` families, P7.9, #1315) each
15/// want one type fragment to interpolate into a larger, still-hand-built
16/// line (a field's own type annotation, a parameter list, …), not a whole
17/// [`TsProgram`]. No source-map/buffer machinery — [`print()`](super::print) owns that
18/// for a whole document; this is the printer's other, narrower entry
19/// point, sharing the same internal recursion rather than a second copy.
20pub fn print_type(ty: &TsType) -> String {
21 let mut out = String::new();
22 render_type(&mut out, ty);
23 out
24}
25
26/// Print a single [`TsExpr`] on its own — the expression-level sibling of
27/// [`print_type`]'s own "one fragment, not a whole document" entry point.
28/// Arc C, step (11) (#1388) need: `emit_icu_placeholder`'s own `Select` arm
29/// stays one opaque, hand-built block-bodied IIFE (at the time, `TsExpr::
30/// Arrow` had no block-body variant at all, and extending it for that one
31/// site was rejected as disproportionate) — its own arm VALUES,
32/// `emit_sub_message`'s now-real `TsExpr` results, still need stringifying
33/// back into that opaque host text. #1435 (Arc E slice 1) later added
34/// [`TsArrowBody::Block`] for a genuinely different real site
35/// (`serialisation.rs`'s `Float` guard); `emit_icu_placeholder`'s own
36/// `Select` arm was not reconverted along with it — out of that slice's own
37/// scope — so this call site's opaque text stays exactly as it was. No
38/// source-map/buffer machinery, matching [`print_type`]/[`print_stmt`]'s
39/// own scope exactly.
40pub fn print_expr(expr: &TsExpr) -> String {
41 let mut out = String::new();
42 render_expr(&mut out, expr, 0, &mut None);
43 out
44}
45
46/// Print a single [`TsStmt`] on its own, at `depth` — the statement-level
47/// sibling of [`print_type`]'s own "one fragment, not a whole document"
48/// entry point. `bynk-emit`'s own #1333 need (`emit_doc_block`, a shared
49/// helper spliced into ~14 still-unconverted callers' own buffers) wants
50/// one statement's own printed text at a caller-supplied depth, not a
51/// whole [`TsProgram`] — no source-map/buffer machinery, matching
52/// [`print_type`]'s own scope exactly, and reusing `render_stmt`'s own
53/// exhaustive per-kind dispatch (this module's own private renderer)
54/// rather than a second copy.
55/// Review of #1402: a `TsStmtKind::Raw` nested inside a `Switch` case's own
56/// body (`emit_stub_rhs`'s own `ReturnsEach` dispatch, Arc C slice 33,
57/// `tests_emit.rs` slice C) carries the identical "no indent of its own,
58/// pre-indented at a fixed absolute depth" hazard `render_class_method`'s
59/// and `render_multiline_object_entry`'s own `debug_assert!`s already guard
60/// — `stmt_contains_raw` already recurses into `Switch` cases, so the same
61/// check applies here, this fragment entry point's own first `Raw`-bearing
62/// `Switch` caller. A bare `Raw` passed directly as `stmt` itself is exempt
63/// (not a false negative — `render_stmt`'s own `Raw` arm never reads
64/// `depth` at all, so calling `print_stmt` on a bare `Raw` is safe at any
65/// depth, the established `print_stmt_renders_raw_text_verbatim_with_no_
66/// added_indent_or_punctuation` contract below): only a Raw *nested inside*
67/// a depth-using wrapper (like this `Switch` case) is the real hazard.
68pub fn print_stmt(stmt: &TsStmt, depth: usize) -> String {
69 debug_assert!(
70 depth == 0 || matches!(stmt.kind, TsStmtKind::Raw(..)) || !stmt_contains_raw(stmt),
71 "print_stmt: a Raw-bearing statement's own baked-in indent only matches depth 0"
72 );
73 let mut out = String::new();
74 render_stmt(&mut out, stmt, depth, None);
75 out
76}
77
78/// [`print_stmt`]'s own sibling (#1477), the `TsDecl::Function`-body
79/// counterpart to [`print_class_method_and_merge`]: identical rendering,
80/// but merges any `nested_map` `stmt` carries — on `stmt` itself, or on
81/// anything nested inside it (a function's body, a class's constructor/
82/// methods, …) — into `map` as it prints, at the real print-time offset —
83/// the same offset `bynk-emit`'s own `emit_free_fn` (`emitter/emit.rs`) used
84/// to recover by exact arithmetic over the returned text, guarded by a
85/// `debug_assert!`, before #1480 converted it to set `nested_map` directly
86/// instead. Kept separate from `print_stmt` itself so every existing
87/// caller's own call sites are untouched. `source_id` is `map`'s
88/// own registered source this statement's content belongs to (see
89/// this crate's own private `MergeTarget`'s own doc for why this can't just be hardcoded).
90///
91/// **Appends to the caller's own `out`, unlike `print_stmt`'s own
92/// return-a-fresh-`String` shape** — the merge computes each checkpoint's
93/// absolute offset from `out.len()` *as this statement's own text is
94/// written*, so it must be the caller's real, already-populated buffer, not
95/// a throwaway local one starting at 0. Returning a fresh string here (the
96/// first shape this function took, caught before merge) would silently
97/// record every checkpoint at the wrong offset the moment the caller
98/// spliced the returned text anywhere but the very start of its own buffer.
99pub fn print_stmt_and_merge(
100 out: &mut String,
101 stmt: &TsStmt,
102 depth: usize,
103 map: &mut SourceMapBuilder,
104 source_id: usize,
105) {
106 debug_assert!(
107 depth == 0 || matches!(stmt.kind, TsStmtKind::Raw(..)) || !stmt_contains_raw(stmt),
108 "print_stmt_and_merge: a Raw-bearing statement's own baked-in indent only matches depth 0"
109 );
110 render_stmt(out, stmt, depth, Some(MergeTarget { map, source_id }));
111}
112
113/// [`print_stmt`], also reporting where each statement that carries a
114/// [`TsStmt::span`] starts in the printed text (back-half paydown 1A.11,
115/// Decision C of #3712). The offset is a byte offset into the returned text,
116/// at the start of the statement's own line, so *before* its indentation; an
117/// inline `if`/`else` branch (no braces, same line as its `if`) starts after
118/// the space that separates it. The statement itself, then every statement
119/// nested in it, is reported in the order printed; a statement with no span
120/// is not reported.
121///
122/// It is the mechanism S5 of the statement-emitter design note (#3708) moves
123/// source-map recording onto, applied one statement at a time: the adapter in
124/// `bynk-emit` adds the indentation it writes before each line and records the
125/// adjusted offsets, which is what a nested checkpoint needs.
126pub fn print_stmt_with_spans(stmt: &TsStmt, depth: usize) -> (String, Vec<(usize, Span)>) {
127 debug_assert!(
128 depth == 0 || matches!(stmt.kind, TsStmtKind::Raw(..)) || !stmt_contains_raw(stmt),
129 "print_stmt_with_spans: a Raw-bearing statement's own baked-in indent only matches depth 0"
130 );
131 let mut map = SourceMapBuilder::new();
132 let mut out = String::new();
133 render_stmt(
134 &mut out,
135 stmt,
136 depth,
137 Some(MergeTarget {
138 map: &mut map,
139 source_id: 0,
140 }),
141 );
142 (out, map.checkpoint_spans())
143}
144
145/// Print a single [`TsObjectEntry`] on its own, at `depth` — the
146/// object-entry sibling of [`print_stmt`]'s own "one fragment, not a whole
147/// document" entry point, `depth` meaning the SAME thing it does for this
148/// crate's own internal multi-line-object renderer: the *object's* own
149/// depth, so the entry itself lands one level deeper, matching an object built by that
150/// renderer exactly. #1337's own real need: `emit_attached_methods` (a
151/// shared helper spliced into `emit_refined_type`/`emit_record_type`/
152/// `emit_sum_type`'s own still-unconverted `&mut String` buffers) now
153/// returns `Vec<TsObjectEntry>` instead of writing text directly — each
154/// caller renders the returned entries one at a time through this, the
155/// same P7.9/#1333 "keep the caller's own signature, print just the
156/// fragment" pattern applied to an object-entry-shaped fragment instead of
157/// a whole statement or type.
158///
159/// Review of #1338, finding 3: a `TsStmtKind::Raw` body statement (e.g.
160/// `emit_method`'s own opaque `lower.rs`-sourced body, or `emit_refined_
161/// type`'s own opaque `emit_refined_checks`-sourced guard body, #1339's
162/// second real use) carries NO indent of its own — its text is captured
163/// pre-indented at a fixed absolute depth by its own caller — so it only
164/// renders correctly when `depth` is `0`. The guard for this now lives in
165/// `render_multiline_object_entry` itself (a private renderer, so named
166/// here in text rather than linked — moved there by review of #1340,
167/// finding 1: this function's own copy missed the `TsExpr::
168/// multiline_object_entries`/`render_expr` call path #1339 added, which
169/// reaches that renderer directly, never through this one), so it fires
170/// for every caller, not just this entry point.
171pub fn print_object_entry(entry: &TsObjectEntry, depth: usize) -> String {
172 let mut out = String::new();
173 render_multiline_object_entry(&mut out, entry, depth, None);
174 out
175}
176
177/// Whether `stmts`, or any block/branch/case nested inside them at any
178/// depth, contains a [`TsStmtKind::Raw`] — the recursive check
179/// [`render_class_method`]'s and [`render_multiline_object_entry`]'s own
180/// `debug_assert!`s need. Review of #1374: a top-level-only scan
181/// (`body.iter().any(...)`) is blind to a `Raw` buried inside an `If`'s own
182/// `Block` — `emit_agent`'s own `commitState` (#1373) is exactly this shape,
183/// a transition's own hoisted-statement `Raw`s sitting inside
184/// `if (__prior !== undefined) { ... }` — so the two guards this exists for
185/// would have silently missed exactly the case they exist to catch. Every
186/// `TsStmtKind` variant is named explicitly, not a wildcard, matching this
187/// crate's own exhaustiveness discipline.
188pub(super) fn contains_raw(stmts: &[TsStmt]) -> bool {
189 stmts.iter().any(stmt_contains_raw)
190}
191
192fn stmt_contains_raw(stmt: &TsStmt) -> bool {
193 match &stmt.kind {
194 TsStmtKind::Raw(..) => true,
195 TsStmtKind::Verbatim { .. }
196 | TsStmtKind::Decl(_)
197 | TsStmtKind::Const { .. }
198 | TsStmtKind::Let { .. }
199 | TsStmtKind::LetList(_)
200 | TsStmtKind::ExprStmt(_)
201 | TsStmtKind::Return(_)
202 | TsStmtKind::Throw(_)
203 | TsStmtKind::Continue(_)
204 | TsStmtKind::Break(_)
205 | TsStmtKind::Assign { .. }
206 | TsStmtKind::Comment(_)
207 | TsStmtKind::DocComment(_)
208 | TsStmtKind::Blank
209 | TsStmtKind::Increment(_) => false,
210 TsStmtKind::If {
211 then_branch,
212 else_branch,
213 ..
214 } => {
215 stmt_contains_raw(then_branch) || else_branch.as_deref().is_some_and(stmt_contains_raw)
216 }
217 TsStmtKind::ForOf { body, .. }
218 | TsStmtKind::For { body, .. }
219 | TsStmtKind::While { body, .. }
220 | TsStmtKind::Labelled { body, .. } => stmt_contains_raw(body),
221 TsStmtKind::TryCatch {
222 try_block,
223 catch_block,
224 finally_block,
225 ..
226 } => {
227 stmt_contains_raw(try_block)
228 || catch_block.as_deref().is_some_and(stmt_contains_raw)
229 || finally_block.as_deref().is_some_and(stmt_contains_raw)
230 }
231 TsStmtKind::Block(stmts) | TsStmtKind::InlineBlock(stmts) => contains_raw(stmts),
232 TsStmtKind::Switch { cases, .. } => cases.iter().any(|c| contains_raw(&c.body)),
233 }
234}
235
236/// Print a single [`TsClassMethod`] on its own, at `depth` — the
237/// class-method sibling of [`print_object_entry`]'s own "one fragment, not
238/// a whole document" entry point. `depth` means the *class's* own depth
239/// (matching `print_object_entry`'s own convention exactly), so the method
240/// itself lands at `depth + 1`, its own body at `depth + 2`. #1359's own
241/// real need: `emit_provider`'s own class wrapper stays hand-written text
242/// (each method's own body needs a per-method source-map sub-builder/
243/// `merge`, and the wrapper's own real spacing — no blank line between
244/// methods — genuinely differs from [`TsDecl::Class`]'s own "one blank
245/// line before each method" policy, `events_fanout.rs`'s real convention,
246/// #1317), so each real method prints through here directly into that
247/// still-hand-written wrapper. Deliberately no automatic blank-line
248/// insertion of its own — the same "caller controls spacing" contract
249/// `print_object_entry` already established.
250pub fn print_class_method(method: &TsClassMethod, depth: usize) -> String {
251 let mut out = String::new();
252 render_class_method(&mut out, method, depth, None);
253 out
254}
255
256/// [`print_class_method`]'s own sibling (#1477): identical rendering, but
257/// merges any of `method.body`'s own direct-child `nested_map`s into `map`
258/// as they print, at the real print-time offset — no reverse-engineering
259/// the offset from the returned text afterward, the way `bynk-emit`'s own
260/// `emit_class_method_and_merge_source_map` (`emitter/emit.rs`) has to
261/// today. Kept as a separate function, not an added parameter on
262/// `print_class_method` itself, so every existing caller's own call sites
263/// are untouched — this is a strict addition.
264///
265/// Appends to the caller's own `out`, the same "must be the real buffer,
266/// not a throwaway local one" reasoning [`print_stmt_and_merge`]'s own doc
267/// explains in full. `source_id`: see this crate's own private `MergeTarget`'s own doc.
268pub fn print_class_method_and_merge(
269 out: &mut String,
270 method: &TsClassMethod,
271 depth: usize,
272 map: &mut SourceMapBuilder,
273 source_id: usize,
274) {
275 render_class_method(out, method, depth, Some(MergeTarget { map, source_id }));
276}