full-stack-skills/rust-skills

rust-macros

Design, name, implement, debug, test, and review Rust declarative and procedural macros, including macrorules matchers and repetition, hygiene, $crate paths, derive, attribute and function-like macros, proc-macro crate naming, syn parsing, quote generation,…

Ver código-fonte
Documento original do Skill

Renderizado do repositório de origem, preservando títulos, exemplos, código, tabelas, links e imagens.

Rust Macros

Use macros for syntax transformation or mechanical generation that functions, traits, generics, and build scripts cannot express cleanly. Keep the generated API smaller and more stable than the macro implementation.

Scope and Routing

Use this skill for macro_rules!, declarative DSLs, derive macros, attribute macros, function-like procedural macros, parsing, token generation, hygiene, diagnostics, and expansion tests.

Route ordinary generic design to rust-stable, crate layout and proc-macro companion crates to rust-workspace, feature and publishing policy to rust-cargo-build, compile-fail strategy to rust-testing, use of the third-party Lombok-like derives to rust-lombok-macros, and UniFFI export/derive usage plus generated foreign bindings to rust-uniffi-building.

Workflow

1. Prove a macro is the right boundary

Write representative invocations and expected expansions first. Prefer a function, trait, derive already provided by the ecosystem, or small handwritten implementation when it keeps diagnostics and navigation clearer. Define supported syntax, edition, MSRV, generated names, visibility, error cases, and semver surface.

2. Choose the smallest macro category

NeedMechanism
Repeat or match Rust token patternsmacro_rules!
Implement a trait for an annotated typederive procedural macro
Transform an annotated itemattribute procedural macro
Parse a custom token invocationfunction-like procedural macro

Use a dedicated proc-macro = true crate for procedural macros. Put shared runtime traits and types in a normal library crate so generated code does not depend on private proc-macro implementation details.

3. Name procedural-macro crates by their public surface

Treat the suffix as an API promise, not a compiler requirement:

Public macro surfacePreferred package suffixExamples
Only #[proc_macro_derive] entry points-derive or the established family spelling such as _deriveserde_derive
A broader suite, especially attribute or function-like macros, or mixed macro kinds-macrostokio-macros, actix-macros
Unclear or unspecified macro scopeAvoid singular -macro; choose a more descriptive name

Choose -derive when every public entry point is a derive macro. The crate may expose several closely related derives; the deciding factor is macro kind, not the exact count. Choose -macros when the crate exposes attribute macros, function-like macros, mixed macro kinds, or intentionally serves as the package family's general macro collection.

Do not publish both <name>-derive and <name>-macros by default. A single proc-macro crate can register any number of derive, attribute, and function-like macros. Prefer one of these layouts:

text
<name>            # public runtime API or facade; may re-export macros
<name>-derive     # derive-only proc-macro crate
text
<name>            # public runtime API or facade; may re-export macros
<name>-macros     # general proc-macro collection
<name>-macro-core # optional normal library for parsing and generation logic

Split -derive and -macros into separate published crates only when users can adopt them independently and the split materially reduces dependencies or compile time, separates release or compatibility policies, or isolates distinct ownership boundaries. Keep their exported macro names and responsibilities non-overlapping. Do not split merely by macro kind or for naming symmetry.

Before publishing, also:

  • Follow the separator already used by the crate family; Cargo package names may contain - or _, while Rust crate identifiers normalize hyphens to underscores.
  • Prefer a facade crate and feature-gated re-exports when most users should not depend on the implementation crate directly.
  • Treat a published crate rename as a migration with ecosystem and semver cost; choose the intended long-term scope early, but do not claim planned macro kinds before they exist.

4. Implement declarative macros hygienically

rust
#[macro_export]
macro_rules! string_list {
    ($($value:expr),* $(,)?) => {{
        let mut output = ::std::vec::Vec::new();
        $(output.push(::std::string::ToString::to_string(&$value));)*
        output
    }};
}
  • Put specific matcher arms before general arms.
  • Use the correct fragment specifier such as expr, ident, ty, pat, item, meta, path, or tt.
  • Support an optional trailing separator only when the public syntax intends it.
  • Use $crate for paths into the defining crate.
  • Avoid repeated evaluation, hidden moves, surprising control flow, and identifiers that collide with caller code.
  • Avoid quadratic TT munchers for large inputs; prefer repetitions or procedural parsing when token volume matters.

5. Parse procedural macros structurally

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

#[proc_macro_derive(Describe)]
pub fn derive_describe(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;
    quote! {
        impl Describe for #name {
            fn type_name() -> &'static str {
                stringify!(#name)
            }
        }
    }
    .into()
}
  • Parse with syn or a purpose-built parser rather than token strings.
  • Preserve spans and combine syn::Error values so users receive multiple useful diagnostics.
  • Generate paths that work after dependency renaming when the public contract requires it.
  • Preserve generics, lifetimes, const parameters, where clauses, attributes, and visibility.
  • Do not panic on invalid user input; emit compile errors at the relevant span.

