rustc_builtin_macros/
cfg.rs1use 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, CFG_TEMPLATE, ParsedDescription, ShouldEmit, parse_cfg_entry,
10};
11use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
12use rustc_hir::attrs::CfgEntry;
13use rustc_hir::{AttrPath, Target};
14use rustc_parse::exp;
15use rustc_parse::parser::Recovery;
16use rustc_span::{ErrorGuaranteed, Span, sym};
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(
44 &mut parser,
45 ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
46 AllowExprMetavar::Yes,
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: ::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 },
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}