Last active
February 13, 2022 08:37
-
-
Save NickAger/e8ab13f6995f7f476191ce228f57a5ab to your computer and use it in GitHub Desktop.
Modification of https://github.com/fivemoreminix/rsc and https://gist.github.com/NickAger/d58f3120388fe899cad1022a01c162b9 - now works.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rsc::{tokenize, parse, Interpreter, TokenizeError, ParseError, InterpretError}; | |
// error handling based on: | |
// * https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html | |
#[derive(Debug)] | |
struct EquationError(pub String); | |
impl<'input_string> From<TokenizeError<'input_string>> for EquationError { | |
fn from(err: TokenizeError<'input_string>) -> EquationError { | |
EquationError(format!("Tokenize Error: {:?}", err)) | |
} | |
} | |
impl<'input_string> From<ParseError<'input_string, f64>> for EquationError { | |
fn from(err: ParseError<'input_string, f64>) -> EquationError { | |
EquationError(format!("Parse Error: {:?}", err)) | |
} | |
} | |
impl<'input_string> From<InterpretError<'input_string>> for EquationError { | |
fn from(err: InterpretError<'input_string>) -> EquationError { | |
EquationError(format!("Interpret Error: {:?}", err)) | |
} | |
} | |
type EvaluateResult = std::result::Result<f64, EquationError>; | |
fn evaluate<'input>(input: &str, interpreter: &mut Interpreter<f64>) -> EvaluateResult { | |
let tokens = tokenize(&input)?; | |
let expr = parse(&tokens)?; | |
let result = interpreter.eval(&expr)?; | |
return Ok(result); | |
} | |
fn pr(x: f64) { | |
println!("{}", x); | |
} | |
fn main() -> Result<(), EquationError> { | |
// Constructs an f64 interpreter with included variables | |
println!("Starting"); | |
let mut interpreter = Interpreter::default(); | |
let result1 = evaluate("5^2", &mut interpreter)?; | |
pr(result1); // prints "25" | |
let result2 = evaluate("x = 3", &mut interpreter)?; | |
pr(result2); // prints "3" | |
let result3 = evaluate("x(3) + 1", &mut interpreter)?; | |
pr(result3); // prints "10" | |
return Ok(()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment