From f81e1731b387aaf0a650a09882d75c6ff9746b09 Mon Sep 17 00:00:00 2001 From: PaddiM8 Date: Thu, 31 Dec 2020 01:03:16 +0100 Subject: [PATCH] Moved js_eval into Context --- kalk/src/parser.rs | 37 +++++++++++++++++++++---------------- kalk_web/index.js | 5 +++-- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/kalk/src/parser.rs b/kalk/src/parser.rs index e4751fc..f062757 100644 --- a/kalk/src/parser.rs +++ b/kalk/src/parser.rs @@ -18,7 +18,7 @@ pub struct Context { pos: usize, symbol_table: SymbolTable, angle_unit: String, - timeout: Option, + timeout: Option, /// This is true whenever the parser is currently parsing a unit declaration. /// It is necessary to keep track of this in order to know when to find (figure out) units that haven't been defined yet. /// Unit names are instead treated as variables. @@ -31,7 +31,9 @@ pub struct Context { contains_equal_sign: bool, } +#[wasm_bindgen] impl Context { + #[wasm_bindgen(constructor)] pub fn new() -> Self { let mut context = Self { tokens: Vec::new(), @@ -60,11 +62,23 @@ impl Context { /// Set the timeout in milliseconds. /// The calculation will stop after this amount of time has passed. #[cfg(not(target_arch = "wasm32"))] - pub fn set_timeout(mut self, timeout: Option) -> Self { + pub fn set_timeout(mut self, timeout: Option) -> Self { self.timeout = timeout; self } + + #[wasm_bindgen(js_name = evaluate)] + #[cfg(not(feature = "rug"))] + pub fn js_eval(&mut self, input: &str) -> Result, JsValue> { + let result = eval(self, input); + + match result { + Ok(Some(value)) => Ok(Some(value)), + Ok(None) => Ok(None), + Err(err) => Err(err.to_string().into()), + } + } } impl Default for Context { @@ -132,24 +146,15 @@ pub fn eval( &context.angle_unit, #[cfg(feature = "rug")] precision, - context.timeout, + if let Some(timeout) = context.timeout { + Some(timeout as u128) + } else { + None + }, ); interpreter.interpret(statements) } -#[wasm_bindgen(js_name = evaluate)] -#[cfg(not(feature = "rug"))] -pub fn js_eval(input: &str) -> Result, JsValue> { - let mut context = Context::new(); - let result = eval(&mut context, input); - - match result { - Ok(Some(value)) => Ok(Some(value)), - Ok(None) => Ok(None), - Err(err) => Err(err.to_string().into()), - } -} - /// Parse expressions/declarations and return a syntax tree. /// /// `None` will be returned if the last statement is a declaration. diff --git a/kalk_web/index.js b/kalk_web/index.js index 2f164ad..dbf0fa6 100644 --- a/kalk_web/index.js +++ b/kalk_web/index.js @@ -1,10 +1,11 @@ main(); async function main() { - const kalk = await import("kalk-rs"); + const kalk = await import("../kalk/pkg"); try { - console.log(kalk.evaluate("5^3").toScientificNotation().toString()); + const context = new kalk.Context(); + console.log(context.evaluate("sum(1, 5, n)").toScientificNotation().toString()); } catch(err) { console.log(err); }