From b3e13dfb5a131ad4a6e4081c51564a3c48738b6c Mon Sep 17 00:00:00 2001 From: Teascade Date: Sun, 21 Jun 2020 01:37:56 +0300 Subject: [PATCH] Add better error messaging --- src/errors.rs | 19 ++++++++++++++++++- src/main.rs | 5 ++++- src/parser.rs | 9 +++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index df68aaf..2200479 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,4 +1,6 @@ use super::parser::Position; +use std::fmt; +use std::fmt::Display; use std::io; #[derive(Debug)] @@ -15,10 +17,25 @@ impl From for GenericError { #[derive(Debug)] pub enum CompilerError { Fatal, - PeekFailed, ExpectedToken(Position, char), ExpectedExpression(Position, Box), ExpectedIdent(Position), ExpectedStatement(Position), ExpectedPattern(Position), } + +impl Display for CompilerError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let text = match self { + CompilerError::Fatal => "Fatal error".to_string(), + CompilerError::ExpectedToken(pos, c) => format!("Expected token '{}' at {}", c, pos), + CompilerError::ExpectedExpression(pos, err) => { + format!("Expected expression at {}.\n {}", pos, err) + } + CompilerError::ExpectedIdent(pos) => format!("Expected ident at {}", pos), + CompilerError::ExpectedStatement(pos) => format!("Expected statement at {}", pos), + CompilerError::ExpectedPattern(pos) => format!("Expected pattern at {}", pos), + }; + write!(f, "{}", text) + } +} diff --git a/src/main.rs b/src/main.rs index 68cdd16..d545e4b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,5 +9,8 @@ use std::path::Path; fn main() { let path = Path::new("reid_src/test.reid"); let reid = Parser::from(open_file(&path).ok().unwrap()).parse(); - println!("Parsed: {:?}", reid); + if let Err(error) = reid { + eprintln!("Syntax error: {}", error); + std::process::exit(1); + } } diff --git a/src/parser.rs b/src/parser.rs index 2c45889..9d5b46b 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,5 +1,8 @@ use super::errors::CompilerError; +use std::fmt; +use std::fmt::Display; + type Ident = String; const ALLOWED_IDENT_CHARS: [char; 38] = [ @@ -325,3 +328,9 @@ impl Expect<'_> { #[derive(Debug, Copy, Clone)] pub struct Position(usize, usize); + +impl Display for Position { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "line {}, column {}", self.0, self.1) + } +}