Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Macros

Macros are compile-time functions that transform tokens into Rune code, letting host libraries add custom syntax or boilerplate-reducing helpers.

Rune supports three kinds of macros:

  • Function-like macros that expand to items (functions, type declarations, etc.).
  • Function-like macros that expand to expressions (statements, blocks, async blocks, etc.).
  • Attribute macros attached to a function.

Macros are currently defined in Rust native modules so that their code is already compiled and ready when a Rune script is compiled.

Script-defined macros (macro fn) are tracked in issue #27.

Because macros live in Rust, they can use Rune’s own parser and token utilities directly.

Writing a native macro

Below is the stringy_math! macro, which expands to an expression.

It uses Rune’s quote! macro, inspired by Rust’s quote crate. Unlike Rust’s quote!, Rune’s version takes a MacroContext so it can record source spans and resolve tokens cleanly:

use crate as rune;
use crate::ast;
use crate::compile;
use crate::macros::{quote, MacroContext, TokenStream};
use crate::parse::Parser;

/// Implementation of the `stringy_math!` macro.
#[rune::macro_]
pub fn stringy_math(
    cx: &mut MacroContext<'_, '_, '_>,
    stream: &TokenStream,
) -> compile::Result<TokenStream> {
    let mut parser = Parser::from_token_stream(stream, cx.input_span());

    let mut output = quote!(0);

    while !parser.is_eof()? {
        let op = parser.parse::<ast::Ident>()?;
        let arg = parser.parse::<ast::Expr>()?;

        output = match cx.resolve(op)? {
            "add" => quote!((#output) + #arg),
            "sub" => quote!((#output) - #arg),
            "div" => quote!((#output) / #arg),
            "mul" => quote!((#output) * #arg),
            _ => return Err(compile::Error::msg(op, "unsupported operation")),
        }
    }

    parser.eof()?;
    Ok(output.into_token_stream(cx)?)
}

Register a #[rune::macro_] function on a Module with Module::macro_meta (or register a plain closure with Module::macro_):

pub fn module() -> Result<rune::Module, rune::ContextError> {
    let mut module = rune::Module::new(["test", "macros"]);
    module.macro_meta(stringy_math)?;
    Ok(module)
}

With this module installed, we can now take stringy_math! for a spin.

use ::test::macros::stringy_math;

pub fn main() {
    stringy_math!(add 10 sub 2 div 3 mul 100)
}

Running this would return 200.