forked from databendlabs/databend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
338 lines (303 loc) · 10.8 KB
/
Copy patherror.rs
File metadata and controls
338 lines (303 loc) · 10.8 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
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::cell::RefCell;
use std::cmp::Ordering;
use std::fmt::Write;
use std::num::IntErrorKind;
use std::num::ParseIntError;
use itertools::Itertools;
use ordered_float::OrderedFloat;
use crate::Range;
use crate::parser::common::transform_span;
use crate::parser::input::Input;
use crate::parser::token::*;
use crate::span::pretty_print_error;
const MAX_DISPLAY_ERROR_COUNT: usize = 60;
/// This error type accumulates errors and their position when backtracking
/// through a parse tree. This take a deepest error at `alt` combinator.
#[derive(Clone, Debug)]
pub struct Error<'a> {
/// The span of the next token of the last valid one when encountering an error.
pub span: Range,
/// List of errors tried in various branches that consumed
/// the same (farthest) length of input.
pub errors: Vec<ErrorKind>,
/// The backtrace stack of the error.
pub contexts: Vec<(Range, &'static str)>,
/// The extra backtrace of error in optional branches.
pub backtrace: &'a Backtrace,
}
/// ErrorKind is the error type returned from parser.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
/// Error generated by `match_token` function
ExpectToken(TokenKind),
/// Error generated by `match_text` function
ExpectText(&'static str),
/// Plain text description of an error
Other(String),
}
impl ErrorKind {
pub fn other(message: impl Into<String>) -> Self {
Self::Other(message.into())
}
}
/// Record the farthest position in the input before encountering an error.
///
/// This is similar to the `Error`, but the information will not get lost
/// even the error is from a optional branch.
#[derive(Debug, Clone)]
pub struct Backtrace {
enabled: bool,
inner: RefCell<Option<BacktraceInner>>,
}
impl Backtrace {
pub fn new() -> Self {
Self {
enabled: true,
inner: RefCell::new(None),
}
}
pub fn disabled() -> Self {
Self {
enabled: false,
inner: RefCell::new(None),
}
}
pub fn clear(&self) {
self.inner.replace(None);
}
/// Restore the backtrace to a previous state.
///
/// This is useful when the furthest-reached error reporting strategy is undesirable,
/// particularly when the furthest path is reached but considered invalid.
pub fn restore(&self, other: Backtrace) {
*self.inner.borrow_mut() = other.inner.into_inner();
}
}
impl Default for Backtrace {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BacktraceInner {
/// The span of the next token of the last valid one when encountering an error.
span: Range,
/// List of errors tried in various branches that consumed
/// the same (farthest) length of input.
errors: Vec<ErrorKind>,
}
impl<'a> nom::error::ParseError<Input<'a>> for Error<'a> {
fn from_error_kind(i: Input<'a>, _: nom::error::ErrorKind) -> Self {
Error {
span: transform_span(&i[..1]).unwrap(),
errors: vec![],
contexts: vec![],
backtrace: i.backtrace,
}
}
fn append(_: Input<'a>, _: nom::error::ErrorKind, other: Self) -> Self {
other
}
fn from_char(_: Input<'a>, _: char) -> Self {
unreachable!()
}
fn or(mut self, mut other: Self) -> Self {
match self.span.start.cmp(&other.span.start) {
Ordering::Equal => {
self.errors.append(&mut other.errors);
self.contexts.clear();
self
}
Ordering::Less => other,
Ordering::Greater => self,
}
}
}
impl<'a> nom::error::ContextError<Input<'a>> for Error<'a> {
fn add_context(input: Input<'a>, ctx: &'static str, mut other: Self) -> Self {
other
.contexts
.push((transform_span(&input.tokens[..1]).unwrap(), ctx));
other
}
}
impl<'a> Error<'a> {
pub fn from_error_kind(input: Input<'a>, kind: ErrorKind) -> Self {
if input.backtrace.enabled {
let mut inner = input.backtrace.inner.borrow_mut();
if let Some(ref mut inner) = *inner {
match input.tokens[0].span.start.cmp(&inner.span.start) {
Ordering::Equal => {
inner.errors.push(kind.clone());
}
Ordering::Less => (),
Ordering::Greater => {
*inner = BacktraceInner {
span: transform_span(&input.tokens[..1]).unwrap(),
errors: vec![kind.clone()],
};
}
}
} else {
*inner = Some(BacktraceInner {
span: transform_span(&input.tokens[..1]).unwrap(),
errors: vec![kind.clone()],
})
};
}
Error {
span: transform_span(&input.tokens[..1]).unwrap(),
errors: vec![kind],
contexts: vec![],
backtrace: input.backtrace,
}
}
}
impl From<fast_float2::Error> for ErrorKind {
fn from(_: fast_float2::Error) -> Self {
ErrorKind::other("unable to parse float number")
}
}
impl From<ParseIntError> for ErrorKind {
fn from(err: ParseIntError) -> Self {
let msg = match err.kind() {
IntErrorKind::InvalidDigit => {
"unable to parse number because it contains invalid characters"
}
IntErrorKind::PosOverflow => "unable to parse number because it positively overflowed",
IntErrorKind::NegOverflow => "unable to parse number because it negatively overflowed",
_ => "unable to parse number",
};
ErrorKind::other(msg)
}
}
impl From<hex::FromHexError> for ErrorKind {
fn from(err: hex::FromHexError) -> Self {
let msg = match err {
hex::FromHexError::InvalidHexCharacter { .. } => {
"unable to parse hex literal because it contains invalid characters"
}
hex::FromHexError::OddLength => {
"unable to parse hex literal because it has an odd number of digits"
}
hex::FromHexError::InvalidStringLength => {
"unable to parse hex literal because it has an invalid length"
}
};
ErrorKind::other(msg)
}
}
/// Suggests corrections using intelligent syntax pattern matching
fn suggest_keyword_correction(
_span_text: &str,
source: &str,
_expected_tokens: &[String],
) -> Option<String> {
use crate::parser::error_suggestion::suggest_correction;
suggest_correction(source)
}
pub fn display_parser_error(error: Error, source: &str) -> String {
let inner = &*error.backtrace.inner.borrow();
let inner = match inner {
Some(inner) => inner,
None => return String::new(),
};
let span_text = &source[std::ops::Range::from(inner.span)];
let mut labels = vec![];
// Plain text error has the highest priority. Only display it if exists.
for (span, kind) in error
.errors
.iter()
.map(|err| (error.span, err))
.chain(inner.errors.iter().map(|err| (inner.span, err)))
{
if let ErrorKind::Other(msg) = kind {
labels = vec![(span, msg.clone())];
break;
}
}
// List all expected tokens in alternative branches.
if labels.is_empty() {
let mut expected_tokens = error
.errors
.iter()
.chain(&inner.errors)
.filter_map(|kind| match kind {
ErrorKind::ExpectToken(EOI) => None,
ErrorKind::ExpectToken(token) if token.is_keyword() => {
Some(format!("`{:?}`", token))
}
ErrorKind::ExpectToken(token) => Some(format!("<{:?}>", token)),
ErrorKind::ExpectText(text) => Some(format!("`{}`", text)),
_ => None,
})
.unique()
.collect::<Vec<_>>();
expected_tokens.sort_by_cached_key(|token| {
OrderedFloat::from(-strsim::jaro_winkler(
&token.to_lowercase(),
&span_text.to_lowercase(),
))
});
// Check for intelligent keyword suggestions first
let has_suggestion = suggest_keyword_correction(span_text, source, &expected_tokens);
let mut msg = if span_text.is_empty() {
"unexpected end of input".to_string()
} else if all_reserved_keywords()
.any(|keyword| keyword.to_lowercase() == span_text.to_lowercase())
&& has_suggestion.is_none()
{
format!("unexpected `{span_text}`. it's reserved keyword, you may avoid using it")
} else {
format!("unexpected `{span_text}`")
};
if let Some(suggestion) = has_suggestion {
write!(msg, ". {}", suggestion).unwrap();
labels = vec![(inner.span, msg)];
// Return early to skip context labels when we have intelligent suggestions
return pretty_print_error(source, labels);
} else {
let mut iter = expected_tokens.iter().enumerate().peekable();
while let Some((i, error)) = iter.next() {
if i == MAX_DISPLAY_ERROR_COUNT {
let more = expected_tokens
.len()
.saturating_sub(MAX_DISPLAY_ERROR_COUNT);
write!(msg, ", or {} more ...", more).unwrap();
break;
} else if i == 0 {
msg += ", expecting ";
} else if iter.peek().is_none() && i == 1 {
msg += " or ";
} else if iter.peek().is_none() {
msg += ", or ";
} else {
msg += ", ";
}
msg += error;
}
labels = vec![(inner.span, msg)];
}
}
// Append contexts as secondary labels.
labels.extend(
error
.contexts
.iter()
.map(|(span, msg)| (*span, format!("while parsing {}", msg))),
);
pretty_print_error(source, labels)
}