bynk-render 0.314.23

Diagnostic rendering for the Bynk compiler: ariadne human output and the short line form, shared by both CLIs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Bynk's shared diagnostic-rendering layer.
//!
//! The presentation layer over [`bynk_syntax::CompileError`]: ariadne human
//! output and the `short`/`json`-feeding line forms. Every renderer takes
//! `&[CompileError]` + `source` + `filename` — it is agnostic about *where* the
//! errors came from. Both CLI front-ends adopt it so they render identically
//! (ADR 0100).
//!
//! **Invariant (ADR 0100):** this crate depends on `bynk-syntax` **only** (plus
//! `ariadne`). It must never see `AttributedError`/`ProjectFailure` (which live
//! in `bynk-emit`): the `AttributedError → CompileError` flattening stays *above*
//! render, in the front-end, so there is no `render → emit` cycle. A function
//! here taking a `ProjectFailure` would not even compile — the dependency isn't
//! present, by design.
//!
//! Extracted from `bynkc` as slice 6 of the crate-decomposition track.

use std::path::Path;

use ariadne::Source;
use bynk_syntax::error::Severity;
use bynk_syntax::{CompileError, span};

/// Render a list of compile errors to a string (for tests) using the given
/// filename as the diagnostic source label.
pub fn render_errors(errors: &[CompileError], source: &str, filename: &str) -> String {
    String::from_utf8_lossy(&render_all(errors, source, filename, true)).into_owned()
}

/// Render a list of compile errors to a string with colour disabled and the
/// given filename as the source label. Unlike [`render_errors`], the output
/// contains no ANSI escape codes, so it is byte-stable — suitable for the
/// committed diagnostic transcripts under `site/src/diagnostics/`.
pub fn render_errors_plain(errors: &[CompileError], source: &str, filename: &str) -> String {
    String::from_utf8_lossy(&render_all(errors, source, filename, false)).into_owned()
}

/// Render to stderr, used by the CLI. Coloured only when [`stderr_color`]
/// allows it.
pub fn print_errors(errors: &[CompileError], source: &str, filename: &str) {
    use std::io::Write;
    let out = render_all(errors, source, filename, stderr_color());
    let _ = std::io::stderr().lock().write_all(&out);
}

/// The ariadne reports for `errors`. A report whose spans touch a line
/// longer than [`MAX_LINE`] renders its own copy of the source, cut by
/// [`cropped`]; the rest share one view of `source`.
fn render_all(errors: &[CompileError], source: &str, filename: &str, color: bool) -> Vec<u8> {
    fn write<'a>(
        err: &'a CompileError,
        filename: &'a str,
        cache: &mut (&'a str, Source<&str>),
        color: bool,
        out: &mut Vec<u8>,
    ) {
        let source = cache.1.text();
        let report = if color {
            err.report_for(filename, source)
        } else {
            err.report_plain_for(filename, source)
        };
        report
            .write(&mut *cache, out)
            .expect("write to Vec<u8> cannot fail");
    }
    let long = long_lines(source);
    let mut cache = (filename, Source::from(source));
    let mut index = None;
    let mut out = Vec::new();
    for err in errors {
        let touches_long = std::iter::once(&err.span)
            .chain(err.labels.iter().map(|(s, _)| s))
            .filter(|s| fits(s, source))
            .any(|s| {
                long.iter()
                    .any(|&(start, end)| s.start <= end && s.end >= start)
            });
        if !touches_long {
            write(err, filename, &mut cache, color, &mut out);
            continue;
        }
        let (shown, shown_err) = cropped(err, source);
        let mut one = Vec::new();
        write(
            &shown_err,
            filename,
            &mut (filename, Source::from(&*shown)),
            color,
            &mut one,
        );
        // ariadne heads the report with the primary span's `line:col` in the
        // text it was given; on a line cut at its start that column is the cut
        // one. Put back the column in the file, as the short form reports it.
        let cut = span::line_col(&shown, shown_err.span.start);
        let real = index
            .get_or_insert_with(|| span::LineIndex::new(source))
            .line_col(source, err.span.start);
        if cut != real {
            one = fix_header(
                &one,
                &format!("{filename}:{}:{}", cut.0, cut.1),
                &format!("{filename}:{}:{}", real.0, real.1),
            );
        }
        out.extend(one);
    }
    out
}

