syntaxe/src/result.rs 7.2 KiB raw
1
//! Parser result types.
2
3
use std::fmt;
4
use std::path::PathBuf;
5
use std::rc::Rc;
6
7
/// A location in a string.
8
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
9
pub struct Location {
10
    /// Byte index (0-indexed).
11
    pub index: usize,
12
    /// Line (1-indexed).
13
    pub line: usize,
14
    /// Column (1-indexed).
15
    pub column: usize,
16
}
17
18
impl Default for Location {
19
    fn default() -> Self {
20
        Self {
21
            index: 0,
22
            line: 1,
23
            column: 1,
24
        }
25
    }
26
}
27
28
/// A sub-string at a specific location.
29
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
30
pub struct Cursor<'a> {
31
    /// The input string reference.
32
    pub input: &'a str,
33
    /// The location of the string reference in the string.
34
    pub location: Location,
35
}
36
37
impl<'a> Cursor<'a> {
38
    /// Create a new cursor.
39
    pub fn new(input: &'a str, location: Location) -> Self {
40
        Self { input, location }
41
    }
42
43
    /// Advance the cursor by consuming `n` characters.
44
    pub fn advance(&self, n: usize) -> Self {
45
        let mut loc = self.location;
46
        let mut chars = self.input.chars();
47
48
        for _ in 0..n {
49
            // SAFETY: Since this function should only be called to consume
50
            // input that we have already peeked at, a missing character
51
            // indicates a bug.
52
            let ch = chars.next().expect("Cursor::advance: unexpected end of input");
53
            if ch == '\n' {
54
                loc.line += 1;
55
                loc.column = 1;
56
            } else {
57
                loc.column += 1;
58
            }
59
            loc.index += ch.len_utf8();
60
        }
61
62
        Self {
63
            input: chars.as_str(),
64
            location: loc,
65
        }
66
    }
67
}
68
69
impl<'a> From<&'a str> for Cursor<'a> {
70
    fn from(input: &'a str) -> Self {
71
        Self {
72
            input,
73
            location: Location::default(),
74
        }
75
    }
76
}
77
78
/// Result of applying a `Parser` to an input.
79
pub type Result<'a, T> = std::result::Result<(T, Cursor<'a>), Error<'a>>;
80
81
/// The specific type of parser error that occurred.
82
#[derive(Debug, Clone)]
83
pub enum ErrorKind<'a> {
84
    /// Expected end of input but found more content.
85
    ExpectedEof,
86
    /// Expected a specific character.
87
    ExpectedChar(char),
88
    /// Expected a specific string.
89
    ExpectedString(&'a str),
90
    /// Expected one of several possible values.
91
    ExpectedOneOf(Vec<Rc<str>>),
92
    /// Expected something described by the string.
93
    ExpectedOther(Rc<str>),
94
    /// A custom error message.
95
    Custom(Rc<str>),
96
    /// Error converting from string using FromStr.
97
    FromStr(Rc<dyn std::error::Error>),
98
    /// Error mapping a value using try_map.
99
    TryMap(Rc<dyn std::error::Error>),
100
    /// Found an unexpected character.
101
    UnexpectedChar(char),
102
    /// Found unexpected end of input.
103
    UnexpectedEof,
104
}
105
106
impl PartialEq for ErrorKind<'_> {
107
    fn eq(&self, other: &Self) -> bool {
108
        use ErrorKind::*;
109
110
        match (self, other) {
111
            (ExpectedEof, ExpectedEof) => true,
112
            (ExpectedChar(a), ExpectedChar(b)) => a == b,
113
            (ExpectedString(a), ExpectedString(b)) => a == b,
114
            (ExpectedOneOf(a), ExpectedOneOf(b)) => a == b,
115
            (FromStr(a), FromStr(b)) => Rc::ptr_eq(a, b),
116
            (TryMap(a), TryMap(b)) => Rc::ptr_eq(a, b),
117
            (ExpectedOther(a), ExpectedOther(b)) => a == b,
118
            (UnexpectedChar(a), UnexpectedChar(b)) => a == b,
119
            (UnexpectedEof, UnexpectedEof) => true,
120
            _ => false,
121
        }
122
    }
