Skip to main content

bynk_driver/
render.rs

1//! Bynk's shared diagnostic-rendering layer.
2//!
3//! The presentation layer over [`bynk_syntax::CompileError`]: ariadne human
4//! output and the `short`/`json`-feeding line forms. Every renderer takes
5//! `&[CompileError]` + `source` + `filename` — it is agnostic about *where* the
6//! errors came from, so both CLI front-ends render identically (ADR 0100).
7//!
8//! **Invariant (ADR 0100, as amended by D2):** this module names `bynk_syntax`
9//! and `ariadne` only (plus `std`). It must never see
10//! `AttributedError`/`ProjectFailure` (which live in `bynk-emit`): the
11//! `AttributedError → CompileError` flattening stays *above* render, in the
12//! driver's `lib.rs`. This was once the crate graph's guarantee (`bynk-render`
13//! depended on `bynk-syntax` only); inside `bynk-driver` the guard test
14//! `render_names_only_syntax_and_ariadne` (this file's `tests`) enforces it.
15//!
16//! Extracted from `bynkc` as slice 6 of the crate-decomposition track; merged
17//! into `bynk-driver` by crate-hygiene slice D2.
18
19use std::path::Path;
20
21use ariadne::Source;
22use bynk_syntax::error::Severity;
23use bynk_syntax::{CompileError, span};
24
25/// Re-exported for [`render_error_in`]'s callers, which say with it which file
26/// each of an error's labels lies in.
27pub use bynk_syntax::error::LabelHome;
28
29/// Render a list of compile errors to a string (for tests) using the given
30/// filename as the diagnostic source label.
31pub fn render_errors(errors: &[CompileError], source: &str, filename: &str) -> String {
32    String::from_utf8_lossy(&render_all(errors, source, filename, true)).into_owned()
33}
34
35/// Render a list of compile errors to a string with colour disabled and the
36/// given filename as the source label. Unlike [`render_errors`], the output
37/// contains no ANSI escape codes, so it is byte-stable — suitable for the
38/// committed diagnostic transcripts under `site/src/diagnostics/`.
39pub fn render_errors_plain(errors: &[CompileError], source: &str, filename: &str) -> String {
40    String::from_utf8_lossy(&render_all(errors, source, filename, false)).into_owned()
41}
42
43/// Render to stderr, used by the CLI; coloured when `color` is on (the
44/// caller's `--color` decision for stderr: `crate::colour::stderr`).
45pub fn print_errors(errors: &[CompileError], source: &str, filename: &str, color: bool) {
46    use std::io::Write;
47    let out = render_all(errors, source, filename, color);
48    let _ = std::io::stderr().lock().write_all(&out);
49}
50
51/// The ariadne reports for `errors`. A report whose spans touch a line
52/// longer than [`MAX_LINE`] renders its own copy of the source, cut by
53/// [`cropped`]; the rest share one view of `source`.
54fn render_all(errors: &[CompileError], source: &str, filename: &str, color: bool) -> Vec<u8> {
55    fn write<'a>(
56        err: &'a CompileError,
57        filename: &'a str,
58        cache: &mut (&'a str, Source<&str>),
59        color: bool,
60        out: &mut Vec<u8>,
61    ) {
62        let source = cache.1.text();
63        let report = if color {
64            err.report_for(filename, source)
65        } else {
66            err.report_plain_for(filename, source)
67        };
68        report
69            .write(&mut *cache, out)
70            .expect("write to Vec<u8> cannot fail");
71    }
72    let long = long_lines(source);
73    let mut cache = (filename, Source::from(source));
74    let mut index = None;
75    let mut out = Vec::new();
76    for err in errors {
77        let touches_long = std::iter::once(&err.span)
78            .chain(err.labels.iter().map(|(s, _)| s))
79            .filter(|s| fits(s, source))
80            .any(|s| {
81                long.iter()
82                    .any(|&(start, end)| s.start <= end && s.end >= start)
83            });
84        if !touches_long {
85            write(err, filename, &mut cache, color, &mut out);
86            continue;
87        }
88        let (shown, shown_err) = cropped(err, source);
89        let mut one = Vec::new();
90        write(
91            &shown_err,
92            filename,
93            &mut (filename, Source::from(&*shown)),
94            color,
95            &mut one,
96        );
97        // ariadne heads the report with the primary span's `line:col` in the
98        // text it was given; on a line cut at its start that column is the cut
99        // one. Put back the column in the file, as the short form reports it.
100        let cut = span::line_col(&shown, shown_err.span.start);
101        let real = index
102            .get_or_insert_with(|| span::LineIndex::new(source))
103            .line_col(source, err.span.start);
104        if cut != real {
105            one = fix_header(
106                &one,
107                &format!("{filename}:{}:{}", cut.0, cut.1),
108                &format!("{filename}:{}:{}", real.0, real.1),
109            );
110        }
111        out.extend(one);
112    }
113    out
114}
115
116/// Render one error whose secondary labels may lie in other files, coloured
117/// as [`render_errors`] is: `homes[i]` says which file `err.labels[i]` lies in
118/// (see [`CompileError::report_in`]). A label in another file is drawn in a
119/// snippet of that file, under its own name, rather than against `source`.
120pub fn render_error_in(
121    err: &CompileError,
122    source: &str,
123    filename: &str,
124    homes: &[LabelHome<'_>],
125) -> String {
126    String::from_utf8_lossy(&render_in(err, source, filename, homes, true)).into_owned()
127}
128
129/// [`render_error_in`] with colour disabled, byte-stable like
130/// [`render_errors_plain`].
131pub fn render_error_in_plain(
132    err: &CompileError,
133    source: &str,
134    filename: &str,
135    homes: &[LabelHome<'_>],
136) -> String {
137    String::from_utf8_lossy(&render_in(err, source, filename, homes, false)).into_owned()
138}
139
140/// [`render_error_in`] to stderr, coloured as [`print_errors`] is.
141pub fn print_error_in(
142    err: &CompileError,
143    source: &str,
144    filename: &str,
145    homes: &[LabelHome<'_>],
146    color: bool,
147) {
148    use std::io::Write;
149    let out = render_in(err, source, filename, homes, color);
150    let _ = std::io::stderr().lock().write_all(&out);
151}
152
153/// The report behind [`render_error_in`]. With every label in `source` it is
154/// [`render_all`]'s. Otherwise the labels in `source` are cut to fit its long
155/// lines as [`render_all`] cuts them (#1666), and the others are added after:
156/// another file is never cut, so a label on one of its long lines becomes a
157/// note instead.
158fn render_in(
159    err: &CompileError,
160    source: &str,
161    filename: &str,
162    homes: &[LabelHome<'_>],
163    color: bool,
164) -> Vec<u8> {
165    let home = |i: usize| homes.get(i).copied().unwrap_or(LabelHome::Primary);
166    if (0..err.labels.len()).all(|i| home(i) == LabelHome::Primary) {
167        return render_all(std::slice::from_ref(err), source, filename, color);
168    }
169    let mut local = err.clone();
170    local.labels.clear();
171    let mut elsewhere = Vec::new();
172    for (i, label) in err.labels.iter().enumerate() {
173        match home(i) {
174            LabelHome::Primary => local.labels.push(label.clone()),
175            other => elsewhere.push((label.clone(), other)),
176        }
177    }
178    let touches_long = |s: &span::Span, text: &str| {
179        fits(s, text)
180            && long_lines(text)
181                .iter()
182                .any(|&(start, end)| s.start <= end && s.end >= start)
183    };
184    let cut = std::iter::once(&local.span)
185        .chain(local.labels.iter().map(|(s, _)| s))
186        .any(|s| touches_long(s, source));
187    let (shown, mut shown_err) = if cut {
188        cropped(&local, source)
189    } else {
190        (source.to_string(), local)
191    };
192    let mut shown_homes = vec![LabelHome::Primary; shown_err.labels.len()];
193    for ((span, label), home) in elsewhere {
194        let home = match home {
195            LabelHome::File { source: text, .. } if touches_long(&span, text) => {
196                LabelHome::Unavailable
197            }
198            other => other,
199        };
200        shown_err.labels.push((span, label));
201        shown_homes.push(home);
202    }
203    let mut cache = Files(vec![(filename, Source::from(shown.as_str()))]);
204    for home in &shown_homes {
205        if let LabelHome::File { filename, source } = *home
206            && !cache.0.iter().any(|(f, _)| *f == filename)
207        {
208            cache.0.push((filename, Source::from(source)));
209        }
210    }
211    let mut out = Vec::new();
212    shown_err
213        .report_in(filename, &shown, &shown_homes, color)
214        .write(&mut cache, &mut out)
215        .expect("write to Vec<u8> cannot fail");
216    if cut {
217        // As in `render_all`: put back the primary span's column in the file.
218        let at_cut = span::line_col(&shown, shown_err.span.start);
219        let real = span::line_col(source, err.span.start);
220        if at_cut != real {
221            out = fix_header(
222                &out,
223                &format!("{filename}:{}:{}", at_cut.0, at_cut.1),
224                &format!("{filename}:{}:{}", real.0, real.1),
225            );
226        }
227    }
228    out
229}
230
231/// A report's sources by filename — the primary file's and each other file a
232/// label lies in. ariadne's own multi-source cache wants `'static` ids.
233struct Files<'a>(Vec<(&'a str, Source<&'a str>)>);
234
235impl<'a> ariadne::Cache<&'a str> for Files<'a> {
236    type Storage = &'a str;
237
238    fn fetch(&mut self, id: &&'a str) -> Result<&Source<&'a str>, impl std::fmt::Debug> {
239        self.0
240            .iter()
241            .find(|(name, _)| name == id)
242            .map(|(_, source)| source)
243            .ok_or_else(|| format!("no source for `{id}`"))
244    }
245
246    fn display<'b>(&self, id: &'b &'a str) -> Option<impl std::fmt::Display + 'b> {
247        Some(*id)
248    }
249}
250
251/// The `[start, end)` byte ranges (line endings excluded) of the lines of
252/// `source` longer than [`MAX_LINE`].
253fn long_lines(source: &str) -> Vec<(usize, usize)> {
254    let mut long = Vec::new();
255    let mut start = 0;
256    for raw in source.split_inclusive('\n') {
257        let len = raw.trim_end_matches(['\n', '\r']).len();
258        if len > MAX_LINE {
259            long.push((start, start + len));
260        }
261        start += raw.len();
262    }
263    long
264}
265
266/// `report` with `cut` replaced by `real` on its header line, the first
267/// carrying ariadne's `╭`: only there, so a message that happens to quote
268/// `cut` is left alone.
269fn fix_header(report: &[u8], cut: &str, real: &str) -> Vec<u8> {
270    let text = String::from_utf8_lossy(report);
271    let Some(corner) = text.find('╭') else {
272        return report.to_vec();
273    };
274    let start = text[..corner].rfind('\n').map_or(0, |i| i + 1);
275    let end = text[corner..].find('\n').map_or(text.len(), |i| corner + i);
276    let header = text[start..end].replacen(cut, real, 1);
277    format!("{}{header}{}", &text[..start], &text[end..]).into_bytes()
278}
279
280/// #1666: a line longer than this (in bytes) is cut to a window when a report
281/// renders it. Rendering cost and output size grow with the line, and a
282/// generated or minified line can be a megabyte.
283pub const MAX_LINE: usize = 400;
284
285/// Bytes kept either side of the labels on a cut line.
286const CONTEXT: usize = 80;
287
288/// One source line as a report sees it after [`cropped`]: where the original
289/// line ends, the window `[win_start, win_end)` of it that is kept, and
290/// where the kept text begins in the cropped source (after any `…`).
291struct LineWindow {
292    end: usize,
293    win_start: usize,
294    win_end: usize,
295    new_text_start: usize,
296}
297
298/// #1666: `source` and `err` as a report should render them, every line
299/// longer than [`MAX_LINE`] cut to a window and marked `…` where text was
300/// dropped, and the error's spans (the primary one and each label's) moved
301/// into the cut text. A window holds the line's labels with [`CONTEXT`] bytes
302/// either side, a label longer than [`MAX_LINE`] keeping only its head; when
303/// the labels are too far apart for that, it holds the primary span's
304/// neighbourhood, and a label left outside becomes a note. A long line without
305/// labels keeps its first [`MAX_LINE`] bytes. Cuts land on char boundaries.
306fn cropped(err: &CompileError, source: &str) -> (String, CompileError) {
307    let spans: Vec<(usize, usize)> = std::iter::once(&err.span)
308        .chain(err.labels.iter().map(|(s, _)| s))
309        .filter(|s| fits(s, source))
310        .map(|s| (s.start, s.end))
311        .collect();
312    let mut out = String::with_capacity(source.len().min(64 * 1024));
313    let mut lines: Vec<LineWindow> = Vec::new();
314    let mut start = 0;
315    for raw in source.split_inclusive('\n') {
316        let line_len = raw.trim_end_matches(['\n', '\r']).len();
317        let end = start + line_len;
318        let (win_start, win_end) = if line_len <= MAX_LINE {
319            (start, end)
320        } else {
321            let mut lo = usize::MAX;
322            let mut hi = 0;
323            for &(s, e) in &spans {
324                if e < start || s > end {
325                    continue;
326                }
327                let s = s.max(start);
328                let e = e.min(end).min(s + MAX_LINE);
329                lo = lo.min(s);
330                hi = hi.max(e);
331            }
332            let (lo, hi) = if lo == usize::MAX {
333                (start, start + MAX_LINE)
334            } else {
335                (
336                    lo.saturating_sub(CONTEXT).max(start),
337                    (hi + CONTEXT).min(end),
338                )
339            };
340            // Labels far apart on one line could still leave a long window;
341            // then keep the primary span's neighbourhood.
342            let (lo, hi) = if hi - lo > MAX_LINE + 2 * CONTEXT {
343                let s = err.span.start.clamp(start, end);
344                (
345                    s.saturating_sub(CONTEXT).max(start),
346                    (s + MAX_LINE).min(end),
347                )
348            } else {
349                (lo, hi)
350            };
351            (floor_char(source, lo), ceil_char(source, hi))
352        };
353        if win_start > start {
354            out.push('…');
355        }
356        let new_text_start = out.len();
357        out.push_str(&source[win_start..win_end]);
358        if win_end < end {
359            out.push('…');
360        }
361        out.push_str(&raw[line_len..]);
362        lines.push(LineWindow {
363            end,
364            win_start,
365            win_end,
366            new_text_start,
367        });
368        start += raw.len();
369    }
370    let line_of = |offset: usize| lines.get(lines.partition_point(|l| l.end < offset));
371    let map = |offset: usize| -> usize {
372        let Some(l) = line_of(offset) else {
373            return out.len();
374        };
375        // An offset cut from the line lands on the nearer edge of its window.
376        l.new_text_start + offset.clamp(l.win_start, l.win_end) - l.win_start
377    };
378    let mut err = err.clone();
379    err.span.start = map(err.span.start);
380    err.span.end = map(err.span.end).max(err.span.start);
381    for (span, _) in &mut err.labels {
382        // Outside means no byte of the label is kept: it starts at or past a
383        // cut end, or ends at or before a cut start (an empty label, before).
384        let outside = line_of(span.start).is_some_and(|l| {
385            (span.start >= l.win_end && l.win_end < l.end)
386                || if span.start == span.end {
387                    span.start < l.win_start
388                } else {
389                    span.end <= l.win_start
390                }
391        });
392        if !fits(span, source) || outside {
393            // Another file's label, or one cut from its line: keep it out of
394            // range of the cut text too, so the report makes it a note.
395            span.start = usize::MAX;
396            span.end = usize::MAX;
397            continue;
398        }
399        span.start = map(span.start);
400        span.end = map(span.end).max(span.start);
401    }
402    (out, err)
403}
404
405/// Whether `span` lies in `source`, on char boundaries: the test a report
406/// applies before underlining a label (otherwise it is a note).
407fn fits(span: &span::Span, source: &str) -> bool {
408    span.start <= span.end
409        && span.end <= source.len()
410        && source.is_char_boundary(span.start)
411        && source.is_char_boundary(span.end)
412}
413
414fn floor_char(s: &str, mut i: usize) -> usize {
415    while !s.is_char_boundary(i) {
416        i -= 1;
417    }
418    i
419}
420
421fn ceil_char(s: &str, mut i: usize) -> usize {
422    while !s.is_char_boundary(i) {
423        i += 1;
424    }
425    i
426}
427
428/// Render project-level errors as plain `[category] message` lines — the
429/// fallback for errors with no file attribution. Rich, source-context rendering
430/// lives in the front-end's project-failure renderer (v0.24).
431pub fn print_project_errors(root: &Path, errors: &[CompileError]) {
432    let _ = root;
433    for err in errors {
434        eprintln!("[{}] {}", err.category, err.message);
435        for note in &err.notes {
436            eprintln!("  note: {note}");
437        }
438        // Finding #47: a label's *text* survives even with nowhere to
439        // underline it (there is no single file to render against here).
440        for (_, label) in &err.labels {
441            eprintln!("  label: {label}");
442        }
443    }
444}
445
446/// v0.38 (ADR 0071): one terse line per diagnostic for tooling consumers
447/// (`bynk check --format short`):
448/// `path:line:col: <severity>[<category>]: <message>`. Line/column are
449/// 1-indexed, computed from the byte span against the source. The VS Code
450/// `bynk` problem-matcher keys off this exact shape — keep it stable.
451pub fn print_errors_short(errors: &[CompileError], source: &str, filename: &str) {
452    eprint!("{}", render_errors_short(errors, source, filename));
453}
454
455/// The string form of [`print_errors_short`] — one `…[category]: message` line
456/// per error, each newline-terminated. The renderer behind the CLI's `--format
457/// short`, exposed for testing.
458///
459/// Finding #47 doesn't reach this one: `tests/check_format_short.rs` locks
460/// `short` to *exactly* one line per diagnostic (the VS Code problem-matcher's
461/// contract), so notes/labels can't grow extra lines here without breaking a
462/// real machine consumer — unlike [`print_project_errors`]/[`render_project_errors`],
463/// which have no such one-line contract.
464pub fn render_errors_short(errors: &[CompileError], source: &str, filename: &str) -> String {
465    let mut out = String::new();
466    for err in errors {
467        out.push_str(&short_line(filename, source, err));
468        out.push('\n');
469    }
470    out
471}
472
473/// One terse `path:line:col: severity[category]: message` line for a single
474/// error against its source. The front-end's project-failure short renderer
475/// flattens an attributed error to `(label, text, error)` and calls this.
476pub fn short_line(filename: &str, source: &str, err: &CompileError) -> String {
477    let (line, col) = span::line_col(source, err.span.start);
478    format!(
479        "{filename}:{line}:{col}: {}[{}]: {}",
480        severity_word(err),
481        err.category,
482        err.message
483    )
484}
485
486/// `"error"` / `"warning"` for an error's [`Severity`].
487pub fn severity_word(err: &CompileError) -> &'static str {
488    match Severity::for_error(err) {
489        Severity::Error => "error",
490        Severity::Warning => "warning",
491        Severity::Hint => "hint",
492    }
493}
494
495/// `errors` without the [`Severity::Hint`] entries — what a terminal prints
496/// (#2838): hints are for the editor and the machine-readable surfaces.
497pub fn without_hints(errors: &[CompileError]) -> Vec<CompileError> {
498    errors
499        .iter()
500        .filter(|e| Severity::for_error(e) != Severity::Hint)
501        .cloned()
502        .collect()
503}
504
505/// Render a list of compile errors as plain `[category] message` lines (with
506/// notes and labels), for test assertion.
507pub fn render_project_errors(errors: &[CompileError]) -> String {
508    let mut out = String::new();
509    for err in errors {
510        out.push_str(&format!("[{}] {}\n", err.category, err.message));
511        for note in &err.notes {
512            out.push_str(&format!("  note: {note}\n"));
513        }
514        for (_, label) in &err.labels {
515            out.push_str(&format!("  label: {label}\n"));
516        }
517    }
518    out
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524    use bynk_syntax::span::Span;
525
526    /// The guard that replaced ADR 0100's crate boundary (D2, Decision H).
527    ///
528    /// `bynk-render` once could not see `AttributedError`/`ProjectFailure`
529    /// because its `Cargo.toml` did not list `bynk-emit`. Inside `bynk-driver`
530    /// the compiler would accept such a use, so this test reads the module's own
531    /// production source (everything before this `tests` module) and fails when
532    /// it names any crate other than `bynk_syntax`, `ariadne` or `std`, or
533    /// reaches into the rest of the driver with `crate::` or `super::`.
534    /// The offences in `production` source: a line naming a crate other than
535    /// `bynk_syntax`, `ariadne` or `std`, or reaching into the rest of the
536    /// driver with `crate::` or `super::` (inside `render`, `super` is the crate
537    /// root). Only `self` is accepted as a local root.
538    fn offences(production: &str) -> Vec<String> {
539        const ALLOWED: [&str; 3] = ["bynk_syntax", "ariadne", "std"];
540        let mut offences = Vec::new();
541        for (n, line) in production.lines().enumerate() {
542            let code = line.split("//").next().unwrap_or("").trim();
543            if code.is_empty() {
544                continue;
545            }
546            for local in ["crate::", "super::"] {
547                if code.contains(local) {
548                    offences.push(format!(
549                        "line {}: `{local}` reaches the rest of the driver: {code}",
550                        n + 1
551                    ));
552                }
553            }
554            // Every `bynk_…` identifier must be `bynk_syntax`.
555            let mut rest = code;
556            while let Some(i) = rest.find("bynk_") {
557                let word: String = rest[i..]
558                    .chars()
559                    .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
560                    .collect();
561                if !ALLOWED.contains(&word.as_str()) {
562                    offences.push(format!("line {}: names `{word}`: {code}", n + 1));
563                }
564                rest = &rest[i + word.len().max(1)..];
565            }
566            // Every `use` must start at an allowed root, or `self`.
567            let import = code.strip_prefix("pub ").unwrap_or(code);
568            if let Some(path) = import.strip_prefix("use ") {
569                let root = path.split("::").next().unwrap_or("").trim();
570                if !ALLOWED.contains(&root) && root != "self" {
571                    offences.push(format!("line {}: `use` of `{root}`: {code}", n + 1));
572                }
573            }
574        }
575        offences
576    }
577
578    #[test]
579    fn render_names_only_syntax_and_ariadne() {
580        let source = include_str!("render.rs");
581        let production = source
582            .split("\n#[cfg(test)]\nmod tests")
583            .next()
584            .expect("split always yields a first piece");
585        assert!(
586            production.len() < source.len(),
587            "the guard could not find this file's test module, so it would scan the tests too"
588        );
589        let offences = offences(production);
590        assert!(
591            offences.is_empty(),
592            "ADR 0100 (amended by D2): render may name only bynk_syntax, ariadne and std — \
593             the AttributedError → CompileError flattening stays above it:\n{}",
594            offences.join("\n")
595        );
596    }
597
598    /// The guard can fail: each way of reaching the rest of the driver or
599    /// `bynk-emit` is flagged, and ordinary render code is not.
600    #[test]
601    fn the_render_guard_flags_what_it_exists_to_flag() {
602        for bad in [
603            "use bynk_emit::ProjectFailure;",
604            "use crate::project::ProjectFailure;",
605            "use super::project::ProjectFailure;",
606            "let f: super::project::ProjectFailure = todo!();",
607            "let f: crate::project::ProjectFailure = todo!();",
608            "pub use bynk_check::Thing;",
609        ] {
610            assert!(!offences(bad).is_empty(), "the guard let `{bad}` through");
611        }
612        let clean = "use std::path::Path;\nuse ariadne::Source;\nuse bynk_syntax::{CompileError, span};\n\
613                     pub use bynk_syntax::error::LabelHome;\nuse self::helper::Thing;\n// use bynk_emit::X;\n";
614        assert_eq!(offences(clean), Vec::<String>::new());
615    }
616
617    /// #2838: a hint is worded `hint`, and a terminal drops it.
618    #[test]
619    fn a_hint_is_worded_as_one_and_dropped_for_the_terminal() {
620        let hint = CompileError::new(
621            "bynk.parse.let_else_staircase",
622            Span::new(0, 1),
623            "flatten this",
624        );
625        let other = CompileError::new("bynk.test", Span::new(0, 1), "kept");
626        assert_eq!(severity_word(&hint), "hint");
627        let kept = without_hints(&[hint, other]);
628        assert_eq!(kept.len(), 1);
629        assert_eq!(kept[0].category, "bynk.test");
630    }
631
632    /// Spans are byte offsets; ariadne 0.6 defaults to character indexing.
633    /// On a line with non-ASCII text before the span, the char-indexed
634    /// underline lands past the target. Pin the byte-indexed placement by
635    /// checking the caret column against the target's display column.
636    #[test]
637    fn underline_is_byte_indexed_on_non_ascii_lines() {
638        // `é` is 2 bytes / 1 display column; `bad` starts at byte 11,
639        // display column 10.
640        let source = "// caféxyz bad\n";
641        let start = source.find("bad").unwrap();
642        let err = CompileError::new(
643            "bynk.test.example",
644            Span::new(start, start + 3),
645            "bad thing",
646        );
647        let rendered = render_errors_plain(&[err], source, "probe.bynk");
648        let source_line = rendered
649            .lines()
650            .find(|l| l.contains("caféxyz"))
651            .expect("snippet line present");
652        let marker_line = rendered
653            .lines()
654            .find(|l| l.contains('┬'))
655            .expect("marker line present");
656        let col_of = |line: &str, target: char| line.chars().take_while(|&c| c != target).count();
657        // The `┬` sits within the underline under `bad` — same display
658        // column as `b`, or one to its right for spans wider than 1.
659        let b_col = col_of(source_line, 'b');
660        let caret_col = col_of(marker_line, '┬');
661        assert!(
662            (b_col..b_col + 3).contains(&caret_col),
663            "caret at display column {caret_col}, expected within `bad` at {b_col}..{}:\n{rendered}",
664            b_col + 3
665        );
666    }
667
668    /// A label whose span lies past the end of the rendered source belongs to
669    /// another file; it must be demoted to a note, not underline unrelated
670    /// text (or panic).
671    #[test]
672    fn out_of_bounds_label_demotes_to_note() {
673        let source = "commons demo\n";
674        let err = CompileError::new("bynk.test.example", Span::new(0, 7), "problem here")
675            .with_label(
676                Span::new(5_000, 5_010),
677                "parameter declared here (in another file)",
678            );
679        let rendered = render_errors_plain(&[err], source, "probe.bynk");
680        assert!(
681            rendered.contains("parameter declared here"),
682            "label text survives as a note:\n{rendered}"
683        );
684    }
685
686    /// A cross-file label whose byte span is *in-bounds* but lands mid-codepoint
687    /// (the file it really belongs to has non-ASCII text) must be demoted, not
688    /// fed to ariadne — a byte offset splitting a codepoint panics its byte→char
689    /// mapping (#716). The rendered source here is all multi-byte, so an odd
690    /// offset is never a char boundary.
691    #[test]
692    fn mid_codepoint_label_demotes_to_note() {
693        let source = "café ☕\n"; // `é` and `☕` are multi-byte
694        let err = CompileError::new("bynk.test.example", Span::new(0, 3), "problem here")
695            .with_label(
696                Span::new(4, 5),
697                "declared here (mid-codepoint, another file)",
698            );
699        // Must not panic, and the label survives as a note rather than a caret.
700        let rendered = render_errors_plain(&[err], source, "probe.bynk");
701        assert!(
702            rendered.contains("declared here (mid-codepoint, another file)"),
703            "a mid-codepoint label must survive as a note:\n{rendered}"
704        );
705    }
706
707    /// #1666: a megabyte line renders as a window around the label, marked
708    /// `…` both ends, with the header naming the label's real column.
709    #[test]
710    fn a_long_line_is_cut_around_the_label() {
711        let pad = "x".repeat(500_000);
712        let source = format!("commons c\n{pad}bad{pad}\n");
713        let start = source.find("bad").unwrap();
714        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
715        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
716        assert!(
717            rendered.len() < 4_000,
718            "{} bytes:\n{rendered}",
719            rendered.len()
720        );
721        assert!(
722            rendered.contains("probe.bynk:2:500001 "),
723            "the header keeps the column in the file:\n{rendered}"
724        );
725        let line = rendered.lines().find(|l| l.contains("xbadx")).unwrap();
726        assert!(line.contains('…') && line.ends_with('…'), "{line}");
727        let caret = rendered.lines().find(|l| l.contains('┬')).unwrap();
728        let col = |l: &str, s: &str| l[..l.find(s).unwrap()].chars().count();
729        assert!((col(line, "bad")..col(line, "bad") + 3).contains(&col(caret, "┬")));
730        // Coloured, the same report is just as small.
731        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
732        assert!(render_errors(&[err], &source, "probe.bynk").len() < 8_000);
733    }
734
735    /// #1666: a cut lands on a char boundary, and a line no longer than
736    /// [`MAX_LINE`] renders as it is.
737    #[test]
738    fn cuts_respect_chars_and_short_lines_are_kept() {
739        let wide = "é".repeat(300); // 600 bytes
740        let short = "y".repeat(MAX_LINE);
741        let source = format!("commons c\n{short}\n{wide}bad{wide}\n");
742        let start = source.find("bad").unwrap();
743        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
744        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
745        assert!(rendered.contains("probe.bynk:3:301 "), "{rendered}");
746        let line = rendered.lines().find(|l| l.contains("ébadé")).unwrap();
747        assert!(line.contains("…éé") && line.contains("éé…"), "{line}");
748
749        let span = Span::new(10, 11);
750        let err = CompileError::new("bynk.test.example", span, "here");
751        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
752        assert!(rendered.contains(&short), "{rendered}");
753    }
754
755    /// #1666: cutting a long line keeps another file's label a note.
756    #[test]
757    fn a_foreign_label_stays_a_note_on_a_cut_line() {
758        let source = format!("commons c\n{}\n", "z".repeat(1_000));
759        let err = CompileError::new("bynk.test.example", Span::new(10, 11), "here")
760            .with_label(Span::new(5_000, 5_010), "declared in another file");
761        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
762        assert!(
763            rendered.contains("Note: declared in another file"),
764            "{rendered}"
765        );
766    }
767
768    /// #1666: labels too far apart for one window keep the primary span's
769    /// neighbourhood; a label cut from it becomes a note rather than a caret
770    /// on the `…`.
771    #[test]
772    fn a_label_cut_from_the_window_becomes_a_note() {
773        let source = format!("commons c\nhere{}there\n", "1 ".repeat(100_000));
774        let there = source.find("there").unwrap();
775        let err = CompileError::new("bynk.test.example", Span::new(10, 14), "primary")
776            .with_label(Span::new(there, there + 5), "far label");
777        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
778        assert!(rendered.len() < 4_000, "{rendered}");
779        assert!(rendered.contains("Note: far label"), "{rendered}");
780        assert!(rendered.contains("probe.bynk:2:1 "), "{rendered}");
781    }
782
783    /// #1666: a CRLF line's `\r` is kept after a cut, outside the window.
784    #[test]
785    fn a_cut_crlf_line_keeps_its_line_ending() {
786        let source = format!("commons c\r\n{}bad\r\n", "w".repeat(1_000));
787        let start = source.find("bad").unwrap();
788        let (shown, _) = cropped(
789            &CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad"),
790            &source,
791        );
792        assert!(shown.starts_with("commons c\r\n…"), "{shown:?}");
793        assert!(shown.ends_with("wbad\r\n"), "{shown:?}");
794    }
795
796    /// #1666 review: a label touching a window edge from outside keeps no
797    /// byte, so it is a note, not a caret on the `…` or on the first kept
798    /// character. The far label forces the primary span's window
799    /// `[primary - CONTEXT, primary + MAX_LINE)`.
800    #[test]
801    fn a_label_touching_the_window_edge_from_outside_is_a_note() {
802        let source = format!("commons c\n{}\n", "q".repeat(20_000));
803        let p = 10 + 1_000;
804        let err = CompileError::new("bynk.test.example", Span::new(p, p + 1), "primary")
805            .with_label(Span::new(p + MAX_LINE, p + MAX_LINE + 3), "after the cut")
806            .with_label(Span::new(p - CONTEXT - 3, p - CONTEXT), "before the cut")
807            .with_label(Span::new(p + 10_000, p + 10_003), "far away");
808        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
809        for (i, label) in ["after the cut", "before the cut", "far away"]
810            .iter()
811            .enumerate()
812        {
813            let note = format!("Note {}: {label}", i + 1);
814            assert!(rendered.contains(&note), "{rendered}");
815        }
816    }
817
818    /// #1666 review: errors over one source, one on a cut line and one on a
819    /// short line, each get the right header; two long lines are cut
820    /// independently.
821    #[test]
822    fn several_errors_and_long_lines_render_independently() {
823        let pad = "x".repeat(5_000);
824        let source = format!("commons c\n{pad}one{pad}\nshort\n{pad}two{pad}\n");
825        let at = |word: &str| source.find(word).unwrap();
826        let err = |word: &str| {
827            CompileError::new("bynk.test.example", Span::new(at(word), at(word) + 3), word)
828        };
829        let errors = [
830            err("one"),
831            CompileError::new(
832                "bynk.test.example",
833                Span::new(at("short"), at("short") + 5),
834                "s",
835            ),
836            err("two"),
837        ];
838        let rendered = render_errors_plain(&errors, &source, "probe.bynk");
839        assert!(rendered.len() < 8_000, "{rendered}");
840        for header in [
841            "probe.bynk:2:5001 ",
842            "probe.bynk:3:1 ",
843            "probe.bynk:4:5001 ",
844        ] {
845            assert!(rendered.contains(header), "{header}:\n{rendered}");
846        }
847        assert!(
848            rendered
849                .lines()
850                .any(|l| l.contains("xonex") && l.ends_with('…'))
851        );
852        assert!(
853            rendered
854                .lines()
855                .any(|l| l.contains("xtwox") && l.ends_with('…'))
856        );
857    }
858
859    /// #1666 review: the coloured report's header names the column in the
860    /// file too.
861    #[test]
862    fn the_coloured_header_keeps_the_column_in_the_file() {
863        let source = format!("commons c\n{}bad\n", "x".repeat(50_000));
864        let start = source.find("bad").unwrap();
865        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
866        let rendered = render_errors(&[err], &source, "probe.bynk");
867        assert!(rendered.contains("probe.bynk:2:50001 "), "{rendered}");
868    }
869
870    /// #1666 review: a header fix touches only the header, not a message
871    /// that quotes the same `path:line:col`.
872    #[test]
873    fn the_header_fix_leaves_the_message_alone() {
874        let source = format!("commons c\n{}bad\n", "x".repeat(1_000));
875        let start = source.find("bad").unwrap();
876        // The cut puts `bad` at column 82 of the shown line.
877        let err = CompileError::new(
878            "bynk.test.example",
879            Span::new(start, start + 3),
880            "see probe.bynk:2:82",
881        );
882        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
883        assert!(
884            rendered.contains("Error: see probe.bynk:2:82"),
885            "{rendered}"
886        );
887        assert!(rendered.contains("[ probe.bynk:2:1001 ]"), "{rendered}");
888    }
889
890    /// #1666 review: a rendered report over CRLF source numbers the cut line
891    /// as in the file.
892    #[test]
893    fn a_cut_crlf_report_keeps_line_numbers() {
894        let source = format!("commons c\r\n\r\n{}bad\r\nnext\r\n", "w".repeat(1_000));
895        let start = source.find("bad").unwrap();
896        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
897        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
898        assert!(rendered.contains("[ probe.bynk:3:1001 ]"), "{rendered}");
899        assert!(
900            rendered
901                .lines()
902                .any(|l| l.starts_with(" 3 │ …") && l.contains("wbad")),
903            "{rendered}"
904        );
905    }
906
907    /// A label in another file is drawn in a snippet of that file; one with
908    /// no text to show, or on one of that file's long lines (#1666, which cuts
909    /// only the primary file), becomes a note.
910    #[test]
911    fn a_label_in_another_file_renders_against_that_file() {
912        let primary = "context app\n\n\nservice api {}\n";
913        let sibling = "context app\nservice api {}\n";
914        let at = |text: &str| text.find("api").unwrap();
915        let err = CompileError::new(
916            "bynk.resolve.duplicate_service",
917            Span::new(at(primary), at(primary) + 3),
918            "already declared",
919        )
920        .with_label(
921            Span::new(at(sibling), at(sibling) + 3),
922            "previously declared here",
923        )
924        .with_label(Span::new(0, 1), "in an injected unit");
925        let homes = [
926            LabelHome::File {
927                filename: "a.bynk",
928                source: sibling,
929            },
930            LabelHome::Unavailable,
931        ];
932        let rendered = render_error_in_plain(&err, primary, "z.bynk", &homes);
933        let (z, a) = rendered.split_once("─[ a.bynk:2:9 ]").expect(&rendered);
934        assert!(z.contains("─[ z.bynk:4:9 ]"), "{rendered}");
935        assert!(!z.contains("previously declared here"), "{rendered}");
936        assert!(a.contains(" 2 │ service api {}"), "{rendered}");
937        assert!(a.contains("previously declared here"), "{rendered}");
938        assert!(rendered.contains("Note: in an injected unit"), "{rendered}");
939
940        let long = format!("context app\n{} service api {{}}\n", "x".repeat(MAX_LINE));
941        let err = CompileError::new("bynk.test", Span::new(0, 7), "msg")
942            .with_label(Span::new(at(&long), at(&long) + 3), "on a long line");
943        let homes = [LabelHome::File {
944            filename: "a.bynk",
945            source: &long,
946        }];
947        let rendered = render_error_in_plain(&err, primary, "z.bynk", &homes);
948        assert!(!rendered.contains("a.bynk"), "{rendered}");
949        assert!(rendered.contains("Note: on a long line"), "{rendered}");
950    }
951
952    /// #1956: a label in another file whose text has non-ASCII before it is
953    /// headed by its own line and column. ariadne 0.6's byte-index mode looked
954    /// the label's char offset up as a byte offset for that header — naming an
955    /// earlier line, or panicking when the offset split a codepoint, as it does
956    /// here (`bynk.bynk`, where first-party labels point, is full of `—`).
957    #[test]
958    fn a_label_in_another_file_after_non_ascii_text_is_headed_by_its_own_position() {
959        let primary = "context app\n\n\nservice api {}\n";
960        let sibling = "context app\n// ———\nservice api {} // é\n";
961        let at = |text: &str| text.find("api").unwrap();
962        let err = CompileError::new("bynk.test", Span::new(at(primary), at(primary) + 3), "msg")
963            .with_label(
964                Span::new(at(sibling), at(sibling) + 3),
965                "previously declared here",
966            );
967        let homes = [LabelHome::File {
968            filename: "a.bynk",
969            source: sibling,
970        }];
971        let rendered = render_error_in_plain(&err, primary, "z.bynk", &homes);
972        let (z, a) = rendered.split_once("─[ a.bynk:3:9 ]").expect(&rendered);
973        assert!(z.contains("─[ z.bynk:4:9 ]"), "{rendered}");
974        assert!(a.contains(" 3 │ service api {} // é"), "{rendered}");
975        assert!(a.contains("previously declared here"), "{rendered}");
976    }
977
978    /// A long primary line is cut (#1666) even when a label lies in another
979    /// file: the report heads with the primary span's column in the file, not
980    /// in the cut text, and the sibling's snippet keeps its own header.
981    #[test]
982    fn a_cut_primary_line_keeps_its_column_beside_a_label_in_another_file() {
983        let primary = format!(
984            "context app\n{} service api {{}}\n",
985            "x".repeat(2 * MAX_LINE)
986        );
987        let sibling = "context app\nservice api {}\n";
988        let at = |text: &str| text.find("api").unwrap();
989        let err = CompileError::new(
990            "bynk.resolve.duplicate_service",
991            Span::new(at(&primary), at(&primary) + 3),
992            "already declared",
993        )
994        .with_label(
995            Span::new(at(sibling), at(sibling) + 3),
996            "previously declared here",
997        );
998        let homes = [LabelHome::File {
999            filename: "a.bynk",
1000            source: sibling,
1001        }];
1002        let rendered = render_error_in_plain(&err, &primary, "z.bynk", &homes);
1003        let col = at(&primary) - primary.find('\n').unwrap();
1004        let (z, a) = rendered.split_once("─[ a.bynk:2:9 ]").expect(&rendered);
1005        assert!(z.contains(&format!("─[ z.bynk:2:{col} ]")), "{rendered}");
1006        assert!(z.contains('…'), "the long primary line is cut: {rendered}");
1007        assert!(!z.contains("previously declared here"), "{rendered}");
1008        assert!(a.contains("previously declared here"), "{rendered}");
1009    }
1010}