/// The `[start, end)` byte ranges (line endings excluded) of the lines of
/// `source` longer than [`MAX_LINE`].
fn long_lines(source: &str) -> Vec<(usize, usize)> {
    let mut long = Vec::new();
    let mut start = 0;
    for raw in source.split_inclusive('\n') {
        let len = raw.trim_end_matches(['\n', '\r']).len();
        if len > MAX_LINE {
            long.push((start, start + len));
        }
        start += raw.len();
    }
    long
}

/// `report` with `cut` replaced by `real` on its header line, the first
/// carrying ariadne's `╭`: only there, so a message that happens to quote
/// `cut` is left alone.
fn fix_header(report: &[u8], cut: &str, real: &str) -> Vec<u8> {
    let text = String::from_utf8_lossy(report);
    let Some(corner) = text.find('╭') else {
        return report.to_vec();
    };
    let start = text[..corner].rfind('\n').map_or(0, |i| i + 1);
    let end = text[corner..].find('\n').map_or(text.len(), |i| corner + i);
    let header = text[start..end].replacen(cut, real, 1);
    format!("{}{header}{}", &text[..start], &text[end..]).into_bytes()
}

/// #1666: a line longer than this (in bytes) is cut to a window when a report
/// renders it. Rendering cost and output size grow with the line, and a
/// generated or minified line can be a megabyte.
pub const MAX_LINE: usize = 400;

/// Bytes kept either side of the labels on a cut line.
const CONTEXT: usize = 80;

/// One source line as a report sees it after [`cropped`]: where the original
/// line ends, the window `[win_start, win_end)` of it that is kept, and
/// where the kept text begins in the cropped source (after any `…`).
struct LineWindow {
    end: usize,
    win_start: usize,
    win_end: usize,
    new_text_start: usize,
}

