Procedural macros operate on Rust's token stream at compile time. Three kinds:

  • Derive macros: #[derive(Serialize)] — implement a trait for a type automatically.
  • Attribute macros: #[rtic::app], #[embassy_executor::task] — transform the item they're applied to.
  • Function-like macros: bitfield! { ... } — arbitrary syntax within the macro invocation.

A minimal derive macro:

// In a proc-macro crate
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(CanFrame)]
pub fn derive_can_frame(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    let name = &ast.ident;
    
    quote! {
        impl CanEncode for #name {
            fn encode(&self, buf: &mut [u8; 13]) {
                // generated encoding based on struct fields
            }
        }
    }.into()
}

The key libraries: syn (parse Rust token streams into AST), quote (generate Rust code from templates), and proc-macro2 (token stream manipulation).

RTIC itself is implemented as a proc macro — the entire task graph, resource sharing, and priority assignment is computed at compile time by transforming the #[rtic::app] module. Understanding proc macros means understanding how RTIC actually works.