forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.rs
More file actions
171 lines (141 loc) · 4.41 KB
/
Copy patherrors.rs
File metadata and controls
171 lines (141 loc) · 4.41 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
use crate::string_utils::StringPositions;
use crate::Cursor;
#[derive(Debug, PartialEq, Clone)]
pub enum ErrorKind {
StaticStr(&'static str),
Str(String),
Eof,
}
impl ErrorKind {
pub fn description(&self) -> &str {
use ErrorKind::*;
match self {
StaticStr(s) => s,
Str(s) => s.as_str(),
Eof => "end of file",
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ParseError<'a> {
errors: Vec<(Cursor<'a>, ErrorKind)>,
}
impl<'a> ParseError<'a> {
pub fn new(input: Cursor<'a>, kind: ErrorKind) -> Self {
Self {
errors: vec![(input, kind)],
}
}
pub fn static_str(input: Cursor<'a>, string: &'static str) -> Self {
Self::new(input, ErrorKind::StaticStr(string))
}
pub fn str(input: Cursor<'a>, string: String) -> Self {
Self::new(input, ErrorKind::Str(string))
}
pub fn eof(input: Cursor<'a>) -> Self {
Self::new(input, ErrorKind::Eof)
}
pub fn push(mut self, input: Cursor<'a>, kind: ErrorKind) -> Self {
self.errors.push((input, kind));
self
}
/// Format an error into a debug trace message.
#[cfg_attr(tarpaulin, rustfmt::skip)]
pub fn format_debug(&self, input: &str, show_err_no: bool) -> String {
use std::iter::repeat;
let mut string_positions = StringPositions::new(input);
let lines: Vec<_> = input.lines().map(String::from).collect();
let mut result = String::new();
for (err_no, (parser_input, err_kind)) in self.errors.iter().rev().enumerate() {
let first_token = parser_input.iter().next();
if show_err_no {
result += &format!("{}: ", err_no);
}
let offset = match first_token {
Some(tok) => tok.span.start,
None => input.len(),
};
let pos = match string_positions.get_pos(offset) {
Some(pos) => pos,
None => string_positions.get_last().unwrap(),
};
result += &format!(
"at line {} col {}, {}:\n",
pos.line,
pos.col,
err_kind.description()
);
result += &lines[pos.line - 1];
result += "\n";
if pos.col > 0 {
result += &repeat(' ').take(pos.col).collect::<String>();
}
result += "^\n\n";
}
result
}
/// Format an error into a user-facing error message.
///
/// Uses the innermost error to build a user-facing error message and
/// position.
#[cfg_attr(tarpaulin, rustfmt::skip)]
pub fn format_user(&self, input: &str) -> String {
let deepest_error = self.errors.first().unwrap();
let new_err = ParseError {
errors: vec![deepest_error.clone()],
};
new_err.format_debug(input, false)
}
}
#[cfg_attr(tarpaulin, rustfmt::skip)]
#[cfg(test)]
mod tests {
use super::*;
use ErrorKind::*;
macro_rules! empty_slice {
() => {{
&[][..]
}};
}
#[test]
fn test_error_kind_description() {
assert_eq!(Str("foo".to_string()).description(), "foo");
assert_eq!(StaticStr("foo").description(), "foo");
assert_eq!(Eof.description(), "end of file");
}
#[test]
fn test_parse_error_factories() {
assert_eq!(
ParseError::str(empty_slice!(), "foo".to_string()),
ParseError {
errors: vec![(empty_slice!(), Str("foo".to_string()))],
}
);
assert_eq!(
ParseError::static_str(empty_slice!(), "foo"),
ParseError {
errors: vec![(empty_slice!(), StaticStr("foo"))],
}
);
assert_eq!(
ParseError::eof(empty_slice!()),
ParseError {
errors: vec![(empty_slice!(), Eof)],
}
);
}
#[test]
fn test_parse_error_push() {
use crate::get_parse_tokens;
let src = "foo";
let toks = get_parse_tokens(src).unwrap();
let tok_eof = &toks[toks.len()..];
let err = ParseError::eof(tok_eof);
assert_eq!(
err.push(&toks[..], StaticStr("some other error")),
ParseError {
errors: vec![(tok_eof, Eof), (&toks[..], StaticStr("some other error")),],
}
);
}
}