Skip to main content

harn_parser/
diagnostic.rs

1use std::io::IsTerminal;
2
3use harn_lexer::Span;
4use yansi::{Color, Paint};
5
6use crate::ParserError;
7
8/// Compute the Levenshtein edit distance between two strings.
9pub fn edit_distance(a: &str, b: &str) -> usize {
10    let a_chars: Vec<char> = a.chars().collect();
11    let b_chars: Vec<char> = b.chars().collect();
12    let n = b_chars.len();
13    let mut prev = (0..=n).collect::<Vec<_>>();
14    let mut curr = vec![0; n + 1];
15    for (i, ac) in a_chars.iter().enumerate() {
16        curr[0] = i + 1;
17        for (j, bc) in b_chars.iter().enumerate() {
18            let cost = if ac == bc { 0 } else { 1 };
19            curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
20        }
21        std::mem::swap(&mut prev, &mut curr);
22    }
23    prev[n]
24}
25
26/// Find the closest match to `name` among `candidates`, within `max_dist` edits.
27pub fn find_closest_match<'a>(
28    name: &str,
29    candidates: impl Iterator<Item = &'a str>,
30    max_dist: usize,
31) -> Option<&'a str> {
32    candidates
33        .filter(|c| c.len().abs_diff(name.len()) <= max_dist)
34        .min_by_key(|c| edit_distance(name, c))
35        .filter(|c| edit_distance(name, c) <= max_dist && *c != name)
36}
37
38/// Render a Rust-style diagnostic message.
39///
40/// Example output:
41/// ```text
42/// error: undefined variable `x`
43///   --> example.harn:5:12
44///    |
45///  5 |     let y = x + 1
46///    |             ^ not found in this scope
47/// ```
48pub fn render_diagnostic(
49    source: &str,
50    filename: &str,
51    span: &Span,
52    severity: &str,
53    message: &str,
54    label: Option<&str>,
55    help: Option<&str>,
56) -> String {
57    let mut out = String::new();
58    let severity_color = severity_color(severity);
59    let gutter = style_fragment("|", Color::Blue, false);
60    let arrow = style_fragment("-->", Color::Blue, true);
61    let help_prefix = style_fragment("help", Color::Cyan, true);
62    let note_prefix = style_fragment("note", Color::Magenta, true);
63
64    // Header: severity + message
65    out.push_str(&style_fragment(severity, severity_color, true));
66    out.push_str(": ");
67    out.push_str(message);
68    out.push('\n');
69
70    // Location line
71    let line_num = span.line;
72    let col_num = span.column;
73
74    let gutter_width = line_num.to_string().len();
75
76    out.push_str(&format!(
77        "{:>width$}{arrow} {filename}:{line_num}:{col_num}\n",
78        " ",
79        width = gutter_width + 1,
80    ));
81
82    // Blank gutter
83    out.push_str(&format!(
84        "{:>width$} {gutter}\n",
85        " ",
86        width = gutter_width + 1,
87    ));
88
89    // Source line
90    let source_line_opt = source.lines().nth(line_num.wrapping_sub(1));
91    if let Some(source_line) = source_line_opt.filter(|_| line_num > 0) {
92        out.push_str(&format!(
93            "{:>width$} {gutter} {source_line}\n",
94            line_num,
95            width = gutter_width + 1,
96        ));
97
98        // Caret line
99        if let Some(label_text) = label {
100            // Calculate span display width using character counts, not byte offsets
101            let span_len = if span.end > span.start && span.start <= source.len() {
102                let span_text = &source[span.start.min(source.len())..span.end.min(source.len())];
103                span_text.chars().count().max(1)
104            } else {
105                1
106            };
107            let col_num = col_num.max(1); // ensure at least 1
108            let padding = " ".repeat(col_num - 1);
109            let carets = style_fragment(&"^".repeat(span_len), severity_color, true);
110            out.push_str(&format!(
111                "{:>width$} {gutter} {padding}{carets} {label_text}\n",
112                " ",
113                width = gutter_width + 1,
114            ));
115        }
116    }
117
118    // Help line
119    if let Some(help_text) = help {
120        out.push_str(&format!(
121            "{:>width$} = {help_prefix}: {help_text}\n",
122            " ",
123            width = gutter_width + 1,
124        ));
125    }
126
127    if let Some(note_text) = fun_note(severity) {
128        out.push_str(&format!(
129            "{:>width$} = {note_prefix}: {note_text}\n",
130            " ",
131            width = gutter_width + 1,
132        ));
133    }
134
135    out
136}
137
138fn severity_color(severity: &str) -> Color {
139    match severity {
140        "error" => Color::Red,
141        "warning" => Color::Yellow,
142        "note" => Color::Magenta,
143        _ => Color::Cyan,
144    }
145}
146
147fn style_fragment(text: &str, color: Color, bold: bool) -> String {
148    if !colors_enabled() {
149        return text.to_string();
150    }
151
152    let mut paint = Paint::new(text).fg(color);
153    if bold {
154        paint = paint.bold();
155    }
156    paint.to_string()
157}
158
159fn colors_enabled() -> bool {
160    std::env::var_os("NO_COLOR").is_none() && std::io::stderr().is_terminal()
161}
162
163fn fun_note(severity: &str) -> Option<&'static str> {
164    if std::env::var("HARN_FUN").ok().as_deref() != Some("1") {
165        return None;
166    }
167
168    Some(match severity {
169        "error" => "the compiler stepped on a rake here.",
170        "warning" => "this still runs, but it has strong 'double-check me' energy.",
171        _ => "a tiny gremlin has left a note in the margins.",
172    })
173}
174
175pub fn parser_error_message(err: &ParserError) -> String {
176    match err {
177        ParserError::Unexpected { got, expected, .. } => {
178            format!("expected {expected}, found {got}")
179        }
180        ParserError::UnexpectedEof { expected, .. } => {
181            format!("unexpected end of file, expected {expected}")
182        }
183    }
184}
185
186pub fn parser_error_label(err: &ParserError) -> &'static str {
187    match err {
188        ParserError::Unexpected { got, .. } if got == "Newline" => "line break not allowed here",
189        ParserError::Unexpected { .. } => "unexpected token",
190        ParserError::UnexpectedEof { .. } => "file ends here",
191    }
192}
193
194pub fn parser_error_help(err: &ParserError) -> Option<&'static str> {
195    match err {
196        ParserError::UnexpectedEof { expected, .. } | ParserError::Unexpected { expected, .. } => {
197            match expected.as_str() {
198                "}" => Some("add a closing `}` to finish this block"),
199                ")" => Some("add a closing `)` to finish this expression or parameter list"),
200                "]" => Some("add a closing `]` to finish this list or subscript"),
201                "fn, struct, enum, or pipeline after pub" => {
202                    Some("use `pub fn`, `pub pipeline`, `pub enum`, or `pub struct`")
203                }
204                _ => None,
205            }
206        }
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn test_basic_diagnostic() {
216        let source = "pipeline default(task) {\n    let y = x + 1\n}";
217        let span = Span {
218            start: 28,
219            end: 29,
220            line: 2,
221            column: 13,
222            end_line: 2,
223        };
224        let output = render_diagnostic(
225            source,
226            "example.harn",
227            &span,
228            "error",
229            "undefined variable `x`",
230            Some("not found in this scope"),
231            None,
232        );
233        assert!(output.contains("error: undefined variable `x`"));
234        assert!(output.contains("--> example.harn:2:13"));
235        assert!(output.contains("let y = x + 1"));
236        assert!(output.contains("^ not found in this scope"));
237    }
238
239    #[test]
240    fn test_diagnostic_with_help() {
241        let source = "let y = xx + 1";
242        let span = Span {
243            start: 8,
244            end: 10,
245            line: 1,
246            column: 9,
247            end_line: 1,
248        };
249        let output = render_diagnostic(
250            source,
251            "test.harn",
252            &span,
253            "error",
254            "undefined variable `xx`",
255            Some("not found in this scope"),
256            Some("did you mean `x`?"),
257        );
258        assert!(output.contains("help: did you mean `x`?"));
259    }
260
261    #[test]
262    fn test_multiline_source() {
263        let source = "line1\nline2\nline3";
264        let span = Span::with_offsets(6, 11, 2, 1); // "line2"
265        let result = render_diagnostic(
266            source,
267            "test.harn",
268            &span,
269            "error",
270            "bad line",
271            Some("here"),
272            None,
273        );
274        assert!(result.contains("line2"));
275        assert!(result.contains("^^^^^"));
276    }
277
278    #[test]
279    fn test_single_char_span() {
280        let source = "let x = 42";
281        let span = Span::with_offsets(4, 5, 1, 5); // "x"
282        let result = render_diagnostic(
283            source,
284            "test.harn",
285            &span,
286            "warning",
287            "unused",
288            Some("never used"),
289            None,
290        );
291        assert!(result.contains("^"));
292        assert!(result.contains("never used"));
293    }
294
295    #[test]
296    fn test_with_help() {
297        let source = "let y = reponse";
298        let span = Span::with_offsets(8, 15, 1, 9);
299        let result = render_diagnostic(
300            source,
301            "test.harn",
302            &span,
303            "error",
304            "undefined",
305            None,
306            Some("did you mean `response`?"),
307        );
308        assert!(result.contains("help:"));
309        assert!(result.contains("response"));
310    }
311
312    #[test]
313    fn test_parser_error_helpers_for_eof() {
314        let err = ParserError::UnexpectedEof {
315            expected: "}".into(),
316            span: Span::with_offsets(10, 10, 3, 1),
317        };
318        assert_eq!(
319            parser_error_message(&err),
320            "unexpected end of file, expected }"
321        );
322        assert_eq!(parser_error_label(&err), "file ends here");
323        assert_eq!(
324            parser_error_help(&err),
325            Some("add a closing `}` to finish this block")
326        );
327    }
328}