Sub topic 14
Cutting repetition with macro_rules
Operator impls are repetitive. A type that supports +, -, * and / on values and references needs many near-identical blocks. This chapter shows how to generate them with declarative macros (macro_rules!).
This chapter assumes you know how to implement Add and its relatives, including Output, reference impls and compound assignment. It also assumes you can read a basic macro_rules! definition.
Where the repetition comes from
Suppose Series wraps a Vec<f64> and is not Copy. Users will want four forms of addition: &a + &b, a + &b, &a + b and a + b. Only one of them contains real logic. The other three forward to it. Multiply that by Sub, Mul and Div and you have a dozen impls that differ in a few identifiers.
A macro fits this job well. The impls differ only in the trait name, the method name and sometimes the operator token. Macros match on those pieces and substitute them.
A macro that forwards reference impls
The plan is to write the &T op &T impl by hand for each trait. The macro generates the other three forms from it.
use std::ops::{Add, Sub};
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Add<&Series> for &Series {
type Output = Series;
fn add(self, rhs: &Series) -> Series {
Series(self.0.iter().zip(&rhs.0).map(|(a, b)| a + b).collect())
}
}
impl Sub<&Series> for &Series {
type Output = Series;
fn sub(self, rhs: &Series) -> Series {
Series(self.0.iter().zip(&rhs.0).map(|(a, b)| a - b).collect())
}
}
macro_rules! forward_ref_binop {
(impl $imp:ident, $method:ident for $t:ty) => {
impl ::std::ops::$imp<$t> for &$t {
type Output = $t;
fn $method(self, rhs: $t) -> $t {
::std::ops::$imp::$method(self, &rhs)
}
}
impl ::std::ops::$imp<&$t> for $t {
type Output = $t;
fn $method(self, rhs: &$t) -> $t {
::std::ops::$imp::$method(&self, rhs)
}
}
impl ::std::ops::$imp<$t> for $t {
type Output = $t;
fn $method(self, rhs: $t) -> $t {
::std::ops::$imp::$method(&self, &rhs)
}
}
};
}
forward_ref_binop!(impl Add, add for Series);
forward_ref_binop!(impl Sub, sub for Series);
fn main() {
let a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
let sum = &a + &b;
assert_eq!(sum, Series(vec![4.0, 6.0]));
assert_eq!(&b - &a, Series(vec![2.0, 2.0]));
assert_eq!(a.clone() + &b, sum);
assert_eq!(&a + b.clone(), sum);
assert_eq!(a + b, sum);
}Each piece of the macro does a specific job:
$imp:identcaptures a trait name such asAdd.$method:identcaptures the method name, such asadd.$t:tycaptures a type. Writing&$tin the output builds the reference type.- The macro refers to the trait as
::std::ops::$imp. This absolute path works at any call site, even in a module that has not importedAdd. - Each forwarding body calls the hand-written
&T op &Timpl. The logic stays in one place per operator.
The two main lines &b - &a and a.clone() + &b pick different generated impls. The compiler selects the impl by operand types, exactly as it does for hand-written code.
One macro for several operators
Sometimes the impls differ only in the operator token. Componentwise arithmetic on Vec2 is an example. The macro can capture the operator as a tt, a single token tree, and paste it into an expression.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
macro_rules! impl_componentwise {
($($imp:ident :: $method:ident => $op:tt),+ $(,)?) => {
$(
impl ::std::ops::$imp for Vec2 {
type Output = Vec2;
fn $method(self, rhs: Vec2) -> Vec2 {
Vec2 { x: self.x $op rhs.x, y: self.y $op rhs.y }
}
}
)+
};
}
macro_rules! impl_assign {
($($imp:ident :: $method:ident => $op:tt),+ $(,)?) => {
$(
impl ::std::ops::$imp for Vec2 {
fn $method(&mut self, rhs: Vec2) {
self.x $op rhs.x;
self.y $op rhs.y;
}
}
)+
};
}
impl_componentwise! {
Add::add => +,
Sub::sub => -,
Mul::mul => *,
Div::div => /,
}
impl_assign! {
AddAssign::add_assign => +=,
SubAssign::sub_assign => -=,
}
fn main() {
let a = Vec2 { x: 6.0, y: 8.0 };
let b = Vec2 { x: 2.0, y: 4.0 };
assert_eq!(a + b, Vec2 { x: 8.0, y: 12.0 });
assert_eq!(a - b, Vec2 { x: 4.0, y: 4.0 });
assert_eq!(a * b, Vec2 { x: 12.0, y: 32.0 });
assert_eq!(a / b, Vec2 { x: 3.0, y: 2.0 });
let mut p = a;
p += b;
p -= Vec2 { x: 1.0, y: 1.0 };
assert_eq!(p, Vec2 { x: 7.0, y: 11.0 });
}The pattern $( ... ),+ $(,)? means "one or more entries separated by commas, with an optional trailing comma". Each entry expands into one impl block. The compound operators += and -= are single tokens in the macro system, so $op:tt captures them.
What the compiler does with the expansion
The macro runs before type checking. It only produces tokens. Everything the earlier chapters covered applies to those tokens as it would to hand-written code.
Several consequences follow:
- The orphan rule still applies. A macro cannot make
impl Add for Vec<f64>legal in your crate. - Overlapping impls still conflict. Invoking
impl_componentwise!twice forAddon the same type produces the usual "conflicting implementations" error. - Errors point at the macro call site and often at the macro definition. Run
cargo expand(from thecargo-expandtool) to see the generated impls. - Macros must be defined textually before they are used in the same module, unless you export them with
#[macro_export]. Exported macros that name your own items should use$crate::paths.
Choosing fragment specifiers
| Fragment | Matches | Typical use in operator macros |
|---|---|---|
| `ident` | A single identifier | Trait name, method name |
| `ty` | A type | The type receiving the impls |
| `tt` | One token or one bracketed group | The operator token, such as `+` or `+=` |
| `expr` | An expression | A body expression passed in by the caller |
Use the narrowest fragment that works. An ident for the trait name fails early and clearly if the caller passes something else. One limit of ty is that it captures a whole type. If you need generic parameters, such as impl<T> Add for Wrapper<T>, the pattern has to capture them separately, usually as $($gen:tt)*. At that point the macro is often harder to read than the impls it replaces.
When a macro is the wrong tool
Macros reduce typing, but they also add a second language to read. Weigh them against the alternatives:
- Three or fewer near-identical impls are usually clearer written out.
- A trait with a default-friendly shape may let you write one generic impl with bounds instead.
- Crates such as
derive_moregenerate common operator impls with#[derive(Add, Mul)]. They are well tested but add a dependency. - Keep the macro private to the module, and keep its arms few. A macro with six arms and nested repetitions is hard to maintain.
Exercise
You call impl_componentwise! { Add::add => + } and, a few lines later in the same module, call impl_componentwise! { Add::add => +, Sub::sub => - }. What happens, and why?
Show answer
Compilation fails with a conflicting implementations error (E0119). The macro expands to ordinary impl Add for Vec2 blocks, and the first and second invocations both generate one. The compiler cannot choose between them. Remove Add::add => + from one of the invocations.
Exercise
Write a macro impl_neg! that takes a type name and generates Neg for a struct with x and y fields, using the same Output = Self convention as Vec2. Which fragment specifier should capture the type?
Show answer
Use ty.
macrorules! implneg {
($t:ty) => {
impl ::std::ops::Neg for $t {
type Output = $t;
fn neg(self) -> $t {
<$t>::newfromxy(-self.x, -self.y)
}
}
};
}
A simpler version avoids a constructor by writing the struct literal with Self: Self { x: -self.x, y: -self.y }. Struct literals cannot be written through a $t:ty path in every case, but Self inside the impl always works, so prefer Self { x: -self.x, y: -self.y } as the body.