]> Witch of Git - jade-rose/blob - toolchain/src/js.rs
Add the wait state to the state machine
[jade-rose] / toolchain / src / js.rs
1 use super::{
2 inst::{Encode, Inst},
3 Error,
4 };
5 use js_sys::{self, Reflect};
6 use std::io::{self, Cursor, Write};
7 use wasm_bindgen::prelude::*;
8
9 #[wasm_bindgen]
10 pub fn assemble(code: &str) -> Result<Vec<u8>, JsValue> {
11 let mut result = Cursor::new(Vec::new());
12 for (i, line) in code.lines().enumerate() {
13 let line = line.trim();
14 if line.is_empty() {
15 continue;
16 }
17 let inst = Inst::parse(line).ok_or_else(|| Error::Io {
18 position: i,
19 error: io::Error::new(io::ErrorKind::InvalidInput, "Parse error"),
20 })?;
21 inst.encode(&mut result)
22 .expect("can always write into a vector");
23 }
24 Ok(result.into_inner())
25 }
26
27 #[wasm_bindgen]
28 pub fn disassemble(data: &[u8]) -> Result<String, JsValue> {
29 let mut input = Cursor::new(data);
30 let mut output = Cursor::new(Vec::new());
31 for inst in super::disassemble(&mut input)? {
32 writeln!(output, "{}", inst).unwrap();
33 }
34 // Can use _unchecked if we want because we control the display impl
35 Ok(String::from_utf8(output.into_inner()).unwrap())
36 }
37
38 impl From<Error> for JsValue {
39 fn from(e: Error) -> JsValue {
40 match e {
41 Error::Io { position, error } => {
42 let obj = js_sys::Error::new(&format!("{}", error)).into();
43 Reflect::set(&obj, &"position".into(), &(position as u32).into()).unwrap();
44 obj
45 }
46 }
47 }
48 }
49
50 #[cfg(test)]
51 mod test {
52 #[test]
53 fn test_assemble() {
54 // test this
55 }
56
57 #[test]
58 fn test_disassemble() {
59 assert!(disassemble(&[0xff]).is_err());
60 }
61 }