Skip to main content

harn_vm/vm/
format.rs

1use super::*;
2
3impl super::Vm {
4    pub fn format_runtime_error(&self, error: &VmError) -> String {
5        let entry_file = self.source_file.as_deref().unwrap_or("<unknown>");
6        let entry_source = self.source_text.as_deref();
7
8        let error_msg = format!("{error}");
9        let mut out = String::new();
10
11        out.push_str(&format!("error: {error_msg}\n"));
12
13        // Prefer captured stack trace (taken before unwinding); fall back to live frames.
14        let frames: Vec<(String, usize, usize, Option<String>)> =
15            if !self.error_stack_trace.is_empty() {
16                self.error_stack_trace
17                    .iter()
18                    .map(|(name, line, col, src)| (name.clone(), *line, *col, src.clone()))
19                    .collect()
20            } else {
21                self.frames
22                    .iter()
23                    .map(|f| {
24                        let idx = if f.ip > 0 { f.ip - 1 } else { 0 };
25                        let line = f.chunk.lines.get(idx).copied().unwrap_or(0) as usize;
26                        let col = f.chunk.columns.get(idx).copied().unwrap_or(0) as usize;
27                        (f.fn_name.clone(), line, col, f.chunk.source_file.clone())
28                    })
29                    .collect()
30            };
31
32        if let Some((_name, line, col, frame_file)) = frames.last() {
33            let line = *line;
34            let col = *col;
35            let filename = frame_file.as_deref().unwrap_or(entry_file);
36            // Read the frame's own source so the caret line is meaningful;
37            // fall back to entry-point source (e.g. for stdlib modules).
38            let owned_source: Option<String> = frame_file
39                .as_deref()
40                .and_then(|p| std::fs::read_to_string(p).ok());
41            let source_for_line: Option<&str> =
42                owned_source.as_deref().or(if frame_file.is_none() {
43                    entry_source
44                } else {
45                    None
46                });
47            if line > 0 {
48                let display_col = if col > 0 { col } else { 1 };
49                let gutter_width = line.to_string().len();
50                out.push_str(&format!(
51                    "{:>width$}--> {filename}:{line}:{display_col}\n",
52                    " ",
53                    width = gutter_width + 1,
54                ));
55                if let Some(source_line) =
56                    source_for_line.and_then(|s| s.lines().nth(line.saturating_sub(1)))
57                {
58                    out.push_str(&format!("{:>width$} |\n", " ", width = gutter_width + 1));
59                    out.push_str(&format!(
60                        "{:>width$} | {source_line}\n",
61                        line,
62                        width = gutter_width + 1,
63                    ));
64                    let caret_col = if col > 0 { col } else { 1 };
65                    let trimmed = source_line.trim();
66                    let leading = source_line
67                        .len()
68                        .saturating_sub(source_line.trim_start().len());
69                    let caret_len = if col > 0 {
70                        Self::token_len_at(source_line, col)
71                    } else {
72                        trimmed.len().max(1)
73                    };
74                    let padding = if col > 0 {
75                        " ".repeat(caret_col.saturating_sub(1))
76                    } else {
77                        " ".repeat(leading)
78                    };
79                    let carets = "^".repeat(caret_len);
80                    out.push_str(&format!(
81                        "{:>width$} | {padding}{carets}\n",
82                        " ",
83                        width = gutter_width + 1,
84                    ));
85                }
86            }
87        }
88
89        // Call stack, bottom-up, skipping the top frame (already shown).
90        if frames.len() > 1 {
91            for (name, line, _col, frame_file) in frames.iter().rev().skip(1) {
92                let display_name = if name.is_empty() { "pipeline" } else { name };
93                if *line > 0 {
94                    let filename = frame_file.as_deref().unwrap_or(entry_file);
95                    out.push_str(&format!(
96                        "  = note: called from {display_name} at {filename}:{line}\n"
97                    ));
98                }
99            }
100        }
101
102        out
103    }
104
105    /// Estimate the length of the token at the given 1-based column position
106    /// in a source line. Scans forward from that position to find a word/operator
107    /// boundary.
108    fn token_len_at(source_line: &str, col: usize) -> usize {
109        let chars: Vec<char> = source_line.chars().collect();
110        let start = col.saturating_sub(1);
111        if start >= chars.len() {
112            return 1;
113        }
114        let first = chars[start];
115        if first.is_alphanumeric() || first == '_' {
116            let mut end = start + 1;
117            while end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
118                end += 1;
119            }
120            end - start
121        } else {
122            1
123        }
124    }
125}