How can the compilation properties be determined in a procedural macro?
Asked Answered
M

0

5

I'm working on a procedural macro that does a lot of work that can slow down compilation considerably. The work done does not effect the semantics of the function; that is, if given the same set of arguments, the returned value is does not change depending on whether the macro is applied.

In an effort to make the edit-comp-test loop quicker, I would like to make the macro a no-op depending on conditions that relate to how the crate is being compiled. I would like to be able to determine two properties in particular:

  1. Why the macro is being executed: Build/Run, Documentation, Testing
  2. Whether the macro being executed for optimized builds.

Cargo exposes the optimization level to build scripts (through environment variables OPT_LEVEL and PROFILE) but does not expose the mode (Build, Documentation, ..). However, none of this information seems to be exposed to procedural macros at all.

Missy answered 21/5, 2019 at 6:1 Comment(3)
For what it's worth, you can write a build script that makes the values of the environment variables available during compilation, either with rustc-env=VAR=VALUE or with rustc-cfg=FEATURE. See the documentation on build scripts for more details.Moneyer
@SvenMarnach Tunneling build script variables by redefining them is something that I had completely overlooked. Thank you for mentioning it. Tunneling env vars solves problem 2 but doesn't solve problem 1 unfortunately. Since it's still helpful, please feel free to post it as a partial answer and I'll gladly upvote it.Missy
@SvenMarnach I have another open question where your solution would be an acceptable answer, so please also feel free to post an answer there so I can accept it. See #56215963Missy

© 2022 - 2024 — McMap. All rights reserved.