type-mapper
A Rust procedural macro crate for powerful type-level pattern matching and transformation. This crate is particularly useful for macro authors who need to perform complex type manipulations at compile time.
Features
- Type pattern matching with wildcards
- Lifetime handling and manipulation
- Recursive type transformations
- Support for generic type parameters
- Path-aware type matching
Limitations
The macro matches on token patterns rather than full types. It performs no validation of generic parameters or type identity.
For example, you cannot tell whether a type named Ordering
was imported from
std::cmd::Ordering
or std::sync::atomic::Ordering
.
Usage
Add this to your Cargo.toml
:
[]
= "0.x.y"
Examples
Type Declaration
The map_types!
macro can be used in a type position:
use map_types;
/// This is an unlikely usage, but macros will generate code like this:
static X: map_types! = 1_u8;
It's mostly useful when writing macros that need to transform types:
use map_types;
use assert_type_eq_all;
define_trait_for!;
define_trait_for!;
assert_type_eq_all!;
assert_type_eq_all!;
// This doesn't compile because we can't test against that missing lifetime
// assert_type_eq_all!(<MyStruct as MyTrait<(&'a u8, &'a u8)>>::Type, (&'static u8, &'static u8));
assert_type_eq_all!;
Basic Type Matching
The crate provides a assert_type_matches!
and assert_type_not_matches!
macros for testing type matches.
use ;
// Simple type matching
assert_type_matches!;
assert_type_matches!;
assert_type_matches!;
assert_type_matches!;
// Wildcard matching
assert_type_matches!;
assert_type_matches!;
assert_type_matches!;
assert_type_not_matches!;
// Type mismatch
assert_type_not_matches!;
assert_type_not_matches!;
assert_type_not_matches!;
Lifetime Handling
use map_types;
use assert_type_eq_all;
/// Make a slice type static.
assert_type_eq_all!;
assert_type_eq_all!;
Recursive Type Matching
Using the internal recurse!
macro, you can match on types recursively.
use map_types;
use assert_type_eq_all;
/// Unwrap an Option type recursively.
assert_type_eq_all!;
assert_type_eq_all!;
assert_type_eq_all!;
Pattern Matching Syntax
The crate supports several pattern matching features:
_
- Wildcard for any type_T
- Named wildcard that can be referenced in the result_T<T>
- Generic type matching_T<>
- Generic type matching with no generics (WARNING: rustfmt may eat the<>
if you don't use#[rustfmt::skip]
)'_
- Wildcard lifetime (will also match no lifetime in a reference)'_A
- Named wildcard lifetime (will also match no lifetime in a reference)'a
- Named lifetime matchingrecurse!(_T)
- Recursive type transformation
Use Cases
This crate is particularly useful for:
- Macro authors who need to transform types
- Creating type-level DSLs
- Implementing complex type-level logic
- Generic type manipulation
- Lifetime manipulation in macros
License
MIT License