1
use std::fmt;
2
use std::io::IsTerminal;
3
use std::ops::Range;
4

            
5
use thiserror::Error;
6

            
7
use crate::ast::Expr;
8

            
9
#[derive(Debug, Clone)]
10
pub struct ParseErrorDetails {
11
    pub message: String,
12
    pub input: String,
13
    pub span: Range<usize>,
14
}
15

            
16
impl ParseErrorDetails {
17
13766
    pub fn new(message: String, input: String, span: Range<usize>) -> Self {
18
13766
        Self {
19
13766
            message,
20
13766
            input,
21
13766
            span,
22
13766
        }
23
13766
    }
24

            
25
10421
    fn find_line_info(&self) -> (usize, usize, &str) {
26
10421
        let offset = self.input.floor_char_boundary(self.span.start);
27
10421
        let before = &self.input[..offset];
28
10421
        let line_num = before.matches('\n').count() + 1;
29
10421
        let line_start = before.rfind('\n').map_or(0, |i| i + 1);
30
10421
        let line_end = self.input[offset..]
31
10421
            .find('\n')
32
10421
            .map_or(self.input.len(), |i| offset + i);
33
10421
        let line = &self.input[line_start..line_end];
34
10421
        let col = self.input[line_start..offset].chars().count();
35
10421
        (line_num, col, line)
36
10421
    }
37

            
38
10421
    pub fn render(&self, use_color: bool) -> String {
39
10421
        let (line_num, col, line) = self.find_line_info();
40
10421
        let line_num_width = line_num.to_string().len().max(1);
41

            
42
10421
        let (red, cyan, reset) = if use_color {
43
            ("\x1b[31m", "\x1b[36m", "\x1b[0m")
44
        } else {
45
10421
            ("", "", "")
46
        };
47

            
48
10421
        let mut output = String::new();
49
10421
        output.push_str(&format!("{red}error:{reset} {}\n", self.message));
50
10421
        output.push_str(&format!(
51
10421
            "{cyan}{:>width$} |{reset}\n",
52
10421
            "",
53
10421
            width = line_num_width
54
10421
        ));
55
10421
        output.push_str(&format!(
56
10421
            "{cyan}{line_num:>line_num_width$} |{reset} {line}\n"
57
10421
        ));
58
10421
        output.push_str(&format!(
59
10421
            "{cyan}{:>width$} |{reset} {}{red}^{reset}\n",
60
10421
            "",
61
10421
            " ".repeat(col),
62
10421
            width = line_num_width
63
10421
        ));
64
10421
        output
65
10421
    }
66

            
67
    pub fn render_auto(&self) -> String {
68
        self.render(std::io::stderr().is_terminal())
69
    }
70
}
71

            
72
impl fmt::Display for ParseErrorDetails {
73
10407
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74
10407
        write!(f, "{}", self.render(false))
75
10407
    }
76
}
77

            
78
#[derive(Error, Debug)]
79
pub enum Error {
80
    #[error("{0}")]
81
    Parse(ParseErrorDetails),
82

            
83
    #[error("Compile error: {0}")]
84
    Compile(String),
85

            
86
    /// A read of the parameter `param` of the closure factory `factory` where
87
    /// no scope holds the hidden variable its lambda captured it into.
88
    #[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
    /// A compile-time ceiling was crossed (the work budget, a recursion or
94
    /// nesting depth). Never a licence to keep emitting: a fold that meets
95
    /// one propagates it instead of falling back to codegen (0014 P13).
96
    #[error("Compile error: {0}")]
97
    Resource(String),
98

            
99
    /// An index / scalar / money mix, or a value of one dimension where another
100
    /// is required.
101
    #[error("Compile error: {0}")]
102
    Dimension(String),
103

            
104
    /// A `RETURN-FROM` the evaluator reached unconditionally: the carried
105
    /// `value` leaves the enclosing `BLOCK` named `block`. Never an operation
106
    /// error, so a fold or probe that meets one propagates it (0014 P14).
107
    #[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

            
127
impl Error {
128
    #[must_use]
129
13752
    pub fn parse(message: String, input: &str, span: Range<usize>) -> Self {
130
13752
        Self::Parse(ParseErrorDetails::new(message, input.to_string(), span))
131
13752
    }
132

            
133
    /// The error of a read of the undefined `name`; a closure factory's hidden
134
    /// variable no scope holds is the compile error naming the factory.
135
    #[must_use]
136
89410
    pub fn undefined_symbol(name: &str) -> Self {
137
89410
        match crate::runtime::SymbolTable::hidden_origin(name) {
138
9
            Some((factory, param)) => Error::UnclosableFactory {
139
9
                factory: factory.to_string(),
140
9
                param: param.to_string(),
141
9
            },
142
89401
            None => crate::runtime::SymbolTable::local_alias_origin(name).map_or_else(
143
79208
                || Error::UndefinedSymbol(name.to_string()),
144
10193
                |function| {
145
10193
                    Error::Compile(format!(
146
10193
                        "{function}: a LABELS function does not outlive its form; a function or lambda that calls it cannot be used outside; not supported yet"
147
10193
                    ))
148
10193
                },
149
            ),
150
        }
151
89410
    }
152

            
153
    #[must_use]
154
2288
    pub fn render(&self, use_color: bool) -> String {
155
2288
        match self {
156
            Error::Parse(details) => details.render(use_color),
157
2288
            _ => self.to_string(),
158
        }
159
2288
    }
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

            
170
pub type Result<T> = std::result::Result<T, Error>;
171

            
172
/// `noun` with the indefinite article its first letter asks for.
173
#[must_use]
174
28997
pub fn with_article(noun: impl fmt::Display) -> String {
175
28997
    let noun = noun.to_string();
176
28997
    let article = match noun.chars().next() {
177
4885
        Some('a' | 'e' | 'i' | 'o' | 'u') => "an",
178
24112
        _ => "a",
179
    };
180
28997
    format!("{article} {noun}")
181
28997
}
182

            
183
#[cfg(test)]
184
#[path = "error_tests.rs"]
185
mod tests;