Skip to content

Commit

Permalink
add emision of IO errors
Browse files Browse the repository at this point in the history
  • Loading branch information
danilopedraza committed Oct 15, 2024
1 parent 17a7303 commit fedbdd3
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 71 deletions.
7 changes: 2 additions & 5 deletions core-browser/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod builtin;

use builtin::{standard_env, STDIN, STDOUT};
use komodo::{error::error_msg, run::run};
use komodo::run::run;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
Expand All @@ -22,10 +22,7 @@ pub fn run_code(source: &str, stdin: &str) -> String {
let run_res = run(source, &mut env);
let mut res = STDOUT.lock().unwrap().clone();
if let Err(err) = run_res {
res.push_str(
&String::from_utf8(error_msg(&err).as_bytes("source.komodo", source))
.unwrap_or_default(),
);
res.push_str(&String::from_utf8(err.as_bytes("source.komodo", source)).unwrap_or_default());
}

res
Expand Down
126 changes: 66 additions & 60 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,70 @@ use crate::{
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
WithPosition(ErrorKind, Position),
IO(String),
}

impl Error {
pub fn with_position(err: ErrorKind, pos: Position) -> Self {
Self::WithPosition(err, pos)
}

pub fn as_bytes(&self, filename: &str, source: &str) -> Vec<u8> {
match self {
Self::WithPosition(err, pos) => {
let mut files = SimpleFiles::new();
let mut writer = Buffer::no_color();
let config = codespan_reporting::term::Config::default();

let file_id = files.add(filename, source);
let diagnostic = Diagnostic::error()
.with_message(error_msg(err))
.with_labels(vec![Label::primary(
file_id,
pos.start..(pos.start + pos.length),
)]);

let _ = term::emit(&mut writer, &config, &files, &diagnostic);

writer.into_inner()
}
Self::IO(err) => err.as_bytes().to_vec(),
}
}

pub fn emit(&self, filename: &str, source: &str) {
match self {
Self::WithPosition(err, pos) => {
let mut files = SimpleFiles::new();
let writer = StandardStream::stderr(term::termcolor::ColorChoice::Always);
let config = codespan_reporting::term::Config::default();

let file_id = files.add(filename, source);
let diagnostic = Diagnostic::error()
.with_message(error_msg(err))
.with_labels(vec![Label::primary(
file_id,
pos.start..(pos.start + pos.length),
)]);

let _ = term::emit(&mut writer.lock(), &config, &files, &diagnostic);
}
Self::IO(err) => eprintln!("{err}"),
}
}

pub fn msg(&self) -> String {
match self {
Self::IO(err) => err.to_string(),
Self::WithPosition(err, _) => error_msg(err),
}
}
}

impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
Self::IO(value.to_string())
}
}

#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -86,18 +144,13 @@ impl Position {
}
}

pub fn error_msg(err: &Error) -> ErrorMessage {
pub fn error_msg(err: &ErrorKind) -> String {
match err {
Error::WithPosition(err, pos) => {
let msg = match err {
ErrorKind::Lexer(err) => lexer_error_msg(err),
ErrorKind::Parser(err) => parser_error_msg(err),
ErrorKind::Weeder(err) => weeder_error_msg(err),
ErrorKind::Exec(err) => exec_error_msg(err),
ErrorKind::Import(err) => import_error_msg(err),
};
ErrorMessage(msg, *pos)
}
ErrorKind::Lexer(err) => lexer_error_msg(err),
ErrorKind::Parser(err) => parser_error_msg(err),
ErrorKind::Weeder(err) => weeder_error_msg(err),
ErrorKind::Exec(err) => exec_error_msg(err),
ErrorKind::Import(err) => import_error_msg(err),
}
}

Expand Down Expand Up @@ -377,49 +430,8 @@ fn symbol_not_found(module: &str, symbol: &str) -> String {
format!("`{symbol}` was not found in the `{module}` module")
}

#[derive(Debug, PartialEq, Eq)]
pub struct ErrorMessage(pub String, pub Position);

impl ErrorMessage {
pub fn as_bytes(&self, filename: &str, source: &str) -> Vec<u8> {
let mut files = SimpleFiles::new();
let mut writer = Buffer::no_color();
let config = codespan_reporting::term::Config::default();

let file_id = files.add(filename, source);
let diagnostic = Diagnostic::error()
.with_message(self.0.to_owned())
.with_labels(vec![Label::primary(
file_id,
self.1.start..(self.1.start + self.1.length),
)]);

let _ = term::emit(&mut writer, &config, &files, &diagnostic);

writer.into_inner()
}

pub fn emit(&self, filename: &str, source: &str) {
let mut files = SimpleFiles::new();
let writer = StandardStream::stderr(term::termcolor::ColorChoice::Always);
let config = codespan_reporting::term::Config::default();

let file_id = files.add(filename, source);
let diagnostic = Diagnostic::error()
.with_message(self.0.to_owned())
.with_labels(vec![Label::primary(
file_id,
self.1.start..(self.1.start + self.1.length),
)]);

let _ = term::emit(&mut writer.lock(), &config, &files, &diagnostic);
}
}

#[cfg(test)]
mod tests {
use crate::cst::tests::dummy_pos;

use super::*;

#[test]
Expand Down Expand Up @@ -474,14 +486,8 @@ mod tests {
#[test]
fn eof_reached() {
assert_eq!(
error_msg(&Error::WithPosition(
ParserError::EOFReached.into(),
dummy_pos()
)),
ErrorMessage(
"The end of the program was reached while reading an expression".into(),
dummy_pos()
),
error_msg(&ParserError::EOFReached.into()),
"The end of the program was reached while reading an expression".to_string(),
);
}

Expand Down
3 changes: 1 addition & 2 deletions core/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::fs;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};

use komodo::error::error_msg;
#[cfg(feature = "repl")]
use komodo::repl::{repl, MyCLI};
use komodo::run::run;
Expand Down Expand Up @@ -31,7 +30,7 @@ fn run_file(path: &str) -> std::io::Result<()> {
let mut env = standard_env(ExecContext::new(reference_path));
let res = run(&input, &mut env);
if let Err(err) = res {
error_msg(&err).emit(path, &input);
err.emit(path, &input);
Err(Error::new(ErrorKind::Other, ""))
} else {
Ok(())
Expand Down
5 changes: 2 additions & 3 deletions core/src/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
ast::ASTNode,
builtin::standard_env,
env::{Environment, ExecContext},
error::{error_msg, Error, ErrorKind, ErrorMessage},
error::{Error, ErrorKind},
lexer::Lexer,
object::Object,
parser::{Parser, ParserError},
Expand Down Expand Up @@ -68,8 +68,7 @@ impl Repl {
}
Err(err) => {
self.code.clear();
let ErrorMessage(msg, _) = error_msg(&err);
(msg, ReplResponse::Error)
(err.msg(), ReplResponse::Error)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ fn get_module_code(module: &ModuleAddress, env: &Environment) -> Result<String,
ModuleAddress::LocalPath { path } => reference_path.join(Path::new(&path)),
};

let source = fs::read_to_string(path).unwrap();
let source = fs::read_to_string(path)?;
Ok(source)
}

Expand Down

0 comments on commit fedbdd3

Please sign in to comment.