monkey_wasm/
lib.rs

1mod utils;
2
3use crate::utils::set_panic_hook;
4use compiler::compiler::Compiler;
5use parser::parse as parser_pase;
6use parser::parse_ast_json_string;
7use wasm_bindgen::prelude::*;
8use wasm_bindgen::throw_str;
9
10// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
11// allocator.
12#[cfg(feature = "wee_alloc")]
13#[global_allocator]
14static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
15
16#[wasm_bindgen]
17pub fn parse(input: &str) -> String {
18    set_panic_hook();
19    match parse_ast_json_string(input) {
20        Ok(node) => node.to_string(),
21        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
22    }
23}
24
25#[wasm_bindgen]
26pub fn compile(input: &str) -> String {
27    set_panic_hook();
28
29    let program = match parser_pase(input) {
30        Ok(ast) => ast,
31        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
32    };
33    let mut compiler = Compiler::new();
34    match compiler.compile(&program) {
35        Ok(bytecode) => return bytecode.instructions.string(),
36        Err(e) => throw_str(format!("compile error: {}", e).as_str()),
37    }
38}