proc-macro-crate
Resolve the real crate name inside Rust procedural macros, even when renamed
Repository Health
Technical Analysis
proc-macro-crate provides support for the equivalent of $crate in procedural macros. In macro_rules!, $crate yields the path of the crate where a macro is declared, but procedural macros have no built-in way to obtain that path, and the common hack of importing a crate under a known name breaks when users rename the dependency in their Cargo.toml.
The crate exposes a single crate_name function that inspects the consuming project’s Cargo.toml (via CARGO_MANIFEST_DIR) and returns the actual name a target crate is imported under. This lets proc-macro authors emit correct, fully-qualified paths in generated code regardless of how downstream users alias their dependencies.
What You Get
- A single
crate_namefunction that resolves a dependency’s actual import name - Correct handling of crates renamed via
package = "..."in Cargo.toml - A
FoundCrateresult distinguishing the current crate from a named import - Manifest discovery through
CARGO_MANIFEST_DIRwith caching for speed - A tiny, focused dependency you drop into any proc-macro crate
Common Use Cases
- Writing derive or attribute macros that reference a companion runtime crate
- Generating fully-qualified paths that survive dependency renaming
- Building macro ecosystems where the runtime and macro crates are separate
- Replacing brittle hard-coded
::my_cratepaths in emitted token streams
Under The Hood
Architecture - The entire crate lives in a single src/lib.rs. Its crate_name function locates the nearest Cargo.toml using the CARGO_MANIFEST_DIR environment variable set by Cargo during compilation, parses the manifest with toml_edit, and scans dependency tables (including renamed entries via the package key) to find how the requested crate is imported. It returns a FoundCrate enum that is either Itself or Name(String).
Tech Stack - Pure Rust, dual-licensed Apache-2.0 OR MIT. It depends on toml_edit to parse manifests and caches parsed results to avoid repeated filesystem work across many macro expansions. It is intended to be paired with syn, quote, and proc-macro2 in a proc-macro crate.
Code Quality - Despite modest star counts, proc-macro-crate is an infrastructure staple with hundreds of millions of downloads, depended on across the Rust ecosystem. It is small, single-purpose, and covered by an integration test suite under tests/, with a clear README explaining the exact problem it solves.
API Design - The API is deliberately minimal: one function, one enum result. Callers ask for a crate by name and get back an identifier to quote! into their output, keeping generated code correct with almost no boilerplate. That narrow surface makes it easy to adopt and hard to misuse.