unitdc-rs/crates/unitdc-web/src/lib.rs
eternal-flame-AD ecc5fb4223
license compliance
Signed-off-by: eternal-flame-AD <yume@yumechi.jp>
2024-07-26 15:54:26 -05:00

70 lines
1.9 KiB
Rust

mod utils;
use js_sys::Function;
use unitdc::interpreter::{Interpreter, Output};
use utils::set_panic_hook;
use wasm_bindgen::prelude::*;
static mut INTERPRETER: Option<Interpreter> = None;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: String);
}
/// Runs a string in the interpreter.
#[wasm_bindgen]
pub fn unitdc_input(input: String) -> Result<(), JsValue> {
unsafe {
if let Some(ref mut interpreter) = INTERPRETER {
interpreter.run_str(&input).map_err(|e| e.to_string())?;
}
}
Ok(())
}
/// Initializes the interpreter, taking a callback function to send output to.
#[wasm_bindgen]
pub fn unitdc_init(js_output: Function) {
unsafe {
INTERPRETER = Some(Interpreter::new(Box::new(move |output| match output {
Output::Quantity(q) => {
js_output
.call2(
&JsValue::NULL,
&JsValue::from("quantity"),
&serde_wasm_bindgen::to_value(&q).unwrap(),
)
.unwrap();
}
Output::QuantityList(q) => {
js_output
.call2(
&JsValue::NULL,
&JsValue::from("quantity_list"),
&serde_wasm_bindgen::to_value(&q).unwrap(),
)
.unwrap();
}
Output::Message(e) => {
js_output
.call2(&JsValue::NULL, &JsValue::from("message"), &JsValue::from(e))
.unwrap();
}
})));
INTERPRETER
.as_mut()
.unwrap()
.run_str(include_str!("../../../unitdc.rc"))
.unwrap();
}
}
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_log::init().expect("could not initialize logger");
set_panic_hook();
Ok(())
}