use std::collections::HashMap;
use d4rt_rs::FromValue;
use d4rt_rs::ToValue;
use d4rt_rs::{Context, Value};
fn main() {
let mut ctx = Context::new();
ctx.register_function("add", |_v, args, _named| {
let a =
i64::from_value(&args[0]).map_err(|e| d4rt_rs::InterpError::runtime(e.to_string()))?;
let b =
i64::from_value(&args[1]).map_err(|e| d4rt_rs::InterpError::runtime(e.to_string()))?;
Ok((a + b).to_value())
});
ctx.register_function("now_ts", |_v, _args, _named| {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
Ok(secs.to_value())
});
let logs: Vec<String> = Vec::new();
let sink = std::rc::Rc::new(std::cell::RefCell::new(logs));
let sink2 = sink.clone();
ctx.set_print_handler(move |s| sink2.borrow_mut().push(s.to_string()));
ctx.eval(
r#"
void main() {
print('add(20, 22) = ${add(20, 22)}');
print('now_ts() = ${now_ts()}');
var fibs = [for (var i = 0; i < 10; i++) i < 2 ? i : (i - 1) * 0 + i];
}
"#,
)
.unwrap();
println!("captured output: {:#?}", sink.borrow());
let result = ctx
.execute(
"int mul(int a, int b) => a * b;",
"mul",
vec![Value::Int(6), Value::Int(7)],
HashMap::new(),
)
.unwrap();
println!("execute('mul', [6, 7]) = {result:?}");
let mut a = Context::new();
let mut b = Context::new();
a.eval("var secret = 'context-a';").unwrap();
b.eval("var secret = 'context-b';").unwrap();
println!("a.secret = {:?}", a.eval_expression("secret").unwrap());
println!("b.secret = {:?}", b.eval_expression("secret").unwrap());
let mut repl = Context::new();
repl.eval("var counter = 0;").unwrap();
for _ in 0..3 {
repl.eval("void main() { counter++; }").unwrap();
}
println!(
"counter after 3 evals = {:?}",
repl.eval_expression("counter").unwrap()
);
}