pest/error.rs
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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! Types for different kinds of parsing failures.
use alloc::borrow::Cow;
use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use core::cmp;
use core::fmt;
use core::mem;
use crate::position::Position;
use crate::span::Span;
use crate::RuleType;
/// Parse-related error type.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub struct Error<R> {
/// Variant of the error
pub variant: ErrorVariant<R>,
/// Location within the input string
pub location: InputLocation,
/// Line/column within the input string
pub line_col: LineColLocation,
path: Option<String>,
line: String,
continued_line: Option<String>,
}
/// Different kinds of parsing errors.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub enum ErrorVariant<R> {
/// Generated parsing error with expected and unexpected `Rule`s
ParsingError {
/// Positive attempts
positives: Vec<R>,
/// Negative attempts
negatives: Vec<R>,
},
/// Custom error with a message
CustomError {
/// Short explanation
message: String,
},
}
/// Where an `Error` has occurred.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum InputLocation {
/// `Error` was created by `Error::new_from_pos`
Pos(usize),
/// `Error` was created by `Error::new_from_span`
Span((usize, usize)),
}
/// Line/column where an `Error` has occurred.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum LineColLocation {
/// Line/column pair if `Error` was created by `Error::new_from_pos`
Pos((usize, usize)),
/// Line/column pairs if `Error` was created by `Error::new_from_span`
Span((usize, usize), (usize, usize)),
}
impl From<Position<'_>> for LineColLocation {
fn from(value: Position<'_>) -> Self {
Self::Pos(value.line_col())
}
}
impl From<Span<'_>> for LineColLocation {
fn from(value: Span<'_>) -> Self {
let (start, end) = value.split();
Self::Span(start.line_col(), end.line_col())
}
}
impl<R: RuleType> Error<R> {
/// Creates `Error` from `ErrorVariant` and `Position`.
///
/// # Examples
///
/// ```
/// # use pest::error::{Error, ErrorVariant};
/// # use pest::Position;
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # open_paren,
/// # closed_paren
/// # }
/// # let input = "";
/// # let pos = Position::from_start(input);
/// let error = Error::new_from_pos(
/// ErrorVariant::ParsingError {
/// positives: vec![Rule::open_paren],
/// negatives: vec![Rule::closed_paren]
/// },
/// pos
/// );
///
/// println!("{}", error);
/// ```
pub fn new_from_pos(variant: ErrorVariant<R>, pos: Position<'_>) -> Error<R> {
let visualize_ws = pos.match_char('\n') || pos.match_char('\r');
let line_of = pos.line_of();
let line = if visualize_ws {
visualize_whitespace(line_of)
} else {
line_of.replace(&['\r', '\n'][..], "")
};
Error {
variant,
location: InputLocation::Pos(pos.pos()),
path: None,
line,
continued_line: None,
line_col: LineColLocation::Pos(pos.line_col()),
}
}
/// Creates `Error` from `ErrorVariant` and `Span`.
///
/// # Examples
///
/// ```
/// # use pest::error::{Error, ErrorVariant};
/// # use pest::{Position, Span};
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # open_paren,
/// # closed_paren
/// # }
/// # let input = "";
/// # let start = Position::from_start(input);
/// # let end = start.clone();
/// # let span = start.span(&end);
/// let error = Error::new_from_span(
/// ErrorVariant::ParsingError {
/// positives: vec![Rule::open_paren],
/// negatives: vec![Rule::closed_paren]
/// },
/// span
/// );
///
/// println!("{}", error);
/// ```
pub fn new_from_span(variant: ErrorVariant<R>, span: Span<'_>) -> Error<R> {
let end = span.end_pos();
let mut end_line_col = end.line_col();
// end position is after a \n, so we want to point to the visual lf symbol
if end_line_col.1 == 1 {
let mut visual_end = end;
visual_end.skip_back(1);
let lc = visual_end.line_col();
end_line_col = (lc.0, lc.1 + 1);
};
let mut line_iter = span.lines();
let sl = line_iter.next().unwrap_or("");
let mut chars = span.as_str().chars();
let visualize_ws = matches!(chars.next(), Some('\n') | Some('\r'))
|| matches!(chars.last(), Some('\n') | Some('\r'));
let start_line = if visualize_ws {
visualize_whitespace(sl)
} else {
sl.to_owned().replace(&['\r', '\n'][..], "")
};
let ll = line_iter.last();
let continued_line = if visualize_ws {
ll.map(str::to_owned)
} else {
ll.map(visualize_whitespace)
};
Error {
variant,
location: InputLocation::Span((span.start(), end.pos())),
path: None,
line: start_line,
continued_line,
line_col: LineColLocation::Span(span.start_pos().line_col(), end_line_col),
}
}
/// Returns `Error` variant with `path` which is shown when formatted with `Display`.
///
/// # Examples
///
/// ```
/// # use pest::error::{Error, ErrorVariant};
/// # use pest::Position;
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # open_paren,
/// # closed_paren
/// # }
/// # let input = "";
/// # let pos = Position::from_start(input);
/// Error::new_from_pos(
/// ErrorVariant::ParsingError {
/// positives: vec![Rule::open_paren],
/// negatives: vec![Rule::closed_paren]
/// },
/// pos
/// ).with_path("file.rs");
/// ```
pub fn with_path(mut self, path: &str) -> Error<R> {
self.path = Some(path.to_owned());
self
}
/// Returns the path set using [`Error::with_path()`].
///
/// # Examples
///
/// ```
/// # use pest::error::{Error, ErrorVariant};
/// # use pest::Position;
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # open_paren,
/// # closed_paren
/// # }
/// # let input = "";
/// # let pos = Position::from_start(input);
/// # let error = Error::new_from_pos(
/// # ErrorVariant::ParsingError {
/// # positives: vec![Rule::open_paren],
/// # negatives: vec![Rule::closed_paren]
/// # },
/// # pos);
/// let error = error.with_path("file.rs");
/// assert_eq!(Some("file.rs"), error.path());
/// ```
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
/// Returns the line that the error is on.
pub fn line(&self) -> &str {
self.line.as_str()
}
/// Renames all `Rule`s if this is a [`ParsingError`]. It does nothing when called on a
/// [`CustomError`].
///
/// Useful in order to rename verbose rules or have detailed per-`Rule` formatting.
///
/// [`ParsingError`]: enum.ErrorVariant.html#variant.ParsingError
/// [`CustomError`]: enum.ErrorVariant.html#variant.CustomError
///
/// # Examples
///
/// ```
/// # use pest::error::{Error, ErrorVariant};
/// # use pest::Position;
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # open_paren,
/// # closed_paren
/// # }
/// # let input = "";
/// # let pos = Position::from_start(input);
/// Error::new_from_pos(
/// ErrorVariant::ParsingError {
/// positives: vec![Rule::open_paren],
/// negatives: vec![Rule::closed_paren]
/// },
/// pos
/// ).renamed_rules(|rule| {
/// match *rule {
/// Rule::open_paren => "(".to_owned(),
/// Rule::closed_paren => "closed paren".to_owned()
/// }
/// });
/// ```
pub fn renamed_rules<F>(mut self, f: F) -> Error<R>
where
F: FnMut(&R) -> String,
{
let variant = match self.variant {
ErrorVariant::ParsingError {
positives,
negatives,
} => {
let message = Error::parsing_error_message(&positives, &negatives, f);
ErrorVariant::CustomError { message }
}
variant => variant,
};
self.variant = variant;
self
}
fn start(&self) -> (usize, usize) {
match self.line_col {
LineColLocation::Pos(line_col) => line_col,
LineColLocation::Span(start_line_col, _) => start_line_col,
}
}
fn spacing(&self) -> String {
let line = match self.line_col {
LineColLocation::Pos((line, _)) => line,
LineColLocation::Span((start_line, _), (end_line, _)) => cmp::max(start_line, end_line),
};
let line_str_len = format!("{}", line).len();
let mut spacing = String::new();
for _ in 0..line_str_len {
spacing.push(' ');
}
spacing
}
fn underline(&self) -> String {
let mut underline = String::new();
let mut start = self.start().1;
let end = match self.line_col {
LineColLocation::Span(_, (_, mut end)) => {
let inverted_cols = start > end;
if inverted_cols {
mem::swap(&mut start, &mut end);
start -= 1;
end += 1;
}
Some(end)
}
_ => None,
};
let offset = start - 1;
let line_chars = self.line.chars();
for c in line_chars.take(offset) {
match c {
'\t' => underline.push('\t'),
_ => underline.push(' '),
}
}
if let Some(end) = end {
underline.push('^');
if end - start > 1 {
for _ in 2..(end - start) {
underline.push('-');
}
underline.push('^');
}
} else {
underline.push_str("^---")
}
underline
}
fn message(&self) -> String {
self.variant.message().to_string()
}
fn parsing_error_message<F>(positives: &[R], negatives: &[R], mut f: F) -> String
where
F: FnMut(&R) -> String,
{
match (negatives.is_empty(), positives.is_empty()) {
(false, false) => format!(
"unexpected {}; expected {}",
Error::enumerate(negatives, &mut f),
Error::enumerate(positives, &mut f)
),
(false, true) => format!("unexpected {}", Error::enumerate(negatives, &mut f)),
(true, false) => format!("expected {}", Error::enumerate(positives, &mut f)),
(true, true) => "unknown parsing error".to_owned(),
}
}
fn enumerate<F>(rules: &[R], f: &mut F) -> String
where
F: FnMut(&R) -> String,
{
match rules.len() {
1 => f(&rules[0]),
2 => format!("{} or {}", f(&rules[0]), f(&rules[1])),
l => {
let non_separated = f(&rules[l - 1]);
let separated = rules
.iter()
.take(l - 1)
.map(f)
.collect::<Vec<_>>()
.join(", ");
format!("{}, or {}", separated, non_separated)
}
}
}
pub(crate) fn format(&self) -> String {
let spacing = self.spacing();
let path = self
.path
.as_ref()
.map(|path| format!("{}:", path))
.unwrap_or_default();
let pair = (self.line_col.clone(), &self.continued_line);
if let (LineColLocation::Span(_, end), Some(ref continued_line)) = pair {
let has_line_gap = end.0 - self.start().0 > 1;
if has_line_gap {
format!(
"{s }--> {p}{ls}:{c}\n\
{s } |\n\
{ls:w$} | {line}\n\
{s } | ...\n\
{le:w$} | {continued_line}\n\
{s } | {underline}\n\
{s } |\n\
{s } = {message}",
s = spacing,
w = spacing.len(),
p = path,
ls = self.start().0,
le = end.0,
c = self.start().1,
line = self.line,
continued_line = continued_line,
underline = self.underline(),
message = self.message()
)
} else {
format!(
"{s }--> {p}{ls}:{c}\n\
{s } |\n\
{ls:w$} | {line}\n\
{le:w$} | {continued_line}\n\
{s } | {underline}\n\
{s } |\n\
{s } = {message}",
s = spacing,
w = spacing.len(),
p = path,
ls = self.start().0,
le = end.0,
c = self.start().1,
line = self.line,
continued_line = continued_line,
underline = self.underline(),
message = self.message()
)
}
} else {
format!(
"{s}--> {p}{l}:{c}\n\
{s} |\n\
{l} | {line}\n\
{s} | {underline}\n\
{s} |\n\
{s} = {message}",
s = spacing,
p = path,
l = self.start().0,
c = self.start().1,
line = self.line,
underline = self.underline(),
message = self.message()
)
}
}
}
impl<R: RuleType> ErrorVariant<R> {
///
/// Returns the error message for [`ErrorVariant`]
///
/// If [`ErrorVariant`] is [`CustomError`], it returns a
/// [`Cow::Borrowed`] reference to [`message`]. If [`ErrorVariant`] is [`ParsingError`], a
/// [`Cow::Owned`] containing "expected [ErrorVariant::ParsingError::positives] [ErrorVariant::ParsingError::negatives]" is returned.
///
/// [`ErrorVariant`]: enum.ErrorVariant.html
/// [`CustomError`]: enum.ErrorVariant.html#variant.CustomError
/// [`ParsingError`]: enum.ErrorVariant.html#variant.ParsingError
/// [`Cow::Owned`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html#variant.Owned
/// [`Cow::Borrowed`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html#variant.Borrowed
/// [`message`]: enum.ErrorVariant.html#variant.CustomError.field.message
/// # Examples
///
/// ```
/// # use pest::error::ErrorVariant;
/// let variant = ErrorVariant::<()>::CustomError {
/// message: String::from("unexpected error")
/// };
///
/// println!("{}", variant.message());
pub fn message(&self) -> Cow<'_, str> {
match self {
ErrorVariant::ParsingError {
ref positives,
ref negatives,
} => Cow::Owned(Error::parsing_error_message(positives, negatives, |r| {
format!("{:?}", r)
})),
ErrorVariant::CustomError { ref message } => Cow::Borrowed(message),
}
}
}
impl<R: RuleType> fmt::Display for Error<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.format())
}
}
impl<R: RuleType> fmt::Display for ErrorVariant<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrorVariant::ParsingError { .. } => write!(f, "parsing error: {}", self.message()),
ErrorVariant::CustomError { .. } => write!(f, "{}", self.message()),
}
}
}
fn visualize_whitespace(input: &str) -> String {
input.to_owned().replace('\r', "␍").replace('\n', "␊")
}
#[cfg(test)]
mod tests {
use super::super::position;
use super::*;
use alloc::vec;
#[test]
fn display_parsing_error_mixed() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![1, 2, 3],
negatives: vec![4, 5, 6],
},
pos,
);
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = unexpected 4, 5, or 6; expected 1, 2, or 3"
]
.join("\n")
);
}
#[test]
fn display_parsing_error_positives() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![1, 2],
negatives: vec![],
},
pos,
);
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = expected 1 or 2"
]
.join("\n")
);
}
#[test]
fn display_parsing_error_negatives() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![],
negatives: vec![4, 5, 6],
},
pos,
);
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = unexpected 4, 5, or 6"
]
.join("\n")
);
}
#[test]
fn display_parsing_error_unknown() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![],
negatives: vec![],
},
pos,
);
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = unknown parsing error"
]
.join("\n")
);
}
#[test]
fn display_custom_pos() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::CustomError {
message: "error: big one".to_owned(),
},
pos,
);
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = error: big one"
]
.join("\n")
);
}
#[test]
fn display_custom_span_two_lines() {
let input = "ab\ncd\nefgh";
let start = position::Position::new(input, 4).unwrap();
let end = position::Position::new(input, 9).unwrap();
let error: Error<u32> = Error::new_from_span(
ErrorVariant::CustomError {
message: "error: big one".to_owned(),
},
start.span(&end),
);
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
"3 | efgh",
" | ^^",
" |",
" = error: big one"
]
.join("\n")
);
}
#[test]
fn display_custom_span_three_lines() {
let input = "ab\ncd\nefgh";
let start = position::Position::new(input, 1).unwrap();
let end = position::Position::new(input, 9).unwrap();
let error: Error<u32> = Error::new_from_span(
ErrorVariant::CustomError {
message: "error: big one".to_owned(),
},
start.span(&end),
);
assert_eq!(
format!("{}", error),
[
" --> 1:2",
" |",
"1 | ab",
" | ...",
"3 | efgh",
" | ^^",
" |",
" = error: big one"
]
.join("\n")
);
}
#[test]
fn display_custom_span_two_lines_inverted_cols() {
let input = "abcdef\ngh";
let start = position::Position::new(input, 5).unwrap();
let end = position::Position::new(input, 8).unwrap();
let error: Error<u32> = Error::new_from_span(
ErrorVariant::CustomError {
message: "error: big one".to_owned(),
},
start.span(&end),
);
assert_eq!(
format!("{}", error),
[
" --> 1:6",
" |",
"1 | abcdef",
"2 | gh",
" | ^----^",
" |",
" = error: big one"
]
.join("\n")
);
}
#[test]
fn display_custom_span_end_after_newline() {
let input = "abcdef\n";
let start = position::Position::new(input, 0).unwrap();
let end = position::Position::new(input, 7).unwrap();
assert!(start.at_start());
assert!(end.at_end());
let error: Error<u32> = Error::new_from_span(
ErrorVariant::CustomError {
message: "error: big one".to_owned(),
},
start.span(&end),
);
assert_eq!(
format!("{}", error),
[
" --> 1:1",
" |",
"1 | abcdef␊",
" | ^-----^",
" |",
" = error: big one"
]
.join("\n")
);
}
#[test]
fn display_custom_span_empty() {
let input = "";
let start = position::Position::new(input, 0).unwrap();
let end = position::Position::new(input, 0).unwrap();
assert!(start.at_start());
assert!(end.at_end());
let error: Error<u32> = Error::new_from_span(
ErrorVariant::CustomError {
message: "error: empty".to_owned(),
},
start.span(&end),
);
assert_eq!(
format!("{}", error),
[
" --> 1:1",
" |",
"1 | ",
" | ^",
" |",
" = error: empty"
]
.join("\n")
);
}
#[test]
fn mapped_parsing_error() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![1, 2, 3],
negatives: vec![4, 5, 6],
},
pos,
)
.renamed_rules(|n| format!("{}", n + 1));
assert_eq!(
format!("{}", error),
[
" --> 2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = unexpected 5, 6, or 7; expected 2, 3, or 4"
]
.join("\n")
);
}
#[test]
fn error_with_path() {
let input = "ab\ncd\nef";
let pos = position::Position::new(input, 4).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![1, 2, 3],
negatives: vec![4, 5, 6],
},
pos,
)
.with_path("file.rs");
assert_eq!(
format!("{}", error),
[
" --> file.rs:2:2",
" |",
"2 | cd",
" | ^---",
" |",
" = unexpected 4, 5, or 6; expected 1, 2, or 3"
]
.join("\n")
);
}
#[test]
fn underline_with_tabs() {
let input = "a\txbc";
let pos = position::Position::new(input, 2).unwrap();
let error: Error<u32> = Error::new_from_pos(
ErrorVariant::ParsingError {
positives: vec![1, 2, 3],
negatives: vec![4, 5, 6],
},
pos,
)
.with_path("file.rs");
assert_eq!(
format!("{}", error),
[
" --> file.rs:1:3",
" |",
"1 | a xbc",
" | ^---",
" |",
" = unexpected 4, 5, or 6; expected 1, 2, or 3"
]
.join("\n")
);
}
#[test]
fn pos_to_lcl_conversion() {
let input = "input";
let pos = Position::new(input, 2).unwrap();
assert_eq!(LineColLocation::Pos(pos.line_col()), pos.into());
}
#[test]
fn span_to_lcl_conversion() {
let input = "input";
let span = Span::new(input, 2, 4).unwrap();
let (start, end) = span.split();
assert_eq!(
LineColLocation::Span(start.line_col(), end.line_col()),
span.into()
);
}
}