rustc_builtin_macros/
cfg.rs

1//! The compiler code necessary to support the cfg! extension, which expands to
2//! a literal `true` or `false` based on whether the given cfg matches the
3//! current compilation environment.
4
5use rustc_ast::tokenstream::TokenStream;
6use rustc_ast::{AttrStyle, token};
7use rustc_attr_parsing as attr;
8use rustc_attr_parsing::parser::MetaItemOrLitParser;
9use rustc_attr_parsing::{
10    AttributeParser, CFG_TEMPLATE, ParsedDescription, ShouldEmit, parse_cfg_entry,
11};
12use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
13use rustc_hir::AttrPath;
14use rustc_hir::attrs::CfgEntry;
15use rustc_parse::exp;
16use rustc_span::{ErrorGuaranteed, Ident, Span};
17
18use crate::errors;
19
20pub(crate) fn expand_cfg(
21    cx: &mut ExtCtxt<'_>,
22    sp: Span,
23    tts: TokenStream,
24) -> MacroExpanderResult<'static> {
25    let sp = cx.with_def_site_ctxt(sp);
26
27    ExpandResult::Ready(match parse_cfg(cx, sp, tts) {
28        Ok(cfg) => {
29            let matches_cfg = attr::eval_config_entry(cx.sess, &cfg).as_bool();
30
31            MacEager::expr(cx.expr_bool(sp, matches_cfg))
32        }
33        Err(guar) => DummyResult::any(sp, guar),
34    })
35}
36
37fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result<CfgEntry, ErrorGuaranteed> {
38    let mut parser = cx.new_parser_from_tts(tts);
39    if parser.token == token::Eof {
40        return Err(cx.dcx().emit_err(errors::RequiresCfgPattern { span }));
41    }
42
43    let meta = MetaItemOrLitParser::parse_single(&mut parser, ShouldEmit::ErrorsAndLints)
44        .map_err(|diag| diag.emit())?;
45    let cfg = AttributeParser::parse_single_args(
46        cx.sess,
47        span,
48        span,
49        AttrStyle::Inner,
50        AttrPath { segments: vec![Ident::from_str("cfg")].into_boxed_slice(), span },
51        None,
52        ParsedDescription::Macro,
53        span,
54        cx.current_expansion.lint_node_id,
55        Some(cx.ecfg.features),
56        ShouldEmit::ErrorsAndLints,
57        &meta,
58        parse_cfg_entry,
59        &CFG_TEMPLATE,
60    )?;
61
62    let _ = parser.eat(exp!(Comma));
63
64    if !parser.eat(exp!(Eof)) {
65        return Err(cx.dcx().emit_err(errors::OneCfgPattern { span }));
66    }
67
68    Ok(cfg)
69}