use wasm_bindgen::prelude::*;
use ruchy::frontend::parser::Parser;
use ruchy::backend::transpiler::Transpiler;
#[wasm_bindgen]
pub struct RuchyCompiler {
transpiler: Transpiler,
}
#[wasm_bindgen]
impl RuchyCompiler {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
console_error_panic_hook::set_once();
Self {
transpiler: Transpiler::new(),
}
}
#[wasm_bindgen]
pub fn compile(&mut self, source: &str) -> Result<String, JsValue> {
let mut parser = Parser::new(source);
let ast = parser
.parse()
.map_err(|e| JsValue::from_str(&format!("Parse error: {}", e)))?;
let rust_code = self
.transpiler
.transpile(&ast)
.map_err(|e| JsValue::from_str(&format!("Transpile error: {}", e)))?;
Ok(rust_code.to_string())
}
#[wasm_bindgen]
pub fn validate(&self, source: &str) -> bool {
Parser::new(source).parse().is_ok()
}
#[wasm_bindgen(getter)]
pub fn version(&self) -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[wasm_bindgen]
pub fn parse_to_json(&self, source: &str) -> Result<String, JsValue> {
let mut parser = Parser::new(source);
let ast = parser
.parse()
.map_err(|e| JsValue::from_str(&format!("Parse error: {}", e)))?;
serde_json::to_string_pretty(&ast)
.map_err(|e| JsValue::from_str(&format!("JSON serialization error: {}", e)))
}
}
impl Default for RuchyCompiler {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn test_compile_simple_function() {
let mut compiler = RuchyCompiler::new();
let result = compiler.compile("fn add(a, b) { a + b }");
assert!(result.is_ok());
}
#[wasm_bindgen_test]
fn test_validate_valid_syntax() {
let mut compiler = RuchyCompiler::new();
assert!(compiler.validate("let x = 42"));
}
#[wasm_bindgen_test]
fn test_validate_invalid_syntax() {
let mut compiler = RuchyCompiler::new();
assert!(!compiler.validate("let x = "));
}
#[wasm_bindgen_test]
fn test_version() {
let mut compiler = RuchyCompiler::new();
assert!(!compiler.version().is_empty());
}
}