问题
I'm working on a procedural macro that needs a place to store state on the system where it is run. The state should be cleaned up when cargo clean
is run.
In the past, I've assumed that the target
directory is the proper place. However, my assumption is likely incorrect because:
- my files and directories may conflict with those of
rustc
andcargo
. - the location of the target directory can change from the default.
In an effort to avoid these issues, I've been attempting to determine a way to locate a location properly but haven't been successful. The closest I've found is the environment variable OUT_DIR
that Cargo sets for build scripts which, unfortunately, isn't set for procedural macro runs.
Note that this question is not a duplicate of Is it possible to store state within Rust's procedural macros?. That question covers procedural macro state in general while this question is about determining a suitable location within a crate's file structure.
回答1:
It appears that the best place for storing temporary files (that both persist across compilation runs and also get cleaned up by Cargo) is to smuggle the location of the temporary directory Cargo sets up for build scripts (OUT_DIR
) to the rest of your compilation environment.
One thing to keep in mind that the same directory will be used by any crate that uses your macros. Make sure to design your macro so that multiple concurrent instances of the macro can use the same directory at the same time without conflict.
Solution in steps:
Place the following line in the build script of your procedural macro crate:
println!("cargo:rustc-env=PROC_ARTIFACT_DIR={}", std::env::var("OUT_DIR").unwrap())
Use
env!("PROC_ARTIFACT_DIR")
in your procedural macros to get the path to the state directory.
Note that this is only a workaround until Cargo provides native support for temp directories for procedural macro crates. Full credit for this method goes to @sven-marnach.
来源:https://stackoverflow.com/questions/56215463/what-is-a-suitable-place-to-store-procedural-macro-artifacts-so-that-they-are-cl