]>
Commit | Line | Data |
---|---|---|
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 | 5 | use rustc_ast as ast; |
74b04a01 XL |
6 | use rustc_ast::token; |
7 | use rustc_ast::tokenstream::TokenStream; | |
8 | use rustc_attr as attr; | |
5e7ed085 | 9 | use rustc_errors::PResult; |
dfeec247 | 10 | use rustc_expand::base::{self, *}; |
923072b8 | 11 | use rustc_macros::SessionDiagnostic; |
dfeec247 | 12 | use rustc_span::Span; |
1a4d82fc | 13 | |
dc9dc135 XL |
14 | pub 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 | 38 | #[derive(SessionDiagnostic)] |
f2b60f7d | 39 | #[diag(builtin_macros::requires_cfg_pattern)] |
923072b8 FG |
40 | struct RequiresCfgPattern { |
41 | #[primary_span] | |
42 | #[label] | |
43 | span: Span, | |
44 | } | |
45 | ||
46 | #[derive(SessionDiagnostic)] | |
f2b60f7d | 47 | #[diag(builtin_macros::expected_one_cfg_pattern)] |
923072b8 FG |
48 | struct OneCfgPattern { |
49 | #[primary_span] | |
50 | span: Span, | |
51 | } | |
52 | ||
53 | fn 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 | } |