/// #1666: `source` and `err` as a report should render them, every line
/// longer than [`MAX_LINE`] cut to a window and marked `…` where text was
/// dropped, and the error's spans (the primary one and each label's) moved
/// into the cut text. A window holds the line's labels with [`CONTEXT`] bytes
/// either side, a label longer than [`MAX_LINE`] keeping only its head; when
/// the labels are too far apart for that, it holds the primary span's
/// neighbourhood, and a label left outside becomes a note. A long line without
/// labels keeps its first [`MAX_LINE`] bytes. Cuts land on char boundaries.
fn cropped(err: &CompileError, source: &str) -> (String, CompileError) {
    let spans: Vec<(usize, usize)> = std::iter::once(&err.span)
        .chain(err.labels.iter().map(|(s, _)| s))
        .filter(|s| fits(s, source))
        .map(|s| (s.start, s.end))
        .collect();
    let mut out = String::with_capacity(source.len().min(64 * 1024));
    let mut lines: Vec<LineWindow> = Vec::new();
    let mut start = 0;
    for raw in source.split_inclusive('\n') {
        let line_len = raw.trim_end_matches(['\n', '\r']).len();
        let end = start + line_len;
        let (win_start, win_end) = if line_len <= MAX_LINE {
            (start, end)
        } else {
            let mut lo = usize::MAX;
            let mut hi = 0;
            for &(s, e) in &spans {
                if e < start || s > end {
                    continue;
                }
                let s = s.max(start);
                let e = e.min(end).min(s + MAX_LINE);
                lo = lo.min(s);
                hi = hi.max(e);
            }
            let (lo, hi) = if lo == usize::MAX {
                (start, start + MAX_LINE)
            } else {
                (
                    lo.saturating_sub(CONTEXT).max(start),
                    (hi + CONTEXT).min(end),
                )
            };
            // Labels far apart on one line could still leave a long window;
            // then keep the primary span's neighbourhood.
            let (lo, hi) = if hi - lo > MAX_LINE + 2 * CONTEXT {
                let s = err.span.start.clamp(start, end);
                (
                    s.saturating_sub(CONTEXT).max(start),
                    (s + MAX_LINE).min(end),
                )
            } else {
                (lo, hi)
            };
            (floor_char(source, lo), ceil_char(source, hi))
        };
        if win_start > start {
            out.push('…');
        }
        let new_text_start = out.len();
        out.push_str(&source[win_start..win_end]);
        if win_end < end {
            out.push('…');
        }
        out.push_str(&raw[line_len..]);
        lines.push(LineWindow {
            end,
            win_start,
            win_end,
            new_text_start,
        });
        start += raw.len();
    }
    let line_of = |offset: usize| lines.get(lines.partition_point(|l| l.end < offset));
    let map = |offset: usize| -> usize {
        let Some(l) = line_of(offset) else {
            return out.len();
        };
        // An offset cut from the line lands on the nearer edge of its window.
        l.new_text_start + offset.clamp(l.win_start, l.win_end) - l.win_start
    };
    let mut err = err.clone();
    err.span.start = map(err.span.start);
    err.span.end = map(err.span.end).max(err.span.start);
    for (span, _) in &mut err.labels {
        // Outside means no byte of the label is kept: it starts at or past a
        // cut end, or ends at or before a cut start (an empty label, before).
        let outside = line_of(span.start).is_some_and(|l| {
            (span.start >= l.win_end && l.win_end < l.end)
                || if span.start == span.end {
                    span.start < l.win_start
                } else {
                    span.end <= l.win_start
                }
        });
        if !fits(span, source) || outside {
            // Another file's label, or one cut from its line: keep it out of
            // range of the cut text too, so the report makes it a note.
            span.start = usize::MAX;
            span.end = usize::MAX;
            continue;
        }
        span.start = map(span.start);
        span.end = map(span.end).max(span.start);
    }
    (out, err)
}

/// Whether `span` lies in `source`, on char boundaries: the test a report
/// applies before underlining a label (otherwise it is a note).
fn fits(span: &span::Span, source: &str) -> bool {
    span.start <= span.end
        && span.end <= source.len()
        && source.is_char_boundary(span.start)
        && source.is_char_boundary(span.end)
}

