Skip to main content

flow_runner/common/
diagnostic.rs

1//! Diagnostics: errors and warnings with a source span, rendered as
2//! underlined snippets.
3
4use crate::common::error::{too_deep, too_large};
5use crate::common::limits::{MAX_REPORT_LINE, REPORT_AFTER, REPORT_BEFORE};
6use std::fmt;
7use std::ops::{Deref, Range};
8use temple_dsl::{CompileError as TempleCompileError, Span};
9
10/// How serious a [`Diagnostic`] is.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum Severity {
14    /// The flow doesn't compile.
15    Error,
16    /// The flow compiles, but something in it looks wrong.
17    Warning,
18}
19
20impl Severity {
21    /// `error` or `warning`.
22    pub fn as_str(self) -> &'static str {
23        match self {
24            Severity::Error => "error",
25            Severity::Warning => "warning",
26        }
27    }
28}
29
30/// One problem found in a `.flow` file.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Diagnostic {
33    /// Whether it stops the flow from compiling.
34    pub severity: Severity,
35    /// What is wrong, in one sentence.
36    pub message: String,
37    /// Where, as byte offsets into the source.
38    pub span: Span,
39    /// A short suggestion, shown under the snippet.
40    pub help: Option<String>,
41}
42
43impl Diagnostic {
44    pub(crate) fn error(span: Span, message: impl Into<String>) -> Self {
45        Diagnostic {
46            severity: Severity::Error,
47            message: message.into(),
48            span,
49            help: None,
50        }
51    }
52
53    pub(crate) fn warning(span: Span, message: impl Into<String>) -> Self {
54        Diagnostic {
55            severity: Severity::Warning,
56            message: message.into(),
57            span,
58            help: None,
59        }
60    }
61
62    /// The same diagnostic with a suggestion.
63    pub(crate) fn with_help(mut self, help: impl Into<String>) -> Self {
64        self.help = Some(help.into());
65        self
66    }
67
68    /// Whether this stops the flow from compiling.
69    pub fn is_error(&self) -> bool {
70        self.severity == Severity::Error
71    }
72
73    /// 1-based line and column of the span's start.
74    pub fn line_col(&self, src: &str) -> (usize, usize) {
75        self.span.line_col(src)
76    }
77
78    /// Render against the source as an underlined snippet:
79    ///
80    /// ```text
81    /// error: unknown node `aproved`
82    ///    --> 12:29
83    ///    |
84    /// 12 |   input.event == 'approve': aproved()
85    ///    |                             ^^^^^^^
86    ///    = help: did you mean `approved`?
87    /// ```
88    pub fn report(&self, src: &str) -> String {
89        report_all(src, std::slice::from_ref(self))
90    }
91
92    /// The snippet for this diagnostic, whose span starts at `at`.
93    fn render(&self, lines: &Lines, at: Placement) -> String {
94        let src = lines.src;
95        let span = self.span.range();
96        let line = lines.line_range(at.line);
97        let span_start = floor_boundary(src, span.start).clamp(line.start, line.end);
98        let window = lines.window(&line, span_start);
99        let lead = if window.start > line.start { "…" } else { "" };
100        let tail = if window.end < line.end { "…" } else { "" };
101        let text = &src[window.clone()];
102        let indent = lead.chars().count() + src[window.start..span_start].chars().count();
103        let span_end = floor_boundary(src, span.end).clamp(span_start, window.end);
104        let width = src[span_start..span_end].chars().count().max(1);
105        let line_number = (at.line + 1).to_string();
106        let gutter = " ".repeat(line_number.len());
107        let mut out = format!(
108            "{label}: {message}\n{gutter} --> {line_number}:{column}\n{gutter} |\n{line_number} | {lead}{text}{tail}\n{gutter} | {spaces}{carets}",
109            label = self.severity.as_str(),
110            message = self.message,
111            column = at.column,
112            spaces = " ".repeat(indent),
113            carets = "^".repeat(width),
114        );
115        if let Some(help) = &self.help {
116            out.push_str(&format!("\n{gutter} = help: {help}"));
117        }
118        out
119    }
120}
121
122/// Where a diagnostic's span starts: a 0-based line and a 1-based column,
123/// counted in characters.
124#[derive(Clone, Copy)]
125struct Placement {
126    line: usize,
127    column: usize,
128}
129
130impl fmt::Display for Diagnostic {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        write!(f, "{}: {}", self.severity.as_str(), self.message)
133    }
134}
135
136/// Render several diagnostics, separated by blank lines.
137fn report_all(src: &str, diagnostics: &[Diagnostic]) -> String {
138    let lines = Lines::new(src);
139    diagnostics
140        .iter()
141        .zip(placements(&lines, diagnostics))
142        .map(|(diagnostic, at)| diagnostic.render(&lines, at))
143        .collect::<Vec<_>>()
144        .join("\n\n")
145}
146
147/// Where each diagnostic's span starts. Columns count characters from the
148/// line's start; taking the spans in order counts each line once, not once
149/// per diagnostic.
150fn placements(lines: &Lines, diagnostics: &[Diagnostic]) -> Vec<Placement> {
151    let src = lines.src;
152    let mut starts: Vec<SpanStart> = diagnostics
153        .iter()
154        .enumerate()
155        .map(|(index, diagnostic)| SpanStart {
156            offset: floor_boundary(src, diagnostic.span.range().start),
157            index,
158        })
159        .collect();
160    starts.sort_unstable_by_key(|start| (start.offset, start.index));
161    let mut placements = vec![Placement { line: 0, column: 1 }; diagnostics.len()];
162    let mut current_line = usize::MAX;
163    let mut counted_to = 0;
164    let mut chars = 0;
165    for start in starts {
166        let line = lines.line_of(start.offset);
167        if line != current_line {
168            current_line = line;
169            counted_to = lines.starts[line];
170            chars = 0;
171        }
172        chars += src[counted_to..start.offset].chars().count();
173        counted_to = start.offset;
174        placements[start.index] = Placement {
175            line,
176            column: chars + 1,
177        };
178    }
179    placements
180}
181
182/// Where one diagnostic's span starts, and which diagnostic it is.
183struct SpanStart {
184    offset: usize,
185    index: usize,
186}
187
188/// Where each line of a source starts, so placing many diagnostics doesn't
189/// scan the source once per diagnostic.
190struct Lines<'a> {
191    src: &'a str,
192    starts: Vec<usize>,
193}
194
195impl<'a> Lines<'a> {
196    fn new(src: &'a str) -> Self {
197        let mut starts = vec![0];
198        starts.extend(
199            src.bytes()
200                .enumerate()
201                .filter(|&(_, byte)| byte == b'\n')
202                .map(|(offset, _)| offset + 1),
203        );
204        Lines { src, starts }
205    }
206
207    /// The 0-based line holding byte `at`.
208    fn line_of(&self, at: usize) -> usize {
209        self.starts.partition_point(|&start| start <= at) - 1
210    }
211
212    /// A line's text as a byte range, without its line break.
213    fn line_range(&self, line: usize) -> Range<usize> {
214        let start = self.starts[line];
215        let mut end = self
216            .starts
217            .get(line + 1)
218            .map_or(self.src.len(), |&next_start| next_start - 1);
219        if self.src[start..end].ends_with('\r') {
220            end -= 1;
221        }
222        start..end
223    }
224
225    /// The part of `line` a report shows: all of it, or a window around
226    /// `span_start` when the line is long.
227    fn window(&self, line: &Range<usize>, span_start: usize) -> Range<usize> {
228        if line.len() <= MAX_REPORT_LINE {
229            return line.clone();
230        }
231        let from = span_start.saturating_sub(REPORT_BEFORE).max(line.start);
232        let to = (span_start + REPORT_AFTER).min(line.end);
233        floor_boundary(self.src, from)..floor_boundary(self.src, to)
234    }
235}
236
237/// The largest char boundary at or before `at`, so a span into the middle
238/// of a character still slices cleanly.
239fn floor_boundary(src: &str, at: usize) -> usize {
240    if at >= src.len() {
241        return src.len();
242    }
243    let mut boundary = at;
244    while !src.is_char_boundary(boundary) {
245        boundary -= 1;
246    }
247    boundary
248}
249
250/// The smallest char boundary at or after `at`, or the end of `src`.
251fn ceil_boundary(src: &str, at: usize) -> usize {
252    let mut boundary = at.min(src.len());
253    while !src.is_char_boundary(boundary) {
254        boundary += 1;
255    }
256    boundary
257}
258
259/// `span` held to `src` and widened to whole characters.
260fn within(src: &str, span: Span) -> Span {
261    let range = span.range();
262    let start = floor_boundary(src, range.start);
263    Span::new(start, ceil_boundary(src, range.end).max(start))
264}
265
266/// A temple compile error as a diagnostic, at its span held to `src`, the
267/// text temple read, and widened to whole characters: temple can point just
268/// past the end of its text, or into a character.
269pub(crate) fn from_temple(error: &TempleCompileError, fallback: Span, src: &str) -> Diagnostic {
270    match error {
271        TempleCompileError::Syntax { message, span } => {
272            Diagnostic::error(within(src, *span), message.clone())
273        }
274        TempleCompileError::TooDeep { limit, span } => {
275            Diagnostic::error(within(src, *span), too_deep("the expression", *limit)).with_help(
276                "split it up with `let`, or use a list method such as `.sum()` or `.any(...)`",
277            )
278        }
279        TempleCompileError::TooLarge { bytes, limit } => {
280            Diagnostic::error(fallback, too_large("the expression", *bytes, *limit))
281        }
282    }
283}
284
285/// The errors and warnings found in one source, in the order they were
286/// found. [`Flow::compile`](crate::Flow::compile) fails with these when any
287/// is an error.
288#[derive(Debug, Clone, Default, PartialEq, Eq)]
289pub struct Diagnostics(Vec<Diagnostic>);
290
291impl Diagnostics {
292    pub(crate) fn new(diagnostics: Vec<Diagnostic>) -> Self {
293        Diagnostics(diagnostics)
294    }
295
296    /// Whether any of them is an error.
297    pub fn has_errors(&self) -> bool {
298        self.0.iter().any(Diagnostic::is_error)
299    }
300
301    /// The errors, without the warnings.
302    pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
303        self.0.iter().filter(|diagnostic| diagnostic.is_error())
304    }
305
306    /// Every diagnostic as a snippet against `src`, separated by blank lines.
307    pub fn report(&self, src: &str) -> String {
308        report_all(src, &self.0)
309    }
310}
311
312impl Deref for Diagnostics {
313    type Target = [Diagnostic];
314    fn deref(&self) -> &[Diagnostic] {
315        &self.0
316    }
317}
318
319impl IntoIterator for Diagnostics {
320    type Item = Diagnostic;
321    type IntoIter = std::vec::IntoIter<Diagnostic>;
322    fn into_iter(self) -> Self::IntoIter {
323        self.0.into_iter()
324    }
325}
326
327impl<'a> IntoIterator for &'a Diagnostics {
328    type Item = &'a Diagnostic;
329    type IntoIter = std::slice::Iter<'a, Diagnostic>;
330    fn into_iter(self) -> Self::IntoIter {
331        self.0.iter()
332    }
333}
334
335impl fmt::Display for Diagnostics {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        let count = self.errors().count();
338        write!(
339            f,
340            "{count} error{} in flow",
341            if count == 1 { "" } else { "s" }
342        )?;
343        for diagnostic in self.errors() {
344            write!(
345                f,
346                "\n  {} (at {}..{})",
347                diagnostic.message, diagnostic.span.start, diagnostic.span.end
348            )?;
349        }
350        Ok(())
351    }
352}
353
354impl std::error::Error for Diagnostics {}