Configuring proc macros from a crate?

Say I have crates A, B, C, and P. Crate P is a proc macro crate that reads a YAML file and uses info from it to generate code for various proc macros used in crates A, B, and C. The same YAML file is used for all three downstream crates, and there many usages of P's macros across the three downstream crates.

Somehow, I need P to know the location of the YAML file to read when compiling, and I'd like to repeat myself as little as possible. Mainly, I'd like to avoid having to specify that path in every macro I use from P in A, B, or C.

Are there any user-friendly ways to specify the path to the YAML file for P from A, B, and/or C? Without much thinking, the two naive options I have are:

  • Hardcode the path into P (this definitely won't work if I want to release the crate)
  • Include the path as the first parameter in every macro that P offers (this is very repetitive and noisy)

I've played around with setting an environment variable, but I don't know of a good way to do this that is user-friendly and also works properly with cargo check, rust-analyzer in VSCode, and IntelliJ Rust (I don't want the user of the crate to have to set an environment variable in a bunch of different places).

Any ideas on how to do this in a nice way? Thank you!

I'm not sure it's a good idea, but you could export a macro from P that takes the path, and expands to a bunch of macro_rules macros that call their respective P macro with the path filled in.

1 Like

In P's proc_macro definition, you can check std::env::var("CARGO_MANIFEST_DIR") to locate the downstream crate. Suppose it is A.

In A's Cargo.toml:

[package.metadata]
yaml_path="/the/yaml/path/for/A"

Then use crate toml to parse the metadata section.

Q.E.D.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.