Skip to main content

proa_cli/
diagnostic.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use serde::Serialize;
8use unicode_width::UnicodeWidthStr;
9
10/// Authored source range. Lines and Unicode scalar columns are one-based;
11/// the end is exclusive (display widths and editor UTF-16 offsets differ).
12#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
13pub struct SourceRange {
14    pub path: PathBuf,
15    pub line: usize,
16    pub column: usize,
17    pub end_line: usize,
18    pub end_column: usize,
19}
20
21impl SourceRange {
22    pub fn from_span(path: &Path, span: proc_macro2::Span) -> Self {
23        let start = span.start();
24        let end = span.end();
25        Self {
26            path: path.to_owned(),
27            line: start.line.max(1),
28            column: start.column + 1,
29            end_line: end.line.max(1),
30            end_column: end.column + 1,
31        }
32    }
33}
34
35#[derive(Debug, Clone, Serialize)]
36pub struct SourceLine {
37    pub number: usize,
38    pub text: String,
39}
40
41/// Evidence retained with a diagnostic, so output never needs to reread a file.
42#[derive(Debug, Clone, Serialize)]
43pub struct SourceLabel {
44    pub range: SourceRange,
45    pub message: String,
46    pub primary: bool,
47    pub source: Vec<SourceLine>,
48}
49
50impl SourceLabel {
51    pub fn new(
52        range: SourceRange,
53        source: &str,
54        message: impl Into<String>,
55        primary: bool,
56    ) -> Self {
57        let lines: Vec<_> = source
58            .lines()
59            .enumerate()
60            .filter_map(|(index, text)| {
61                let number = index + 1;
62                let near_start = number >= range.line.saturating_sub(1)
63                    && number <= range.line.saturating_add(2);
64                let near_end = number >= range.end_line.saturating_sub(1)
65                    && number <= range.end_line.saturating_add(1);
66                (near_start || near_end).then(|| SourceLine {
67                    number,
68                    text: text.to_owned(),
69                })
70            })
71            .collect();
72        Self {
73            range,
74            message: message.into(),
75            primary,
76            source: lines,
77        }
78    }
79}
80
81#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
82#[serde(rename_all = "kebab-case")]
83pub enum SuggestionApplicability {
84    MachineApplicable,
85    MaybeIncorrect,
86}
87
88#[derive(Debug, Clone, Serialize)]
89pub struct Suggestion {
90    pub message: String,
91    pub range: SourceRange,
92    pub replacement: String,
93    pub applicability: SuggestionApplicability,
94}
95
96#[derive(Debug, Clone, Copy, Eq, PartialEq)]
97pub enum Severity {
98    Error,
99    Warning,
100    Info,
101}
102
103impl Severity {
104    /// Ordering rank for severity filtering (higher = more severe).
105    pub const fn rank(self) -> u8 {
106        match self {
107            Self::Error => 2,
108            Self::Warning => 1,
109            Self::Info => 0,
110        }
111    }
112
113    pub const fn as_str(self) -> &'static str {
114        match self {
115            Self::Error => "error",
116            Self::Warning => "warning",
117            Self::Info => "info",
118        }
119    }
120}
121
122impl Serialize for Severity {
123    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
124    where
125        S: serde::Serializer,
126    {
127        serializer.serialize_str(self.as_str())
128    }
129}
130
131#[derive(Debug, Clone)]
132pub struct Diagnostic {
133    pub path: PathBuf,
134    pub line: usize,
135    pub column: usize,
136    pub severity: Severity,
137    pub code: &'static str,
138    pub message: String,
139    pub help: Option<String>,
140    pub labels: Vec<SourceLabel>,
141    pub notes: Vec<String>,
142    pub suggestions: Vec<Suggestion>,
143}
144
145impl Diagnostic {
146    pub fn new(
147        path: impl AsRef<Path>,
148        line: usize,
149        column: usize,
150        severity: Severity,
151        code: &'static str,
152        message: impl Into<String>,
153    ) -> Self {
154        Self {
155            path: path.as_ref().to_path_buf(),
156            line,
157            column,
158            severity,
159            code,
160            message: message.into(),
161            help: None,
162            labels: Vec::new(),
163            notes: Vec::new(),
164            suggestions: Vec::new(),
165        }
166    }
167
168    pub fn with_help(mut self, help: impl Into<String>) -> Self {
169        self.help = Some(help.into());
170        self
171    }
172
173    pub fn with_label(mut self, label: SourceLabel) -> Self {
174        self.labels.push(label);
175        self
176    }
177
178    pub fn with_note(mut self, note: impl Into<String>) -> Self {
179        self.notes.push(note.into());
180        self
181    }
182
183    pub fn with_suggestion(mut self, suggestion: Suggestion) -> Self {
184        self.suggestions.push(suggestion);
185        self
186    }
187}
188
189impl fmt::Display for Diagnostic {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        if !self.labels.is_empty() {
192            writeln!(
193                f,
194                "{}[{}]: {}",
195                self.severity.as_str(),
196                self.code,
197                self.message
198            )?;
199            for label in &self.labels {
200                render_label(f, label)?;
201            }
202            for note in &self.notes {
203                writeln!(f, "   = note: {note}")?;
204            }
205            if let Some(help) = &self.help {
206                writeln!(f, "   = help: {help}")?;
207            }
208            for suggestion in &self.suggestions {
209                writeln!(f, "   = help: {}", suggestion.message)?;
210                for line in suggestion.replacement.lines() {
211                    writeln!(f, "           {line}")?;
212                }
213            }
214            return Ok(());
215        }
216        writeln!(
217            f,
218            "{}:{}:{}: {}[{}]: {}",
219            self.path.display(),
220            self.line,
221            self.column,
222            self.severity.as_str(),
223            self.code,
224            self.message
225        )?;
226        if let Some(help) = &self.help {
227            writeln!(f, "  help: {help}")?;
228        }
229        for note in &self.notes {
230            writeln!(f, "  note: {note}")?;
231        }
232        for suggestion in &self.suggestions {
233            writeln!(
234                f,
235                "  help: {}: {}",
236                suggestion.message, suggestion.replacement
237            )?;
238        }
239        Ok(())
240    }
241}
242
243fn render_label(f: &mut fmt::Formatter<'_>, label: &SourceLabel) -> fmt::Result {
244    let range = &label.range;
245    let arrow = if label.primary { "-->" } else { ":::" };
246    writeln!(
247        f,
248        "  {arrow} {}:{}:{}",
249        crate::source::display_path(&range.path).display(),
250        range.line,
251        range.column
252    )?;
253    let width = label
254        .source
255        .last()
256        .map_or(range.line, |line| line.number)
257        .to_string()
258        .len();
259    writeln!(f, " {:width$} |", "")?;
260    let mut previous = None;
261    for line in &label.source {
262        if previous.is_some_and(|number| line.number > number + 1) {
263            writeln!(f, " {:width$} | ...", "")?;
264        }
265        writeln!(f, " {:>width$} | {}", line.number, line.text)?;
266        if line.number == range.line {
267            let column = range
268                .column
269                .saturating_sub(1)
270                .min(line.text.chars().count());
271            let authored_prefix: String = line.text.chars().take(column).collect();
272            let prefix: String = authored_prefix
273                .split_inclusive('\t')
274                .map(|segment| {
275                    let text = segment.trim_end_matches('\t');
276                    let mut spaces = " ".repeat(text.width());
277                    if segment.ends_with('\t') {
278                        spaces.push('\t');
279                    }
280                    spaces
281                })
282                .collect();
283            let available = line.text.chars().count().saturating_sub(column).max(1);
284            let length = if range.end_line == range.line {
285                range
286                    .end_column
287                    .saturating_sub(range.column)
288                    .max(1)
289                    .min(available)
290            } else {
291                available
292            };
293            let highlighted: String = line.text.chars().skip(column).take(length).collect();
294            let underline = if label.primary { '^' } else { '-' }
295                .to_string()
296                .repeat(highlighted.width().max(1));
297            writeln!(f, " {:width$} | {prefix}{underline} {}", "", label.message)?;
298        }
299        previous = Some(line.number);
300    }
301    if !label.source.iter().any(|line| line.number == range.line) {
302        writeln!(f, " {:width$} | {}", "", label.message)?;
303    }
304    writeln!(f, " {:width$} |", "")
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn severity_rank_orders_error_over_warning_over_info() {
313        assert!(Severity::Error.rank() > Severity::Warning.rank());
314        assert!(Severity::Warning.rank() > Severity::Info.rank());
315    }
316
317    #[test]
318    fn severity_serializes_as_lowercase_string() {
319        assert_eq!(
320            serde_json::to_string(&Severity::Warning).unwrap(),
321            "\"warning\""
322        );
323        assert_eq!(
324            serde_json::to_string(&Severity::Error).unwrap(),
325            "\"error\""
326        );
327    }
328
329    #[test]
330    fn display_includes_location_code_and_help() {
331        let diagnostic = Diagnostic::new(
332            Path::new("src/page.rs"),
333            4,
334            9,
335            Severity::Warning,
336            "perf/vec",
337            "Vec in a render path",
338        )
339        .with_help("use stack storage");
340
341        let rendered = diagnostic.to_string();
342        assert_eq!(
343            rendered,
344            "src/page.rs:4:9: warning[perf/vec]: Vec in a render path\n  help: use stack storage\n"
345        );
346    }
347
348    #[test]
349    fn display_omits_help_line_when_absent() {
350        let diagnostic = Diagnostic::new(
351            Path::new("src/page.rs"),
352            1,
353            1,
354            Severity::Info,
355            "render/advisory",
356            "advisory",
357        );
358
359        assert_eq!(
360            diagnostic.to_string(),
361            "src/page.rs:1:1: info[render/advisory]: advisory\n"
362        );
363    }
364}
365
366#[cfg(test)]
367mod frame_tests {
368    use super::*;
369    #[test]
370    fn source_frames_have_primary_related_evidence_and_repairs() {
371        let range = SourceRange {
372            path: "src/product.md.rs".into(),
373            line: 2,
374            column: 5,
375            end_line: 2,
376            end_column: 13,
377        };
378        let related = SourceRange {
379            path: "src/product.html.rs".into(),
380            line: 1,
381            column: 1,
382            end_line: 1,
383            end_column: 8,
384        };
385        let diag = Diagnostic::new(
386            &range.path,
387            2,
388            5,
389            Severity::Error,
390            "render/content-coverage",
391            "Product Markdown omits RestockNotice",
392        )
393        .with_label(SourceLabel::new(
394            range.clone(),
395            "fn render_md() {\n    md_sync! {}\n}",
396            "the notice is absent here",
397            true,
398        ))
399        .with_label(SourceLabel::new(
400            related,
401            "notice.render(cx)",
402            "rendered in HTML",
403            false,
404        ))
405        .with_note("constructing a child does not render it")
406        .with_suggestion(Suggestion {
407            message: "acknowledge an intentional omission inside render_md".into(),
408            range,
409            replacement: "proa_macros::omit!(RestockNotice);".into(),
410            applicability: SuggestionApplicability::MaybeIncorrect,
411        });
412        assert_eq!(diag.to_string(),"error[render/content-coverage]: Product Markdown omits RestockNotice\n  --> src/product.md.rs:2:5\n   |\n 1 | fn render_md() {\n 2 |     md_sync! {}\n   |     ^^^^^^^^ the notice is absent here\n 3 | }\n   |\n  ::: src/product.html.rs:1:1\n   |\n 1 | notice.render(cx)\n   | ------- rendered in HTML\n   |\n   = note: constructing a child does not render it\n   = help: acknowledge an intentional omission inside render_md\n           proa_macros::omit!(RestockNotice);\n");
413    }
414    #[test]
415    fn rust_span_columns_are_unicode_scalar_offsets() {
416        let expr: syn::Expr = syn::parse_str("(\"🦀\", value)").unwrap();
417        let syn::Expr::Tuple(tuple) = expr else {
418            panic!()
419        };
420        let range = SourceRange::from_span(
421            Path::new("test.rs"),
422            syn::spanned::Spanned::span(&tuple.elems[1]),
423        );
424        assert_eq!(range.column, 7);
425        assert_eq!(range.end_column, 12);
426    }
427}
428
429#[cfg(test)]
430mod unicode_frame_tests {
431    use super::*;
432    #[test]
433    fn source_underlines_use_display_width_after_wide_characters() {
434        let r = SourceRange {
435            path: "md.rs".into(),
436            line: 1,
437            column: 3,
438            end_line: 1,
439            end_column: 8,
440        };
441        let d = Diagnostic::new("md.rs", 1, 3, Severity::Info, "test/frame", "frame")
442            .with_label(SourceLabel::new(r, "🦀 value", "value", true));
443        assert!(d.to_string().contains("   |    ^^^^^ value"));
444    }
445}