macros_rust
Installation
SKILL.md
Contains Shell Commands
This skill contains shell command directives (!`command`) that may execute system commands. Review carefully before installing.
Rust Macros
Patterns from The Little Book of Rust Macros. Two families: declarative (macro_rules!, "macro-by-example") and procedural (compiler plugins that map TokenStream → TokenStream). Prefer declarative for simple syntactic code-gen; reach for procedural when you need to inspect/transform AST (especially #[derive]).
Golden rules
- A syntax extension must expand to a complete, valid AST node for its position (a full expression, item, etc.) — never a partial fragment like
1 +. - Metavariables captured as a non-
tt/ident/lifetimefragment become opaque AST nodes: you can only substitute them into the output, never re-match or inspect their contents afterward. macro_rules!is hygienic for local variables and labels — identifiers it introduces can't collide with or capture the caller's, and vice versa. Names that must resolve at the call site (types, fns, other macros) are not auto-hygienic; reference your own crate's items via$crate. Procedural macros are NOT hygienic by default:quote!stamps new identifiers withSpan::call_site(), so they can collide with or capture call-site names — useSpan::mixed_site()formacro_rules!-like hygiene (see Procedural macros).- Expansion is iterative: a macro may expand to another macro invocation, re-expanded until no invocations remain (bounded by the recursion limit).
Declarative macros (macro_rules!)
macro_rules! name {
(matcher) => { transcriber }; // rule 1
(other) => { ... }; // rule 2 — first matching rule wins, tried top-to-bottom
}