]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/cfg.rs
Add missing lifetime specifier
[rust.git] / src / libsyntax_ext / cfg.rs
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.
4
5 use errors::DiagnosticBuilder;
6
7 use syntax::ast;
8 use syntax::ext::base::{self, *};
9 use syntax::ext::build::AstBuilder;
10 use syntax::attr;
11 use syntax::tokenstream;
12 use syntax::parse::token;
13 use syntax_pos::Span;
14
15 pub fn expand_cfg(
16     cx: &mut ExtCtxt<'_>,
17     sp: Span,
18     tts: &[tokenstream::TokenTree],
19 ) -> Box<dyn base::MacResult + 'static> {
20     let sp = sp.apply_mark(cx.current_expansion.mark);
21
22     match parse_cfg(cx, sp, tts) {
23         Ok(cfg) => {
24             let matches_cfg = attr::cfg_matches(&cfg, cx.parse_sess, cx.ecfg.features);
25             MacEager::expr(cx.expr_bool(sp, matches_cfg))
26         }
27         Err(mut err) => {
28             err.emit();
29             DummyResult::expr(sp)
30         }
31     }
32 }
33
34 fn parse_cfg<'a>(
35     cx: &mut ExtCtxt<'a>,
36     sp: Span,
37     tts: &[tokenstream::TokenTree],
38 ) -> Result<ast::MetaItem, DiagnosticBuilder<'a>> {
39     let mut p = cx.new_parser_from_tts(tts);
40
41     if p.token == token::Eof {
42         let mut err = cx.struct_span_err(sp, "macro requires a cfg-pattern as an argument");
43         err.span_label(sp, "cfg-pattern required");
44         return Err(err);
45     }
46
47     let cfg = p.parse_meta_item()?;
48
49     let _ = p.eat(&token::Comma);
50
51     if !p.eat(&token::Eof) {
52         return Err(cx.struct_span_err(sp, "expected 1 cfg-pattern"));
53     }
54
55     Ok(cfg)
56 }