From 107a81fa556f0bf0e1ea32c934c951f60e975a26 Mon Sep 17 00:00:00 2001 From: Erin Date: Thu, 21 Jul 2022 13:17:56 +0200 Subject: [PATCH] Improved error handling --- src/error.rs | 10 +++++----- src/lexer.rs | 23 ++++++++++++++++++++++- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/error.rs b/src/error.rs index ce0ba7a..270f3e6 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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::>() @@ -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(), } )) diff --git a/src/lexer.rs b/src/lexer.rs index 2203b2b..9dee259 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -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> { 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"), + } + } +}