Get compiler version/edition from proc macro?

I’m writing a custom derive that uses some standard but ugly hacks to avoid namespace collisions. However, those hacks are unnecessary in the 2018 edition. Is it possible, either from the proc macro or using #[cfg(...)] or something like that, to detect a) the compiler version and/or, b) the edition being used to compile the current crate so that I can do the nice thing for 2018?

If the proc macro crate itself has 2018 edition, then in most cases you should be able to simply use 2018 edition techniques in the macro, it will be usable on 2015 edition anyway due to edition hygiene.

Indeed, “edition hygiene” should solve all cases of this that are unique to proc macros.

For other cases, see: RFC: #[cfg(accessible(…) / version(…))]

Does this include code generated by a proc macro? E.g., let’s say I have a proc macro defined in a crate with edition 2018, and it’s consumed by a crate with edition 2015. Is the compiler smart enough to parse the code generated by the proc macro as 2018 even though the surrounding code is 2015?

I’m almost certain this is the case for declarative macros, and I don’t know of any reason it wouldn’t be true of proc macros, but someone else would have to confirm.

OK, cool! cc @dtolnay who’s been helping me with this, and would likely know for sure.

I have relied on edition hygiene in proc macros in the case of 2015 macros invoked from 2018 crates, since serde_derive emits code containing try as an identifier. I haven’t used it for paths / extern crate related code in 2018 macros invoked from 2015 crates. Hopefully that works! Try it out.

If it doesn’t work, please report, it generally means a bug.
(Or a rare case of edition being set globally rather than per-span, like for NLL.)

Cool, thanks folks! Seems to work so far, albeit not with a huge amount of testing.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.