Skip to content

Commit 95011db

Browse files
committed
Make compile error failable
1 parent 20dfbab commit 95011db

File tree

3 files changed

+14
-6
lines changed

3 files changed

+14
-6
lines changed

src/error.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use lalrpop_util::ParseError;
22
use std::fmt;
33
use unicode_width::UnicodeWidthStr;
4+
#[cfg(feature = "wasm")]
5+
use wasm_bindgen::JsValue;
46

57
#[derive(Debug)]
68
pub struct Error {
@@ -39,6 +41,13 @@ impl fmt::Display for Error {
3941

4042
impl std::error::Error for Error {}
4143

44+
#[cfg(feature = "wasm")]
45+
impl Into<JsValue> for Error {
46+
fn into(self) -> JsValue {
47+
JsValue::null() // FIXME: somehow convert the error
48+
}
49+
}
50+
4251
impl Error {
4352
fn new(file_name: &str, message: String, source: &str, pos: usize) -> Self {
4453
let mut line = 1;

src/lib.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,19 +129,18 @@ const JS_PRELUDE: &str = include_str!("prelude.js");
129129

130130
#[cfg(feature = "js")]
131131
#[cfg_attr(feature = "wasm", wasm_bindgen)]
132-
pub fn compile_to_js(source: &str) -> String {
132+
pub fn compile_to_js(source: &str) -> Result<String, crate::error::Error> {
133133
let parser = ProgramParser::new();
134134

135135
let program = parser
136136
.parse(&source)
137-
.map_err(|error| Error::from_parse_error("unknown", &source, error))
138-
.expect("Failed");
137+
.map_err(|error| Error::from_parse_error("unknown", &source, error))?;
139138

140139
let allocator = Allocator::default();
141140

142141
let converter = AstConverter::new(AstBuilder::new(&allocator));
143142
let program = converter.convert(program);
144143
let js = Codegen::new().build(&program);
145144

146-
format!("{JS_PRELUDE}{}", js.code)
145+
Ok(format!("{JS_PRELUDE}{}", js.code))
147146
}

src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ fn main() -> Result<()> {
2727

2828
path.set_extension("js");
2929

30-
fs::write(&path, compile_to_js(&source))?;
30+
fs::write(&path, compile_to_js(&source)?)?;
3131
}
3232
Commands::Run { path } => {
3333
let source = fs::read_to_string(&path)?;
34-
let source = compile_to_js(&source);
34+
let source = compile_to_js(&source)?;
3535

3636
Command::new("deno")
3737
.arg("eval")

0 commit comments

Comments
 (0)