]>
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 XL |
10 | use rustc_expand::base::{self, *}; |
11 | use rustc_span::Span; | |
1a4d82fc | 12 | |
dc9dc135 XL |
13 | pub fn expand_cfg( |
14 | cx: &mut ExtCtxt<'_>, | |
15 | sp: Span, | |
e1599b0c | 16 | tts: TokenStream, |
dc9dc135 | 17 | ) -> Box<dyn base::MacResult + 'static> { |
e1599b0c | 18 | let sp = cx.with_def_site_ctxt(sp); |
0731742a XL |
19 | |
20 | match parse_cfg(cx, sp, tts) { | |
21 | Ok(cfg) => { | |
5e7ed085 FG |
22 | let matches_cfg = attr::cfg_matches( |
23 | &cfg, | |
24 | &cx.sess.parse_sess, | |
25 | cx.current_expansion.lint_node_id, | |
26 | cx.ecfg.features, | |
27 | ); | |
0731742a XL |
28 | MacEager::expr(cx.expr_bool(sp, matches_cfg)) |
29 | } | |
30 | Err(mut err) => { | |
31 | err.emit(); | |
e1599b0c | 32 | DummyResult::any(sp) |
0731742a XL |
33 | } |
34 | } | |
35 | } | |
36 | ||
5e7ed085 | 37 | fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a, ast::MetaItem> { |
1a4d82fc | 38 | let mut p = cx.new_parser_from_tts(tts); |
0731742a XL |
39 | |
40 | if p.token == token::Eof { | |
41 | let mut err = cx.struct_span_err(sp, "macro requires a cfg-pattern as an argument"); | |
42 | err.span_label(sp, "cfg-pattern required"); | |
43 | return Err(err); | |
44 | } | |
45 | ||
46 | let cfg = p.parse_meta_item()?; | |
1a4d82fc | 47 | |
0531ce1d XL |
48 | let _ = p.eat(&token::Comma); |
49 | ||
9cc50fc6 | 50 | if !p.eat(&token::Eof) { |
0731742a | 51 | return Err(cx.struct_span_err(sp, "expected 1 cfg-pattern")); |
1a4d82fc JJ |
52 | } |
53 | ||
0731742a | 54 | Ok(cfg) |
1a4d82fc | 55 | } |