Sub topic 14
Cutting repetition with macro_rules
This chapter assumes you have read the earlier chapters on Add, Output, and reference impls. You should also know the basics of declarative macros: a macro_rules! definition is a set of patterns, each paired with code to generate.
The repetition problem
Operator impls are nearly identical from one trait to the next. Add and Sub for a vector type differ only in the trait name, the method name, and the operator token. Reference impls add more copies. Each one forwards to the by-value impl.
Writing these by hand is tedious, and typos creep in. A macro can generate them from a short description.
A macro for componentwise operators
The macro below takes a trait name, a method name, and an operator token. It expands to a complete impl.
use std::ops::{Add, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
macro_rules! impl_componentwise {
($trait:ident, $method:ident, $op:tt) => {
impl $trait for Vec2 {
type Output = Vec2;
fn $method(self, rhs: Vec2) -> Vec2 {
Vec2 { x: self.x $op rhs.x, y: self.y $op rhs.y }
}
}
};
}
impl_componentwise!(Add, add, +);
impl_componentwise!(Sub, sub, -);
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
assert_eq!(a + b, Vec2 { x: 4.0, y: 6.0 });
assert_eq!(a - b, Vec2 { x: -2.0, y: -2.0 });
}Each fragment specifier says what kind of syntax the placeholder matches:
| Placeholder | Specifier | Matches |
|---|---|---|
| `$trait` | `ident` | A name such as `Add` |
| `$method` | `ident` | A name such as `add` |
| `$op` | `tt` | A single token tree, such as `+` |
The operator must be a tt. A bare + is not an expression, so expr would not match it. A tt accepts one token and can be pasted between two operands.
Forwarding reference impls
The second macro generates the three reference combinations from an existing by-value impl. It requires the type to be Copy, because each impl dereferences its reference operands.
use std::ops::{Add, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
macro_rules! impl_componentwise {
($trait:ident, $method:ident, $op:tt) => {
impl $trait 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! forward_ref_binop {
($trait:ident, $method:ident, $t:ty) => {
impl<'a> $trait<$t> for &'a $t {
type Output = <$t as $trait<$t>>::Output;
fn $method(self, rhs: $t) -> Self::Output {
$trait::$method(*self, rhs)
}
}
impl<'a> $trait<&'a $t> for $t {
type Output = <$t as $trait<$t>>::Output;
fn $method(self, rhs: &'a $t) -> Self::Output {
$trait::$method(self, *rhs)
}
}
impl<'a, 'b> $trait<&'a $t> for &'b $t {
type Output = <$t as $trait<$t>>::Output;
fn $method(self, rhs: &'a $t) -> Self::Output {
$trait::$method(*self, *rhs)
}
}
};
}
impl_componentwise!(Add, add, +);
impl_componentwise!(Sub, sub, -);
forward_ref_binop!(Add, add, Vec2);
forward_ref_binop!(Sub, sub, Vec2);
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
assert_eq!(&a + &b, Vec2 { x: 4.0, y: 6.0 });
assert_eq!(a - &b, Vec2 { x: -2.0, y: -2.0 });
assert_eq!(&b - a, Vec2 { x: 2.0, y: 2.0 });
}Four invocations now produce eight trait impls for the type, plus the four arithmetic combinations on &Vec2. Adding Mul or Div costs one more line each.
Common errors
- Using
exprfor the operator. The compiler reports "no rules expected the token+". Usett. - Calling a forwarding macro before the by-value impl exists. The
Outputprojection<$t as $trait<$t>>::Outputthen fails to resolve. - Applying the forwarding macro to a non-
Copytype. The*selfdereference fails to compile. Clone inside the macro instead, or write those impls by hand. - Defining the macro after its first use.
macro_rules!is textually scoped, so the definition must appear earlier in the file or module.
Exercise
Why is the operator parameter in impl_componentwise declared as $op:tt instead of $op:expr?
Show answer
An operator such as + is a single token, not a complete expression, so an expr fragment cannot match it. A tt fragment matches any single token tree, so the macro can place it between self.x and rhs.x in the expansion.
Exercise
Write the invocation that would generate the by-value Mul impl for Vec2 where each component is multiplied by the matching component of the other operand. Does this conflict with Mul<f64> for Vec2 from the Rhs chapter?
Show answer
impl_componentwise!(Mul, mul, *); It does not conflict. The macro produces Mul<Vec2> for Vec2, and Mul<f64> for Vec2 is a different trait instantiation because the Rhs parameter differs.