Module :: proc_macro_tools
A comprehensive toolkit for writing robust and maintainable procedural macros in Rust.
Why macro_tools?
Writing procedural macros can be challenging due to:
- Complex token stream manipulation - Manually handling token streams is error-prone and verbose
- Boilerplate-heavy code - Common patterns require significant repetitive code
- Poor error handling - Difficult to generate helpful error messages for macro users
- Limited type introspection - Extracting type information from parsed syntax trees is complex
macro_tools
solves these problems by providing:
- 🛠️ High-level utilities for token stream manipulation
- 🔍 Advanced parsers for attributes, generics, and types
- 🎯 Precise error reporting with span-aware messages
- 📦 Zero-dependency core - Only depends on
syn
,quote
, andproc-macro2
- 🚀 Proven in production - Battle-tested in real-world macro systems
Quick Start
Add macro_tools
to your Cargo.toml
:
[]
= "0.24.0"
Example: Extract Type Parameters
use ;
// Parse a type and extract its parameters
let code = qt!;
let tree_type = .unwrap;
// Extract type parameters
let params = type_parameters;
params.iter.for_each;
// Output: i32
Try out cargo run --example macro_tools_extract_type_parameters
.
See code.
Example: Parse Attributes with Properties
This example shows the structure of attribute parsing. For a complete working example with all trait implementations, see the full example file.
use *;
// Define a custom attribute with properties
// After implementing required traits (AttributeComponent, Parse, etc.)
// you can parse attributes like this:
// let attr : syn::Attribute = syn::parse_quote!( #[ custom( enabled = true, name = "example" ) ] );
// let parsed = CustomAttribute::from_meta( &attr )?;
// assert!( parsed.enabled.value() );
Try out cargo run --example macro_tools_parse_attributes
.
See code.
Features
🎯 Type Analysis Tools
Extract and analyze type information:
typ
- Type parsing and parameter extraction utilities- Extract nested generic parameters
- Parse complex type expressions
- Handle path types, arrays, tuples, and more
🔧 Generic Parameter Utilities
Advanced generic parameter manipulation:
generic_params
- Tools for working withsyn::Generics
- Decompose generics for different contexts
- Merge generic parameters from multiple sources
- Filter and transform generic parameters
- Generate appropriate tokens for impl blocks
📝 Attribute Parsing Framework
Powerful attribute parsing with derive-macro-like experience:
attr
- Attribute parsing utilities- Parse structured attributes with properties
- Support for optional, boolean, and custom property types
- Generate helpful error messages
- Composable attribute parsing with the
Assign
trait
🔍 Syntax Tree Helpers
Work with Rust syntax trees effectively:
struct_like
- Parse and manipulate struct-like itemsitem_struct
- Struct-specific utilitiesquantifier
- Extract quantifiers from type expressionsname
- Name and path manipulationpunctuated
- Work with punctuated sequences
🛠️ Token Stream Utilities
Core utilities for procedural macros:
tokens
- Token stream manipulationequation
- Parse and generate equationsdiag
- Enhanced diagnostics with custom error formatting
Advanced Example: Generic Function Implementation
The purpose of typ::type_parameters
is to extract type parameters from a given Rust type.
In this example, we generate a type core::option::Option<i8, i16, i32, i64>
and extract its type parameters.
Try out cargo run --example macro_tools_trivial
.
See code.
Example: Attribute Properties
This example demonstrates an approach to parsing attributes and their properties.
The attributes are collected into a struct that aggregates them, and attribute properties
are parsed using reusable components from a library. The example shows how to use
AttributePropertyBoolean
for parsing boolean properties and the roles of the traits
AttributePropertyComponent
and AttributeComponent
. The Assign
trait is
also used to simplify the logic of assigning fields.
Attributes are collected into a ItemAttributes
struct, and attribute properties are parsed
using reusable components like AttributePropertyBoolean
.
AttributeComponent
: A trait that defines how an attribute should be parsed from asyn::Attribute
.AttributePropertyComponent
: A trait that defines a marker for attribute properties.Assign
: A trait that simplifies the logic of assigning fields to a struct. Using a component-based approach requires each field to have a unique type, which aligns with the strengths of strongly-typed languages. This method ensures that the logic of assigning values to fields is encapsulated within the fields themselves, promoting modularity and reusability.
The reusable property components from the library come with parameters that distinguish different properties of the same type. This is useful when an attribute has multiple boolean properties, for instance. Such an approach helps to avoid limitations where it is always possible to define traits for custom types, while it may not be possible for types defined in other crates.
Try out cargo run --example macro_tools_attr_prop
.
See code.
Real-World Use Cases
macro_tools
is ideal for:
- Derive Macros - Building derive macros with proper error handling and type analysis
- Attribute Macros - Parsing complex attributes with multiple properties
- Code Generation - Generating boilerplate code based on type structure
- DSL Implementation - Creating domain-specific languages with procedural macros
Documentation
For detailed documentation, visit:
Contributing
We welcome contributions! Please see our Contributing Guide.
License
Licensed under the MIT License. See LICENSE for details.
Repository
To add to your project
Try out from the repository