43 lines
1.1 KiB
Rust
43 lines
1.1 KiB
Rust
use boa_engine::{Context, JsResult, JsString, JsValue, NativeFunction, Source};
|
|
use std::str::FromStr;
|
|
|
|
fn main() -> JsResult<()> {
|
|
let js_code = r#"
|
|
let two = 1 + 1;
|
|
let definitely_not_four = two + "2";
|
|
|
|
println(definitely_not_four);
|
|
|
|
println(0.1 + 0.2);
|
|
|
|
println(Date.now(), 1, new Date()+'');
|
|
"#;
|
|
|
|
// Instantiate the execution context
|
|
let mut context = Context::default();
|
|
|
|
let println =
|
|
|_this: &JsValue, args: &[JsValue], _context: &mut Context| -> JsResult<JsValue> {
|
|
let mut vals = vec![];
|
|
args.iter()
|
|
.for_each(|arg| vals.push(arg.display().to_string()));
|
|
println!("{}", vals.join(" "));
|
|
Ok(JsValue::undefined())
|
|
};
|
|
|
|
_ = context.register_global_callable(
|
|
JsString::from_str("println").unwrap(),
|
|
0,
|
|
NativeFunction::from_copy_closure(println),
|
|
);
|
|
|
|
// Parse the source code
|
|
let result = context.eval(Source::from_bytes(js_code))?;
|
|
|
|
if !result.is_undefined() {
|
|
println!("{}", result.display());
|
|
}
|
|
|
|
Ok(())
|
|
}
|