Improved error handling

main
ondra05 2022-07-21 13:17:56 +02:00
parent 2b25c384c6
commit 7306465455
2 changed files with 27 additions and 6 deletions

View File

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

View File

@ -1,3 +1,5 @@
use std::fmt::Display;
use logos::{Lexer, Logos};
use ordered_float::OrderedFloat;
@ -24,7 +26,7 @@ pub enum Token<'a> {
#[token("'")]
Quote,
// Values
#[regex("\"(\\.|[^\"])*\"", (lex_slice::<1, 1>))]
String(&'a str),
@ -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>> {
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"),
}
}
}