bynk_ts/source_map.rs
1//! Source-map construction (debugging track; ADR 0103). Relocated from
2//! `bynk-emit/src/emitter/source_map.rs` unchanged (P7.5, #1307, Decision B)
3//! — `bynk-emit`'s current lowering keeps calling this exact API, from its
4//! new crate path, for as long as it still splices handler/test-case bodies
5//! through local buffers. [`crate::printer::print`] uses the same type a
6//! second, simpler way: no [`SourceMapBuilder::merge`] call, since the
7//! printer owns one buffer for the whole [`crate::TsProgram`] and never
8//! splices — `record`ing directly from each statement's own span as it
9//! writes is what closes R7.4 ("the source map is produced by the printer
10//! from `TsNode.span`. No phase before the printer records an offset")
11//! structurally, for that path, from this slice.
12//!
13//! It records **checkpoints** — `(byte offset into the generated buffer,
14//! source id, source span)` triples — at statement, match-arm, and
15//! declaration boundaries, and resolves them into a source-map v3 document
16//! once the buffer is complete.
17//!
18//! The design is line-level and statement-anchored (ADR 0103 D1). A
19//! checkpoint marks "every generated line from here until the next
20//! checkpoint maps to this source span" — the nearest-enclosing-statement
21//! rule (D2).
22//!
23//! **v0.70 — spliced bodies and multiple sources.** Free-function bodies
24//! lower straight into the main buffer, so their byte offsets are correct.
25//! Service / agent handler bodies and test-case bodies lower into a *local*
26//! buffer that is later spliced into the module, so their offsets must be
27//! **rebased at the splice**. [`SourceMapBuilder::merge`] does that,
28//! line-anchored so it is correct for both verbatim (`push_str`) and
29//! line-by-line (indent-prepended) splices — both preserve line structure. A
30//! test module aggregates several `.bynk` files, so the builder carries a
31//! list of `sources` and each checkpoint a source id.
32
33use bynk_syntax::span::{LineIndex, Span};
34
35/// Escape a string for interpolation into a JSON string literal. Vendored
36/// from `bynk_project::json_string` (P7.5, #1307, Decision A) rather than
37/// depending on the whole of `bynk-project` for one ~20-line, dependency-free
38/// function — this crate depends on `bynk-syntax` only (`src/lib.rs`'s own
39/// module doc).
40fn json_string(s: &str) -> String {
41 let mut out = String::with_capacity(s.len() + 2);
42 out.push('"');
43 for c in s.chars() {
44 match c {
45 '"' => out.push_str("\\\""),
46 '\\' => out.push_str("\\\\"),
47 '\n' => out.push_str("\\n"),
48 '\r' => out.push_str("\\r"),
49 '\t' => out.push_str("\\t"),
50 // The rest of C0 has no short escape; `\u00xx` is the only form.
51 c if (c as u32) < 0x20 => {
52 use std::fmt::Write as _;
53 let _ = write!(out, "\\u{:04x}", c as u32);
54 }
55 c => out.push(c),
56 }
57 }
58 out.push('"');
59 out
60}
61
62/// Accumulates source-map checkpoints during emission. Lives behind a
63/// `RefCell` on `bynk-emit`'s `LowerCtx` so the deep lowering chain and the
64/// declaration loop can both record without fighting the borrow checker. A
65/// *sub*-builder (one per spliced body) records against its local buffer,
66/// then is [`merge`](Self::merge)d into the module builder at the splice
67/// offset.
68#[derive(Debug, Default, Clone, PartialEq)]
69pub struct SourceMapBuilder {
70 /// `(name, text)` per source file referenced by this map. Index 0 is the
71 /// primary source (the file being emitted); test modules add more.
72 sources: Vec<(String, String)>,
73 /// `(generated byte offset, source id, source span)`, in record order —
74 /// which is *not* guaranteed sorted once `merge` injects a spliced
75 /// body's checkpoints, so `to_v3` sorts by generated line.
76 checkpoints: Vec<(usize, usize, Span)>,
77}
78
79impl SourceMapBuilder {
80 pub fn new() -> Self {
81 Self::default()
82 }
83
84 /// Register a source file, returning its id (index into `sources`).
85 /// Idempotent by name, so a test module that registers the same `.bynk`
86 /// file for several cases reuses one id. The first registered source is
87 /// the primary one (`record` targets it).
88 pub fn add_source(&mut self, name: impl Into<String>, text: impl Into<String>) -> usize {
89 let name = name.into();
90 if let Some(i) = self.sources.iter().position(|(n, _)| *n == name) {
91 return i;
92 }
93 self.sources.push((name, text.into()));
94 self.sources.len() - 1
95 }
96
97 /// Record that generated text from `byte_offset` onward originates at
98 /// `span` in the **primary** source (id 0), until the next checkpoint.
99 /// Callers pass `out.len()` before appending the statement's text.
100 /// Sub-builders use this; `merge` re-tags the source id.
101 pub fn record(&mut self, byte_offset: usize, span: Span) {
102 self.record_in(byte_offset, 0, span);
103 }
104
105 /// [`record`](Self::record) against the registered source `source_id`
106 /// rather than the primary one: the printer records a statement's span in
107 /// whichever source the statement it is printing belongs to (1A.15).
108 pub fn record_in(&mut self, byte_offset: usize, source_id: usize, span: Span) {
109 if let Some(last) = self.checkpoints.last_mut()
110 && last.0 == byte_offset
111 && last.1 == source_id
112 {
113 last.2 = span;
114 return;
115 }
116 self.checkpoints.push((byte_offset, source_id, span));
117 }
118
119 /// Every checkpoint as `(generated offset, span)`, in recording order: what
120 /// `bynk_ts::print_stmt_with_spans` reports.
121 pub(crate) fn checkpoint_spans(&self) -> Vec<(usize, Span)> {
122 self.checkpoints
123 .iter()
124 .map(|&(offset, _, span)| (offset, span))
125 .collect()
126 }
127
128 /// Shift every recorded checkpoint's generated-buffer offset forward by
129 /// `delta` bytes. For a sub-builder whose checkpoints were recorded
130 /// against a local buffer's *pre*-splice contents, call this right after
131 /// text is inserted before byte 0 of that buffer (e.g. `emit_service`'s
132 /// subscriber-filter/schema-gate prologue, #1363) so the checkpoints
133 /// stay correct against the buffer's new contents before [`merge`](Self::merge) reads
134 /// them — `merge` resolves each checkpoint's line against `sub_text` as
135 /// handed to it, which has no way to know a prologue was spliced in
136 /// ahead of the recorded offsets.
137 pub fn shift_checkpoints(&mut self, delta: usize) {
138 for checkpoint in &mut self.checkpoints {
139 checkpoint.0 += delta;
140 }
141 }
142
143 /// Merge a sub-builder's body checkpoints into this module builder,
144 /// rebased to the spliced body's position and re-tagged to `source_id`
145 /// (v0.70).
146 ///
147 /// `sub_text` is the body's local buffer; `out` is the module buffer
148 /// *after* the body has been spliced into it; `base_byte` is
149 /// `out.len()` captured *before* the splice (where the body's first
150 /// line starts in `out`). The merge is **line-anchored**: a checkpoint
151 /// on body line *k* maps to module line `base_line + k`, so it is
152 /// correct whether the splice appended the body verbatim (handlers) or
153 /// rebuilt it line-by-line with indentation (tests) — both preserve
154 /// line structure. Column is irrelevant: maps are line-level.
155 pub fn merge(
156 &mut self,
157 sub: &SourceMapBuilder,
158 sub_text: &str,
159 out: &str,
160 base_byte: usize,
161 source_id: usize,
162 ) {
163 let sub_starts = generated_line_starts(sub_text);
164 let out_starts = generated_line_starts(out);
165 let base_line = line_of_offset(&out_starts, base_byte);
166 for &(off, _sub_src, span) in &sub.checkpoints {
167 let body_line = line_of_offset(&sub_starts, off);
168 let out_line = base_line + body_line;
169 if out_line < out_starts.len() {
170 self.checkpoints
171 .push((out_starts[out_line], source_id, span));
172 }
173 }
174 }
175
176 /// Serialise to a source-map v3 JSON document over the registered
177 /// `sources`. `generated` is the finished buffer; `generated_file` is
178 /// the `file` field. Returns `None` when nothing resolves (no sources,
179 /// or no in-range checkpoint).
180 pub fn to_v3(&self, generated: &str, generated_file: &str) -> Option<String> {
181 if self.sources.is_empty() {
182 return None;
183 }
184 let line_starts = generated_line_starts(generated);
185 // One line index per source, built once: a checkpoint resolves per
186 // emitted line, so `line_col`'s scan-from-0 would be O(checkpoints ×
187 // source size) (#732). Binary-search each lookup instead.
188 let source_indexes: Vec<LineIndex> = self
189 .sources
190 .iter()
191 .map(|(_, t)| LineIndex::new(t))
192 .collect();
193 // Resolve each checkpoint to (generated line, source id, source line, col),
194 // all 0-based. Drop any whose span falls outside its source's text (a
195 // defensive guard for multi-file aggregation).
196 let mut resolved: Vec<(usize, usize, usize, usize)> = Vec::new();
197 for &(offset, src, span) in &self.checkpoints {
198 let Some((_, text)) = self.sources.get(src) else {
199 continue;
200 };
201 if span.start > text.len() {
202 continue;
203 }
204 let gen_line = line_of_offset(&line_starts, offset);
205 let (sl, sc) = source_indexes[src].line_col(text, span.start);
206 resolved.push((gen_line, src, sl - 1, sc - 1));
207 }
208 if resolved.is_empty() {
209 return None;
210 }
211 // Stable sort by generated line: `merge` injects body checkpoints out of
212 // record order, and the forward pass below needs ascending lines. For ties
213 // the later-recorded (more specific) checkpoint stays last and wins.
214 resolved.sort_by_key(|r| r.0);
215
216 let total_lines = line_starts.len();
217 let first_line = resolved[0].0;
218
219 let mut mappings = String::new();
220 for _ in 0..first_line {
221 mappings.push(';');
222 }
223 // Previous-segment state for VLQ delta encoding (source id, source line,
224 // source column persist across lines; generated column is always 0 here).
225 let (mut prev_src, mut prev_sl, mut prev_sc) = (0i64, 0i64, 0i64);
226 let mut ri = 0usize;
227 for line in first_line..total_lines {
228 if line > first_line {
229 mappings.push(';');
230 }
231 while ri + 1 < resolved.len() && resolved[ri + 1].0 <= line {
232 ri += 1;
233 }
234 let (_, src, sl, sc) = resolved[ri];
235 let (src, sl, sc) = (src as i64, sl as i64, sc as i64);
236 vlq_encode(0, &mut mappings); // generated column 0
237 vlq_encode(src - prev_src, &mut mappings);
238 vlq_encode(sl - prev_sl, &mut mappings);
239 vlq_encode(sc - prev_sc, &mut mappings);
240 prev_src = src;
241 prev_sl = sl;
242 prev_sc = sc;
243 }
244
245 let names = self
246 .sources
247 .iter()
248 .map(|(n, _)| json_string(n))
249 .collect::<Vec<_>>()
250 .join(",");
251 let contents = self
252 .sources
253 .iter()
254 .map(|(_, t)| json_string(t))
255 .collect::<Vec<_>>()
256 .join(",");
257 Some(format!(
258 "{{\"version\":3,\"file\":{},\"sources\":[{}],\"sourcesContent\":[{}],\"names\":[],\"mappings\":{}}}",
259 json_string(generated_file),
260 names,
261 contents,
262 json_string(&mappings),
263 ))
264 }
265}
266
267/// Byte offset of the start of each generated line (line 0 starts at 0).
268fn generated_line_starts(s: &str) -> Vec<usize> {
269 let mut starts = vec![0usize];
270 for (i, b) in s.bytes().enumerate() {
271 if b == b'\n' {
272 starts.push(i + 1);
273 }
274 }
275 starts
276}
277
278/// 0-based generated line containing `offset`, by binary search over line starts.
279fn line_of_offset(line_starts: &[usize], offset: usize) -> usize {
280 match line_starts.binary_search(&offset) {
281 Ok(i) => i,
282 Err(i) => i - 1,
283 }
284}
285
286/// Base64 VLQ-encode a single signed value, appending to `out`.
287fn vlq_encode(value: i64, out: &mut String) {
288 const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
289 let mut v = if value < 0 {
290 ((-value) as u64) << 1 | 1
291 } else {
292 (value as u64) << 1
293 };
294 loop {
295 let mut digit = (v & 0b11111) as usize;
296 v >>= 5;
297 if v != 0 {
298 digit |= 0b100000;
299 }
300 out.push(B64[digit] as char);
301 if v == 0 {
302 break;
303 }
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 fn build(generated: &str, b: &SourceMapBuilder) -> String {
312 b.to_v3(generated, "x.ts").unwrap()
313 }
314
315 /// Pull the `mappings` string back out of the hand-built JSON document.
316 fn extract_mappings(json: &str) -> String {
317 let key = "\"mappings\":\"";
318 let start = json.find(key).unwrap() + key.len();
319 let rest = &json[start..];
320 rest[..rest.find('"').unwrap()].to_string()
321 }
322
323 /// Decode each generated line's `(source_id, source_line)` (0-based), for the
324 /// single-segment-per-line maps this builder emits.
325 fn decode(mappings: &str) -> Vec<Option<(i64, i64)>> {
326 const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
327 let dec = |s: &str| -> Vec<i64> {
328 let mut out = Vec::new();
329 let (mut shift, mut acc) = (0i64, 0i64);
330 for &c in s.as_bytes() {
331 let d = B64.iter().position(|&b| b == c).unwrap() as i64;
332 acc += (d & 0b11111) << shift;
333 if d & 0b100000 != 0 {
334 shift += 5;
335 } else {
336 out.push(if acc & 1 == 1 { -(acc >> 1) } else { acc >> 1 });
337 shift = 0;
338 acc = 0;
339 }
340 }
341 out
342 };
343 let (mut src, mut sl) = (0i64, 0i64);
344 let mut lines = Vec::new();
345 for seg in mappings.split(';') {
346 if seg.is_empty() {
347 lines.push(None);
348 continue;
349 }
350 let f = dec(seg); // [genCol, srcIdxDelta, srcLineDelta, srcCol]
351 src += f[1];
352 sl += f[2];
353 lines.push(Some((src, sl)));
354 }
355 lines
356 }
357
358 #[test]
359 fn vlq_round_numbers() {
360 let mut s = String::new();
361 for (v, want) in [(0, "A"), (1, "C"), (-1, "D"), (16, "gB")] {
362 s.clear();
363 vlq_encode(v, &mut s);
364 assert_eq!(s, want);
365 }
366 }
367
368 #[test]
369 fn single_source_maps_each_line_to_nearest_checkpoint() {
370 let source = "header\nstmtA\nstmtB\n";
371 let off_a = source.find("stmtA").unwrap();
372 let off_b = source.find("stmtB").unwrap();
373 let generated = "g0\ng1\ng2\ng3\n";
374 let g2 = generated.find("g2").unwrap();
375
376 let mut b = SourceMapBuilder::new();
377 b.add_source("x.bynk", source);
378 b.record(0, Span::new(off_a, off_a + 5)); // gen line 0 -> src line 1 (0-based)
379 b.record(g2, Span::new(off_b, off_b + 5)); // gen line 2 -> src line 2
380
381 let json = build(generated, &b);
382 assert!(json.contains("\"sources\":[\"x.bynk\"]"));
383 let lines = decode(&extract_mappings(&json));
384 // All from source 0; lines 1,1,2,2,(trailing 2).
385 assert_eq!(
386 lines,
387 vec![
388 Some((0, 1)),
389 Some((0, 1)),
390 Some((0, 2)),
391 Some((0, 2)),
392 Some((0, 2))
393 ]
394 );
395 }
396
397 #[test]
398 fn merge_line_anchors_a_spliced_body_under_a_second_source() {
399 // Module buffer: a declaration line from source 0, then a spliced body
400 // (two lines) from source 1, indent-prepended (line-by-line splice).
401 let mod_src = "service api\n";
402 let body_src = " let a = 1\n let b = 2\n"; // the .bynk body, source 1
403 let off_a = body_src.find("let a").unwrap();
404 let off_b = body_src.find("let b").unwrap();
405
406 let mut module = SourceMapBuilder::new();
407 let s0 = module.add_source("mod.bynk", mod_src);
408 assert_eq!(s0, 0);
409 // The module's own declaration checkpoint (source 0, line 1).
410 module.record(0, Span::new(0, 7));
411
412 // Lower the body into a local buffer with a sub-builder.
413 let sub_text = "const a = 1;\nconst b = 2;\n";
414 let mut sub = SourceMapBuilder::new();
415 sub.record(0, Span::new(off_a, off_a + 5)); // body line 0 -> body src line 0
416 let bl1 = sub_text.find("const b").unwrap();
417 sub.record(bl1, Span::new(off_b, off_b + 5)); // body line 1 -> body src line 1
418
419 // Splice the body into the module buffer line-by-line with indentation
420 // (mirrors the real test-body splice), capturing base before the splice.
421 let mut out = String::from("export const api = {};\n"); // gen line 0
422 let base = out.len();
423 for line in sub_text.lines() {
424 out.push_str(" ");
425 out.push_str(line);
426 out.push('\n');
427 }
428 // gen line 1 <- body line 0, gen line 2 <- body line 1.
429 let s1 = module.add_source("body.bynk", body_src);
430 module.merge(&sub, sub_text, &out, base, s1);
431
432 let json = module.to_v3(&out, "mod.ts").unwrap();
433 assert!(json.contains("\"sources\":[\"mod.bynk\",\"body.bynk\"]"));
434 let lines = decode(&extract_mappings(&json));
435 // gen 0 -> (src0, line0); gen 1 -> (src1, line0); gen 2 -> (src1, line1).
436 assert_eq!(lines[0], Some((0, 0)));
437 assert_eq!(lines[1], Some((1, 0)));
438 assert_eq!(lines[2], Some((1, 1)));
439 }
440
441 #[test]
442 fn shift_checkpoints_keeps_a_prepended_prologue_from_shifting_body_lines() {
443 // Mirrors `emit_service`'s own sequence (#1363): a sub-builder records
444 // checkpoints against the body's pre-insert text, a one-line prologue
445 // is then prepended to the *body buffer itself* (not `sub`'s view of
446 // it), and `merge` is finally called with the post-insert buffer.
447 let body_src = " let a = 1\n let b = 2\n"; // the .bynk body
448 let off_a = body_src.find("let a").unwrap();
449 let off_b = body_src.find("let b").unwrap();
450
451 let mut sub = SourceMapBuilder::new();
452 let mut body_out = "const a = 1;\nconst b = 2;\n".to_string();
453 sub.record(0, Span::new(off_a, off_a + 5)); // body line 0 -> body src line 0
454 let bl1 = body_out.find("const b").unwrap();
455 sub.record(bl1, Span::new(off_b, off_b + 5)); // body line 1 -> body src line 1
456
457 // The prologue insert `emit_service` does, plus the rebase this fix adds.
458 let prologue = "if (!(guard)) return undefined;\n";
459 body_out.insert_str(0, prologue);
460 sub.shift_checkpoints(prologue.len());
461
462 let mut module = SourceMapBuilder::new();
463 let s0 = module.add_source("body.bynk", body_src);
464 let mut out = String::from("export const api = {\n"); // gen line 0
465 let base = out.len();
466 out.push_str(&body_out); // verbatim splice, as emit_service does
467 out.push_str("};\n");
468 module.merge(&sub, &body_out, &out, base, s0);
469
470 let json = module.to_v3(&out, "mod.ts").unwrap();
471 let lines = decode(&extract_mappings(&json));
472 // gen 1 is the prologue line (still tagged from the nearest-preceding
473 // checkpoint); gen 2 is `const a = 1;` -> src line 0; gen 3 is
474 // `const b = 2;` -> src line 1 — not shifted onto each other's lines.
475 assert_eq!(
476 lines[2],
477 Some((0, 0)),
478 "body's own first statement keeps its real source line"
479 );
480 assert_eq!(
481 lines[3],
482 Some((0, 1)),
483 "body's own second statement keeps its real source line"
484 );
485 }
486
487 #[test]
488 fn empty_builder_serialises_to_none() {
489 assert!(SourceMapBuilder::new().to_v3("x\n", "x.ts").is_none());
490 }
491
492 #[test]
493 fn json_string_escapes_control_characters_and_quotes() {
494 assert_eq!(json_string("a\"b"), "\"a\\\"b\"");
495 assert_eq!(json_string("a\\b"), "\"a\\\\b\"");
496 assert_eq!(json_string("a\nb"), "\"a\\nb\"");
497 assert_eq!(json_string("a\u{1}b"), "\"a\\u0001b\"");
498 assert_eq!(json_string("plain"), "\"plain\"");
499 }
500}