Improved error handling

This commit is contained in:
Erin 2022-07-21 13:17:56 +02:00 committed by ondra05
parent bbbfed7913
commit 107a81fa55
2 changed files with 27 additions and 6 deletions

View file

@ -20,7 +20,7 @@ impl<'a> Error<'a> {
Some(Token::Error) => { Some(Token::Error) => {
format!("Invalid token: {}", &src[e.span()].fg(Color::Yellow)) format!("Invalid token: {}", &src[e.span()].fg(Color::Yellow))
} }
Some(t) => format!("Unexpected token `{t:?}`"), Some(t) => format!("Unexpected token {}", t.fg(Color::Yellow)),
None => "Unexpected end of input".to_owned(), None => "Unexpected end of input".to_owned(),
}) })
.with_label( .with_label(
@ -29,7 +29,7 @@ impl<'a> Error<'a> {
"Expected: {}", "Expected: {}",
e.expected() e.expected()
.map(|exp| match exp { .map(|exp| match exp {
Some(expected) => format!("{expected:?}"), Some(expected) => format!("{expected}"),
None => "end of input".to_owned(), None => "end of input".to_owned(),
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
@ -39,8 +39,8 @@ impl<'a> Error<'a> {
), ),
SimpleReason::Unclosed { span, delimiter } => { SimpleReason::Unclosed { span, delimiter } => {
let msg = format!( let msg = format!(
"Unclosed delimiter: {:?}", "Unclosed delimiter: {}",
format!("{delimiter:?}").fg(Color::Yellow) delimiter.to_string().fg(Color::Yellow)
); );
report report
.with_message(&msg) .with_message(&msg)
@ -54,7 +54,7 @@ impl<'a> Error<'a> {
.with_message(format!( .with_message(format!(
"Must be closed before {}", "Must be closed before {}",
match e.found() { match e.found() {
Some(x) => format!("{x:?}"), Some(x) => x.to_string(),
None => "the end of input".to_owned(), None => "the end of input".to_owned(),
} }
)) ))

View file

@ -1,3 +1,5 @@
use std::fmt::Display;
use logos::{Lexer, Logos}; use logos::{Lexer, Logos};
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
@ -53,3 +55,22 @@ fn lex_slice<'a, const S: usize, const E: usize>(lexer: &mut Lexer<'a, Token<'a>
fn lex_float<'a>(lexer: &mut Lexer<'a, Token<'a>>) -> Option<OrderedFloat<f64>> { fn lex_float<'a>(lexer: &mut Lexer<'a, Token<'a>>) -> Option<OrderedFloat<f64>> {
lexer.slice().parse().ok() lexer.slice().parse().ok()
} }
impl<'a> Display for Token<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Token::LeftParen => write!(f, "("),
Token::RightParen => write!(f, ")"),
Token::LeftBracket => write!(f, "["),
Token::RightBracket => write!(f, "]"),
Token::LeftCurly => write!(f, "{{"),
Token::RightCurly => write!(f, "}}"),
Token::Quote => write!(f, "'"),
Token::String(s) => write!(f, "\"{s}\""),
Token::Number(n) => write!(f, "{n}"),
Token::Symbol(sym) => write!(f, "{sym}"),
Token::Keyword(kw) => write!(f, ":{kw}"),
Token::Error => write!(f, "Invalid token"),
}
}
}