bynk_render/lib.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. Both CLI front-ends adopt it so they render identically
7//! (ADR 0100).
8//!
9//! **Invariant (ADR 0100):** this crate depends on `bynk-syntax` **only** (plus
10//! `ariadne`). It must never see `AttributedError`/`ProjectFailure` (which live
11//! in `bynk-emit`): the `AttributedError → CompileError` flattening stays *above*
12//! render, in the front-end, so there is no `render → emit` cycle. A function
13//! here taking a `ProjectFailure` would not even compile — the dependency isn't
14//! present, by design.
15//!
16//! Extracted from `bynkc` as slice 6 of the crate-decomposition track.
17
18use std::path::Path;
19
20use ariadne::Source;
21use bynk_syntax::error::Severity;
22use bynk_syntax::{CompileError, span};
23
24/// Render a list of compile errors to a string (for tests) using the given
25/// filename as the diagnostic source label.
26pub fn render_errors(errors: &[CompileError], source: &str, filename: &str) -> String {
27 let mut out = Vec::new();
28 let mut cache = (filename, Source::from(source));
29 for err in errors {
30 err.report_for(filename, source)
31 .write(&mut cache, &mut out)
32 .expect("write to Vec<u8> cannot fail");
33 }
34 String::from_utf8_lossy(&out).into_owned()
35}
36
37/// Render a list of compile errors to a string with colour disabled and the
38/// given filename as the source label. Unlike [`render_errors`], the output
39/// contains no ANSI escape codes, so it is byte-stable — suitable for the
40/// committed diagnostic transcripts under `site/src/diagnostics/`.
41pub fn render_errors_plain(errors: &[CompileError], source: &str, filename: &str) -> String {
42 let mut out = Vec::new();
43 let mut cache = (filename, Source::from(source));
44 for err in errors {
45 err.report_plain_for(filename, source)
46 .write(&mut cache, &mut out)
47 .expect("write to Vec<u8> cannot fail");
48 }
49 String::from_utf8_lossy(&out).into_owned()
50}
51
52/// Render to stderr with color, used by the CLI.
53pub fn print_errors(errors: &[CompileError], source: &str, filename: &str) {
54 let mut cache = (filename, Source::from(source));
55 for err in errors {
56 let _ = err.report_for(filename, source).eprint(&mut cache);
57 }
58}
59
60/// Render project-level errors as plain `[category] message` lines — the
61/// fallback for errors with no file attribution. Rich, source-context rendering
62/// lives in the front-end's project-failure renderer (v0.24).
63pub fn print_project_errors(root: &Path, errors: &[CompileError]) {
64 let _ = root;
65 for err in errors {
66 eprintln!("[{}] {}", err.category, err.message);
67 for note in &err.notes {
68 eprintln!(" note: {note}");
69 }
70 }
71}
72
73/// v0.38 (ADR 0071): one terse line per diagnostic for tooling consumers
74/// (`bynkc check --format short`):
75/// `path:line:col: <severity>[<category>]: <message>`. Line/column are
76/// 1-indexed, computed from the byte span against the source. The VS Code
77/// `bynkc` problem-matcher keys off this exact shape — keep it stable.
78pub fn print_errors_short(errors: &[CompileError], source: &str, filename: &str) {
79 eprint!("{}", render_errors_short(errors, source, filename));
80}
81
82/// The string form of [`print_errors_short`] — one `…[category]: message` line
83/// per error, each newline-terminated. The renderer behind the CLI's `--format
84/// short`, exposed for testing.
85pub fn render_errors_short(errors: &[CompileError], source: &str, filename: &str) -> String {
86 let mut out = String::new();
87 for err in errors {
88 out.push_str(&short_line(filename, source, err));
89 out.push('\n');
90 }
91 out
92}
93
94/// One terse `path:line:col: severity[category]: message` line for a single
95/// error against its source. The front-end's project-failure short renderer
96/// flattens an attributed error to `(label, text, error)` and calls this.
97pub fn short_line(filename: &str, source: &str, err: &CompileError) -> String {
98 let (line, col) = span::line_col(source, err.span.start);
99 format!(
100 "{filename}:{line}:{col}: {}[{}]: {}",
101 severity_word(err),
102 err.category,
103 err.message
104 )
105}
106
107/// `"error"` / `"warning"` for an error's [`Severity`].
108pub fn severity_word(err: &CompileError) -> &'static str {
109 match Severity::for_error(err) {
110 Severity::Error => "error",
111 Severity::Warning => "warning",
112 }
113}
114
115/// Render a list of compile errors as plain `[category] message` lines (with
116/// notes), for test assertion.
117pub fn render_project_errors(errors: &[CompileError]) -> String {
118 let mut out = String::new();
119 for err in errors {
120 out.push_str(&format!("[{}] {}\n", err.category, err.message));
121 for note in &err.notes {
122 out.push_str(&format!(" note: {note}\n"));
123 }
124 }
125 out
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use bynk_syntax::span::Span;
132
133 /// Spans are byte offsets; ariadne 0.6 defaults to character indexing.
134 /// On a line with non-ASCII text before the span, the char-indexed
135 /// underline lands past the target. Pin the byte-indexed placement by
136 /// checking the caret column against the target's display column.
137 #[test]
138 fn underline_is_byte_indexed_on_non_ascii_lines() {
139 // `é` is 2 bytes / 1 display column; `bad` starts at byte 11,
140 // display column 10.
141 let source = "-- caféxyz bad\n";
142 let start = source.find("bad").unwrap();
143 let err = CompileError::new(
144 "bynk.test.example",
145 Span::new(start, start + 3),
146 "bad thing",
147 );
148 let rendered = render_errors_plain(&[err], source, "probe.bynk");
149 let source_line = rendered
150 .lines()
151 .find(|l| l.contains("caféxyz"))
152 .expect("snippet line present");
153 let marker_line = rendered
154 .lines()
155 .find(|l| l.contains('┬'))
156 .expect("marker line present");
157 let col_of = |line: &str, target: char| line.chars().take_while(|&c| c != target).count();
158 // The `┬` sits within the underline under `bad` — same display
159 // column as `b`, or one to its right for spans wider than 1.
160 let b_col = col_of(source_line, 'b');
161 let caret_col = col_of(marker_line, '┬');
162 assert!(
163 (b_col..b_col + 3).contains(&caret_col),
164 "caret at display column {caret_col}, expected within `bad` at {b_col}..{}:\n{rendered}",
165 b_col + 3
166 );
167 }
168
169 /// A label whose span lies past the end of the rendered source belongs to
170 /// another file; it must be demoted to a note, not underline unrelated
171 /// text (or panic).
172 #[test]
173 fn out_of_bounds_label_demotes_to_note() {
174 let source = "commons demo\n";
175 let err = CompileError::new("bynk.test.example", Span::new(0, 7), "problem here")
176 .with_label(
177 Span::new(5_000, 5_010),
178 "parameter declared here (in another file)",
179 );
180 let rendered = render_errors_plain(&[err], source, "probe.bynk");
181 assert!(
182 rendered.contains("parameter declared here"),
183 "label text survives as a note:\n{rendered}"
184 );
185 }
186
187 /// A cross-file label whose byte span is *in-bounds* but lands mid-codepoint
188 /// (the file it really belongs to has non-ASCII text) must be demoted, not
189 /// fed to ariadne — a byte offset splitting a codepoint panics its byte→char
190 /// mapping (#716). The rendered source here is all multi-byte, so an odd
191 /// offset is never a char boundary.
192 #[test]
193 fn mid_codepoint_label_demotes_to_note() {
194 let source = "café ☕\n"; // `é` and `☕` are multi-byte
195 let err = CompileError::new("bynk.test.example", Span::new(0, 3), "problem here")
196 .with_label(
197 Span::new(4, 5),
198 "declared here (mid-codepoint, another file)",
199 );
200 // Must not panic, and the label survives as a note rather than a caret.
201 let rendered = render_errors_plain(&[err], source, "probe.bynk");
202 assert!(
203 rendered.contains("declared here (mid-codepoint, another file)"),
204 "a mid-codepoint label must survive as a note:\n{rendered}"
205 );
206 }
207}