feat: add error framework
All checks were successful
ci/woodpecker/push/build Pipeline was successful

Currently implemented:
- SyntaxError
- IO error
This commit is contained in:
Laurens Miers 2025-05-31 13:15:38 +02:00
parent 6f27e7f3fc
commit 5fa862a0ab
2 changed files with 65 additions and 9 deletions

42
src/error.rs Normal file
View file

@ -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<std::io::Error> for RunError {
fn from(err: std::io::Error) -> RunError {
RunError::Io(err)
}
}
impl From<SyntaxError> for RunError {
fn from(err: SyntaxError) -> RunError {
RunError::Syntax(err)
}
}

View file

@ -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<String>,
}
fn run(lines: io::Lines<io::BufReader<File>>) {
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<io::BufReader<File>>) -> 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<dyn std::error::Error>> {
fn main() -> Result<(), RunError> {
let args = Args::parse();
if let Some(script) = args.script {