Skip to main content

bynk_driver/
coverage.rs

1//! `bynkc test --coverage` — remap V8 line coverage onto `.bynk` source.
2//!
3//! The test runner already owns the two artefacts a coverage tool needs and a
4//! user cannot reconstruct: it launches the `node` process that executes the
5//! suite, and it holds the source maps from `.bynk` → emitted `.ts`. This module
6//! is the "one genuinely new piece" the coverage proposal (issue #854, ADR
7//! recorded at merge) calls out: it reads the raw V8 coverage the runtime writes
8//! to `NODE_V8_COVERAGE`, and attributes each executed / unexecuted line back to
9//! `.bynk` source through **two** line-level source-map hops:
10//!
11//! 1. `out-js/**/*.js.map` — tsc's map, `.js` line → emitted `.ts` line. `tsc`
12//!    does **not** chain input maps, so this hop only reaches the `.ts`.
13//! 2. `out/**/*.ts.map` — the emitter's map (ADR 0103), `.ts` line → `.bynk`
14//!    line. Statement-anchored and line-level (generated column always 0).
15//!
16//! Composed, a covered `.js` line lands on a `.bynk` line. Emitted glue with no
17//! `.bynk` origin (codec wrappers, capability injection, the module header) is
18//! **unmapped** in hop 2, so it contributes nothing — it is counted as
19//! out-of-scope, never as uncovered user code (the proposal's map-fidelity
20//! mitigation, for free).
21//!
22//! **Decisions realised here** (recorded in the ADR): line/statement coverage
23//! only, no branch coverage (DECISION B) — a `.bynk` line is *covered* if any
24//! generated line mapping to it executed; and the measured set excludes the
25//! `tests/` tree and the workers scaffold (DECISION D), filtered once on the
26//! `out-js`-relative path of the executed `.js` — the emitted tree's own
27//! top-level `tests/`/`workers/` dirs — before the maps are even consulted. The
28//! `.bynk` side is deliberately *not* re-filtered, so a user source that merely
29//! lives under a dir named `tests`/`workers` is still measured.
30
31use std::collections::{BTreeMap, HashMap};
32use std::path::{Component, Path, PathBuf};
33
34use serde::Deserialize;
35
36/// Per-`.bynk`-file line coverage, keyed by a project-relative display path.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct FileCoverage {
39    /// Project-relative `.bynk` path (forward-slashed), e.g. `src/limiter.bynk`.
40    pub path: String,
41    /// Covered executable lines (1-based count).
42    pub covered: u32,
43    /// Total executable lines attributed to this file (1-based count).
44    pub total: u32,
45    /// The uncovered executable lines, 1-based and ascending — the exact set the
46    /// proposal's fixtures pin.
47    pub uncovered: Vec<u32>,
48    /// The covered executable lines, 1-based and ascending (#2104): with
49    /// `uncovered`, every executable line, so an editor can mark both.
50    pub covered_lines: Vec<u32>,
51}
52
53/// A whole-run coverage report: one [`FileCoverage`] per measured `.bynk` file,
54/// sorted by path, plus the derived totals.
55#[derive(Debug, Clone, PartialEq, Eq, Default)]
56pub struct CoverageReport {
57    pub files: Vec<FileCoverage>,
58}
59
60impl CoverageReport {
61    /// Total covered executable lines across every measured file.
62    pub fn total_covered(&self) -> u32 {
63        self.files.iter().map(|f| f.covered).sum()
64    }
65
66    /// Total executable lines across every measured file.
67    pub fn total_lines(&self) -> u32 {
68        self.files.iter().map(|f| f.total).sum()
69    }
70
71    /// Whole-run percentage (0–100), rounded to the nearest integer. A run that
72    /// attributed no executable line is reported as 100% (nothing to cover).
73    pub fn total_percent(&self) -> u32 {
74        percent(self.total_covered(), self.total_lines())
75    }
76
77    /// Whether the report attributed no `.bynk` line at all — an empty measured
78    /// set (e.g. an integration-only project whose only executed code is the
79    /// workers scaffold DECISION D drops).
80    pub fn is_empty(&self) -> bool {
81        self.files.is_empty()
82    }
83}
84
85/// Coverage percentage of `covered`/`total`, rounded; `total == 0` → 100. Only a
86/// genuinely complete run reads 100%: round-half-up would report `995/1000` as
87/// `100%` while lines are still uncovered — self-contradicting in the table and
88/// a false green for a CI gate keyed on the JSON `percent` — so a run with any
89/// uncovered line is clamped to at most 99.
90pub fn percent(covered: u32, total: u32) -> u32 {
91    if total == 0 || covered >= total {
92        100
93    } else {
94        let rounded = (covered as u64 * 100 + total as u64 / 2) / total as u64;
95        (rounded as u32).min(99)
96    }
97}
98
99// -- V8 coverage JSON (the `NODE_V8_COVERAGE` output shape) --
100
101#[derive(Deserialize)]
102struct V8Document {
103    #[serde(default)]
104    result: Vec<V8Script>,
105}
106
107#[derive(Deserialize)]
108struct V8Script {
109    url: String,
110    #[serde(default)]
111    functions: Vec<V8Function>,
112}
113
114#[derive(Deserialize)]
115struct V8Function {
116    #[serde(default)]
117    ranges: Vec<V8Range>,
118}
119
120#[derive(Deserialize)]
121struct V8Range {
122    #[serde(rename = "startOffset")]
123    start: usize,
124    #[serde(rename = "endOffset")]
125    end: usize,
126    count: i64,
127    /// Set after parsing on the first range of a V8 function entry, which is
128    /// the whole function's own range; the rest are nested block ranges.
129    #[serde(skip)]
130    function: bool,
131}
132
133/// Collect coverage from a finished run and attribute it to `.bynk` source.
134///
135/// - `v8_dir` — the directory `NODE_V8_COVERAGE` was pointed at.
136/// - `out_js_root` — where the executed `.js` and tsc's `.js.map` live.
137/// - `out_root` — where the emitted `.ts` and the emitter's `.ts.map` live.
138/// - `source_root` — the project root the `.bynk` paths are relativised against.
139///
140/// Any file it cannot read or parse is skipped rather than failing the run —
141/// coverage is a report *about* a run that already happened, so a partial map
142/// should degrade the numbers, never abort. Reading the V8 directory is the one
143/// hard error surfaced (it is the runner's own temp dir).
144pub fn collect_coverage(
145    v8_dir: &Path,
146    out_js_root: &Path,
147    out_root: &Path,
148    source_root: &Path,
149) -> std::io::Result<CoverageReport> {
150    let canonical_root = source_root.canonicalize().ok();
151    // 1. Fold every V8 document into per-script merged ranges. A single-process
152    //    run writes one file, but Node may split across several; merging the
153    //    ranges (and taking the innermost at lookup time) is correct either way.
154    let mut scripts: HashMap<PathBuf, Vec<V8Range>> = HashMap::new();
155    for entry in std::fs::read_dir(v8_dir)? {
156        let path = entry?.path();
157        if path.extension().and_then(|e| e.to_str()) != Some("json") {
158            continue;
159        }
160        let Ok(text) = std::fs::read_to_string(&path) else {
161            continue;
162        };
163        let Ok(doc) = serde_json::from_str::<V8Document>(&text) else {
164            continue;
165        };
166        for script in doc.result {
167            let Some(fs_path) = file_url_to_path(&script.url) else {
168                continue;
169            };
170            let canon = std::fs::canonicalize(&fs_path).unwrap_or(fs_path);
171            let ranges = scripts.entry(canon).or_default();
172            for func in script.functions {
173                let first = ranges.len();
174                ranges.extend(func.ranges);
175                if let Some(r) = ranges.get_mut(first) {
176                    r.function = true;
177                }
178            }
179        }
180    }
181
182    let out_js_canon =
183        std::fs::canonicalize(out_js_root).unwrap_or_else(|_| out_js_root.to_path_buf());
184
185    // Accumulate per `.bynk` file: the executable lines seen, and which executed.
186    let mut acc: BTreeMap<String, FileAcc> = BTreeMap::new();
187
188    for (script_id, (script_path, ranges)) in scripts.iter().enumerate() {
189        let Ok(rel) = script_path.strip_prefix(&out_js_canon) else {
190            continue;
191        };
192        // DECISION D: drop the workers scaffold, the emitted test modules, and
193        // the runtime — before the maps are consulted. These are the emitted
194        // `out-js` paths, so the filter is on the generated tree, not `.bynk`.
195        if !is_measurable_emitted(rel) {
196            continue;
197        }
198        let Ok(js_text) = std::fs::read_to_string(script_path) else {
199            continue;
200        };
201        // Hop 1: tsc's `.js.map` sits beside the `.js`.
202        let js_map_path = append_ext(script_path, "map");
203        let Some(js_map) = std::fs::read_to_string(&js_map_path)
204            .ok()
205            .and_then(|s| SourceMap::parse(&s))
206        else {
207            continue;
208        };
209        // Hop 2: the emitter's `.ts.map`, mirrored under `out/` at the same rel
210        // path (tsc's `rootDir: "."`, `outDir: "../out-js"` keeps the tree 1:1).
211        let ts_rel = rel.with_extension("ts");
212        let ts_map_path = append_ext(&out_root.join(&ts_rel), "map");
213        let Some(ts_map) = std::fs::read_to_string(&ts_map_path)
214            .ok()
215            .and_then(|s| SourceMap::parse(&s))
216        else {
217            continue;
218        };
219
220        let line_reps = line_representatives(&js_text);
221        for (js_line, rep_off) in line_reps.iter().enumerate() {
222            let Some(off) = rep_off else { continue };
223            // The verdict for this generated line is the *innermost* V8 range
224            // covering it — see [`innermost_range`]. A generated line covered by
225            // no range (the trailing `sourceMappingURL` comments) attributes
226            // nothing.
227            let Some(hit) = innermost_range(*off, ranges) else {
228                continue;
229            };
230            let Some(js_segs) = js_map.lines.get(js_line) else {
231                continue;
232            };
233            for &(_js_src, ts_line) in js_segs {
234                let Some(ts_segs) = ts_map.lines.get(ts_line as usize) else {
235                    continue;
236                };
237                for &(bynk_src, bynk_line) in ts_segs {
238                    let Some(bynk_abs) = ts_map.sources.get(bynk_src) else {
239                        continue;
240                    };
241                    let disp = relativise(bynk_abs, source_root, canonical_root.as_deref());
242                    // DECISION D is enforced once, authoritatively, on the emitted
243                    // tree by `is_measurable_emitted` (the `tests/` and `workers/`
244                    // top-level dirs of `out-js`). We deliberately do *not* re-filter
245                    // on the `.bynk` side: a user source that merely lives under a
246                    // dir named `tests`/`workers` (e.g. `src/workers/helpers.bynk`)
247                    // is real code whose `.js` already passed the emitted filter, so
248                    // dropping it here would silently omit it from coverage.
249                    let file = acc.entry(disp).or_default();
250                    // Lines are 1-based in every report the user sees. See
251                    // [`FileAcc::observe`] for how the generated lines mapping to
252                    // one `.bynk` line combine into its verdict.
253                    let line1 = bynk_line + 1;
254                    file.observe(line1, script_id, hit);
255                }
256            }
257        }
258    }
259
260    let files = acc
261        .into_iter()
262        .map(|(path, a)| {
263            let total = a.lines.len() as u32;
264            let mut covered_lines = Vec::new();
265            let mut uncovered = Vec::new();
266            for (&line, verdict) in &a.lines {
267                if verdict.covered() {
268                    covered_lines.push(line);
269                } else {
270                    uncovered.push(line);
271                }
272            }
273            FileCoverage {
274                path,
275                covered: covered_lines.len() as u32,
276                total,
277                uncovered,
278                covered_lines,
279            }
280        })
281        .collect();
282    Ok(CoverageReport { files })
283}
284
285#[derive(Default)]
286struct FileAcc {
287    /// Per 1-based `.bynk` line, what the generated lines mapping to it showed.
288    /// `BTreeMap` keeps the uncovered list ascending for free.
289    lines: BTreeMap<u32, LineVerdict>,
290}
291
292#[derive(Default)]
293struct LineVerdict {
294    /// Executed (`count > 0`) ranges mapping to the line, as `(script, start, end)`.
295    executed: Vec<(usize, usize, usize)>,
296    /// Never-entered function ranges mapping to the line, in the same form.
297    uncalled_fns: Vec<(usize, usize, usize)>,
298}
299
300impl LineVerdict {
301    /// Covered if some executed range does not strictly contain an uncalled
302    /// function that maps to the line. Offsets are only comparable within one
303    /// script, hence the script id.
304    fn covered(&self) -> bool {
305        self.executed.iter().any(|&(es, estart, eend)| {
306            !self.uncalled_fns.iter().any(|&(fs, fstart, fend)| {
307                es == fs && estart <= fstart && fend <= eend && (fend - fstart) < (eend - estart)
308            })
309        })
310    }
311}
312
313impl FileAcc {
314    /// Record that a generated position in `script` whose innermost V8 range is
315    /// `hit` maps to `line`.
316    ///
317    /// The line is covered if some generated line mapping to it executed
318    /// (ADR 0271 DECISION B), with one exception: an uncalled *function* vetoes
319    /// an executed range that strictly contains it. That keeps a hoisted export
320    /// (a whole-module range enclosing the function, mapped to its declaration
321    /// line) from masking an uncalled function, while an unrelated sibling
322    /// function, whatever its size, decides nothing. A not-taken *block* never
323    /// vetoes: whether V8 split a block range out depends on which code ran, so
324    /// letting it decide made one line's verdict vary with the test subset
325    /// (#2270).
326    fn observe(&mut self, line: u32, script: usize, hit: Hit) {
327        let slot = self.lines.entry(line).or_default();
328        let entry = (script, hit.start, hit.end);
329        if hit.count > 0 {
330            slot.executed.push(entry);
331        } else if hit.function {
332            slot.uncalled_fns.push(entry);
333        }
334    }
335}
336
337/// A V8 range containing a sampled offset.
338#[derive(Clone, Copy, Debug, PartialEq, Eq)]
339struct Hit {
340    start: usize,
341    end: usize,
342    count: i64,
343    /// A whole-function range, as opposed to a nested block range.
344    function: bool,
345}
346
347/// The **innermost** (smallest-span) V8 range containing `off`. V8 block coverage
348/// nests a not-taken block's `count: 0` range inside
349/// its enclosing function's `count: N` range, so the smallest containing range
350/// is the precise verdict for that position. `None` if no range contains `off`.
351fn innermost_range(off: usize, ranges: &[V8Range]) -> Option<Hit> {
352    let mut best: Option<Hit> = None;
353    for r in ranges {
354        if r.start <= off && off < r.end {
355            let span = r.end - r.start;
356            match best {
357                Some(b)
358                    if span > b.end - b.start
359                        || (span == b.end - b.start && r.count <= b.count) => {}
360                _ => {
361                    best = Some(Hit {
362                        start: r.start,
363                        end: r.end,
364                        count: r.count,
365                        function: r.function,
366                    })
367                }
368            }
369        }
370    }
371    best
372}
373
374/// For each generated line, the **UTF-16 offset** of its first non-whitespace
375/// char — the position sampled against the V8 ranges. `None` for a blank line
376/// (nothing to attribute; such lines carry no mapping anyway).
377///
378/// #2146: a leading `export ` is skipped. The runner compiles to ES modules, so
379/// a function line reads `export function f(…) {`, and V8's range for `f`
380/// starts at `function`: sampling the `export` keyword would land in the
381/// module's range, which ran at load, and count an uncalled function's
382/// declaration line as covered.
383///
384/// V8 coverage `startOffset`/`endOffset` index the source as a JS string, i.e.
385/// in UTF-16 code units, not UTF-8 bytes (the same space `v8-to-istanbul`/`c8`
386/// use). For ASCII-only output the two coincide, but a single non-ASCII char
387/// earlier in the file (a Unicode `.bynk` string literal carried into the `.js`)
388/// shifts every later byte offset relative to V8's counting, which would select
389/// the wrong range. So offsets are accumulated in UTF-16 units to match.
390fn line_representatives(text: &str) -> Vec<Option<usize>> {
391    let mut out = Vec::new();
392    let mut u16_off = 0usize;
393    for line in text.split_inclusive('\n') {
394        let mut rep = None;
395        let mut o = u16_off;
396        for c in line.chars() {
397            if c.is_whitespace() {
398                o += c.len_utf16();
399            } else {
400                rep = Some(o);
401                break;
402            }
403        }
404        if let Some(start) = rep {
405            let rest = line.trim_start();
406            if let Some(after) = rest.strip_prefix("export ")
407                && !after.trim().is_empty()
408            {
409                // `export ` and the spaces after it are ASCII, so the bytes
410                // skipped are as many UTF-16 units.
411                rep = Some(start + rest.len() - after.trim_start().len());
412            }
413        }
414        out.push(rep);
415        u16_off += line.chars().map(char::len_utf16).sum::<usize>();
416    }
417    out
418}
419
420/// Whether an emitted `out-js`-relative path is a file we measure: not the
421/// `tests/` tree, not the `workers/` scaffold, not the shared runtime, and a
422/// `.js` module (DECISION D).
423fn is_measurable_emitted(rel: &Path) -> bool {
424    if rel.extension().and_then(|e| e.to_str()) != Some("js") {
425        return false;
426    }
427    let mut comps = rel.components();
428    match comps.next() {
429        Some(Component::Normal(c)) if c == "tests" || c == "workers" => return false,
430        _ => {}
431    }
432    // The runtime helpers are framework code, never user source.
433    if rel == Path::new("runtime.js") {
434        return false;
435    }
436    true
437}
438
439/// Relativise an absolute `.bynk` source path against the project root, forward-
440/// slashed. Falls back to the file name, then the path verbatim, so an
441/// out-of-tree source (a synthetic unit) still renders something legible.
442///
443/// `canonical_root` is `source_root` canonicalised (#2104): a relative root
444/// (`bynk test .`) never prefixes an absolute map source, which collapsed
445/// `src/window.bynk` to `window.bynk`, so the absolute form is tried too.
446fn relativise(abs: &str, source_root: &Path, canonical_root: Option<&Path>) -> String {
447    let p = Path::new(abs);
448    for root in std::iter::once(source_root).chain(canonical_root) {
449        if let Ok(rel) = p.strip_prefix(root) {
450            return forward_slash(rel);
451        }
452    }
453    // The map source is stored forward-slashed absolute; the root may be a
454    // different textual form of the same dir. Fall back to the file name.
455    p.file_name()
456        .map(|n| n.to_string_lossy().into_owned())
457        .unwrap_or_else(|| abs.to_string())
458}
459
460fn forward_slash(p: &Path) -> String {
461    p.components()
462        .filter_map(|c| match c {
463            Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
464            _ => None,
465        })
466        .collect::<Vec<_>>()
467        .join("/")
468}
469
470/// Convert a `file://` URL to a filesystem path, minimally percent-decoding.
471/// Returns `None` for a non-`file:` URL (e.g. `node:internal/...`).
472fn file_url_to_path(url: &str) -> Option<PathBuf> {
473    let rest = url.strip_prefix("file://")?;
474    // `file:///abs` → `/abs`; a host part is not expected for local coverage.
475    let path = rest
476        .strip_prefix('/')
477        .map(|r| format!("/{r}"))
478        .unwrap_or_else(|| rest.to_string());
479    Some(PathBuf::from(percent_decode(&path)))
480}
481
482/// Minimal `%XX` percent-decoding — enough for paths with spaces in a temp dir.
483fn percent_decode(s: &str) -> String {
484    let bytes = s.as_bytes();
485    let mut out = Vec::with_capacity(bytes.len());
486    let mut i = 0;
487    while i < bytes.len() {
488        if bytes[i] == b'%' && i + 2 < bytes.len() {
489            let hi = (bytes[i + 1] as char).to_digit(16);
490            let lo = (bytes[i + 2] as char).to_digit(16);
491            if let (Some(h), Some(l)) = (hi, lo) {
492                out.push((h * 16 + l) as u8);
493                i += 3;
494                continue;
495            }
496        }
497        out.push(bytes[i]);
498        i += 1;
499    }
500    String::from_utf8_lossy(&out).into_owned()
501}
502
503/// Append `.ext` to a path's file name (`foo.js` + `map` → `foo.js.map`), unlike
504/// [`Path::with_extension`] which would replace `js`.
505fn append_ext(path: &Path, ext: &str) -> PathBuf {
506    let mut name = path
507        .file_name()
508        .map(|n| n.to_os_string())
509        .unwrap_or_default();
510    name.push(".");
511    name.push(ext);
512    path.with_file_name(name)
513}
514
515// -- Source-map v3 (the subset needed for line attribution) --
516
517/// A decoded source-map: its `sources` list and, per generated line (0-based),
518/// the segments on that line as `(source_index, source_line_0based)`. Generated
519/// and source columns are decoded to keep the VLQ deltas honest, then dropped —
520/// attribution is line-level on both hops.
521struct SourceMap {
522    sources: Vec<String>,
523    lines: Vec<Vec<(usize, u32)>>,
524}
525
526impl SourceMap {
527    fn parse(json: &str) -> Option<SourceMap> {
528        #[derive(Deserialize)]
529        struct Raw {
530            #[serde(default)]
531            sources: Vec<String>,
532            #[serde(default)]
533            mappings: String,
534        }
535        let raw: Raw = serde_json::from_str(json).ok()?;
536        Some(SourceMap {
537            sources: raw.sources,
538            lines: decode_line_mappings(&raw.mappings),
539        })
540    }
541}
542
543/// Decode a v3 `mappings` string into, per generated line, its `(src_idx,
544/// src_line)` segments (both 0-based). Follows the VLQ delta rules: the source
545/// index/line/column deltas persist across segments *and* lines; the generated
546/// column resets at each line boundary. A one-field segment (generated column
547/// only, no source) carries no attribution and is skipped.
548fn decode_line_mappings(mappings: &str) -> Vec<Vec<(usize, u32)>> {
549    let mut lines = Vec::new();
550    // Source index and source line are independent running totals that persist
551    // across segments and lines (the source column would be a third, but line
552    // attribution never needs it). The generated column resets each line and is
553    // irrelevant here, so it is decoded but discarded.
554    let (mut src, mut src_line) = (0i64, 0i64);
555    for seg_line in mappings.split(';') {
556        let mut segs = Vec::new();
557        for seg in seg_line.split(',') {
558            if seg.is_empty() {
559                continue;
560            }
561            let fields = vlq_decode(seg);
562            if fields.len() >= 4 {
563                src += fields[1];
564                src_line += fields[2];
565                if src >= 0 && src_line >= 0 {
566                    segs.push((src as usize, src_line as u32));
567                }
568            }
569        }
570        lines.push(segs);
571    }
572    lines
573}
574
575/// Base64-VLQ-decode one segment into its signed fields.
576fn vlq_decode(seg: &str) -> Vec<i64> {
577    const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
578    let mut out = Vec::new();
579    let (mut shift, mut acc) = (0u32, 0i64);
580    for &c in seg.as_bytes() {
581        let Some(d) = B64.iter().position(|&b| b == c).map(|p| p as i64) else {
582            continue;
583        };
584        acc += (d & 0b11111) << shift;
585        if d & 0b100000 != 0 {
586            shift += 5;
587        } else {
588            let value = if acc & 1 == 1 { -(acc >> 1) } else { acc >> 1 };
589            out.push(value);
590            shift = 0;
591            acc = 0;
592        }
593    }
594    out
595}
596
597// -- Rich rendering --
598
599/// Render the human coverage summary — a per-file bar, percentage, covered/total
600/// line count, and the uncovered-line ranges — plus a total row. Trailing
601/// newline. An empty report renders a single "no coverage attributed" note.
602pub fn render_rich(report: &CoverageReport) -> String {
603    let mut out = String::new();
604    out.push_str("\nCoverage\n");
605    if report.is_empty() {
606        out.push_str("  (no executable `.bynk` lines were attributed)\n");
607        return out;
608    }
609    let name_w = report
610        .files
611        .iter()
612        .map(|f| f.path.len())
613        .max()
614        .unwrap_or(0)
615        .max(5);
616    for f in &report.files {
617        let pct = percent(f.covered, f.total);
618        out.push_str(&format!(
619            "  {:<name_w$}  {}  {:>3}%   ({}/{} lines)",
620            f.path,
621            bar(f.covered, f.total),
622            pct,
623            f.covered,
624            f.total,
625        ));
626        if !f.uncovered.is_empty() {
627            out.push_str(&format!("  uncovered: {}", format_ranges(&f.uncovered)));
628        }
629        out.push('\n');
630    }
631    let dashes = "─".repeat(name_w + 24);
632    out.push_str(&format!("  {dashes}\n"));
633    out.push_str(&format!(
634        "  {:<name_w$}  {}  {:>3}%   ({}/{} lines)\n",
635        "total",
636        bar(report.total_covered(), report.total_lines()),
637        report.total_percent(),
638        report.total_covered(),
639        report.total_lines(),
640    ));
641    out
642}
643
644/// An 8-cell coverage bar: filled `▓` proportional to the covered fraction, the
645/// remainder `·`.
646fn bar(covered: u32, total: u32) -> String {
647    const CELLS: u32 = 8;
648    let filled = if total == 0 {
649        CELLS
650    } else {
651        (covered as u64 * CELLS as u64 / total as u64) as u32
652    };
653    let mut s = String::new();
654    for _ in 0..filled {
655        s.push('▓');
656    }
657    for _ in filled..CELLS {
658        s.push('·');
659    }
660    s
661}
662
663/// Compress a sorted line list into comma-separated ranges: `[6,7,8,51]` →
664/// `"6-8, 51"`.
665pub fn format_ranges(lines: &[u32]) -> String {
666    let mut parts = Vec::new();
667    let mut i = 0;
668    while i < lines.len() {
669        let start = lines[i];
670        let mut end = start;
671        while i + 1 < lines.len() && lines[i + 1] == end + 1 {
672            end += 1;
673            i += 1;
674        }
675        if start == end {
676            parts.push(format!("{start}"));
677        } else {
678            parts.push(format!("{start}-{end}"));
679        }
680        i += 1;
681    }
682    parts.join(", ")
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    #[test]
690    fn a_relative_root_still_relativises_through_its_canonical_form() {
691        // #2104: `bynk test .` hands a relative root; the map's sources are
692        // absolute, so only the canonical root prefixes them.
693        let abs = "/work/shop/src/window.bynk";
694        assert_eq!(
695            relativise(abs, Path::new("."), Some(Path::new("/work/shop"))),
696            "src/window.bynk"
697        );
698        assert_eq!(
699            relativise(abs, Path::new("/work/shop"), None),
700            "src/window.bynk"
701        );
702        // Outside the root: the file name, as before.
703        assert_eq!(
704            relativise(abs, Path::new("."), Some(Path::new("/elsewhere"))),
705            "window.bynk"
706        );
707    }
708
709    #[test]
710    fn vlq_decodes_signed_fields() {
711        // "AAAA" → [0,0,0,0]; "AAEA" → [0,0,2,0]; "AACE" → [0,0,1,2]; "D" → [-1].
712        assert_eq!(vlq_decode("AAAA"), vec![0, 0, 0, 0]);
713        assert_eq!(vlq_decode("AAEA"), vec![0, 0, 2, 0]);
714        assert_eq!(vlq_decode("AACE"), vec![0, 0, 1, 2]);
715        assert_eq!(vlq_decode("D"), vec![-1]);
716    }
717
718    #[test]
719    fn line_mappings_track_running_source_line() {
720        // The emitter's `.ts.map` for the two-fn spike: 5 blank lines, then
721        // src lines 2,3,3,6,7,8 (0-based) — running deltas across lines.
722        let m = ";;;;;AAEA;AACE;AAAA;AAGF;AACE;AACA";
723        let lines = decode_line_mappings(m);
724        assert_eq!(lines[0], vec![]);
725        assert_eq!(lines[5], vec![(0, 2)]);
726        assert_eq!(lines[6], vec![(0, 3)]);
727        assert_eq!(lines[7], vec![(0, 3)]);
728        assert_eq!(lines[8], vec![(0, 6)]);
729        assert_eq!(lines[9], vec![(0, 7)]);
730        assert_eq!(lines[10], vec![(0, 8)]);
731    }
732
733    #[test]
734    fn innermost_range_prefers_the_tightest_span() {
735        // A module range (count 1) with a nested uncalled-fn range (count 0):
736        // a position inside the fn is uncovered, one outside it is covered.
737        let ranges = vec![
738            V8Range {
739                start: 0,
740                end: 100,
741                count: 1,
742                function: true,
743            },
744            V8Range {
745                start: 40,
746                end: 60,
747                count: 0,
748                function: true,
749            },
750        ];
751        let hit = |start, end, count| Hit {
752            start,
753            end,
754            count,
755            function: true,
756        };
757        assert_eq!(innermost_range(10, &ranges), Some(hit(0, 100, 1)));
758        assert_eq!(innermost_range(50, &ranges), Some(hit(40, 60, 0)));
759        assert_eq!(innermost_range(200, &ranges), None); // outside every range
760    }
761
762    fn hit(start: usize, end: usize, count: i64, function: bool) -> Hit {
763        Hit {
764            start,
765            end,
766            count,
767            function,
768        }
769    }
770
771    #[test]
772    fn file_acc_lets_an_uncalled_function_veto_the_executed_range_enclosing_it() {
773        // The hoisted-export hazard: a `.bynk` line reached both by a wide
774        // module range that ran (the `exports.f = f;` line) and the function
775        // range inside it that did not (the never-called body). → uncovered.
776        let mut acc = FileAcc::default();
777        acc.observe(7, 0, hit(0, 352, 1, true));
778        acc.observe(7, 0, hit(100, 161, 0, true));
779        assert!(!acc.lines[&7].covered());
780    }
781
782    #[test]
783    fn file_acc_does_not_let_an_unrelated_uncalled_function_veto() {
784        // #2270 review: two sibling helpers anchored to one line. Whatever their
785        // relative sizes, an uncalled one does not veto a called one.
786        for (called, uncalled) in [((0, 200), (300, 350)), ((0, 50), (300, 600))] {
787            let mut acc = FileAcc::default();
788            acc.observe(5, 0, hit(called.0, called.1, 2, true));
789            acc.observe(5, 0, hit(uncalled.0, uncalled.1, 0, true));
790            assert!(acc.lines[&5].covered(), "{called:?} vs {uncalled:?}");
791        }
792        // The same ranges in different scripts are never nested.
793        let mut acc = FileAcc::default();
794        acc.observe(5, 0, hit(0, 500, 1, true));
795        acc.observe(5, 1, hit(10, 20, 0, true));
796        assert!(acc.lines[&5].covered());
797    }
798
799    #[test]
800    fn file_acc_ignores_a_not_taken_block_on_an_executed_line() {
801        // #2270: a not-taken block range (a guard's `throw`, an unused arm)
802        // mapping to a line that also ran does not make the line uncovered.
803        let mut acc = FileAcc::default();
804        acc.observe(5, 0, hit(0, 671, 2, true));
805        acc.observe(5, 0, hit(10, 59, 0, false));
806        acc.observe(5, 0, hit(100, 214, 2, false));
807        assert!(acc.lines[&5].covered());
808        // With only the not-taken block, the line is uncovered.
809        let mut only = FileAcc::default();
810        only.observe(5, 0, hit(10, 59, 0, false));
811        assert!(!only.lines[&5].covered());
812    }
813
814    #[test]
815    fn file_acc_covers_a_line_when_an_executed_range_is_inside_an_uncalled_function() {
816        // The executed range is narrower than the uncalled function and nested
817        // in it (a count-N block inside a count-0 function cannot happen in V8,
818        // but equal spans must not veto either): covered.
819        let mut acc = FileAcc::default();
820        acc.observe(3, 0, hit(10, 20, 1, false));
821        acc.observe(3, 0, hit(0, 100, 0, true));
822        assert!(acc.lines[&3].covered());
823        let mut tie = FileAcc::default();
824        tie.observe(3, 0, hit(0, 100, 1, true));
825        tie.observe(3, 0, hit(0, 100, 0, true));
826        assert!(tie.lines[&3].covered());
827    }
828
829    #[test]
830    fn line_representatives_pick_first_nonspace() {
831        let reps = line_representatives("ab\n    cd\n\n  \nx");
832        assert_eq!(reps[0], Some(0)); // "ab"
833        assert_eq!(reps[1], Some(7)); // "    cd" → 'c' at 3+4
834        assert_eq!(reps[2], None); // blank
835        assert_eq!(reps[3], None); // whitespace-only
836        assert_eq!(reps[4], Some(14)); // "x"
837    }
838
839    #[test]
840    fn line_representatives_skip_a_leading_export() {
841        // #2146: an ES module's `export function f() {` samples at `function`,
842        // where V8's range for `f` starts, not at `export` (the module range).
843        let reps = line_representatives("export function f() {\n  export  const x = 1;\nexport\n");
844        assert_eq!(reps[0], Some(7)); // "function"
845        assert_eq!(reps[1], Some(32)); // 22 + 2 indent + "export  " → 'c'
846        assert_eq!(reps[2], Some(45)); // a bare `export` keeps its own offset
847    }
848
849    #[test]
850    fn line_representatives_count_utf16_units_not_bytes() {
851        // An em-dash (`—`, U+2014: 3 UTF-8 bytes, 1 UTF-16 unit) on line 0 must
852        // not shift line 1's offset — V8 counts UTF-16 units, so a byte-based
853        // accumulator would report 9 (7 + 2) here and mis-sample the ranges.
854        let reps = line_representatives("a — b\nx");
855        assert_eq!(reps[0], Some(0)); // "a — b"
856        // "a — b\n" = 6 UTF-16 units (byte length would be 8: '—' is 3 bytes).
857        assert_eq!(reps[1], Some(6)); // "x" at UTF-16 offset 6, not byte 8
858        // An astral char (`🎉`, 2 UTF-16 units) shifts by 2, matching V8.
859        let reps = line_representatives("🎉\ny");
860        assert_eq!(reps[0], Some(0));
861        assert_eq!(reps[1], Some(3)); // 🎉(2) + '\n'(1) = 3
862    }
863
864    #[test]
865    fn format_ranges_compresses_runs() {
866        assert_eq!(format_ranges(&[6, 7, 8, 51]), "6-8, 51");
867        assert_eq!(format_ranges(&[3]), "3");
868        assert_eq!(format_ranges(&[1, 2, 4, 5, 6]), "1-2, 4-6");
869        assert_eq!(format_ranges(&[]), "");
870    }
871
872    #[test]
873    fn percent_rounds_and_guards_zero() {
874        assert_eq!(percent(0, 0), 100);
875        assert_eq!(percent(42, 49), 86);
876        assert_eq!(percent(2, 5), 40);
877        assert_eq!(percent(11, 11), 100);
878    }
879
880    #[test]
881    fn percent_never_reports_100_for_an_incomplete_run() {
882        // Round-half-up would give 100 here; a run with any uncovered line must
883        // read at most 99 so the table and the JSON `percent` never falsely green.
884        assert_eq!(percent(995, 1000), 99);
885        assert_eq!(percent(199, 200), 99);
886        assert_eq!(percent(1000, 1000), 100); // genuinely complete
887        assert_eq!(percent(0, 5), 0);
888    }
889
890    #[test]
891    fn measurable_filter_drops_tests_workers_runtime() {
892        assert!(is_measurable_emitted(Path::new("src/limiter.js")));
893        assert!(is_measurable_emitted(Path::new("limiter.js")));
894        assert!(!is_measurable_emitted(Path::new("tests/main.js")));
895        assert!(!is_measurable_emitted(Path::new("workers/api/handlers.js")));
896        assert!(!is_measurable_emitted(Path::new("runtime.js")));
897        assert!(!is_measurable_emitted(Path::new("src/limiter.js.map")));
898    }
899
900    #[test]
901    fn file_url_round_trips_to_path() {
902        assert_eq!(
903            file_url_to_path("file:///private/tmp/a%20b/out-js/m.js"),
904            Some(PathBuf::from("/private/tmp/a b/out-js/m.js"))
905        );
906        assert_eq!(file_url_to_path("node:internal/modules"), None);
907    }
908}