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(
30                cx.sess,
31                &cfg,
32                cx.current_expansion.lint_node_id,
33                ShouldEmit::ErrorsAndLints,
34            )
35            .as_bool();
36
37            MacEager::expr(cx.expr_bool(sp, matches_cfg))
38        }
39        Err(guar) => DummyResult::any(sp, guar),
40    })
41}
42
43fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result<CfgEntry, ErrorGuaranteed> {
44    let mut parser = cx.new_parser_from_tts(tts);
45    if parser.token == token::Eof {
46        return Err(cx.dcx().emit_err(errors::RequiresCfgPattern { span }));
47    }
48
49    let meta = MetaItemOrLitParser::parse_single(&mut parser, ShouldEmit::ErrorsAndLints)
50        .map_err(|diag| diag.emit())?;
51    let cfg = AttributeParser::parse_single_args(
52        cx.sess,
53        span,
54        span,
55        AttrStyle::Inner,
56        AttrPath { segments: vec![Ident::from_str("cfg")].into_boxed_slice(), span },
57        ParsedDescription::Macro,
58        span,
59        cx.current_expansion.lint_node_id,
60        Some(cx.ecfg.features),
61        ShouldEmit::ErrorsAndLints,
62        &meta,
63        parse_cfg_entry,
64        &CFG_TEMPLATE,
65    )?;
66
67    let _ = parser.eat(exp!(Comma));
68
69    if !parser.eat(exp!(Eof)) {
70        return Err(cx.dcx().emit_err(errors::OneCfgPattern { span }));
71    }
72
73    Ok(cfg)
74}