agentleFS
botirkhaltaevbotirkhaltaev/botir-skills/skills/rust-macros/SKILL.md

rust-macros

Skill4 starsChanged 3 months agoApache-2.0View on GitHub

Write declarative and procedural Rust macros. Use when creating macro_rules! macros, derive macros, attribute macros, or function-like proc macros. Covers metavariables, repetitions, TT munching, syn/quote/proc-macro2.

  • Installs packages

We split this skill into the rules it gives an agent

1 rule. 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 4 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use @ prefix for internal helper rules:

    line 98

“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Rust Macros

Comprehensive guide based on The Little Book of Rust Macros, the Rust Reference, and procedural macro workshop materials.

When to Use This Skill

  • Writing macro_rules! declarative macros
  • Creating derive macros (#[derive(MyTrait)])
  • Creating attribute macros (#[my_attr])
  • Creating function-like proc macros (my_macro!(...))
  • Debugging macro expansion issues
  • Understanding hygiene, metavariables, and fragment specifiers

Declarative Macros (macro_rules!)

Basic Syntax

macro_rules! say_hello {
    () => { println!("Hello!") };
    ($name:expr) => { println!("Hello, {}!", $name) };
}

say_hello!();           // "Hello!"
say_hello!("world");    // "Hello, world!"

Fragment Specifiers

SpecifierMatchesExample
exprExpression2 + 2, foo()
tyTypei32, Vec<String>
identIdentifierfoo, MyStruct
patPatternSome(x), _
pathPathstd::io::Error
ttToken treeany single token or (...) [...] {...} group
stmtStatementlet x = 1
blockBlock{ ... }
itemItemfn foo() {}
literalLiteral42, "hi"
lifetimeLifetime'a, 'static
visVisibilitypub, pub(crate)
metaAttribute contentderive(Debug)

Repetitions

macro_rules! vec_of {
    ($($element:expr),* $(,)?) => {
        {
            let mut v = Vec::new();
            $(v.push($element);)*
            v
        }
    };
}

let v = vec_of![1, 2, 3];

Repetition operators:

  • * — zero or more
  • + — one or more
  • ? — zero or one

Multiple Rules (Pattern Matching)

macro_rules! calculate {
    (add $a:expr, $b:expr) => { $a + $b };
    (mul $a:expr, $b:expr) => { $a * $b };
}

Rules are tried top-to-bottom; first match wins.

TT Muncher Pattern

Process tokens one at a time recursively:

macro_rules! count {
    () => { 0usize };
    ($head:tt $($tail:tt)*) => { 1usize + count!($($tail)*) };
}

assert_eq!(count!(a b c d), 4);

Internal Rules Pattern

Use @ prefix for internal helper rules:

macro_rules! my_macro {
    // Public entry
    ($($input:tt)*) => { my_macro!(@internal [] $($input)*) };
    // Internal accumulator
    (@internal [$($acc:tt)*]) => { /* done */ };
    (@internal [$($acc:tt)*] $head:tt $($tail:tt)*) => {
        my_macro!(@internal [$($acc)* $head] $($tail)*)
    };
}

Procedural Macros

Setup

Proc macros live in their own crate:

# Cargo.toml
[lib]
proc-macro = true

[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
proc-macro2 = "1"

Derive Macro

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(MyTrait)]
pub fn derive_my_trait(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    let expanded = quote! {
        impl MyTrait for #name {
            fn describe(&self) -> &'static str {
                stringify!(#name)
            }
        }
    };

    TokenStream::from(expanded)
}

Attribute Macro

#[proc_macro_attribute]
pub fn log_calls(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as syn::ItemFn);
    let name = &input.sig.ident;
    let block = &input.block;
    let sig = &input.sig;

    let expanded = quote! {
        #sig {
            println!("calling {}", stringify!(#name));
            #block
        }
    };

    TokenStream::from(expanded)
}

Function-like Proc Macro

#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
    let query = input.to_string();
    // Parse and validate SQL at compile time
    let expanded = quote! { /* ... */ };
    TokenStream::from(expanded)
}

Debugging Macros

# Expand all macros
cargo expand

# Expand a specific item
cargo expand my_module::MyStruct

# Install cargo-expand
cargo install cargo-expand

Reference Map

  • references/declarative-macros.md — macro_rules! patterns, hygiene, scoping
  • references/procedural-macros.md — syn/quote, derive/attribute/function-like
  • references/macro-patterns.md — TT muncher, push-down, callbacks, counting

Key References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.