Xpersona
M

Macros Code Review

CLAWHUB · Unverified

Reviews Rust macro code for hygiene issues, fragment misuse, compile-time impact, and procedural macro patterns. Use when reviewing macro_rules! definitions,... Skill: Macros Code Review Owner: anderskev Summary: Reviews Rust macro code for hygiene issues, fragment misuse, compile-time impact, and procedural macro patterns. Use when reviewing macro_rules! definitions,... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-06-01T02:26:02.772Z | auto - Updated Gate 4 instructions to reference the $1 skill rather than "beagle-rust:review-verification-protocol". - No logic or chec

62
Rank
84
Safety
1.1k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:macros-code-review
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-macros-code-review/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

114,935 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: macros-code-review
description: "Reviews Rust macro code for hygiene issues, fragment misuse, compile-time impact, and procedural macro patterns. Use when reviewing macro_rules! definitions, procedural macros, derive macros, or attribute macros."
---

# Macros Code Review

## Review Workflow

1. **Check `Cargo.toml`** -- Note Rust edition (2024 reserves `gen` keyword, affecting macro output), proc-macro crate dependencies (`syn`, `quote`, `proc-macro2`), and feature flags (e.g., `syn` with minimal features)
2. **Check macro type** -- Determine if reviewing declarative (`macro_rules!`), function-like proc macro, attribute macro, or derive macro
3. **Check if a macro is needed** -- If the transformation is type-based, generics are better. Macros are for structural/repetitive code generation that generics cannot express
4. **Scan macro definitions** -- Read full macro bodies including all match arms, not just the invocation site
5. **Check each category** -- Work through the checklist below, loading references as needed
6. **Gates** -- Complete **Gates** below before reporting; do not substitute informal “I verified.”

## Gates (before reporting findings)

Complete in order. **Do not emit findings** until **Gate 4** passes for each issue.

**Gate 1 — Crate context (on disk)**  
**PASS when:** You opened the reviewed crate’s `Cargo.toml` (workspace member path if applicable) and recorded Rust `edition`, whether the crate is `proc-macro = true`, and relevant proc-macro dependencies or `syn` / `quote` feature flags.  
**Blocks rationalization:** Edition 2024 findings (`gen`, `unsafe extern`, generated `unsafe` bodies) and `syn` “full” vs minimal flags require this — do not flag edition-specific macro output without matching `edition` from the file.

**Gate 2 — Macro definitions read**  
**PASS when:** For every macro you critique, you read the full definition (all `macro_rules!` arms, or the proc-macro entry plus helpers you rely on), not only call sites or partial expansions.  
**Artifact:** At least one path per macro to the defining `.rs` file(s) you used.

**Gate 3 — Per-finding evidence**  
**PASS when:** Each planned issue has `[FILE:LINE]` from the current tree for the macro definition, attribute/derive site, or generated code location you are discussing (not from memory, docs-only, or another branch).

**Gate 4 — Pre-report protocol**  
**PASS when:** You loaded and applied the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill, including **Macro-Specific Verification** for hygiene, fragment type, and proc-macro performance claims. **Then** add findings.

## Output Format

Report findings as:

```text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
```

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| Fragment types, repetition, hygiene boundaries (vars vs types), `$crate` paths, TT-muncher pattern + recursion

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "macros-code-review",
  "version": "1.0.3",
  "publishedAt": 1780280762772
}

references/declarative-macros.md

# Declarative Macros

## Fragment Types

Each fragment type constrains what tokens the matcher will accept. Using the wrong type causes confusing parse errors or overly greedy matching.

| Fragment | Matches | Use When |
|----------|---------|----------|
| `:ident` | Identifier (`foo`, `my_var`) | Naming generated items, variables, or modules |
| `:expr` | Any expression (`x + 1`, `foo()`) | Values to compute or pass to functions |
| `:ty` | Type (`u32`, `Vec<String>`) | Type parameters for generics or trait impls |
| `:tt` | Single token tree (`foo`, `(a + b)`) | Catch-all when other fragments are too restrictive |
| `:path` | Path (`std::io::Error`, `crate::Foo`) | Importing or referencing items |
| `:pat` | Pattern (`Some(x)`, `1..=5`) | Match arms, `let` bindings |
| `:stmt` | Statement (`let x = 1;`) | Injecting statements into generated blocks |
| `:item` | Item (`fn`, `struct`, `impl`) | Generating top-level definitions |
| `:block` | Block (`{ ... }`) | Function bodies, closures |
| `:meta` | Attribute content (`derive(Debug)`) | Forwarding attributes |
| `:literal` | Literal value (`42`, `"hello"`) | Compile-time constants |
| `:vis` | Visibility (`pub`, `pub(crate)`, empty) | Controlling generated item visibility |
| `:lifetime` | Lifetime (`'a`, `'static`) | Lifetime-generic generated code |

### Common Fragment Mistakes

**`:expr` can be broader than intended** -- It matches full expressions, which can make some macro arms too permissive. Prefer narrower fragments like `:tt` when you need stricter syntax boundaries.

**`:ty` cannot be followed by `>`** -- After matching a type, the parser cannot distinguish `>` as closing a generic vs part of an expression. Structure matchers to avoid this ambiguity.

**`:pat` changed in edition 2021+** -- Now matches `|` patterns (e.g., `A | B`). Use `:pat_param` if you need the pre-2021 behavior that stops at `|`.

## Repetition Syntax

