Skip to main content

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::parser::{AllowExprMetavar, MetaItemOrLitParser};
8use rustc_attr_parsing::{
9    self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, ParsedDescription, ShouldEmit,
10    parse_cfg_entry,
11};
12use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
13use rustc_hir::attrs::CfgEntry;
14use rustc_hir::{AttrPath, Target};
15use rustc_parse::exp;
16use rustc_parse::parser::Recovery;
17use rustc_span::{ErrorGuaranteed, Span, sym};
18
19use crate::errors;
20
21pub(crate) fn expand_cfg(
22    cx: &mut ExtCtxt<'_>,
23    sp: Span,
24    tts: TokenStream,
25) -> MacroExpanderResult<'static> {
26    let sp = cx.with_def_site_ctxt(sp);
27
28    ExpandResult::Ready(match parse_cfg(cx, sp, tts) {
29        Ok(cfg) => {
30            let matches_cfg = attr::eval_config_entry(cx.sess, &cfg).as_bool();
31
32            MacEager::expr(cx.expr_bool(sp, matches_cfg))
33        }
34        Err(guar) => DummyResult::any(sp, guar),
35    })
36}
37
38fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result<CfgEntry, ErrorGuaranteed> {
39    let mut parser = cx.new_parser_from_tts(tts);
40    if parser.token == token::Eof {
41        return Err(cx.dcx().emit_err(errors::RequiresCfgPattern { span }));
42    }
43
44    let meta = MetaItemOrLitParser::parse_single(
45        &mut parser,
46        ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
47        AllowExprMetavar::Yes,
48    )
49    .map_err(|diag| diag.emit())?;
50    let cfg = AttributeParser::parse_single_args(
51        cx.sess,
52        span,
53        span,
54        AttrStyle::Inner,
55        AttrPath { segments: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::cfg]))vec![sym::cfg].into_boxed_slice(), span },
56        None,
57        AttributeSafety::Normal,
58        ParsedDescription::Macro,
59        span,
60        cx.current_expansion.lint_node_id,
61        // Doesn't matter what the target actually is here.
62        Target::Crate,
63        Some(cx.ecfg.features),
64        ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
65        &meta,
66        parse_cfg_entry,
67        &CFG_TEMPLATE,
68    )?;
69
70    let _ = parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma));
71
72    if !parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eof,
    token_type: ::rustc_parse::parser::token_type::TokenType::Eof,
}exp!(Eof)) {
73        return Err(cx.dcx().emit_err(errors::OneCfgPattern { span }));
74    }
75
76    Ok(cfg)
77}