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/// A structured fix for the error it is attached to (v0.26, ADR 0054).
27///
28/// `edits` are span → replacement: an empty replacement deletes the span; an
29/// empty span inserts at its position. Spans are offsets into the same source
30/// text as the error's own span.
31#[derive(Debug, Clone)]
32pub struct Suggestion {
33 /// Human-facing action title, e.g. "remove `Clock` from the `given` clause".
34 pub message: String,
35 pub edits: Vec<(Span, String)>,
36 pub applicability: Applicability,
37}
38
39/// Whether a [`Suggestion`] can be applied without review (mirrors rustc;
40/// gates a future CLI `--fix` and the LSP's one-click apply).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Applicability {
43 /// The fix is exactly right — safe to apply mechanically.
44 MachineApplicable,
45 /// The fix contains placeholder text a human must complete; never
46 /// auto-applied.
47 HasPlaceholders,
48}
49
50/// Severity classification for a [`CompileError`]. Mirrors LSP severity levels
51/// so the LSP server can map diagnostics to the protocol without reinterpreting
52/// error categories. Lives in the syntax leaf beside `CompileError` (it
53/// classifies one): shared by the IDE diagnose path (`bynk-ide`) and the
54/// `short`/`json` renderers, without either depending on the other.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Severity {
57 Error,
58 Warning,
59}
60
61impl Severity {
62 /// Classify a [`CompileError`] by its category prefix.
63 ///
64 /// `bynk.parse.orphan_doc_block`, `bynk.given.unused_capability`,
65 /// `bynk.list.deprecated_function`, and the `bynk.index.*` hygiene hints
66 /// (`missing`/`unused`, ADR 0118 D4) are warnings; everything else is an
67 /// error. Future categories can be added as the diagnostic surface grows.
68 pub fn for_error(err: &CompileError) -> Severity {
69 match err.category {
70 "bynk.parse.orphan_doc_block"
71 | "bynk.given.unused_capability"
72 | "bynk.list.deprecated_function"
73 | "bynk.index.missing"
74 | "bynk.index.unused"
75 // A computed secret name is legal and sometimes reasonable; the
76 // program is correct, `deploy` simply cannot see it (ADR 0196 D1).
77 | "bynk.secrets.computed_name" => Severity::Warning,
78 _ => Severity::Error,
79 }
80 }
81}
82
83/// Split diagnostics into `(errors, warnings)` by severity (ADR 0117). The build
84/// fails iff the `errors` half is non-empty; the `warnings` half surfaces but
85/// does not gate compilation. Relative order within each half is preserved.
86pub fn partition_by_severity(
87 diagnostics: Vec<CompileError>,
88) -> (Vec<CompileError>, Vec<CompileError>) {
89 diagnostics
90 .into_iter()
91 .partition(|d| Severity::for_error(d) == Severity::Error)
92}
93
94impl CompileError {
95 pub fn new(category: &'static str, span: Span, message: impl Into<String>) -> Self {
96 Self {
97 category,
98 span,
99 message: message.into(),
100 labels: Vec::new(),
101 notes: Vec::new(),
102 suggestions: Vec::new(),
103 }
104 }
105
106 pub fn with_label(mut self, span: Span, label: impl Into<String>) -> Self {
107 self.labels.push((span, label.into()));
108 self
109 }
110
111 pub fn with_note(mut self, note: impl Into<String>) -> Self {
112 self.notes.push(note.into());
113 self
114 }
115
116 /// Attach a machine-applicable fix (v0.26). Mirrors [`Self::with_note`];
117 /// the suggestion is authored where the diagnostic is raised.
118 pub fn with_suggestion(
119 mut self,
120 message: impl Into<String>,
121 edits: Vec<(Span, String)>,
122 applicability: Applicability,
123 ) -> Self {
124 self.suggestions.push(Suggestion {
125 message: message.into(),
126 edits,
127 applicability,
128 });
129 self
130 }
131
132 /// Build an [`ariadne::Report`] for this error, anchored to the given
133 /// filename. Colour is on (for the CLI and human-facing test output).
134 pub fn report<'a>(
135 &'a self,
136 filename: &'a str,
137 ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
138 self.report_for(filename, usize::MAX)
139 }
140
141 /// [`Self::report`], bounded by the rendered source's byte length: a label
142 /// whose span lies past the end of the source belongs to *another* file
143 /// (e.g. a `uses`-imported callee's "declared here"), and rendering it
144 /// against this file would underline unrelated text. Such labels are
145 /// demoted to notes so the information survives without the misplacement.
146 pub fn report_for<'a>(
147 &'a self,
148 filename: &'a str,
149 source_len: usize,
150 ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
151 self.report_with_config(filename, Config::default(), source_len)
152 }
153
154 /// Build a colourless [`ariadne::Report`], for transcripts committed to the
155 /// repo — no ANSI escape codes, so the output is byte-stable across machines.
156 pub fn report_plain<'a>(
157 &'a self,
158 filename: &'a str,
159 ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
160 self.report_plain_for(filename, usize::MAX)
161 }
162
163 /// [`Self::report_plain`], bounded by the source length — see
164 /// [`Self::report_for`].
165 pub fn report_plain_for<'a>(
166 &'a self,
167 filename: &'a str,
168 source_len: usize,
169 ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
170 self.report_with_config(filename, Config::default().with_color(false), source_len)
171 }
172
173 fn report_with_config<'a>(
174 &'a self,
175 filename: &'a str,
176 config: Config,
177 source_len: usize,
178 ) -> Report<'a, (&'a str, std::ops::Range<usize>)> {
179 let primary_span = (filename, self.span.range());
180 // Spans are byte offsets into the UTF-8 source; ariadne 0.6 defaults
181 // to character indexing, which misplaces the underline on any line
182 // with non-ASCII text before the span.
183 let mut builder = Report::build(ReportKind::Error, primary_span.clone())
184 .with_config(config.with_index_type(IndexType::Byte))
185 .with_code(self.category)
186 .with_message(&self.message)
187 .with_label(
188 Label::new(primary_span)
189 .with_message(&self.message)
190 .with_color(Color::Red),
191 );
192
193 for (span, label) in &self.labels {
194 if span.end > source_len {
195 // The label's span lies in another file — demote to a note
196 // rather than underlining unrelated text in this one.
197 builder = builder.with_note(label);
198 continue;
199 }
200 builder = builder.with_label(
201 Label::new((filename, span.range()))
202 .with_message(label)
203 .with_color(Color::Yellow),
204 );
205 }
206
207 for note in &self.notes {
208 builder = builder.with_note(note);
209 }
210
211 builder.finish()
212 }
213}
214
215#[cfg(test)]
216mod warning_channel_tests {
217 use super::*;
218 use crate::span::Span;
219
220 #[test]
221 fn partition_splits_by_severity() {
222 let warn = CompileError::new("bynk.given.unused_capability", Span::default(), "unused");
223 let err = CompileError::new("bynk.types.argument_mismatch", Span::default(), "bad");
224 let (errors, warnings) = partition_by_severity(vec![warn, err]);
225 assert_eq!(errors.len(), 1);
226 assert_eq!(errors[0].category, "bynk.types.argument_mismatch");
227 assert_eq!(warnings.len(), 1);
228 assert_eq!(warnings[0].category, "bynk.given.unused_capability");
229 }
230}