rustc_builtin_macros/
cfg.rs1use 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::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 )
48 .map_err(|diag| diag.emit())?;
49 let cfg = AttributeParser::parse_single_args(
50 cx.sess,
51 span,
52 span,
53 AttrStyle::Inner,
54 AttrPath { segments: <[_]>::into_vec(::alloc::boxed::box_new([sym::cfg]))vec![sym::cfg].into_boxed_slice(), span },
55 None,
56 ParsedDescription::Macro,
57 span,
58 cx.current_expansion.lint_node_id,
59 Target::Crate,
61 Some(cx.ecfg.features),
62 ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
63 &meta,
64 parse_cfg_entry,
65 &CFG_TEMPLATE,
66 )?;
67
68 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));
69
70 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)) {
71 return Err(cx.dcx().emit_err(errors::OneCfgPattern { span }));
72 }
73
74 Ok(cfg)
75}