2014-10-12 01:05:54 +00: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.
|
2013-08-01 13:03:03 +00:00
|
|
|
|
2019-02-04 12:49:54 +00:00
|
|
|
use crate::errors::DiagnosticBuilder;
|
|
|
|
|
2018-12-04 19:10:32 +00:00
|
|
|
use syntax::ast;
|
2019-02-04 12:49:54 +00:00
|
|
|
use syntax::ext::base::{self, *};
|
2015-12-10 14:23:14 +00:00
|
|
|
use syntax::ext::build::AstBuilder;
|
|
|
|
use syntax::attr;
|
2016-06-20 15:49:33 +00:00
|
|
|
use syntax::tokenstream;
|
2015-12-10 14:23:14 +00:00
|
|
|
use syntax::parse::token;
|
2016-06-21 22:08:13 +00:00
|
|
|
use syntax_pos::Span;
|
2013-08-01 13:03:03 +00:00
|
|
|
|
2019-02-04 12:49:54 +00:00
|
|
|
pub fn expand_cfg<'cx>(cx: &mut ExtCtxt<'_>,
|
2014-08-28 01:46:52 +00:00
|
|
|
sp: Span,
|
2016-06-20 15:49:33 +00:00
|
|
|
tts: &[tokenstream::TokenTree])
|
2018-07-12 09:58:16 +00:00
|
|
|
-> Box<dyn base::MacResult + 'static> {
|
2018-03-18 20:51:53 +00:00
|
|
|
let sp = sp.apply_mark(cx.current_expansion.mark);
|
2018-12-04 19:10:32 +00:00
|
|
|
|
|
|
|
match parse_cfg(cx, sp, tts) {
|
|
|
|
Ok(cfg) => {
|
|
|
|
let matches_cfg = attr::cfg_matches(&cfg, cx.parse_sess, cx.ecfg.features);
|
|
|
|
MacEager::expr(cx.expr_bool(sp, matches_cfg))
|
|
|
|
}
|
|
|
|
Err(mut err) => {
|
|
|
|
err.emit();
|
|
|
|
DummyResult::expr(sp)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_cfg<'a>(
|
|
|
|
cx: &mut ExtCtxt<'a>,
|
|
|
|
sp: Span,
|
|
|
|
tts: &[tokenstream::TokenTree],
|
|
|
|
) -> Result<ast::MetaItem, DiagnosticBuilder<'a>> {
|
2014-07-03 09:42:24 +00:00
|
|
|
let mut p = cx.new_parser_from_tts(tts);
|
2018-12-04 19:10:32 +00: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 13:03:03 +00:00
|
|
|
|
2018-02-07 14:32:26 +00:00
|
|
|
let _ = p.eat(&token::Comma);
|
|
|
|
|
2015-12-30 23:11:53 +00:00
|
|
|
if !p.eat(&token::Eof) {
|
2018-12-04 19:10:32 +00:00
|
|
|
return Err(cx.struct_span_err(sp, "expected 1 cfg-pattern"));
|
2014-09-25 03:22:57 +00:00
|
|
|
}
|
|
|
|
|
2018-12-04 19:10:32 +00:00
|
|
|
Ok(cfg)
|
2013-08-01 13:03:03 +00:00
|
|
|
}
|