eval_context/
eval_context.rs

1extern crate alloc;
2use exp_rs::EvalContext;
3use libm::*;
4use std::println;
5
6// The Real type alias would be useful if we needed to work with both f32 and f64,
7// but since our functions are specialized via macros, we don't need it here.
8
9// Helper macro to wrap C math functions for f64
10#[cfg(feature = "f64")]
11macro_rules! c_fn {
12    ($name:ident) => {
13        |args: &[f64]| $name(args[0])
14    };
15}
16
17// Helper macro to wrap C math functions for f32
18#[cfg(feature = "f32")]
19macro_rules! c_fn {
20    ($name:ident) => {
21        |args: &[f32]| $name(args[0])
22    };
23}
24
25fn main() {
26    let mut ctx = EvalContext::new();
27
28    #[cfg(feature = "f64")]
29    {
30        ctx.register_native_function("sin", 1, c_fn!(sin));
31        ctx.register_native_function("cos", 1, c_fn!(cos));
32        ctx.register_native_function("tan", 1, c_fn!(tan));
33        ctx.register_native_function("exp", 1, c_fn!(exp));
34        ctx.register_native_function("log", 1, c_fn!(log));
35        ctx.register_native_function("sqrt", 1, c_fn!(sqrt));
36        ctx.register_expression_function("fancy", &["x"], "sin(x) + cos(x) + 42")
37            .unwrap();
38    }
39
40    #[cfg(feature = "f32")]
41    {
42        ctx.register_native_function("sin", 1, c_fn!(sinf));
43        ctx.register_native_function("cos", 1, c_fn!(cosf));
44        ctx.register_native_function("tan", 1, c_fn!(tanf));
45        ctx.register_native_function("exp", 1, c_fn!(expf));
46        ctx.register_native_function("log", 1, c_fn!(logf));
47        ctx.register_native_function("sqrt", 1, c_fn!(sqrtf));
48        ctx.register_expression_function("fancy", &["x"], "sin(x) + cos(x) + 42")
49            .unwrap();
50    }
51
52    let exprs = [
53        "sin(1.0)",
54        "cos(1.0)",
55        "sqrt(9)",
56        "fancy(0.5)",
57        "fancy(2.0) + sqrt(16)",
58    ];
59
60    for expr in &exprs {
61        match exp_rs::engine::interp(expr, Some(std::rc::Rc::new(ctx.clone()))) {
62            Ok(val) => {
63                println!("{} = {}", expr, val);
64                // For no_std, replace with your platform's output method
65            }
66            Err(e) => {
67                println!("Error evaluating {}: {}", expr, e);
68            }
69        }
70    }
71}