pub struct HostFunction { /* private fields */ }Expand description
A function implemented by the host application, bound to an expression through
Bindings::function and called like a built-in.
Arguments and results cross the boundary as JSON: None stands for undefined, and a
function passed as an argument arrives as None; HostCall::function gives a handle to
call it (ADR 0011). An error returned by the function stops the evaluation; its position and
token are set to the call site when it has none.
use jlens_core::{Bindings, Expression, HostFunction};
use serde_json::json;
let tax = HostFunction::with_signature("<n-n?:n>", |args, _call| {
let amount = args[0].as_ref().and_then(|v| v.as_f64()).unwrap_or(0.0);
let rate = args[1].as_ref().and_then(|v| v.as_f64()).unwrap_or(0.25);
Ok(Some(json!(amount * rate)))
})
.unwrap();
let bindings = Bindings::new().function("tax", tax);
// `price.$tax()` takes its amount from the context, as the `-` in the signature allows.
let expr = Expression::compile("$tax(200) + price.$tax()").unwrap();
let result = expr.evaluate(Some(&json!({"price": 8})), &bindings).unwrap();
assert_eq!(result, Some(json!(52)));Implementations§
Source§impl HostFunction
impl HostFunction
Sourcepub fn new<F>(arity: usize, imp: F) -> Self
pub fn new<F>(arity: usize, imp: F) -> Self
A function without a signature, declaring arity parameters.
The arity plays the part of a JavaScript function’s length. Higher-order functions use
it to decide which arguments to pass ($map passes the index only to functions of two
parameters or more), and partial application ($f(?, 2)) to know how many parameters
there are. Arguments are passed as given, however many the call has: index them with
get.
Sourcepub fn with_signature<F>(signature: &str, imp: F) -> Result<Self>
pub fn with_signature<F>(signature: &str, imp: F) -> Result<Self>
A function with a signature such as <n-n?:n>, which arguments are
checked against before each call, as for built-in functions (T0410, T0412). The
function then receives at least one argument per parameter in the signature (None for
a missing optional one), and the context value where a parameter has the - modifier.
The arity is the number of parameters in the signature.
Fails with the signature’s syntax error (S0401, S0402) if it is invalid.