2020-01-09 11:18:47 +01:00
|
|
|
//! The compiler code necessary to support the cfg! extension, which expands to
|
|
|
|
//! a literal `true` or `false` based on whether the given cfg matches the
|
|
|
|
//! current compilation environment.
|
2019-02-04 21:49:54 +09:00
|
|
|
|
2020-04-27 23:26:11 +05:30
|
|
|
use rustc_ast as ast;
|
2020-02-29 20:37:32 +03:00
|
|
|
use rustc_ast::token;
|
|
|
|
use rustc_ast::tokenstream::TokenStream;
|
2020-01-11 13:15:20 +01:00
|
|
|
use rustc_attr as attr;
|
2022-01-27 09:44:25 +00:00
|
|
|
use rustc_errors::PResult;
|
2019-12-29 17:23:55 +03:00
|
|
|
use rustc_expand::base::{self, *};
|
2019-12-31 20:15:40 +03:00
|
|
|
use rustc_span::Span;
|
2013-08-01 23:03:03 +10:00
|
|
|
|
2019-06-11 13:20:33 +03:00
|
|
|
pub fn expand_cfg(
|
|
|
|
cx: &mut ExtCtxt<'_>,
|
|
|
|
sp: Span,
|
2019-08-31 20:08:06 +03:00
|
|
|
tts: TokenStream,
|
2019-06-11 13:20:33 +03:00
|
|
|
) -> Box<dyn base::MacResult + 'static> {
|
2019-09-14 21:17:11 +01:00
|
|
|
let sp = cx.with_def_site_ctxt(sp);
|
2018-12-04 14:10:32 -05:00
|
|
|
|
|
|
|
match parse_cfg(cx, sp, tts) {
|
|
|
|
Ok(cfg) => {
|
2022-02-27 22:26:24 +01:00
|
|
|
let matches_cfg = attr::cfg_matches(
|
|
|
|
&cfg,
|
|
|
|
&cx.sess.parse_sess,
|
|
|
|
cx.current_expansion.lint_node_id,
|
|
|
|
cx.ecfg.features,
|
|
|
|
);
|
2018-12-04 14:10:32 -05:00
|
|
|
MacEager::expr(cx.expr_bool(sp, matches_cfg))
|
|
|
|
}
|
|
|
|
Err(mut err) => {
|
|
|
|
err.emit();
|
2019-08-13 20:51:54 +03:00
|
|
|
DummyResult::any(sp)
|
2018-12-04 14:10:32 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-27 09:44:25 +00:00
|
|
|
fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a, ast::MetaItem> {
|
2014-07-03 11:42:24 +02:00
|
|
|
let mut p = cx.new_parser_from_tts(tts);
|
2018-12-04 14:10:32 -05:00
|
|
|
|
|
|
|
if p.token == token::Eof {
|
|
|
|
let mut err = cx.struct_span_err(sp, "macro requires a cfg-pattern as an argument");
|
|
|
|
err.span_label(sp, "cfg-pattern required");
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
let cfg = p.parse_meta_item()?;
|
2013-08-01 23:03:03 +10:00
|
|
|
|
2018-02-07 09:32:26 -05:00
|
|
|
let _ = p.eat(&token::Comma);
|
|
|
|
|
2015-12-31 12:11:53 +13:00
|
|
|
if !p.eat(&token::Eof) {
|
2018-12-04 14:10:32 -05:00
|
|
|
return Err(cx.struct_span_err(sp, "expected 1 cfg-pattern"));
|
2014-09-24 20:22:57 -07:00
|
|
|
}
|
|
|
|
|
2018-12-04 14:10:32 -05:00
|
|
|
Ok(cfg)
|
2013-08-01 23:03:03 +10:00
|
|
|
}
|