From c1c5c2628344ddde8062e561da36586729caa7a0 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 5 Dec 2021 18:50:52 -0800 Subject: [PATCH] Add rustversion::cfg! macro --- build/build.rs | 8 +++++++- src/lib.rs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/build/build.rs b/build/build.rs index 1531251..798edc1 100644 --- a/build/build.rs +++ b/build/build.rs @@ -36,7 +36,7 @@ fn main() { }; let version = match rustc::parse(&string) { - Some(version) => format!("{:#?}\n", version), + Some(version) => version, None => { eprintln!( "Error: unexpected output from `rustc --version`: {:?}\n\n\ @@ -47,6 +47,12 @@ fn main() { } }; + if version.minor < 38 { + // Prior to 1.38, a #[proc_macro] is not allowed to be named `cfg`. + println!("cargo:rustc-cfg=cfg_macro_not_allowed"); + } + + let version = format!("{:#?}\n", version); let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not set"); let out_file = Path::new(&out_dir).join("version.rs"); fs::write(out_file, version).expect("failed to write version.rs"); diff --git a/src/lib.rs b/src/lib.rs index d58804d..d816dc0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -227,3 +227,18 @@ pub fn attr(args: TokenStream, input: TokenStream) -> TokenStream { .and_then(|args| expand::try_attr(args, input)) .unwrap_or_else(Error::into_compile_error) } + +#[cfg(not(cfg_macro_not_allowed))] +#[proc_macro] +pub fn cfg(input: TokenStream) -> TokenStream { + use proc_macro::{Ident, Span, TokenTree}; + (|| { + let ref mut args = iter::new(input); + let expr = expr::parse(args)?; + token::parse_end(args)?; + let boolean = expr.eval(RUSTVERSION); + let ident = Ident::new(&boolean.to_string(), Span::call_site()); + Ok(TokenStream::from(TokenTree::Ident(ident))) + })() + .unwrap_or_else(Error::into_compile_error) +}