Skip to content

Commit

Permalink
Add rustversion::cfg! macro
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Dec 6, 2021
1 parent 29338df commit c1c5c26
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 7 additions & 1 deletion build/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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\
Expand All @@ -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");
Expand Down
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit c1c5c26

Please sign in to comment.