]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_builtin_macros/src/cfg.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_builtin_macros / src / cfg.rs
CommitLineData
dfeec247
XL
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.
9fa01778 4
3dfed10e 5use rustc_ast as ast;
74b04a01
XL
6use rustc_ast::token;
7use rustc_ast::tokenstream::TokenStream;
8use rustc_attr as attr;
5e7ed085 9use rustc_errors::PResult;
dfeec247 10use rustc_expand::base::{self, *};
923072b8 11use rustc_macros::SessionDiagnostic;
dfeec247 12use rustc_span::Span;
1a4d82fc 13
dc9dc135
XL
14pub fn expand_cfg(
15 cx: &mut ExtCtxt<'_>,
16 sp: Span,
e1599b0c 17 tts: TokenStream,
dc9dc135 18) -> Box<dyn base::MacResult + 'static> {
e1599b0c 19 let sp = cx.with_def_site_ctxt(sp);
0731742a
XL
20
21 match parse_cfg(cx, sp, tts) {
22 Ok(cfg) => {
5e7ed085
FG
23 let matches_cfg = attr::cfg_matches(
24 &cfg,
25 &cx.sess.parse_sess,
26 cx.current_expansion.lint_node_id,
27 cx.ecfg.features,
28 );
0731742a
XL
29 MacEager::expr(cx.expr_bool(sp, matches_cfg))
30 }
31 Err(mut err) => {
32 err.emit();
e1599b0c 33 DummyResult::any(sp)
0731742a
XL
34 }
35 }
36}
37
923072b8
FG
38#[derive(SessionDiagnostic)]
39#[error(slug = "builtin-macros-requires-cfg-pattern")]
40struct RequiresCfgPattern {
41 #[primary_span]
42 #[label]
43 span: Span,
44}
45
46#[derive(SessionDiagnostic)]
47#[error(slug = "builtin-macros-expected-one-cfg-pattern")]
48struct OneCfgPattern {
49 #[primary_span]
50 span: Span,
51}
52
53fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<'a, ast::MetaItem> {
1a4d82fc 54 let mut p = cx.new_parser_from_tts(tts);
0731742a
XL
55
56 if p.token == token::Eof {
923072b8 57 return Err(cx.create_err(RequiresCfgPattern { span }));
0731742a
XL
58 }
59
60 let cfg = p.parse_meta_item()?;
1a4d82fc 61
0531ce1d
XL
62 let _ = p.eat(&token::Comma);
63
9cc50fc6 64 if !p.eat(&token::Eof) {
923072b8 65 return Err(cx.create_err(OneCfgPattern { span }));
1a4d82fc
JJ
66 }
67
0731742a 68 Ok(cfg)
1a4d82fc 69}