Skip to content

RFC: Procedural macros in same package as app #3826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Changes from 24 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
093a48a
Add proposal
ora-0 May 28, 2025
6400116
Change "crate" to "package"
ora-0 May 29, 2025
bd3762d
Implement feedback from pre-RFC
ora-0 May 30, 2025
2abc88c
General edits
ora-0 May 30, 2025
cf956c9
Add info about pr
ora-0 May 30, 2025
3ce11c2
Revision 1: Implement feedback; Rethink `proc-macro` directory
ora-0 May 31, 2025
269863b
Revision 2: Rename macro.rs to procmacro.rs; Add detail in example an…
ora-0 Jun 1, 2025
001a769
fix capitalisation
ora-0 Jun 3, 2025
a4cc177
change config to cfg
ora-0 Jun 3, 2025
dad0bef
Change default location to proc-macro/lib.rs
ora-0 Jun 3, 2025
f4ef425
Split explanation into guide-level and reference-level
ora-0 Jun 3, 2025
6e1111a
Specify visibility of `macros` within the reference-level explanation…
ora-0 Jun 3, 2025
3b34d68
Reform the linking behaviour specified by `build.rs` with `macros`
ora-0 Jun 3, 2025
2a98d11
Discover drawbacks
ora-0 Jun 3, 2025
9fd805f
Reapply config -> cfg
ora-0 Jun 4, 2025
4731ce1
Add drawback relating to other build systems
ora-0 Jun 4, 2025
1488bdb
Add detail for environment variables
ora-0 Jun 4, 2025
904a687
Include changes to the cli
ora-0 Jun 4, 2025
2f47429
Specify building behaviour in target/
ora-0 Jun 4, 2025
1dc76b1
Remove last point in #future-possibilities
ora-0 Jun 4, 2025
cfb4c32
Move current behaviour to #motivations
ora-0 Jun 4, 2025
c7f34c5
Allow `cargo test --macros`
ora-0 Jun 5, 2025
3f94b5b
Remove `CARGO_CFG_PROC_MACRO`
ora-0 Jun 5, 2025
ff89040
Prefer `proc-macro` over `macros` when possible
ora-0 Jun 5, 2025
ad1964f
Finish unfinished sentence
ora-0 Jun 6, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 200 additions & 0 deletions text/3778-proc-macro-in-same-package-as-app.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
- Feature Name: `proc-macro-in-same-package-as-app`
- Start Date: 2025-05-30
- RFC PR: [rust-lang/rfcs#3826](https://github.com/rust-lang/rfcs/pull/3826)
- Rust Issue: [rust-lang/rust#0000](https://github.com/rust-lang/rust/issues/0000) tbd

# Summary
[summary]: #summary

Have a new target in a cargo project, called `proc-macro`. Its default location is in `proc-macro/lib.rs`. This would be like the `tests` directory in that it is alongside the source code. It would eliminate the need to create an extra package for proc macros.

# Motivation
[motivation]: #motivation

A common thing to ask about proc macros when first learning them is: "Why on earth does it have to be in a separate package?!" Of course, we eventually get to know that the reason is that proc macros are basically *compiler plugins*, meaning that they have to be compiled first, before the main code is compiled. So in summary, one needs to be compiled before the other.

Currently, we create a new proc macro as so:
1. Create a new package
2. In its cargo.toml, specify that it is a proc macro package
3. In the main project, add the package as a dependency
4. Implement the proc macro in the new package

While this doesn't seem like a lot, with reasons explained later, could actually be making code worse.

It doesn't have to be this way though, because we already have this mechanism of compiling one thing before another – for example, the `tests` directory. It relies on the `src` directory being built first, and likewise we could introduce a `proc-macro` target that would compile before `src`.

**To be absolutely clear**, this is not a proposal for same-*crate* proc macros (unlike previous proposals), but same-*package* proc macros: a much simpler problem.

The motivation of this new target comes down to just convenience. This may sound crude at first, but convenience is a key part of any feature in software. It is known in UX design that every feature has an *interaction cost*: how much effort do I need to put in to use the feature? For example, a feature with low interaction cost, with text editor support, is renaming a variable. Just press F2 and type in a new name. What this provides is incredibly useful – without it, having a subpar variable/function name needed a high interaction cost, especially if it is used across multiple files, and as a result, we are discouraged to change variable names to make it better, when we have retrospect. With a lower interaction cost, the renaming operation is greatly promoted, and leads to better code.

This proposal aims smooth out the user experience when it comes to creating new proc macro, and achieve a similar effect to the F2 operation. It is important to emphasise that proc macros can dramatically simplify code, especially derive macros, but they a lot of the times aren't used because of all the extra hoops one has to get through. This would make proc macros (more of) "yet another feature", rather than a daunting one.
Copy link

@hanna-kruppe hanna-kruppe Jun 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm missing a clear statement which proc-macros is this feature for?

The motivation section focuses on the ease of introducing a proc macro in a library that currently doesn't have one. I have sympathy for that, the proc-macro <-> build script/decl-macro switcheroo isn't fun. If the feature was tightly scoped to experimentation and simple library-internal use, the build order questions discussed in #3826 (comment) have a clear, simple answer. Dependents also wouldn't need to know that the proc macro exists, let alone opt in/out with crate features (cc #3826 (comment)).

But it seems quite a few people commenting here see this feature as a general replacement for "library re-exports proc-macros" -- and it's not like we can stop people from re-exporting the proc macros like that, even if that wasn't the intended usage. If the feature isn't designed with that in mind then there's a risk it'll end up as a newbie trap: easier to get started, but once you get serious you have to dig yourself back out of the downsides of the easier way. But in that case, the feature will become much more complicated. Thus, my questions: Is it an explicit design goal that essentially any library providing proc macros could use this feature? If not, what's out of scope and how would people pick between using this feature and making a separate crate?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you see as the downsides to designing a proc-macro in this way? I don't think I've seen those raised yet in this discussion.

I've seen this as a general way of doing proc-macros and would see this feature not to be worth it (or maybe actively opposed) if this is for smaller scope and then people grow out of it. In general, I'm not thrilled with cramming everything into a single package to avoid having a workspace and feel that to meet what people want in doing that would move cargo away from what its good for. That said, I feel like this doesn't run into those problems and can help avoid some proc-macro problems (e.g. the proc-macro logically depends on the library it re-exports but can't declare that relationship nor is it obvious of a problem for users to solve or how to solve it).

Copy link

@hanna-kruppe hanna-kruppe Jun 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, I share your gut feeling that this feature probably isn't worth it if it's only useful for small, simple macros, but I didn't want to prejudice my comment with that. The downsides I see with trying to do "everything" are mostly the complexity that I expect will be required to address all of the concerns raised in other comment threads. To avoid introducing downsides compared to a separate package, this feature will need:

  • Support for both the "proc-macro is compiled independently of library" use case (generally faster builds) and the "library also uses its associated proc-macro internally" use cases. (RFC: Procedural macros in same package as app #3826 (comment))
  • Ability to make the proc-macro part of the package optional, like the common derive = ["dep:foo_derive"] feature. In general this needs to be a proper feature because it may interact in complex ways with ordinary features of the package. (RFC: Procedural macros in same package as app #3826 (comment))
  • Ability for some crates to depend only on the library without pulling in the proc-macro parts, even if other parts of the dependency graph require both. For example, crates like time and jiff depend only on serde and write impls by hand; as long as other crates in the build depend directly on serde_derive (not via serde/derive) the former crates can still be compiled independently of the proc-macro and its dependencies.

All of these points (and others we may find) can be addressed in theory. But not all of them seem to have straightforward solutions that fit in the scope of what a package currently is. For example, something like required-features on a packages' proc-macros could serve the second bullet point, but the third one needs a way to say "I only depend on this part of that package" (here: the lib, not the proc-macro) which doesn't currently exist and seems like a step towards "N things in 1 package instead of N packages in a workspace".

can help avoid some proc-macro problems (e.g. the proc-macro logically depends on the library it re-exports but can't declare that relationship nor is it obvious of a problem for users to solve or how to solve it).

This is a problem worth solving, but I'd prefer a solution that existing libraries with separate foo_derive packages can adopt without breaking their users who depend directly on foo_derive (most notably, serde). For example, if the proc-macro package could directly express which library package+version it's coupled in its manifest, that only requires a sufficiently new MSRV but no package restructuring.

Copy link
Contributor

@epage epage Jun 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe there is something I'm missing but I feel like the answers to these questions are fairly simple; the author just needs to take the time to enumerate and write it up.

For example:

Support for both the "proc-macro is compiled independently of library" use case (generally faster builds) and the "library also uses its associated proc-macro internally" use cases.

This is no different than the regular proc-macro situation. If you are like serde today, in both cases the core functionality will be blocked on the derive building. However, if you have a derive like clap or serde after serde-rs/serde#2608, the proc-macro and the core library will be built in parallel and the re-export library will be blocked on both. Again, no difference between a separate package and same package.

Ability to make the proc-macro part of the package optional, like the common derive = ["dep:foo_derive"] feature. In general this needs to be a proper feature because it may interact in complex ways with ordinary features of the package

This is why I brought up [proc-macro] table so you can do

[proc-macro]
required-features = ["derive"]

And with that, your proc-macro is now skipped if derive is not enabled using existing Cargo functionality.

You mentioned a problem with this related to addressing one of N libraries in a package. That didn't quite make sense to me but if its related to the other points, then I addressed those.

Ability for some crates to depend only on the library without pulling in the proc-macro parts, even if other parts of the dependency graph require both.

While true that if everyone depended on serde_derive, rather than serde/derive, people could depend on serde without a slow down. This is unlikely to ever happen though so this is a benefit in theory. Instead, we need serde-rs/serde#2608 wrapped up and then libraries like serde_json can depend on serde_core without the need for cooperation from every dependency. As a bonus, this will mean that we can see a serde_derive v2!

This is a problem worth solving, but I'd prefer a solution that existing libraries with separate foo_derive packages can adopt without breaking their users who depend directly on foo_derive (most notably, serde). For example, if the proc-macro package could rust-lang/rust#54363 (comment) in its manifest, that only requires a sufficiently new MSRV but no package restructuring.

That proposal has a lot of complexity to it that I do not see it being likely to happen.

This introduces cycles between packages, particularly for publishing. There are ways to solve problems with that but taking just one part as an example, this would require a new publish API which has been stalled out for years.

This also takes a concern I have with this proposal being able to solve $crate (#3826 (comment)) and greatly increase the complexity for solving it because it would extend from determining information from a strict child-parent relationship to an arbitrary relationship as we work through the build graph.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no different than the regular proc-macro situation. If you are like serde today, in both cases the core functionality will be blocked on the derive building. However, if you have a derive like clap or serde after serde-rs/serde#2608, the proc-macro and the core library will be built in parallel and the re-export library will be blocked on both. Again, no difference between a separate package and same package.

The difference is that with separate packages, it's clear how any of the three options can expressed. The library either depends on the associated proc-macro package or doesn't; a facade crate like clap is just a separate package that depends on both the library and the proc-macro. If library and proc-macro are part of the same package, there needs to be some new way to express these dependencies (possibly optional/feature-gated) between the library and the proc macros within the same package. It's less clear to me what this would look like than with the required-features thing.

As I've said, I'm sure there's many ways to design support for this. But without having seen a complete proposal for all aspects, I'm no sure whether the end result will truly be better than the status quo.

While true that if everyone depended on serde_derive, rather than serde/derive, people could depend on serde without a slow down. This is unlikely to ever happen though so this is a benefit in theory.

It's not a theoretical benefit. Inertia is strong, of course, but I've seen a few big dependency trees reach this goal. For example, most configurations of wasmtime before the switch from bincode to postcard achieved it, as long as you disabled the profiling feature (and the postcard thing is fixable). Also, new libraries with derives can do the "please depend on foo and foo-derive separately" thing from the start and avoid offering a derive feature in the first place (I've done that for a new library I started recently). This should remain expressible with "proc-macro in same package" if we want all proc macros to adopt this style (modulo MSRV and backwards compatibility issues).

Besides, I don't understand how a clap-style (or serde/serde_core-style) split would interact with this RFC. Assuming the "at most one library per package" rule remains in place, that means there's still going to be at least two packages involved. If that's going to be the recommended approach, the simplicity the RFC cites as motivation is mostly lost. If you put the proc-macro into the package that re-exports the underlying library crate (e.g., clap_derive becomes a [proc-macro] of clap while clap_builder remains separate) you still have the problem that the package with the derive and the package with the traits being derived are separate and their version needs to match exactly. If the $crate-for-proc-macro angle works out (seems very speculative to me at this point) then you'd keep that benefit, but the other benefits seem much less applicable than in the "one package for everything" case.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thus, my questions: Is it an explicit design goal that essentially any library providing proc macros could use this feature?

It wasn't an initial goal, but in the pre-RFC and RFC there has been a need to do it so a lot of the revisions do have that in mind. There is still a lot of room of iterations.

Ability to make the proc-macro part of the package optional... Ability for some crates to depend only on the library without pulling in the proc-macro parts, even if other parts of the dependency graph require both.

You can just use conditional compilation on your proc macros. It'll just be like how you gate all other features. Unless I'm overlooking something.

It feels that some of the criticisms, while valid, are a bit too fixated on the idea of the separation between proc-macro packages and library packages. There was really no reason for them to be separated in the first place, except for build system, which I think most of us can agree is an unfortunate blocker. In an ideal world, proc macros and code can coexist together, and this is a close equivalent.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Besides, I don't understand how a clap-style (or serde/serde_core-style) split would interact with this RFC. Assuming the "at most one library per package" rule remains in place, that means there's still going to be at least two packages involved. If that's going to be the recommended approach, the simplicity the RFC cites as motivation is mostly lost.

I fundamentally disagree with the motivation of the RFC. If that motivation was the sole motivation, I would be a hard "no" on this. imo if people have a problem with managing a workspace, we should work to improve workspaces. I mentioned earlier in this thread (#3826 (comment)) that I generally disagree with cramming everything into a package. For more on this topic, see https://blog.rust-lang.org/inside-rust/2024/02/13/this-development-cycle-in-cargo-1-77/#when-to-use-packages-or-workspaces

As I mentioned before (#3826 (comment)), the main benefit this gives us is a happy path for declaring the relationship between the proc-macro and the library it generates code against. As a secondary motivation is I see this as a fundamental step towards unblocking $crate though there are likely other blockers.

So for clap, I would merge clap_derive into clap and keep clap_builder as a separate package.

The difference is that with separate packages, it's clear how any of the three options can expressed. The library either depends on the associated proc-macro package or doesn't; a facade crate like clap is just a separate package that depends on both the library and the proc-macro. If library and proc-macro are part of the same package, there needs to be some new way to express these dependencies (possibly optional/feature-gated) between the library and the proc macros within the same package. It's less clear to me what this would look like than with the required-features thing.

As I've said, I'm sure there's many ways to design support for this. But without having seen a complete proposal for all aspects, I'm no sure whether the end result will truly be better than the status quo.

I think there is something missing in our communication because you seem to still feel there are significant open questions on this point while I feel that I explain how this naturally falls out of the design and there isn't anything special to this (though the RFC does need to explicitly call this all out).

If there are lingering concerns, feel free to reach out to me for a call for us to work this out.

It's not a theoretical benefit. Inertia is strong, of course, but I've seen a few big dependency trees reach this goal. For example, most configurations of wasmtime before the switch from bincode to postcard achieved it, as long as you disabled the profiling feature (and jamesmunns/postcard#130). Also, new libraries with derives can do the "please depend on foo and foo-derive separately" thing from the start and avoid offering a derive feature in the first place (I've done that for a new library I started recently). This should remain expressible with "proc-macro in same package" if we want all proc macros to adopt this style (modulo MSRV and backwards compatibility issues).

Ok, so I take back my saying its theoretical. I still think it is not a workflow we should prioritize in our designs. Cargo is an opinionated tool focused on usability. Having to do that much precise coordination across a dependency tree seems like the wrong answer with Cargo's design.

Copy link

@hanna-kruppe hanna-kruppe Jun 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for elaborating on your perspective on what the RFC should be, @epage, this helps me understand your previous comments better. Also thanks for offering a call, but I think at this point it's probably a better use of everyone's time to let the RFC catch up with the discussion and propose a more detailed design. Then I'll open more focused comment threads if I still have concerns, because then I'll be able to phrase them more precisely since I'll have less guessing to do about what precisely is proposed.

The one thing that I'd like to ask you which the updated RFC probably won't answer is about your plan to merge clap_derive into clap. I'm not sure whether you think the main benefit of the RFC (happy path for declaring relationship between proc-macro and the library is generated code for) applies to that case. I don't think it does, because the derive would still be in a separate package (clap) from the traits that the derive implements (clap_builder), i.e., you'd still need clap to depend on a specific, pinned version of clap_builder. Am I missing something or are you not expecting this benefit to apply in this setup? (Of course, proc-macro $crate, if it works out, would still be useful in this case.)

@ora-0 I'd say I care more about the build system POV (which units of work exist in the build and how they depend on each other) than about packages per se. In essence, if the goal is that every proc macro should share a package with its associated library, then I'm asking what that means for the dependency graph at the build system level. If some useful dependency graphs would be inexpressible in that future style, then I'd consider that a downside of the RFC and would like to discuss the impact. Conversely, if the RFC doesn't restrict our ability to massage the work done by the build system in the most favorable shape (compared to the status quo), I'd like the RFC to spell out how this is possible.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The one thing that I'd like to ask you which the updated RFC probably won't answer is about your plan to merge clap_derive into clap. I'm not sure whether you think the main benefit of the RFC (happy path for declaring relationship between proc-macro and the library is generated code for) applies to that case. I don't think it does, because the derive would still be in a separate package (clap) from the traits that the derive implements (clap_builder), i.e., you'd still need clap to depend on a specific, pinned version of clap_builder. Am I missing something or are you not expecting this benefit to apply in this setup? (Of course, proc-macro $crate, if it works out, would still be useful in this case.)

There are two common dependency problems when you have a lib -> lib_derive relationship

  • lib requires a minimum version of lib_derive but lib_derive needs to declare a minimum version on lib.
    • The simplest way of solving that is with lib using lib_derive = "=1.0.100".
    • If you merge lib_derive into the lib package, this problem goes away.
    • If you also have a lib_core, that doesn't matter because lib_derive only needed a minimum version requirement and lib already has that on lib_core
  • lib_derive using internal APIs of lib which requires a = requirement.
    • If you merge them, this goes away.
    • If lib re-exports a lib_core which actually has the internal API, then you will still need a = requirement.
    • Hopefully instead lib will only re-export public APIs from lib_core and the private API used by the former lib_derive could live inside of lib.

Since clap_derive does not generate code using a private API from clap, it could be merged into clap without a problem. In fact, I could remove the use of = in clap today by having clap_derive declare a target.cfg(false).dependencies on clap_builder. I don't remember why I haven't done that.

serde_derive does use private APIs. I've not followed the serde_core PR too closely on whether those are living inside of serde or serde_core.


An objection to this one might raise is "How much harder is typing in `cargo new` than `mkdir proc-macro`?" But we should consider if we would still use as much integration tests if the `tests` directory if it is required to be in a seperate package. The answer is most likely less. This is because (1) having a new package requires ceremony, like putting in a new dependency in cargo.toml, and (2) requires adding to the project structure. A *tiny* bit in lowering the interaction cost, even from 2 steps to 1, can greatly improve the user experience.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMHO, a greater motivation is to avoid having to make several upload to crates.io and making sure to keep them in sync.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me, its less of an issue publishing multiple crates but getting the pattern right. In general, there is a conflict in people wanting to treat a package as a whole workspace the the format complexity that doing so entails (details). I'm generally in favor of encouraging splitting packages.

proc-macros are odd because they have a logical dependency on the library that re-exports them because they generate code that calls into that library. Its easy to overlook this problem and there isn't a great way to declare this relationship today. The options are

  • Have the re-exporting package use a = dependency on the proc-macro
  • Have the proc-macro have a [target."cfg(false)".dependencies] on a sibling package that the re-exporting package also re-exports

If this also helps towards $crate, then great!


Another benefit is that a library developer don't have to manage two packages if one requires proc macros, and make them be in sync with each other.

In summary (TL;DR), the effort one needs to put in to use a feature is extremely important. Proc macros currently has a higher ceiling, needing one to create a whole new package in order to use it, and lowering the ceiling, even just a little bit, could massively improve user experience. This proposal can lower it.

# Guide-level explanation
[guide-level-explanation]: #guide-level-explanation

After this change, we create a new proc macro like this:
1. Create a new folder in the root of the project called `proc-macro`
2. Implement the proc macro in a new `lib.rs` in the new folder.

To build only the macro, use:
```console
$ cargo build --proc-macro
```

## Importing
[importing]: #importing
To use the proc macro, simply import it via `macros::*`.
```rust
use macros::my_macro;
```

Note that macros is only available to inside the package (i.e. bin, lib, examples...). This means that one would have to reexport the macros in `lib.rs` in order for users of a library to use it. It would still be available in `main.rs`, `tests`, `examples`, etc, though.

## An example
Suppose you are developing a library that would have normal functions as well as proc macros. The file structure would look like this:
```
My-Amazing-Library
|---proc-macro
| |---lib.rs
|---src
| |---lib.rs
|---cargo.toml
```
`proc-macro/lib.rs` defines macros, which will be made available to `src/lib.rs`. `src/lib.rs` can use the macros defined, and reexport the macros to make it available to anyone using the library.

Now, to make the macros available, reexport them, and if you want gate a macro behind a feature flag, it would be like how you would normally also, with cfg:
```rust
// in src/lib.rs
#[cfg(feature = "my_feature")]
pub use proc_macro::a_niche_macro;
pub use proc_macro::a_common_macro; // (not gated)
```

Finally, testing is also how you would expect it. It would be made available to the `tests` directory. ([importing])

# Reference-level explanation
[reference-level-explanation]: #reference-level-explanation

The package targets would be compiled in the following order:
1. `build`
2. `proc-macro`
3. `lib`
4. `bin`s
5. ...

The macros would be available to all targets built afterwards. Exports of `proc-macro` is only available inside the package, so any publicly available ones need to be reexported in `lib`.

Any libraries to be linked, as specified in `build.rs` via stdout, are not to be available to `proc-macro`. In addition, linker arguments can be passed through `cargo::rustc-link-arg-proc-macro=FLAG` via stdout of `build.rs`.

Any artifacts created during compilation are to be in `target/_profile_/deps`, as usual. The compiled macros crate would be passed into rustc with `--extern=proc_macro=target/_profile_/deps/lib_____` when compiling the other crates. Finally, the compiled lib_____ would be put in `target/proc-macro/`, along with its `.d` file.

## Cfg and Environment Variables
During compilation, it would set the `proc_macro` cfg variable (i.e. `assert!(cfg!(proc_macro))` would be ok in the `proc-macro` crate).

As well as those it, the following environment variables are set. For conciseness, this RFC will not attempt to outline the use of all environment variables. Refer to the [documentation](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates).
- `CARGO`
- `CARGO_MANIFEST_DIR`
- `CARGO_MANIFEST_PATH`
- `CARGO_PKG_VERSION`
- `CARGO_PKG_VERSION_MAJOR`
- `CARGO_PKG_VERSION_MINOR`
- `CARGO_PKG_VERSION_PATCH`
- `CARGO_PKG_VERSION_PRE`
- `CARGO_PKG_AUTHORS`
- `CARGO_PKG_NAME`
- `CARGO_PKG_DESCRIPTION`
- `CARGO_PKG_HOMEPAGE`
- `CARGO_PKG_REPOSITORY`
- `CARGO_PKG_LICENSE`
- `CARGO_PKG_LICENSE_FILE`
- `CARGO_PKG_RUST_VERSION`
- `CARGO_PKG_README`
- `OUT_DIR`
- `CARGO_PRIMARY_PACKAGE`

## Cargo.toml configs
Libraries like `syn`, `quote`, and `proc-macro2`, would be included under `[build-dependecies]` in the cargo.toml. (Perhaps we should put it in a new dependency section for proc macros?)

Like `tests` or `lib`, this would have its own `[proc-macro]` section in cargo.toml.

Here are all the options available under it, the values set are its default.
```toml
[proc-macro]
name = "macros"
path = "proc-macro/lib.rs"
test = true
doctest = true
bench = false
doc = true
proc-macro = true # (cannot be changed)
```

To disable automatic finding, use:
```toml
[package]
autoprocmacro = false
```

## Cargo CLI Additions
- `cargo build --proc-macro` – Compile `proc-macro` only
- `cargo build --all-targets` – Equivalent to specifying `--lib --bins --tests --benches --examples --proc-macro`
- `cargo test --proc-macro` – Test `proc-macro` only

## Documentation

There would be a new item listed under "Crates" of the sidebar, for the new crate. This shoul

# Drawbacks
[drawbacks]: #drawbacks

1. Added complexity - Somewhat increases maintainance cost of cargo
2. Migrations - Existing crates now need to migrate to the new system, taking time, and it may cause some exisiting code that's always using the latest version of libraries to break.
3. Build systems that aren't Cargo needs to update to keep up with this feature

# Rationale and alternatives
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like @ogoffart pointed out, this isn't new. It would be good to step through past discussions and compare to where those landed

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you go into the motivation for --macros?

This is an ineresting one because build scripts do not have a --build-script but we do have --lib and --bins. What makes this fall into one camp or the other?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's because when one types cargo build, the build script is compiled and ran, but the others, including macros, are only compiled.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That doesn't quite make sense to me. We could have a cargo build --build-script and just build it and not run it. Build scripts are not an addressable target / artifact in cargo today but a means to an end. Conceptually, the proc macro crate is also a means to an end but it will have a final artifact.

Whether to have the flag or not can also be affected by whether we support unit tests inside of it (we don't for build scripts) so you can run cargo test --macros.

Note: even if nothing is changed from this, this fleshes out the rationale and should be included / summarized in the RFC.

Side note: whats interesting is we're working on moving build scripts out into their own packages while this does the opposite for proc macros. I think the use cases are different enough that one does not affect the other but kind of interesting to observe.

Copy link
Contributor

@epage epage Jun 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should talk through naming

  • --macros flag
  • extern crate macros;
  • [proc-macro]
  • proc-macro/lib.rs

Why aren't we consistent? Why have the name in one direction or the other?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's true. Do we prefer proc-macro or macros? The first is more explicit but the second is shorter. I guess the second one could create some confusion on whether or not it's procedural or declarative, but that might not be that big of a problem. What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would lean towards proc-macro as that is already what we stabilized, see https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a discussion under the Rationale and Alternatives that speaks to what was considered for naming and why the current option was chosen?

[rationale-and-alternatives]: #rationale-and-alternatives

1. Use `crate::proc_macro::*` as the import path

This would require changes to rustc, when there is a simpler solution.

2. Have it within `src/proc-macro.rs`

The problem with this is the confusion it creates for users. Someone looking through `src/` aren't able to see which files are part of the library, or part of proc macro. In addition, having it within the same directory have led some users, like with `lib.rs` and `main.rs`, to use `mod` for importing when they meant `use` from the library.

3. Eliminate the need for new proc macro files/folders entirely, have the compiler work out where the proc macros are and separate them.

This would suffer from the same issue as the last alternative, plus being harder to implement.

4. Introspection

Harder to implement, with less payoff relative to the amount of work required.

# Prior art
[prior-art]: #prior-art

1. Zig comptime: metaprogramming code can sit directly next to application code.
2. Declarative macros: can sit side by side as well, but is less powerful.
3. Lisp macros: same as last two, except more powerful.
4. `tests` directory, and `build.rs`: compiled at a different time as the main code.
5. `Makefiles`, or other build systems: they allow for customisability for when code is built.

# Unresolved questions
[unresolved-questions]: #unresolved-questions

1. Should proc macro dependencies be listed under `[build-dependencies]`, or a new `[proc-macro-dependencies]` section?
2. What case should `proc-macro/` be? No spaces, kebab case, or snake? Having no spaces would be the most agnostic solution
2. ~~Should we import like `crate::proc_macro::file::macro`, or via a new keyword, like `crate_macros::file::macro`? The latter would avoid name collisions, but might be more confusing.~~

# Future possibilities
[future-possibilities]: #future-possibilities

1. As described in the [motivation] section, this proposal is aimed to make the process of creating proc macros easier. So a natural extension of this is to remove the need of third-party libraries like syn and proc-macro2. There is already an effort to implement quote, so they might be a possibility.

2. This might enable for some sort of `$crate` metavariable.