Skip to main content

bynk_syntax/
error.rs

1//! Compiler diagnostics.
2//!
3//! Every error has a category (a dotted namespace string like
4//! `bynk.parse.expected_token`), a primary span, a primary message, and
5//! optionally some secondary labels and notes. Rendering goes through
6//! [`ariadne`] for source-pointing colour output.
7
8use ariadne::{Color, Config, IndexType, Label, Report, ReportKind};
9
10use crate::span::Span;
11
12/// A compile error.
13#[derive(Debug, Clone)]
14pub struct CompileError {
15    pub category: &'static str,
16    pub span: Span,
17    pub message: String,
18    pub labels: Vec<(Span, String)>,
19    pub notes: Vec<String>,
20    /// v0.26 (ADR 0054): machine-applicable fixes, authored at the diagnosis
21    /// site — the only place the exact spans and replacement are known.
22    /// Consumed by the LSP (`codeAction`) and, later, a CLI `--fix`.
23    pub suggestions: Vec<Suggestion>,
24}
25
26/// Which file one of a [`CompileError`]'s secondary labels lies in, for
27/// [`CompileError::report_in`]. A label's span is a byte offset into its own
28/// file's text, which need not be the file the error itself is reported in.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum LabelHome<'a> {
31    /// The file the error is reported in.
32    Primary,
33    /// Another file: the name to show it under and its text.
34    File { filename: &'a str, source: &'a str },
35    /// A file with no text to show — the label is rendered as a note.
36    Unavailable,
37}
38
39/// A structured fix for the error it is attached to (v0.26, ADR 0054).
40///
41/// `edits` are span → replacement: an empty replacement deletes the span; an
42/// empty span inserts at its position. Spans are offsets into the same source
43/// text as the error's own span.
44#[derive(Debug, Clone)]
45pub struct Suggestion {
46    /// Human-facing action title, e.g. "remove `Clock` from the `given` clause".
47    pub message: String,
48    pub edits: Vec<(Span, String)>,
49    pub applicability: Applicability,
50}
51
52/// Whether a [`Suggestion`] can be applied without review (mirrors rustc;
53/// gates a future CLI `--fix` and the LSP's one-click apply).
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Applicability {
56    /// The fix is exactly right — safe to apply mechanically.
57    MachineApplicable,
58    /// The fix contains placeholder text a human must complete; never
59    /// auto-applied.
60    HasPlaceholders,
61    /// The fix is a complete edit but changes meaning the author must choose
62    /// (`derives Ord` makes declaration order significant): offered as a quick
63    /// fix, never taken by a fix-all or `--fix`.
64    MaybeIncorrect,
65}
66
67/// Severity classification for a [`CompileError`]. Mirrors LSP severity levels
68/// so the LSP server can map diagnostics to the protocol without reinterpreting
69/// error categories. Lives in the syntax leaf beside `CompileError` (it
70/// classifies one): shared by the IDE diagnose path (`bynk-ide`) and the
71/// `short`/`json` renderers, without either depending on the other.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Severity {
74    Error,
75    Warning,
76}
77
78impl Severity {
79    /// Classify a [`CompileError`] by its category's registered severity
80    /// (`crate::diagnostics::REGISTRY`) — the registry entry built via `warn`
81    /// is the single source of truth for which codes are non-failing
82    /// warnings (ADR 0117); everything else defaults to `Error`, including a
83    /// category that isn't registered at all (which `tests/diagnostics_registry.rs`
84    /// asserts cannot happen for a code actually emitted in source).
85    pub fn for_error(err: &CompileError) -> Severity {
86        crate::diagnostics::lookup(err.category)
87            .map(|d| d.severity)
88            .unwrap_or(Severity::Error)
89    }
90}
91
92/// Split diagnostics into `(errors, warnings)` by severity (ADR 0117). The build
93/// fails iff the `errors` half is non-empty; the `warnings` half surfaces but
94/// does not gate compilation. Relative order within each half is preserved.
95pub fn partition_by_severity(
96    diagnostics: Vec<CompileError>,
97) -> (Vec<CompileError>, Vec<CompileError>) {
98    diagnostics
99        .into_iter()
100        .partition(|d| Severity::for_error(d) == Severity::Error)
101}
102
103impl CompileError {
104    pub fn new(category: &'static str, span: Span, message: impl Into<String>) -> Self {
105        Self {
106            category,
107            span,
108            message: message.into(),
109            labels: Vec::new(),
110            notes: Vec::new(),
111            suggestions: Vec::new(),
112        }
113    }
114
115    /// Shift every span in this diagnostic — the primary span, secondary
116    /// labels, and suggestion edits — right by `delta` bytes. Used to rebase a
117    /// diagnostic produced against a substring (e.g. an interpolation hole
118    /// re-lexed on its own) into the full source, so the location is correct
119    /// and every span stays a valid char boundary. (#716.)
120    pub fn offset_spans(mut self, delta: usize) -> Self {
121        self.span = self.span.offset(delta);
122        for (span, _) in &mut self.labels {
123            *span = span.offset(delta);
124        }
125        for suggestion in &mut self.suggestions {
126            for (span, _) in &mut suggestion.edits {
127                *span = span.offset(delta);
128            }
129        }
130        self
131    }
132
133    pub fn with_label(mut self, span: Span, label: impl Into<String>) -> Self {
134        self.labels.push((span, label.into()));
135        self
136    }
137
138    pub fn with_note(mut self, note: impl Into<String>) -> Self {
139        self.notes.push(note.into());
140        self
141    }
142
143    /// Attach a machine-applicable fix (v0.26). Mirrors [`Self::with_note`];
144    /// the suggestion is authored where the diagnostic is raised.
145    pub fn with_suggestion(
146        mut self,
147        message: impl Into<String>,
148        edits: Vec<(Span, String)>,
149        applicability: Applicability,
150    ) -> Self {
151        self.suggestions.push(Suggestion {
152            message: message.into(),
153            edits,
154            applicability,
155        });
156        self
157    }
158
159    /// Build an [`ariadne::Report`] for this error, rendered against `source`
160    /// (labelled `filename`). Colour is on (for the CLI and human-facing test
161    /// output). Every secondary label is taken to lie in `source` too; see
162    /// [`Self::report_in`] for one whose labels may lie in other files.
163    ///
164    /// A **secondary** label whose span does not sit cleanly within `source`
165    /// belongs to *another* file — a cross-file "declared here" pointing at a
166    /// `uses`-imported callee, or (#696) at a sibling file in a multi-file unit.
167    /// Rendering it here would underline unrelated text, and a byte span that
168    /// lands mid-codepoint would panic ariadne's byte→char mapping (#716). Such a
169    /// label is demoted to a note so the information survives without the
170    /// misplacement or the panic. The demotion test is deliberately conservative:
171    /// out-of-bounds **or** not on a char boundary of `source`. It cannot catch a
172    /// cross-file span that happens to be in-bounds and boundary-aligned — a
173    /// caller that knows each label's file passes it to [`Self::report_in`].
174    pub fn report_for<'a>(
175        &'a self,
176        filename: &'a str,
177        source: &str,
178    ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
179        self.report_with_config(filename, source, &[], Config::default())
180    }
181
182    /// [`Self::report_for`] with colour disabled, for transcripts committed to
183    /// the repo — no ANSI escape codes, so the output is byte-stable across
184    /// machines.
185    pub fn report_plain_for<'a>(
186        &'a self,
187        filename: &'a str,
188        source: &str,
189    ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
190        self.report_with_config(filename, source, &[], Config::default().with_color(false))
191    }
192
193    /// [`Self::report_for`] for an error whose secondary labels may lie in other
194    /// files: `homes[i]` says which file `self.labels[i]` lies in (a label past
195    /// the end of `homes` is [`LabelHome::Primary`]). A label in another file is
196    /// drawn against that file's text, under its own filename, so the report's
197    /// cache must hold every [`LabelHome::File`] source as well as `source`.
198    /// `color` picks [`Self::report_for`]'s or [`Self::report_plain_for`]'s
199    /// output.
200    pub fn report_in<'a>(
201        &'a self,
202        filename: &'a str,
203        source: &str,
204        homes: &[LabelHome<'a>],
205        color: bool,
206    ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
207        self.report_with_config(filename, source, homes, Config::default().with_color(color))
208    }
209
210    /// True when `span` sits cleanly inside `source` — in-bounds and on char
211    /// boundaries at both ends — so ariadne can underline it without misplacing
212    /// the caret or panicking on a byte offset that splits a codepoint (#716).
213    fn label_fits(span: &Span, source: &str) -> bool {
214        span.end <= source.len()
215            && source.is_char_boundary(span.start)
216            && source.is_char_boundary(span.end)
217    }
218
219    /// `span`'s byte range in `source` as the char range ariadne indexes by.
220    /// An offset inside a codepoint counts from that codepoint's start; one
221    /// past the end stays past it by the same amount, so ariadne still sees an
222    /// out-of-bounds span as out of bounds.
223    fn char_range(source: &str, span: &Span) -> std::ops::Range<usize> {
224        let at = |byte: usize| {
225            if byte > source.len() {
226                source.chars().count() + (byte - source.len())
227            } else {
228                source[..source.floor_char_boundary(byte)].chars().count()
229            }
230        };
231        at(span.start)..at(span.end)
232    }
233
234    fn report_with_config<'a>(
235        &'a self,
236        filename: &'a str,
237        source: &str,
238        homes: &[LabelHome<'a>],
239        config: Config,
240    ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
241        let primary_span = (filename, Self::char_range(source, &self.span));
242        // ADR 0117: a warning-severity diagnostic must render as a warning, not
243        // an error — `report_with_config` is the only `ReportKind` in the
244        // workspace, so this is the one place that decides it.
245        let kind = match Severity::for_error(self) {
246            Severity::Error => ReportKind::Error,
247            Severity::Warning => ReportKind::Warning,
248        };
249        // Spans are byte offsets into the UTF-8 source, but ariadne is handed
250        // char offsets ([`Self::char_range`]), each converted against the text
251        // its span lies in. Its `IndexType::Byte` mode is wrong for a label in
252        // another file: ariadne 0.6 heads that file's snippet by looking the
253        // label's *char* offset up as a byte offset, so the header names the
254        // wrong line and column after any non-ASCII text — and panics when
255        // that offset splits a codepoint (#1956: `bynk.bynk` is full of `—`).
256        let mut builder = Report::build(kind, primary_span.clone())
257            .with_config(config.with_index_type(IndexType::Char))
258            .with_code(self.category)
259            .with_message(&self.message)
260            .with_label(
261                Label::new(primary_span)
262                    .with_message(&self.message)
263                    .with_color(Color::Red),
264            );
265
266        for (i, (span, label)) in self.labels.iter().enumerate() {
267            let (label_file, label_source) = match homes.get(i).unwrap_or(&LabelHome::Primary) {
268                LabelHome::Primary => (filename, source),
269                LabelHome::File { filename, source } => (*filename, *source),
270                LabelHome::Unavailable => {
271                    builder = builder.with_note(label);
272                    continue;
273                }
274            };
275            if !Self::label_fits(span, label_source) {
276                // The label's span does not fit its file's source — demote to a
277                // note rather than underlining unrelated text (or panicking on a
278                // mid-codepoint offset).
279                builder = builder.with_note(label);
280                continue;
281            }
282            builder = builder.with_label(
283                Label::new((label_file, Self::char_range(label_source, span)))
284                    .with_message(label)
285                    .with_color(Color::Yellow),
286            );
287        }
288
289        for note in &self.notes {
290            builder = builder.with_note(note);
291        }
292
293        // Finding #49 (ADR 0054): a structured suggestion previously reached
294        // only the LSP's code-action surface; the CLI never rendered it at
295        // all. Shown as a `help:`-prefixed note — mirrors rustc's own
296        // note/help distinction — rather than a new ariadne builder call, so
297        // it composes with an arbitrary number of suggestions.
298        for suggestion in &self.suggestions {
299            builder = builder.with_note(format!("help: {}", suggestion.message));
300        }
301
302        builder.finish()
303    }
304}
305
306#[cfg(test)]
307mod warning_channel_tests {
308    use super::*;
309    use crate::span::Span;
310
311    #[test]
312    fn partition_splits_by_severity() {
313        let warn = CompileError::new("bynk.given.unused_capability", Span::default(), "unused");
314        let err = CompileError::new("bynk.types.argument_mismatch", Span::default(), "bad");
315        let (errors, warnings) = partition_by_severity(vec![warn, err]);
316        assert_eq!(errors.len(), 1);
317        assert_eq!(errors[0].category, "bynk.types.argument_mismatch");
318        assert_eq!(warnings.len(), 1);
319        assert_eq!(warnings[0].category, "bynk.given.unused_capability");
320    }
321
322    /// `report_with_config` (the only `ReportKind` in the workspace) hardcoded
323    /// `ReportKind::Error`, so a warning-severity diagnostic printed "Error:"
324    /// and there was no way for a renderer built on `report_for` to tell them
325    /// apart. It must pick the `ReportKind` from `Severity::for_error`.
326    #[test]
327    fn report_for_renders_warning_severity_as_a_warning_not_an_error() {
328        let source = "commons w\n\nfn f() -> Int { 1 }\n";
329        let warn = CompileError::new("bynk.given.unused_capability", Span::default(), "unused");
330        let rendered = {
331            let mut out = Vec::new();
332            let mut cache = ("w.bynk", ariadne::Source::from(source));
333            warn.report_plain_for("w.bynk", source)
334                .write(&mut cache, &mut out)
335                .unwrap();
336            String::from_utf8(out).unwrap()
337        };
338        assert!(
339            rendered.contains("Warning:"),
340            "expected a `Warning:` report for a warning-severity category, got:\n{rendered}"
341        );
342        assert!(
343            !rendered.contains("Error:"),
344            "a warning-severity category must not render as `Error:`, got:\n{rendered}"
345        );
346
347        let err = CompileError::new("bynk.types.argument_mismatch", Span::default(), "mismatch");
348        let rendered_err = {
349            let mut out = Vec::new();
350            let mut cache = ("w.bynk", ariadne::Source::from(source));
351            err.report_plain_for("w.bynk", source)
352                .write(&mut cache, &mut out)
353                .unwrap();
354            String::from_utf8(out).unwrap()
355        };
356        assert!(
357            rendered_err.contains("Error:"),
358            "an error-severity category must still render as `Error:`, got:\n{rendered_err}"
359        );
360    }
361}