-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.rs
More file actions
401 lines (337 loc) · 12.7 KB
/
errors.rs
File metadata and controls
401 lines (337 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//! Errors
use lalrpop_util::ParseError;
use thiserror::Error;
use crate::{
errors::diagnostics::{ExprDiagnosisSeverity, ExprDiagnostic, get_range},
lexer::Token,
span::{Span, Spanned},
};
pub type ExprResult<T> = std::result::Result<T, Vec<ExprErrorS>>;
#[derive(Debug, Error, PartialEq)]
pub enum ExprError {
#[error("There was an error lexing expression: {0}")]
LexError(#[from] LexicalError),
#[error("There was an error in the expression syntax: {0}")]
SyntaxError(#[from] SyntaxError),
}
impl diagnostics::AsDiagnostic for ExprError {
fn as_diagnostic(&self, source: &str, span: &Span) -> ExprDiagnostic {
match self {
ExprError::LexError(e) => e.as_diagnostic(source, span),
ExprError::SyntaxError(e) => e.as_diagnostic(source, span),
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Error)]
pub enum LexicalError {
#[default]
#[error("Invalid token")]
InvalidToken,
}
impl diagnostics::AsDiagnostic for LexicalError {
fn as_diagnostic(&self, source: &str, span: &Span) -> ExprDiagnostic {
let error_code = "lexical".to_string();
match self {
LexicalError::InvalidToken => ExprDiagnostic {
code: error_code,
range: get_range(source, span),
severity: Some(ExprDiagnosisSeverity::ERROR),
message: format!("{self}"),
},
}
}
}
#[derive(Debug, Clone, Error, PartialEq)]
pub enum SyntaxError {
#[error("extraneous input: {token:?}")]
ExtraToken { token: String },
#[error("invalid input")]
InvalidToken,
#[error("unexpected end of file; expected: {expected:?}")]
UnrecognizedEOF { expected: Vec<String> },
#[error("unexpected {token:?}; expected: {expected:?}")]
UnrecognizedToken {
token: String,
expected: Vec<String>,
},
}
impl SyntaxError {
pub fn from_parser_error(
err: ParseError<usize, Token, ExprErrorS>,
source: &str,
) -> ExprErrorS {
match err {
ParseError::InvalidToken { location } => {
(SyntaxError::InvalidToken.into(), location..location)
}
ParseError::UnrecognizedEof { location, expected } => (
SyntaxError::UnrecognizedEOF { expected }.into(),
location..location,
),
ParseError::UnrecognizedToken {
token: (start, _, end),
expected,
} => (
SyntaxError::UnrecognizedToken {
token: source[start..end].to_string(),
expected,
}
.into(),
start..end,
),
ParseError::ExtraToken {
token: (start, _, end),
} => (
SyntaxError::ExtraToken {
token: source[start..end].to_string(),
}
.into(),
start..end,
),
ParseError::User { error } => error,
}
}
}
impl diagnostics::AsDiagnostic for SyntaxError {
fn as_diagnostic(&self, source: &str, span: &Span) -> ExprDiagnostic {
let error_code = "syntax".to_string();
match self {
SyntaxError::ExtraToken { token: _ } => ExprDiagnostic {
code: error_code,
range: get_range(source, span),
severity: Some(ExprDiagnosisSeverity::ERROR),
message: format!("{self}"),
},
SyntaxError::InvalidToken => ExprDiagnostic {
code: error_code,
range: get_range(source, span),
severity: Some(ExprDiagnosisSeverity::ERROR),
message: format!("{self}"),
},
SyntaxError::UnrecognizedEOF { expected: _ } => ExprDiagnostic {
code: error_code,
range: get_range(source, span),
severity: Some(ExprDiagnosisSeverity::ERROR),
message: format!("{self}"),
},
SyntaxError::UnrecognizedToken {
token: _,
expected: _,
} => ExprDiagnostic {
code: error_code,
range: get_range(source, span),
severity: Some(ExprDiagnosisSeverity::ERROR),
message: format!("{self}"),
},
}
}
}
pub type ExprErrorS = Spanned<ExprError>;
pub mod diagnostics {
use codespan_reporting::diagnostic::{Diagnostic, Label, Severity};
use line_col::LineColLookup;
use crate::{errors::ExprErrorS, span::Span};
pub fn get_diagnostics(errs: &[ExprErrorS], source: &str) -> Vec<Diagnostic<usize>> {
errs.iter()
.map(|(err, span)| {
let a = err.as_diagnostic(source, span);
let b = a.to_diagnostic(span).with_message(a.message.clone());
b
})
.collect()
}
pub trait AsDiagnostic {
fn as_diagnostic(&self, source: &str, span: &Span) -> ExprDiagnostic;
}
#[derive(Debug, Eq, PartialEq, Clone, Default)]
pub struct ExprDiagnostic {
pub code: String,
pub range: ExprDiagnosticRange,
pub severity: Option<ExprDiagnosisSeverity>,
pub message: String,
}
impl ExprDiagnostic {
pub fn to_diagnostic(
&self,
span: &Span,
) -> codespan_reporting::diagnostic::Diagnostic<usize> {
codespan_reporting::diagnostic::Diagnostic {
severity: ExprDiagnosisSeverity::ERROR.to_severity(),
code: Some(self.code.clone()),
message: self.message.clone(),
labels: vec![Label::primary(0, span.clone())],
notes: vec![],
}
}
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
pub struct ExprDiagnosisSeverity(i32);
#[allow(dead_code)]
impl ExprDiagnosisSeverity {
pub const ERROR: ExprDiagnosisSeverity = ExprDiagnosisSeverity(1);
pub const WARNING: ExprDiagnosisSeverity = ExprDiagnosisSeverity(2);
pub const INFORMATION: ExprDiagnosisSeverity = ExprDiagnosisSeverity(3);
pub const HINT: ExprDiagnosisSeverity = ExprDiagnosisSeverity(4);
}
impl ExprDiagnosisSeverity {
fn to_severity(&self) -> Severity {
match *self {
ExprDiagnosisSeverity::HINT => Severity::Help,
ExprDiagnosisSeverity::INFORMATION => Severity::Note,
ExprDiagnosisSeverity::WARNING => Severity::Warning,
ExprDiagnosisSeverity::ERROR => Severity::Error,
_ => panic!("Invalid diagnosis severity: {}", self.0),
}
}
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default)]
pub struct ExprDiagnosticPosition {
pub line: u32,
pub character: u32,
}
impl ExprDiagnosticPosition {
pub fn new(line: u32, character: u32) -> ExprDiagnosticPosition {
ExprDiagnosticPosition { line, character }
}
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, Default)]
pub struct ExprDiagnosticRange {
/// The range's start position (inclusive)
pub start: ExprDiagnosticPosition,
/// The range's end position (exclusive)
pub end: ExprDiagnosticPosition,
}
impl ExprDiagnosticRange {
pub fn new(
start: ExprDiagnosticPosition,
end: ExprDiagnosticPosition,
) -> ExprDiagnosticRange {
ExprDiagnosticRange { start, end }
}
}
pub fn get_range(source: &str, span: &Span) -> ExprDiagnosticRange {
ExprDiagnosticRange::new(
get_position(source, span.start),
get_position(source, span.end),
)
}
pub fn get_position(source: &str, idx: usize) -> ExprDiagnosticPosition {
let (line, character) = index_to_position(source, idx);
ExprDiagnosticPosition::new(line as u32, character as u32)
}
/// Map index to position (line, column)
///
/// Line and column are zero based
pub fn index_to_position(source: &str, index: usize) -> (usize, usize) {
let lookup = LineColLookup::new(source);
let (line, char) = lookup.get(index);
(line - 1, char - 1)
}
/// Map position (line, column) to index
///
/// Line and column are zero based
pub fn position_to_index(source: &str, position: (usize, usize)) -> usize {
let (line, character) = position;
let lines = source.split('\n');
let lines_before = lines.take(line);
let line_chars_before = lines_before.fold(0usize, |acc, e| acc + e.len() + 1);
let chars = character;
line_chars_before + chars
}
#[cfg(test)]
mod index_position_fn_tests {
use super::*;
#[test]
fn it_should_convert_index_to_position() {
let source = "let a = 123;\nlet b = 456;";
let index = 17usize;
let expected_position = (1, 4);
let index_to_position = index_to_position(source, index);
let actual_position = index_to_position;
assert_eq!(expected_position, actual_position);
}
#[test]
fn it_should_convert_position_to_index() {
let source = "let a = 123;\nlet b = 456;";
let position = (1, 4);
let expected_index = 17usize;
let actual_index = position_to_index(source, position);
assert_eq!(expected_index, actual_index);
}
#[test]
fn it_should_convert_position_to_index_and_back() {
let source = "let a = 123;\nlet b = 456;";
let position = (1, 4);
let actual_index = position_to_index(source, position);
assert_eq!(position, index_to_position(source, actual_index));
}
#[test]
fn it_should_convert_position_to_index_and_back_b() {
let source = "let a = 123;\n{\n let b = 456;\n}";
let position = (2, 12);
let actual_index = position_to_index(source, position);
assert_eq!(position, index_to_position(source, actual_index));
}
#[test]
fn it_should_convert_position_to_index_b() {
let source = "let a = 123;\n{\n let b = 456;\n}";
let position = (2, 12);
let actual_index = position_to_index(source, position);
assert_eq!(27, actual_index);
}
#[test]
fn it_should_convert_position_to_index_c() {
let source = "let a = 123;\nlet b = 456;\nlet c = 789;";
let position = (2, 8);
let actual_index = position_to_index(source, position);
assert_eq!(34, actual_index);
}
#[test]
fn it_should_convert_position_to_index_d() {
let source = "let a = 123;\nlet b = 456;\nlet c = 789;\nlet d = 000;";
let position = (3, 8);
let actual_index = position_to_index(source, position);
assert_eq!(47, actual_index);
}
#[test]
fn it_should_convert_position_to_index_e() {
let source = "let a = 123;\nlet b = 456;\nlet c = 789;\nlet d = 000;\nlet e = 999;";
let position = (4, 8);
let actual_index = position_to_index(source, position);
assert_eq!(60, actual_index);
}
#[test]
fn it_should_convert_position_to_index_f() {
let source = "let a = 123;\nlet b = 456;\nlet c = 789;\nlet d = 000;\nlet e = 999;\n";
let position = (4, 8);
let actual_index = position_to_index(source, position);
assert_eq!(60, actual_index);
}
}
#[cfg(test)]
mod error_to_diagnostics_tests {
use crate::errors::{ExprError, LexicalError};
use super::*;
use std::ops::Range;
fn dummy_source() -> &'static str {
"("
}
fn dummy_range() -> Span {
Range { start: 1, end: 1 }
}
#[test]
fn it_converts_lexerror_to_diagnostic() {
let source = dummy_source();
let expected_range = dummy_range();
let error = ExprError::LexError(LexicalError::InvalidToken);
let diagnostics = get_diagnostics(&[(error, expected_range.clone())], source);
assert_eq!(1, diagnostics.len());
let diagnostic = &diagnostics[0];
assert_eq!(Some("lexical".to_string()), diagnostic.code);
assert_eq!("Invalid token".to_string(), diagnostic.message);
assert_eq!(Severity::Error, diagnostic.severity);
assert_eq!(1, diagnostic.labels.len());
assert_eq!(Label::primary(0, expected_range), diagnostic.labels[0]);
}
}
}