Add better error messaging

This commit is contained in:
Sofia 2020-06-21 01:37:56 +03:00
parent bea027d730
commit b3e13dfb5a
3 changed files with 31 additions and 2 deletions

View File

@ -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<io::Error> for GenericError {
#[derive(Debug)]
pub enum CompilerError {
Fatal,
PeekFailed,
ExpectedToken(Position, char),
ExpectedExpression(Position, Box<CompilerError>),
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)
}
}

View File

@ -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);
}
}

View File

@ -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)
}
}