1use std::fmt;
2use std::io::IsTerminal;
3use std::ops::Range;
4
5use thiserror::Error;
6
7use crate::ast::Expr;
8
9#[derive(Debug, Clone)]
10pub struct ParseErrorDetails {
11 pub message: String,
12 pub input: String,
13 pub span: Range<usize>,
14}
15
16impl ParseErrorDetails {
17 pub fn new(message: String, input: String, span: Range<usize>) -> Self {
18 Self {
19 message,
20 input,
21 span,
22 }
23 }
24
25 fn find_line_info(&self) -> (usize, usize, &str) {
26 let offset = self.input.floor_char_boundary(self.span.start);
27 let before = &self.input[..offset];
28 let line_num = before.matches('\n').count() + 1;
29 let line_start = before.rfind('\n').map_or(0, |i| i + 1);
30 let line_end = self.input[offset..]
31 .find('\n')
32 .map_or(self.input.len(), |i| offset + i);
33 let line = &self.input[line_start..line_end];
34 let col = self.input[line_start..offset].chars().count();
35 (line_num, col, line)
36 }
37
38 pub fn render(&self, use_color: bool) -> String {
39 let (line_num, col, line) = self.find_line_info();
40 let line_num_width = line_num.to_string().len().max(1);
41
42 let (red, cyan, reset) = if use_color {
43 ("\x1b[31m", "\x1b[36m", "\x1b[0m")
44 } else {
45 ("", "", "")
46 };
47
48 let mut output = String::new();
49 output.push_str(&format!("{red}error:{reset} {}\n", self.message));
50 output.push_str(&format!(
51 "{cyan}{:>width$} |{reset}\n",
52 "",
53 width = line_num_width
54 ));
55 output.push_str(&format!(
56 "{cyan}{line_num:>line_num_width$} |{reset} {line}\n"
57 ));
58 output.push_str(&format!(
59 "{cyan}{:>width$} |{reset} {}{red}^{reset}\n",
60 "",
61 " ".repeat(col),
62 width = line_num_width
63 ));
64 output
65 }
66
67 pub fn render_auto(&self) -> String {
68 self.render(std::io::stderr().is_terminal())
69 }
70}
71
72impl fmt::Display for ParseErrorDetails {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 write!(f, "{}", self.render(false))
75 }
76}
77
78#[derive(Error, Debug)]
79pub enum Error {
80 #[error("{0}")]
81 Parse(ParseErrorDetails),
82
83 #[error("Compile error: {0}")]
84 Compile(String),
85
86 #[error(
89 "Compile error: {factory}'s lambda reads its parameter {param} here, where a closure factory cannot be used"
90 )]
91 UnclosableFactory { factory: String, param: String },
92
93 #[error("Compile error: {0}")]
97 Resource(String),
98
99 #[error("Compile error: {0}")]
102 Dimension(String),
103
104 #[error("Compile error: RETURN-FROM '{block}' has no enclosing BLOCK")]
108 Transfer { block: String, value: Box<Expr> },
109
110 #[error("Runtime error: {0}")]
111 Runtime(String),
112
113 #[error("Undefined symbol: {0}")]
114 UndefinedSymbol(String),
115
116 #[error("Type error: expected {expected}, got {actual}")]
117 Type { expected: String, actual: String },
118
119 #[error("Arity error: {name} expects {expected} arguments, got {actual}")]
120 Arity {
121 name: String,
122 expected: usize,
123 actual: usize,
124 },
125}
126
127impl Error {
128 #[must_use]
129 pub fn parse(message: String, input: &str, span: Range<usize>) -> Self {
130 Self::Parse(ParseErrorDetails::new(message, input.to_string(), span))
131 }
132
133 #[must_use]
136 pub fn undefined_symbol(name: &str) -> Self {
137 match crate::runtime::SymbolTable::hidden_origin(name) {
138 Some((factory, param)) => Error::UnclosableFactory {
139 factory: factory.to_string(),
140 param: param.to_string(),
141 },
142 None => crate::runtime::SymbolTable::local_alias_origin(name).map_or_else(
143 || Error::UndefinedSymbol(name.to_string()),
144 |function| {
145 Error::Compile(format!(
146 "{function}: a LABELS function does not outlive its form; a function or lambda that calls it cannot be used outside; not supported yet"
147 ))
148 },
149 ),
150 }
151 }
152
153 #[must_use]
154 pub fn render(&self, use_color: bool) -> String {
155 match self {
156 Error::Parse(details) => details.render(use_color),
157 _ => self.to_string(),
158 }
159 }
160
161 #[must_use]
162 pub fn render_auto(&self) -> String {
163 match self {
164 Error::Parse(details) => details.render_auto(),
165 _ => self.to_string(),
166 }
167 }
168}
169
170pub type Result<T> = std::result::Result<T, Error>;
171
172#[must_use]
174pub fn with_article(noun: impl fmt::Display) -> String {
175 let noun = noun.to_string();
176 let article = match noun.chars().next() {
177 Some('a' | 'e' | 'i' | 'o' | 'u') => "an",
178 _ => "a",
179 };
180 format!("{article} {noun}")
181}
182
183#[cfg(test)]
184#[path = "error_tests.rs"]
185mod tests;