macro_rules! itsy_api {
($vis:vis $type_name:ident, $context_type:ty, {
$(
fn $name:tt(&mut $context:ident $(, $arg_name:ident: $($arg_type:tt)+)*) $(-> $ret_type:ident)? $code:block
)*
} ) => { ... };
}
Expand description
Creates an opaque type defining an API of Itsy-callable Rust functions.
The resolver, compiler and VM are generic over this type to ensure that the generated Itsy API-bindings match the given Rust API.
itsy_api!( [ <Visibility> ] <TypeName>, <ContextType>, { <Implementations> });
Currently supported parameter types are Rust primitives as well as String and &str.
Examples
The following example defines a few Rust functions and calls them from itsy code.
use itsy::{itsy_api, build_str, runtime::VM};
// A custom context accessible to the functions defined below.
struct MyContext {
// ...
}
// Define an API of Rust functions that are callable from the Itsy script.
itsy_api!(MyAPI, MyContext, {
fn intense_computation(&mut context, a: i16, b: i16) -> i16 {
a * b
}
fn print(&mut context, val: i16) {
println!("{}", val);
}
});
fn main() {
let mut context = MyContext { /* ... */ };
// Compile a short Itsy program and bind it to our MyAPI.
let program = build_str::<MyAPI>("
fn main() {
print(intense_computation(4, 5));
}
").unwrap();
// Create a new VM and run the program.
let mut vm = VM::new(&program);
vm.run(&mut context);
}
Output:
20