fn floor_char(s: &str, mut i: usize) -> usize {
    while !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

fn ceil_char(s: &str, mut i: usize) -> usize {
    while !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

/// #1666: whether diagnostics on stderr are coloured: only when stderr is a
/// terminal and `NO_COLOR` is unset or empty (<https://no-color.org>). Colour
/// piped into a file or a CI log is noise, and ariadne colours per character,
/// so it multiplied the output's size by about twenty.
///
/// #1777: `FORCE_COLOR` (<https://force-color.org>) or `CLICOLOR_FORCE`
/// (<https://bixense.com/clicolors/>), set to anything but the empty string or
/// `0`, turns colour on without a terminal, for `less -R` or a CI log that
/// renders ANSI. `0` means "don't force", not "force off": `NO_COLOR` is the
/// off switch, and it wins over both. That is clap's order for `NO_COLOR` and
/// `CLICOLOR_FORCE`; clap doesn't read `FORCE_COLOR`, so only
/// `CLICOLOR_FORCE` also colours clap's own help and errors.
pub fn stderr_color() -> bool {
    use std::io::IsTerminal;
    color_allowed(std::io::stderr().is_terminal(), |name| {
        std::env::var_os(name)
    })
}

/// [`stderr_color`]'s decision, over whether stderr is a terminal and a
/// lookup of the environment.
fn color_allowed(is_terminal: bool, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
    let set = |name| var(name).is_some_and(|v| !v.is_empty());
    let forced = |name| var(name).is_some_and(|v| !v.is_empty() && v != "0");
    if set("NO_COLOR") {
        false
    } else {
        is_terminal || forced("FORCE_COLOR") || forced("CLICOLOR_FORCE")
    }
}

/// Render project-level errors as plain `[category] message` lines — the
/// fallback for errors with no file attribution. Rich, source-context rendering
/// lives in the front-end's project-failure renderer (v0.24).
pub fn print_project_errors(root: &Path, errors: &[CompileError]) {
    let _ = root;
    for err in errors {
        eprintln!("[{}] {}", err.category, err.message);
        for note in &err.notes {
            eprintln!("  note: {note}");
        }
        // Finding #47: a label's *text* survives even with nowhere to
        // underline it (there is no single file to render against here).
        for (_, label) in &err.labels {
            eprintln!("  label: {label}");
        }
    }
}

/// v0.38 (ADR 0071): one terse line per diagnostic for tooling consumers
/// (`bynkc check --format short`):
/// `path:line:col: <severity>[<category>]: <message>`. Line/column are
/// 1-indexed, computed from the byte span against the source. The VS Code
/// `bynkc` problem-matcher keys off this exact shape — keep it stable.
pub fn print_errors_short(errors: &[CompileError], source: &str, filename: &str) {
    eprint!("{}", render_errors_short(errors, source, filename));
}

/// The string form of [`print_errors_short`] — one `…[category]: message` line
/// per error, each newline-terminated. The renderer behind the CLI's `--format
/// short`, exposed for testing.
///
/// Finding #47 doesn't reach this one: `tests/check_format_short.rs` locks
/// `short` to *exactly* one line per diagnostic (the VS Code problem-matcher's
/// contract), so notes/labels can't grow extra lines here without breaking a
/// real machine consumer — unlike [`print_project_errors`]/[`render_project_errors`],
/// which have no such one-line contract.
pub fn render_errors_short(errors: &[CompileError], source: &str, filename: &str) -> String {
    let mut out = String::new();
    for err in errors {
        out.push_str(&short_line(filename, source, err));
        out.push('\n');
    }
    out
}

/// One terse `path:line:col: severity[category]: message` line for a single
/// error against its source. The front-end's project-failure short renderer
/// flattens an attributed error to `(label, text, error)` and calls this.
pub fn short_line(filename: &str, source: &str, err: &CompileError) -> String {
    let (line, col) = span::line_col(source, err.span.start);
    format!(
        "{filename}:{line}:{col}: {}[{}]: {}",
        severity_word(err),
        err.category,
        err.message
    )
}

/// `"error"` / `"warning"` for an error's [`Severity`].
pub fn severity_word(err: &CompileError) -> &'static str {
    match Severity::for_error(err) {
        Severity::Error => "error",
        Severity::Warning => "warning",
    }
}

/// Render a list of compile errors as plain `[category] message` lines (with
/// notes and labels), for test assertion.
pub fn render_project_errors(errors: &[CompileError]) -> String {
    let mut out = String::new();
    for err in errors {
        out.push_str(&format!("[{}] {}\n", err.category, err.message));
        for note in &err.notes {
            out.push_str(&format!("  note: {note}\n"));
        }
        for (_, label) in &err.labels {
            out.push_str(&format!("  label: {label}\n"));
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use bynk_syntax::span::Span;

    /// Spans are byte offsets; ariadne 0.6 defaults to character indexing.
    /// On a line with non-ASCII text before the span, the char-indexed
    /// underline lands past the target. Pin the byte-indexed placement by
    /// checking the caret column against the target's display column.
    #[test]
    fn underline_is_byte_indexed_on_non_ascii_lines() {
        // `é` is 2 bytes / 1 display column; `bad` starts at byte 11,
        // display column 10.
        let source = "-- caféxyz bad\n";
        let start = source.find("bad").unwrap();
        let err = CompileError::new(
            "bynk.test.example",
            Span::new(start, start + 3),
            "bad thing",
        );
        let rendered = render_errors_plain(&[err], source, "probe.bynk");
        let source_line = rendered
            .lines()
            .find(|l| l.contains("caféxyz"))
            .expect("snippet line present");
        let marker_line = rendered
            .lines()
            .find(|l| l.contains('┬'))
            .expect("marker line present");
        let col_of = |line: &str, target: char| line.chars().take_while(|&c| c != target).count();
        // The `┬` sits within the underline under `bad` — same display
        // column as `b`, or one to its right for spans wider than 1.
        let b_col = col_of(source_line, 'b');
        let caret_col = col_of(marker_line, '┬');
        assert!(
            (b_col..b_col + 3).contains(&caret_col),
            "caret at display column {caret_col}, expected within `bad` at {b_col}..{}:\n{rendered}",
            b_col + 3
        );
    }

    /// A label whose span lies past the end of the rendered source belongs to
    /// another file; it must be demoted to a note, not underline unrelated
    /// text (or panic).
    #[test]
    fn out_of_bounds_label_demotes_to_note() {
        let source = "commons demo\n";
        let err = CompileError::new("bynk.test.example", Span::new(0, 7), "problem here")
            .with_label(
                Span::new(5_000, 5_010),
                "parameter declared here (in another file)",
            );
        let rendered = render_errors_plain(&[err], source, "probe.bynk");
        assert!(
            rendered.contains("parameter declared here"),
            "label text survives as a note:\n{rendered}"
        );
    }

    /// A cross-file label whose byte span is *in-bounds* but lands mid-codepoint
    /// (the file it really belongs to has non-ASCII text) must be demoted, not
    /// fed to ariadne — a byte offset splitting a codepoint panics its byte→char
    /// mapping (#716). The rendered source here is all multi-byte, so an odd
    /// offset is never a char boundary.
    #[test]
    fn mid_codepoint_label_demotes_to_note() {
        let source = "café ☕\n"; // `é` and `☕` are multi-byte
        let err = CompileError::new("bynk.test.example", Span::new(0, 3), "problem here")
            .with_label(
                Span::new(4, 5),
                "declared here (mid-codepoint, another file)",
            );
        // Must not panic, and the label survives as a note rather than a caret.
        let rendered = render_errors_plain(&[err], source, "probe.bynk");
        assert!(
            rendered.contains("declared here (mid-codepoint, another file)"),
            "a mid-codepoint label must survive as a note:\n{rendered}"
        );
    }

    /// #1666: colour needs a terminal, and `NO_COLOR` set to anything but
    /// the empty string turns it off. #1777: `FORCE_COLOR` or
    /// `CLICOLOR_FORCE`, set to anything but the empty string or `0`, turns
    /// it on without one; `NO_COLOR` wins over both.
    #[test]
    fn color_needs_a_terminal_or_a_force_and_no_no_color() {
        use std::ffi::OsString;
        let allowed = |is_terminal, vars: &[(&str, &str)]| {
            color_allowed(is_terminal, |name| {
                vars.iter()
                    .find(|(n, _)| *n == name)
                    .map(|(_, v)| OsString::from(v))
            })
        };
        assert!(allowed(true, &[]));
        assert!(allowed(true, &[("NO_COLOR", "")]));
        assert!(!allowed(true, &[("NO_COLOR", "1")]));
        assert!(!allowed(false, &[]));
        assert!(!allowed(false, &[("NO_COLOR", "")]));

        for force in ["FORCE_COLOR", "CLICOLOR_FORCE"] {
            assert!(allowed(false, &[(force, "1")]), "{force}=1");
            assert!(allowed(false, &[(force, "true")]), "{force}=true");
            assert!(!allowed(false, &[(force, "")]), "{force}= is unset");
            assert!(!allowed(false, &[(force, "0")]), "{force}=0 doesn't force");
            assert!(allowed(true, &[(force, "0")]), "{force}=0 doesn't forbid");
            assert!(allowed(false, &[(force, "1"), ("NO_COLOR", "")]));
            assert!(!allowed(false, &[(force, "1"), ("NO_COLOR", "1")]));
            assert!(!allowed(true, &[(force, "1"), ("NO_COLOR", "1")]));
        }
    }

    /// #1666: a megabyte line renders as a window around the label, marked
    /// `…` both ends, with the header naming the label's real column.
    #[test]
    fn a_long_line_is_cut_around_the_label() {
        let pad = "x".repeat(500_000);
        let source = format!("commons c\n{pad}bad{pad}\n");
        let start = source.find("bad").unwrap();
        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(
            rendered.len() < 4_000,
            "{} bytes:\n{rendered}",
            rendered.len()
        );
        assert!(
            rendered.contains("probe.bynk:2:500001 "),
            "the header keeps the column in the file:\n{rendered}"
        );
        let line = rendered.lines().find(|l| l.contains("xbadx")).unwrap();
        assert!(line.contains('…') && line.ends_with('…'), "{line}");
        let caret = rendered.lines().find(|l| l.contains('┬')).unwrap();
        let col = |l: &str, s: &str| l[..l.find(s).unwrap()].chars().count();
        assert!((col(line, "bad")..col(line, "bad") + 3).contains(&col(caret, "┬")));
        // Coloured, the same report is just as small.
        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
        assert!(render_errors(&[err], &source, "probe.bynk").len() < 8_000);
    }

    /// #1666: a cut lands on a char boundary, and a line no longer than
    /// [`MAX_LINE`] renders as it is.
    #[test]
    fn cuts_respect_chars_and_short_lines_are_kept() {
        let wide = "é".repeat(300); // 600 bytes
        let short = "y".repeat(MAX_LINE);
        let source = format!("commons c\n{short}\n{wide}bad{wide}\n");
        let start = source.find("bad").unwrap();
        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(rendered.contains("probe.bynk:3:301 "), "{rendered}");
        let line = rendered.lines().find(|l| l.contains("ébadé")).unwrap();
        assert!(line.contains("…éé") && line.contains("éé…"), "{line}");

        let span = Span::new(10, 11);
        let err = CompileError::new("bynk.test.example", span, "here");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(rendered.contains(&short), "{rendered}");
    }

    /// #1666: cutting a long line keeps another file's label a note.
    #[test]
    fn a_foreign_label_stays_a_note_on_a_cut_line() {
        let source = format!("commons c\n{}\n", "z".repeat(1_000));
        let err = CompileError::new("bynk.test.example", Span::new(10, 11), "here")
            .with_label(Span::new(5_000, 5_010), "declared in another file");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(
            rendered.contains("Note: declared in another file"),
            "{rendered}"
        );
    }

    /// #1666: labels too far apart for one window keep the primary span's
    /// neighbourhood; a label cut from it becomes a note rather than a caret
    /// on the `…`.
    #[test]
    fn a_label_cut_from_the_window_becomes_a_note() {
        let source = format!("commons c\nhere{}there\n", "1 ".repeat(100_000));
        let there = source.find("there").unwrap();
        let err = CompileError::new("bynk.test.example", Span::new(10, 14), "primary")
            .with_label(Span::new(there, there + 5), "far label");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(rendered.len() < 4_000, "{rendered}");
        assert!(rendered.contains("Note: far label"), "{rendered}");
        assert!(rendered.contains("probe.bynk:2:1 "), "{rendered}");
    }

    /// #1666: a CRLF line's `\r` is kept after a cut, outside the window.
    #[test]
    fn a_cut_crlf_line_keeps_its_line_ending() {
        let source = format!("commons c\r\n{}bad\r\n", "w".repeat(1_000));
        let start = source.find("bad").unwrap();
        let (shown, _) = cropped(
            &CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad"),
            &source,
        );
        assert!(shown.starts_with("commons c\r\n…"), "{shown:?}");
        assert!(shown.ends_with("wbad\r\n"), "{shown:?}");
    }

    /// #1666 review: a label touching a window edge from outside keeps no
    /// byte, so it is a note, not a caret on the `…` or on the first kept
    /// character. The far label forces the primary span's window
    /// `[primary - CONTEXT, primary + MAX_LINE)`.
    #[test]
    fn a_label_touching_the_window_edge_from_outside_is_a_note() {
        let source = format!("commons c\n{}\n", "q".repeat(20_000));
        let p = 10 + 1_000;
        let err = CompileError::new("bynk.test.example", Span::new(p, p + 1), "primary")
            .with_label(Span::new(p + MAX_LINE, p + MAX_LINE + 3), "after the cut")
            .with_label(Span::new(p - CONTEXT - 3, p - CONTEXT), "before the cut")
            .with_label(Span::new(p + 10_000, p + 10_003), "far away");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        for (i, label) in ["after the cut", "before the cut", "far away"]
            .iter()
            .enumerate()
        {
            let note = format!("Note {}: {label}", i + 1);
            assert!(rendered.contains(&note), "{rendered}");
        }
    }

    /// #1666 review: errors over one source, one on a cut line and one on a
    /// short line, each get the right header; two long lines are cut
    /// independently.
    #[test]
    fn several_errors_and_long_lines_render_independently() {
        let pad = "x".repeat(5_000);
        let source = format!("commons c\n{pad}one{pad}\nshort\n{pad}two{pad}\n");
        let at = |word: &str| source.find(word).unwrap();
        let err = |word: &str| {
            CompileError::new("bynk.test.example", Span::new(at(word), at(word) + 3), word)
        };
        let errors = [
            err("one"),
            CompileError::new(
                "bynk.test.example",
                Span::new(at("short"), at("short") + 5),
                "s",
            ),
            err("two"),
        ];
        let rendered = render_errors_plain(&errors, &source, "probe.bynk");
        assert!(rendered.len() < 8_000, "{rendered}");
        for header in [
            "probe.bynk:2:5001 ",
            "probe.bynk:3:1 ",
            "probe.bynk:4:5001 ",
        ] {
            assert!(rendered.contains(header), "{header}:\n{rendered}");
        }
        assert!(
            rendered
                .lines()
                .any(|l| l.contains("xonex") && l.ends_with('…'))
        );
        assert!(
            rendered
                .lines()
                .any(|l| l.contains("xtwox") && l.ends_with('…'))
        );
    }

    /// #1666 review: the coloured report's header names the column in the
    /// file too.
    #[test]
    fn the_coloured_header_keeps_the_column_in_the_file() {
        let source = format!("commons c\n{}bad\n", "x".repeat(50_000));
        let start = source.find("bad").unwrap();
        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
        let rendered = render_errors(&[err], &source, "probe.bynk");
        assert!(rendered.contains("probe.bynk:2:50001 "), "{rendered}");
    }

    /// #1666 review: a header fix touches only the header, not a message
    /// that quotes the same `path:line:col`.
    #[test]
    fn the_header_fix_leaves_the_message_alone() {
        let source = format!("commons c\n{}bad\n", "x".repeat(1_000));
        let start = source.find("bad").unwrap();
        // The cut puts `bad` at column 82 of the shown line.
        let err = CompileError::new(
            "bynk.test.example",
            Span::new(start, start + 3),
            "see probe.bynk:2:82",
        );
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(
            rendered.contains("Error: see probe.bynk:2:82"),
            "{rendered}"
        );
        assert!(rendered.contains("[ probe.bynk:2:1001 ]"), "{rendered}");
    }

    /// #1666 review: a rendered report over CRLF source numbers the cut line
    /// as in the file.
    #[test]
    fn a_cut_crlf_report_keeps_line_numbers() {
        let source = format!("commons c\r\n\r\n{}bad\r\nnext\r\n", "w".repeat(1_000));
        let start = source.find("bad").unwrap();
        let err = CompileError::new("bynk.test.example", Span::new(start, start + 3), "bad");
        let rendered = render_errors_plain(&[err], &source, "probe.bynk");
        assert!(rendered.contains("[ probe.bynk:3:1001 ]"), "{rendered}");
        assert!(
            rendered
                .lines()
                .any(|l| l.starts_with(" 3 │ …") && l.contains("wbad")),
            "{rendered}"
        );
    }
}