Skip to main content

rustfmt_nightly/parse/macros/
cfg_if.rs

1use std::panic::{AssertUnwindSafe, catch_unwind};
2
3use rustc_ast::ast;
4use rustc_ast::token::TokenKind;
5use rustc_parse::exp;
6use rustc_parse::parser::{AllowConstBlockItems, ForceCollect};
7use rustc_span::symbol::kw;
8
9use crate::parse::macros::build_stream_parser;
10use crate::parse::session::ParseSess;
11
12pub(crate) fn parse_cfg_if<'a>(
13    psess: &'a ParseSess,
14    mac: &'a ast::MacCall,
15) -> Result<Vec<ast::Item>, &'static str> {
16    let result = catch_unwind(AssertUnwindSafe(|| parse_cfg_if_inner(psess, mac)));
17    let dcx = psess.inner().dcx();
18    let recovered = dcx.has_errors().is_some();
19    dcx.reset_err_count();
20    match result {
21        Ok(Ok(_)) if recovered => Err("cfg_if! parsed with recovery"),
22        Ok(res) => res,
23        Err(..) => Err("failed to parse cfg_if!"),
24    }
25}
26
27fn parse_cfg_if_inner<'a>(
28    psess: &'a ParseSess,
29    mac: &'a ast::MacCall,
30) -> Result<Vec<ast::Item>, &'static str> {
31    let ts = mac.args.tokens.clone();
32    let mut parser = build_stream_parser(psess.inner(), ts);
33
34    let mut items = vec![];
35    let mut process_if_cfg = true;
36
37    while parser.token.kind != TokenKind::Eof {
38        if process_if_cfg {
39            if !parser.eat_keyword(exp!(If)) {
40                return Err("Expected `if`");
41            }
42
43            if !matches!(parser.token.kind, TokenKind::Pound) {
44                return Err("Failed to parse attributes");
45            }
46
47            // Inner attributes are not actually syntactically permitted here, but we don't
48            // care about inner vs outer attributes in this position. Our purpose with this
49            // special case parsing of cfg_if macros is to ensure we can correctly resolve
50            // imported modules that may have a custom `path` defined.
51            //
52            // As such, we just need to advance the parser past the attribute and up to
53            // to the opening brace.
54            // See also https://github.com/rust-lang/rust/pull/79433
55            parser
56                .parse_attribute(rustc_parse::parser::attr::InnerAttrPolicy::Permitted)
57                .map_err(|e| {
58                    e.cancel();
59                    "Failed to parse attributes"
60                })?;
61        }
62
63        if !parser.eat(exp!(OpenBrace)) {
64            return Err("Expected an opening brace");
65        }
66
67        while parser.token != TokenKind::CloseBrace && parser.token.kind != TokenKind::Eof {
68            let item = match parser.parse_item(ForceCollect::No, AllowConstBlockItems::Yes) {
69                Ok(Some(item_ptr)) => *item_ptr,
70                Ok(None) => continue,
71                Err(err) => {
72                    err.cancel();
73                    parser.psess.dcx().reset_err_count();
74                    return Err(
75                        "Expected item inside cfg_if block, but failed to parse it as an item",
76                    );
77                }
78            };
79            if let ast::ItemKind::Mod(..) = item.kind {
80                items.push(item);
81            }
82        }
83
84        if !parser.eat(exp!(CloseBrace)) {
85            return Err("Expected a closing brace");
86        }
87
88        if parser.eat(exp!(Eof)) {
89            break;
90        }
91
92        if !parser.eat_keyword(exp!(Else)) {
93            return Err("Expected `else`");
94        }
95
96        process_if_cfg = parser.token.is_keyword(kw::If);
97    }
98
99    Ok(items)
100}