Your Rust team is offered a `#[route]` attribute macro and an `sql!` checker; when do you accept a procedural macro over a generic API or `macro_rules!`?
answer
- climb the ladder: fn, generic, macro_rules
- what only a proc macro can do
- build, IDE and debugging cost
- keep the macro as thin sugar
- code that runs at build time
basics
~20 sAccept one only when a function, a generic API or macro_rules! cannot do the job: reading an item, generating new identifiers, or validating a language at compile time. Keep it thin over a normal API and budget its build and tooling cost.
solid answer
~50 sI climb a ladder. A plain function or a generic API such as `Router::get("/users", list_users)` with `F: Fn() -> String` is type-checked, visible to every tool and adds no build step. `macro_rules!` comes next, when the job is syntax that fits fragment specifiers. A procedural macro is justified only when the code must **read** the decorated item (its signature, to generate extraction code), **invent** identifiers or tables from it, or **check** a foreign language such as SQL at compile time with good errors. Even then it costs something: syn on every build's critical path, code readers cannot see without expanding it, unhygienic output, editors that must run the macro, and arbitrary code running at build time. So I accept it as thin sugar over a public generic API, preferably a maintained crate, with trybuild tests and a measured build-time cost.
code
rust · 24 linesstruct Router {
routes: Vec<(&'static str, &'static str, Box<dyn Fn() -> String>)>,
}
impl Router {
fn new() -> Self {
Router { routes: Vec::new() }
}
fn get<F: Fn() -> String + 'static>(mut self, path: &'static str, handler: F) -> Self {
self.routes.push(("GET", path, Box::new(handler)));
self
}
}
fn list_users() -> String {
String::from("[alice, bob]")
}
fn main() {
let router = Router::new().get("/users", list_users);
for (method, path, handler) in &router.routes {
println!("{method} {path} -> {}", handler());
}
}go deeper
Recall that a function or generic is tried first, macro_rules! second, and a procedural macro last, because each step is harder to read and build.
Explain what a procedural macro can do that a generic cannot: read an item, invent names, validate a language at compile time.
Quantify the costs in your own build with timings, and keep any accepted macro thin, tested with trybuild and re-emitting the user's item.
Own the policy: when a macro may join core crates, who maintains its diagnostics, how much build time it may add, and why a typed API remains the escape hatch.
## The decision a lead owns A team member proposes `#[route(GET, "/users")]` on handlers and an `sql!` macro that rejects bad queries at build time. Both remove boilerplate, and both put a compiler plugin into the build. There is no universal answer. The question is whether what only a procedural macro can do is worth what every engineer pays for it on every build. ## The ladder of alternatives 1. **A plain function or a generic API.** `Router::new().get("/users", list_users)` with `F: Fn() -> String + 'static` (see the example) is ordinary Rust. Errors are type errors at the call, the editor can jump to its definition, and it costs nothing beyond ordinary compilation. 2. **A `const fn` check.** A simple check of a literal, such as "starts with SELECT", can run in an inline `const { assert!(...) }` block. A failure is a compile error (`E0080`, evaluation panicked) with no macro crate at all, though a full SQL parser in `const fn` is impractical. 3. **`macro_rules!`.** It is the right tool when the job is syntax: a variable number of arguments, or items stamped from a template with names the caller passes in. It needs no extra crate and no syn, and it is partly hygienic. It cannot be an attribute on stable, though: in Rust 1.99, `macro_rules!` attributes fail with `E0658` as unstable, and so does the `${concat(...)}` expression that would paste identifiers together. 4. **A procedural macro.** Use one only for what the first three cannot do: - **reading an item's structure**, such as a handler's parameter list, to generate the code that extracts each argument from a request; - **inventing names**, such as `list_users_route`, built from the item's own name; - **compile-time validation of a foreign language** (SQL, a route pattern, a format) with errors spanned on the bad token. If a generic API plus a one-line registration call does the job, the macro is buying only fewer keystrokes. ## What a procedural macro costs | Cost | Where it shows up | |---|---| | Build time | the macro crate, proc-macro2, quote and often syn with `full` sit on the critical path; the macro re-runs on every compile, unoptimised by default | | Readability | the code that runs is not the code on screen; reviewers need `cargo expand` | | Hygiene | output is unhygienic, so it must use absolute paths and unlikely names to avoid clashing with the caller's items | | Tooling | editors have to build and run the macro to see the items it generates | | Error quality | bad spans point users at generated code; good ones take deliberate work and tests | | Trust | the macro runs arbitrary code with the compiler's file and network access, the same concern as a build script | `sql!` adds one more. If it checks against a live database, every build needs that database. Checking against a committed schema file avoids that. ## Rules that make a yes safe - **Thin sugar over a public API.** A proc-macro crate may export only macros, so the runtime types live in a normal crate, which re-exports the macro. The expansion should call that crate's generic API. Anyone can then skip the macro, and the generated code stays small. - **Re-emit the user's item.** An attribute macro's output replaces the item. A macro that keeps the handler as written and only adds registration beside it surprises nobody. - **Prefer a maintained crate** over a home-grown one, unless the domain is truly yours. - **Tests as a contract:** unit tests on a `proc_macro2` core, trybuild `pass` and `compile_fail` cases with reviewed `.stderr` snapshots. - **Measure** with `cargo build --timings` before and after, and set a budget for how much build time the macro may add. ## When the answer is no - The macro saves a line per call site but hides control flow, such as retries or locking, inside the expansion. - One generic function with a trait bound would express the same thing. - The team cannot maintain syn-based code, and nobody owns the macro's diagnostics. - The "validation" only checks things a type would check better. A good principal answer names the trade-off and does not ban macros outright. The route macro may earn its place in a framework used by many services and not in a single small service. The `sql!` checker may earn it when malformed queries have reached production.
- Why should a `#[route]` macro expand to calls into a public generic API rather than to self-contained generated code?Because then the macro is only sugar. Users who hit an edge case can call the API directly, the generated code stays small, and the API is type-checked as ordinary Rust. A proc-macro crate cannot export anything but macros anyway, so the runtime types already live in a normal crate that re-exports the macro.
- What would make you reject an `sql!` that validates queries against a live database during the build?It makes every build, including CI and offline laptops, depend on a reachable database whose schema matches. Builds are no longer reproducible, and build machines need credentials. I would accept compile-time validation against a schema file committed with the code, refreshed by an explicit step, so the check stays deterministic.
- Procedural macros have no cost once the crate has compiled
- A proc macro is the default way to remove any repetitive code
- Generated code is hygienic, so name clashes with the caller cannot happen
- A macro is needed to accept any function as a handler
- Compile-time checks in a macro are always better than a typed API
Assumes Rust 1.99; macro_rules! attributes and the ${concat} metavariable expression are unstable there, so an attribute or a pasted identifier needs a procedural macro on stable.