macro_rules! declarative macros work as in Rust, matching token patterns and expanding repetitions. components! generates several component structs from one short description.
Procedural macros are an Oxeon extension. They’re compiled to WebAssembly and run sandboxed at compile time, so a macro sees only its input tokens and can’t do I/O. That makes them safe to use in mods from untrusted sources.
13_macros.ox
// Declarative macros work as in Rust. Procedural macros are compiled to
// WebAssembly and run sandboxed at compile time (syntax provisional).
macro_rules! square {
($x:expr) => {
$x * $x
};
}
macro_rules! components {
($($name:ident { $($field:ident : $ty:ty),* $(,)? })*) => {
$(
#[derive(Component, Reflect, Default)]
struct $name { $($field: $ty),* }
)*
};
}
components! {
Speed { value: f32 }
Armor { value: f32, max: f32 }
}
fn use_macros() {
let nine = square!(3);
let list = vec![1, 2, 3];
let msg = format!("{nine} {list:?}");
}
// A procedural macro lives in its own `macros` module and receives and
// returns token streams. It cannot do I/O: it only sees its input tokens.
mod macros {
use oxeon::macros::{TokenStream, quote};
#[proc_macro_derive(Describe)]
pub fn derive_describe(input: TokenStream) -> TokenStream {
let name = input.type_name();
quote! {
impl Describe for #name {
fn describe(&self) -> String {
stringify!(#name).to_string()
}
}
}
}
}