From 5fa862a0abe957ea2d40833ba987efcd65fb0b33 Mon Sep 17 00:00:00 2001 From: Laurens Miers Date: Sat, 31 May 2025 13:15:38 +0200 Subject: [PATCH] feat: add error framework Currently implemented: - SyntaxError - IO error --- src/error.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 32 +++++++++++++++++++++++--------- 2 files changed, 65 insertions(+), 9 deletions(-) create mode 100644 src/error.rs diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..8d1077a --- /dev/null +++ b/src/error.rs @@ -0,0 +1,42 @@ +use core::fmt; + +#[derive(Debug, Clone)] +pub struct SyntaxError { + line: u32, + location: String, + message: String, +} + +impl fmt::Display for SyntaxError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[line {} ] Error {}: {}",self.line, self.location, self.message) + } +} + +#[allow(dead_code)] +#[derive(Debug)] +pub enum RunError { + Io(std::io::Error), + Syntax(SyntaxError) +} + +impl fmt::Display for RunError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + RunError::Io(err) => write!(f, "IO Error: {}", err), + RunError::Syntax(err) => write!(f, "Syntax Error: {}", err), + } + } +} + +impl From for RunError { + fn from(err: std::io::Error) -> RunError { + RunError::Io(err) + } +} + +impl From for RunError { + fn from(err: SyntaxError) -> RunError { + RunError::Syntax(err) + } +} diff --git a/src/main.rs b/src/main.rs index 6f34f70..acb88fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,6 @@ +mod error; +use error::RunError; + use clap::Parser; use std::fs::File; use std::io::{self, BufRead, Write}; @@ -10,20 +13,27 @@ struct Args { script: Option, } -fn run(lines: io::Lines>) { - for line in lines { - println!("Line: {}", line.unwrap()); - } +fn run_line(line: String) -> Result<(), RunError> { + println!("Line: {}", line); + Ok(()) } -fn run_file(script: String) -> Result<(), io::Error> { - let file = File::open(script)?; - run(io::BufReader::new(file).lines()); +fn run(lines: io::Lines>) -> Result<(), RunError> { + for line in lines { + run_line(line.unwrap())?; + } Ok(()) } -fn run_prompt() -> Result<(), io::Error> { +fn run_file(script: String) -> Result<(), RunError> { + let file = File::open(script)?; + run(io::BufReader::new(file).lines())?; + + Ok(()) +} + +fn run_prompt() -> Result<(), RunError> { loop { print!("> "); io::stdout().flush()?; @@ -34,12 +44,16 @@ fn run_prompt() -> Result<(), io::Error> { break; } println!("input: '{}', {}", buffer, buffer.len()); + match run_line(buffer) { + Ok(()) => continue, + Err(error) => println!("{}", error), + }; } Ok(()) } -fn main() -> Result<(), Box> { +fn main() -> Result<(), RunError> { let args = Args::parse(); if let Some(script) = args.script {