123
}
124
125
impl Eq for ErrorKind<'_> {}
126
127
/// A parser error.
128
#[derive(Debug, Clone, PartialEq, Eq)]
129
pub struct Error<'a> {
130
    /// Error message (without source location).
131
    pub kind: ErrorKind<'a>,
132
    /// The place in the input where the error occurred.
133
    pub cursor: Cursor<'a>,
134
    /// File path of the source.
135
    pub path: Option<PathBuf>,
136
}
137
138
impl<'a> Error<'a> {
139
    /// Create a new parser error from a message.
140
    pub fn new(kind: ErrorKind<'a>, cursor: Cursor<'a>) -> Self {
141
        Self {
142
            kind,
143
            cursor,
144
            path: None,
145
        }
146
    }
147
148
    /// Returns the unparsed portion of the input at the error location
149
    pub fn unparsed(&self) -> &'a str {
150
        self.cursor.input
151
    }
152
153
    /// Returns a description of what was expected, if applicable
154
    pub fn expected(&self) -> Option<Rc<str>> {
155
        match &self.kind {
156
            ErrorKind::ExpectedChar(c) => Some(c.to_string().into()),
157
            ErrorKind::ExpectedString(s) => Some((*s).into()),
158
            ErrorKind::ExpectedOther(s) => Some(s.clone()),
159
            ErrorKind::ExpectedEof => Some("end of file".into()),
160
            _ => None,
161
        }
162
    }
163
164
    /// Returns a formatted error message including file location and details
165
    pub fn explain(&self) -> String {
166
        format!(
167
            "{}:{}:{}: error: {}",
168
            self.path
169
                .as_ref()
170
                .map(|p| p.display().to_string())
171
                .unwrap_or("<stdin>".to_owned()),
172
            self.cursor.location.line,
173
            self.cursor.location.column,
174
            self,
175
        )
176
    }
177
}
178
179
impl std::fmt::Display for Error<'_> {
180
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181
        let input = self.cursor.input;
182
        let eof = input.is_empty();
183
        let actual = input
184
            .find('\n')
185
            .map(|i| if i > 0 { &input[..i] } else { "\n" })
186
            .unwrap_or(input);
187
        match &self.kind {
188
            ErrorKind::ExpectedEof => {
189
                write!(f, "expected end-of-input, got `{actual}`")
190
            }
191
            ErrorKind::ExpectedChar(c) => {
192
                if eof {
193
                    write!(f, "expected '{c}', got end-of-input")
194
                } else {
195
                    write!(f, "expected '{c}', got `{actual}`")
196
                }
197
            }
198
            ErrorKind::ExpectedString(s) => {
199
                if eof {
200
                    write!(f, "expected `{s}`, got end-of-input")
201
                } else {
202
                    write!(f, "expected `{s}`, got `{actual}`")
203
                }
204
            }
205
            ErrorKind::ExpectedOther(expected) => {
206
                if eof {
207
                    write!(f, "expected {expected}, got end-of-input")
208
                } else {
209
                    write!(f, "expected {expected}, got `{actual}`")
210
                }
211
            }
212
            ErrorKind::ExpectedOneOf(expected) => {
213
                let choices = expected
214
                    .iter()
215
                    .map(|c| format!("`{c}`"))
216
                    .collect::<Vec<_>>()
217
                    .join(", ");
218
                if eof {
219
                    write!(f, "expected one of {choices}, got end-of-input")
220
                } else {
221
                    write!(f, "expected one of {choices}, got `{actual}`")
222
                }
223
            }
224
            ErrorKind::Custom(err) => {
225
                write!(f, "{err}")
226
            }
227
            ErrorKind::FromStr(e) => {
228
                write!(f, "string conversion failed: {e}")
229
            }
230
            ErrorKind::TryMap(e) => {
231
                write!(f, "value conversion failed: {e}")
232
            }
233
            ErrorKind::UnexpectedEof => {
234
                write!(f, "unexpected end-of-input")
235
            }
236
            ErrorKind::UnexpectedChar(c) => {
237
                write!(f, "unexpected '{c}'")
238
            }
239
        }
240
    }
241
}
242
243
impl std::error::Error for Error<'_> {}