```rust
// Zero or more, comma-separated
$($item:expr),*

// One or more, semicolon-separated
$($stmt:stmt);+

// Zero or more with trailing separator tolerance
$($item:expr),* $(,)?

// Nested repetition (for key-value pairs)
$($key:expr => $value:expr),*
```

The separator goes **between** repetitions. To include a terminator **after each** repetition, place it inside the `$()`:

```rust
// Semicolon AFTER each, not between:
$($key:expr => $value:expr;)*
// Expands: key1 => val1; key2 => val2;
```

## Common Patterns

### Test Battery

Generate multiple test modules from a compact specification:

```rust
macro_rules! test_battery {
    ($($t:ty as $name:ident),* $(,)?) => {
        $(
            mod $name {
                use super::*;
                #[test]
                fn basic() { run_test::<$t>(Default::default()) }
                #[test]
                fn edge_case() { run_test::<$t>(edge_value()) }
            }
        )*
    }
}

test_battery!(u8 as u8_tests, u32 as u32_tests, i64 as i64_tests);
```

### Trait Impl for Many Types

```rust
macro_rule

references/procedural-macros.md

# Procedural Macros

## Three Types

| Type | Annotation | Behavior |
|------|-----------|----------|
| Function-like | `#[proc_macro]` | `fn(TokenStream) -> TokenStream` -- replaces invocation |
| Attribute | `#[proc_macro_attribute]` | `fn(attr, item) -> TokenStream` -- replaces annotated item |
| Derive | `#[proc_macro_derive(Trait)]` | `fn(TokenStream) -> TokenStream` -- appends after item |

**Attribute macro gotcha:** The return replaces the item entirely. Forgetting to include the original item in the output deletes it silently.

**Derive macro constraint:** Cannot modify the annotated item. Output is appended. Helper attributes (`#[my_helper(skip)]`) are markers consumed by the derive, not independent macros.

## Parsing with `syn`

Minimize features to reduce compile time:

```toml
# BAD -- enables everything, slow to compile
syn = { version = "2", features = ["full"] }

# GOOD -- only what derive macros need
syn = { version = "2", features = ["derive"] }
```

Standard parsing pattern:

```rust
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;
    quote! {
        impl MyTrait for #name {
            fn method(&self) -> &'static str { ::core::stringify!(#name) }
        }
    }.into()
}
```

## Generating Code with `quote`

Interpolation with `#var` and repetition with `#(#items)*`:

```rust
let field_names: Vec<_> = fields.iter().map(|f| &f.ident).collect();
let tokens = quote! {
    impl ::core::fmt::Debug for #name {
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
            f.debug_struct(::core::stringify!(#name))
                #(.field(::core::stringify!(#field_names), &self.#field_names))*
                .finish()
        }
    }
};
```

## Span Handling

Spans tie generated tokens to source locations. Correct spans produce good error messages.

| Span | Resolution | Use For |
|------|------------|---------|
| `Span::call_site()` | At macro invocation | Generated items visible to callers |
| `Span::mixed_site()` | Variables at def site, types at call site | Private variables (matches `macro_rules!` hygiene) |
| `Span::def_site()` | At macro definition | Unstable/nightly only |

Always propagate input spans to related output tokens:

```rust
// BAD -- error points to macro definition
let method = Ident::new("process", Span::call_site());

// GOOD -- error points to the user's field
let method = Ident::new(&format!("process_{}", field_name), field_name.span());
```

## Error Reporting

A proc macro that panics crashes the compiler. Use `syn::Error` with spans instead:

```rust
// BAD -- unhelpful ICE
panic!("MyTrait requires at least one field");

// GOOD -- compiler error pointing to the struct
return syn::Error::new_spanned(&input.ident, "requires at least one field")
    .to_compile_error().into();
```

Collect multiple err

skill-card.md

## Description:

Reviews Rust macro code for hygiene issues, fragment misuse, compile-time impact, and procedural macro patterns.

This skill is ready for commercial/non-commercial use.

## Publisher:

[anderskev](https://clawhub.ai/user/anderskev)

### License/Terms of Use:

MIT-0

## Use Case:

Developers and engineers use this skill to review Rust declarative and procedural macros for correctness, hygiene, diagnostics, compile-time impact, and edition-specific risks before reporting code-review findings.

### Deployment Geography for Use:

Global

## Known Risks and Mitigations:

Risk: A macro review may require the agent to read Rust project files in the active workspace.

Mitigation: Run the review only in the intended project workspace and avoid including unrelated sensitive files in scope.

Risk: One reporting gate depends on a separate review-verification-protocol skill.

Mitigation: Ensure that companion skill is available, or perform equivalent macro-specific verification before reporting findings.

Risk: Incomplete crate context or partial macro-definition review can lead to incorrect findings.

Mitigation: Follow the skill's gates: inspect Cargo.toml, read full macro definitions, and cite current-tree file and line evidence for every issue.

## Reference(s):

- [Declarative Macros](references/declarative-macros.md)
- [Procedural Macros](references/procedural-macros.md)
- [ClawHub skill page](https://clawhub.ai/anderskev/skills/macros-code-review)

## Skill Output:

**Output Type(s):** [analysis, markdown, guidance]

**Output Format:** [Markdown code-review findings with file and line references, severity labels, and concise explanations.]

**Output Parameters:** [1D]

**Other Properties Related to Output:** [Findings are gated on crate-context review, complete macro-definition reading, current-tree file and line evidence, and a separate review-verification protocol.]

## Skill Version(s):

1.0.3 (source: server release evidence)

## Ethical Considerations:

Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.

Sponsored

Ads related to Macros Code Review and adjacent AI workflows.