6. Test the public expansion contract

Use several layers:

bash
cargo fmt --all --check
cargo check --workspace --all-targets --all-features
cargo test --workspace --all-targets --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo expand --package example-crate
  • Runtime and doctest cases prove successful generated behavior.
  • trybuild or equivalent UI tests lock accepted and rejected syntax plus diagnostics.
  • Expansion snapshots are review aids, not the only correctness gate.
  • Test generic, lifetime, visibility, renamed-dependency, no-std, feature, and edition combinations that the macro claims to support.

Nightly trace_macros! is an optional diagnostic tool, not a stable default.

Read Macro Reference for matcher and procedural-macro details. Read Execution Scenarios for representative requests.

Review Checklist

  • Could a function, trait, or derive replace the macro?
  • Is caller input evaluated exactly as documented?
  • Are $crate, spans, generics, and visibility handled correctly?
  • Can invalid input trigger a proc-macro panic?
  • Does generated unsafe code expose a documented safe contract?
  • Are compile-fail diagnostics tested without overspecifying unstable wording?
  • Does the generated public API create an intentional semver commitment?

Completion Criteria

  • Define supported syntax and expected expansion before implementation.
  • Use the smallest suitable macro category.
  • Preserve hygiene, spans, generics, visibility, and edition compatibility.
  • Cover successful expansions and rejected syntax with caller-shaped tests.
  • Pass formatting, check, tests, and Clippy on supported configurations.

Upstream Sources

Data Privacy

This skill does not collect, store, or transmit user data. Generated code may embed input literals, so review expansion output for secrets before publishing artifacts.

do mesmo repositório

Mais Skills

Todos os Skills
full-stack-skills
Comunidade

rust-api-design

Design Rust library APIs that follow the Rust API Guidelines — naming (C-CASE, C-CONV, C-GETTER), interop traits (C-COMMON-TRAITS, C-CONVERT, C-ITER, C-SERDE), predictability (C-INTUITIVE, C-CONST), flexibility (C-GENERIC, C-NEWTYPE, C-EXT), type safety (C-BOOL, C-NONZERO, C-WRAPPER, C-STR), dependability (C-PANIC, C-UNWRAP), debuggability (C-DEBUG), and future-proofing (C-SEALED, C-STRUCT-FIELD, C-NON-EXHAUSTIVE). Use when users design a public crate API, choose between generics/concrete/newtype, decide trait bounds, hide implementation, avoid breakage, or ask "what is idiomatic Rust API design"; hand semver and publish workflow to rust-semver, lint config to rust-style-clippy, and in-crate layout to rust-module-layout.

instalações
1
GitHub Stars
5
Atualizado
19 de set.
full-stack-skills
Comunidade

rust-by-example

Show Rust patterns through short compilable examples — type conversions (From/Into/TryFrom/as/Deref), flow control (if let/while let/match/loop), functions and closures (Fn/FnMut/FnOnce, captures), modules (mod/use/pub/super/self), generics and traits (bounds/associated types/trait objects), error handling (?/Result/thiserror/anyhow), attributes (derive/cfg/inline/allow), unsafe (raw pointers/unions/ABI), procedural macros (derive/attribute/function-like), and inline asm. Use when users ask "how do I write X in Rust", need a concrete pattern with copy-pasteable code, or are migrating from Java/Python/Go/C++ and want the Rust equivalent; hand architecture decisions to rust-api-design/rust-workspace, std API selection to rust-stdlib, and async runtime to rust-concurrency.

instalações
1
GitHub Stars
5
Atualizado
19 de set.
full-stack-skills
Comunidade

rust-cargo-build

Configure, operate, diagnose, and automate Cargo for Rust packages and workspaces. Cover manifests and targets, commands, dependency resolution and features, profiles, build scripts, configuration and environment variables, caches and build diagnostics, cross-compilation, registries, packaging, publishing, metadata, CI reproducibility, and stable-versus-nightly feature gates. Use for Cargo.toml, Cargo.lock, .cargo/config.toml, cargo build/check/run/tree/metadata/package/publish, resolver or feature problems, build output and performance, private registries, and beginner Cargo workflows. Route crate selection and supply-chain audits to rust-dependencies, workspace topology to rust-workspace, test design to rust-testing, documentation design to rust-documentation, lint policy to rust-style-clippy, and API compatibility decisions to rust-semver.

instalações
1
GitHub Stars
5
Atualizado
19 de set.
full-stack-skills
Comunidade

rust-cli

Design, implement, test, and release production Rust command-line applications, including command contracts, subcommands, configuration precedence, stdin/stdout/stderr, exit codes, file safety, daemon IPC, terminal handling, packaging, and process-level tests. Use when users ask for a Rust CLI, command parser, clap integration, Unix-style pipelines, daemon clients, PTY/TUI behavior, shell completion, or CLI release engineering.

instalações
1
GitHub Stars
5
Atualizado
19 de set.