Skip to main content

rustfmt_nightly/parse/macros/
cfg_select.rs

1//! See [`cfg_select!` reference](
2//! https://doc.rust-lang.org/nightly/reference/conditional-compilation.html#the-cfg_select-macro
3//! ) for grammar.
4
5use std::panic::{AssertUnwindSafe, catch_unwind};
6
7use rustc_ast::ast;
8use rustc_ast::token;
9use rustc_ast::token::{Token, TokenKind};
10use rustc_ast::tokenstream::TokenStream;
11use rustc_parse::exp;
12use rustc_parse::parser::{AllowConstBlockItems, ForceCollect};
13use rustc_span::Span;
14use tracing::debug;
15
16use crate::comment::contains_comment;
17use crate::expr::is_unsafe_block;
18use crate::parse::macros::build_stream_parser;
19use crate::parse::session::ParseSess;
20use crate::rewrite::RewriteContext;
21use crate::spanned::Spanned;
22
23// NB: parser recovery can return `Ok(expr)` (or other non-terminals) and still emit errors. We need
24// to properly reset the shared error count.
25
26pub(crate) fn parse_items_from_cfg_select<'a>(
27    psess: &'a ParseSess,
28    mac: &'a ast::MacCall,
29) -> Result<Vec<ast::Item>, &'static str> {
30    let result = catch_unwind(AssertUnwindSafe(|| {
31        parse_items_from_cfg_select_inner(psess, mac)
32    }));
33    let dcx = psess.inner().dcx();
34    let recovered = dcx.has_errors().is_some();
35    dcx.reset_err_count();
36    match result {
37        Ok(Ok(_)) if recovered => Err("cfg_select! parsed with recovery"),
38        Ok(res) => res,
39        Err(..) => Err("failed to parse cfg_select!"),
40    }
41}
42
43fn parse_items_from_cfg_select_inner<'a>(
44    psess: &'a ParseSess,
45    mac: &'a ast::MacCall,
46) -> Result<Vec<ast::Item>, &'static str> {
47    let ts = mac.args.tokens.clone();
48    let mut parser = build_stream_parser(psess.inner(), ts);
49
50    if parser.token == TokenKind::OpenBrace {
51        return Err("Expression position cfg_select! not yet supported");
52    }
53
54    let mut items = vec![];
55
56    while parser.token.kind != TokenKind::Eof {
57        if !parser.eat_keyword(exp!(Underscore)) {
58            parser.parse_attr_item(ForceCollect::No).map_err(|e| {
59                e.cancel();
60                "Failed to parse attr item"
61            })?;
62        }
63
64        if !parser.eat(exp!(FatArrow)) {
65            return Err("Expected a fat arrow");
66        }
67
68        if !parser.eat(exp!(OpenBrace)) {
69            return Err("Expected an opening brace");
70        }
71
72        while parser.token != TokenKind::CloseBrace && parser.token.kind != TokenKind::Eof {
73            let item = match parser
74                .parse_item(ForceCollect::No, AllowConstBlockItems::DoesNotMatter)
75            {
76                Ok(Some(item_ptr)) => *item_ptr,
77                Ok(None) => {
78                    // Advance the parser by at least one token to prevent an infinite loop
79                    parser.bump();
80                    continue;
81                }
82                Err(err) => {
83                    err.cancel();
84                    return Err(
85                        "Expected item inside cfg_select block, but failed to parse it as an item",
86                    );
87                }
88            };
89            if let ast::ItemKind::Mod(..) = item.kind {
90                items.push(item);
91            }
92        }
93
94        if !parser.eat(exp!(CloseBrace)) {
95            return Err("Expected a closing brace");
96        }
97
98        if parser.eat(exp!(Eof)) {
99            break;
100        }
101    }
102
103    Ok(items)
104}
105
106/// LHS predicate of a `cfg_select!` arm.
107pub(crate) enum CfgSelectFormatPredicate {
108    /// Example: the `unix` in `unix => {}`. Notably, outer or inner attributes are not permitted.
109    Cfg(ast::MetaItemInner),
110    /// `_` in `_ => {}`.
111    Wildcard(Span),
112}
113
114impl Spanned for CfgSelectFormatPredicate {
115    fn span(&self) -> rustc_span::Span {
116        match self {
117            Self::Cfg(meta_item_inner) => meta_item_inner.span(),
118            Self::Wildcard(span) => *span,
119        }
120    }
121}
122
123/// Each `$predicate => $production` arm in `cfg_select!`.
124pub(crate) struct CfgSelectArm {
125    /// The `$predicate` part.
126    pub(crate) predicate: CfgSelectFormatPredicate,
127    /// Span of `=>`.
128    pub(crate) arrow: Token,
129    /// The RHS `$production` expression.
130    pub(crate) expr: Box<ast::Expr>,
131    /// `cfg_select!` arms `$production`s can be optionally `,` terminated, like `match` arms.
132    /// The `,` is not needed when `$production` is itself braced `{}`.
133    pub(crate) trailing_comma: Option<Span>,
134}
135
136impl PartialEq for &CfgSelectArm {
137    fn eq(&self, other: &Self) -> bool {
138        // consider the arms equal if they have the same span
139        self.span() == other.span()
140    }
141}
142
143impl Spanned for CfgSelectArm {
144    fn span(&self) -> Span {
145        self.predicate
146            .span()
147            .with_hi(if let Some(comma) = self.trailing_comma {
148                comma.hi()
149            } else {
150                self.expr.span.hi()
151            })
152    }
153}
154
155impl std::fmt::Debug for CfgSelectArm {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        match &self.predicate {
158            CfgSelectFormatPredicate::Cfg(cfg_entry) => cfg_entry.fmt(f)?,
159            CfgSelectFormatPredicate::Wildcard(t) => t.fmt(f)?,
160        };
161        write!(f, "=> {:?}", self.expr)
162    }
163}
164
165impl CfgSelectArm {
166    /// Is the `cfg_select!` arm written with two consecutive blocks in a way that we can apply a
167    /// concise formatting happy path? For example:
168    ///
169    /// ```text
170    /// $predicate => {{}}
171    /// ```
172    ///
173    /// If so, extract the inner block. rustfmt will preserve the double block syntax.
174    pub(crate) fn maybe_double_block_concise_formatting(
175        &self,
176        context: &RewriteContext<'_>,
177    ) -> Option<&ast::Expr> {
178        // To be able to safely use the concise double block `{{ ... }}` concise formatting, the
179        // outer block must satisfy all of the following properties:
180        //
181        // 1. It has a single statement that's also a block
182        // 2. It doesn't have a label
183        // 3. It isn't an unsafe block
184        // 4. It doesn't have any attributes
185        // 5. There are no comments between the outer blocks and the inner blocks, i.e.
186        //    ```
187        //    { /* A */ { ... } /* B */ }
188        //    ```
189        let outer_expr = &self.expr;
190        match &outer_expr.kind {
191            ast::ExprKind::Block(outer_block, label)
192                if let [stmt] = outer_block.stmts.as_slice()
193                    && label.is_none()
194                    && !is_unsafe_block(&outer_block)
195                    && self.expr.attrs.is_empty() =>
196            {
197                match &stmt.kind {
198                    // The inner expr has to be a block.
199                    ast::StmtKind::Expr(e)
200                        if let ast::ExprKind::Block(ref inner_block, _inner_label) = e.kind =>
201                    {
202                        // Check for comments in between outer/inner blocks. If there are in-between
203                        // comments, we should not apply the concise formatting. Let's call them
204                        // ```
205                        // {   { ... }   }
206                        // ^---       ^---
207                        // pre_sp     post_sp
208                        // ```
209                        let pre_sp = outer_block.span.until(inner_block.span);
210                        let post_sp = outer_block.span.with_lo(inner_block.span.hi());
211                        if contains_comment(context.snippet(pre_sp))
212                            || contains_comment(context.snippet(post_sp))
213                        {
214                            None
215                        } else {
216                            Some(e)
217                        }
218                    }
219                    _ => None,
220                }
221            }
222            _ => None,
223        }
224    }
225}
226
227// FIXME(ytmimi) would be nice if rustfmt didn't need to implement parsing logic on its own
228// and could instead just call rustc_attr_parsing::parse_cfg_select, but this is fine for now.
229pub(crate) fn parse_cfg_select_arms(
230    psess: &ParseSess,
231    ts: TokenStream,
232) -> Option<Vec<CfgSelectArm>> {
233    let result = catch_unwind(AssertUnwindSafe(|| parse_cfg_select_arms_inner(psess, ts)));
234    let dcx = psess.inner().dcx();
235    let recovered = dcx.has_errors().is_some();
236    dcx.reset_err_count();
237    match result {
238        Ok(Some(_)) if recovered => {
239            debug!("cfg_select! arms parsed with recovery");
240            None
241        }
242        Ok(arms) => arms,
243        Err(..) => {
244            debug!("failed to parse cfg_select! arms");
245            None
246        }
247    }
248}
249
250fn parse_cfg_select_arms_inner(psess: &ParseSess, ts: TokenStream) -> Option<Vec<CfgSelectArm>> {
251    let mut cfg_select_predicates = vec![];
252    let mut parser = build_stream_parser(psess.inner(), ts);
253
254    while parser.token != token::Eof {
255        let predicate = if parser.eat_keyword(exp!(Underscore)) {
256            CfgSelectFormatPredicate::Wildcard(parser.prev_token.span)
257        } else {
258            let Ok(meta_item) = parser.parse_meta_item_inner().map_err(|e| e.cancel()) else {
259                debug!("Failed to parse cfg entry in cfg_select! predicate");
260                return None;
261            };
262
263            CfgSelectFormatPredicate::Cfg(meta_item)
264        };
265
266        if let Err(e) = parser.expect(exp!(FatArrow)) {
267            e.cancel();
268            debug!("Expected to find a `=>` after cfg_select! predicate.");
269            return None;
270        };
271
272        let arrow = parser.prev_token;
273
274        let Ok(expr) = parser.parse_expr().map_err(|e| e.cancel()) else {
275            debug!("Couldn't parse cfg_select! arm body after `=>`.");
276            return None;
277        };
278
279        let trailing_comma = if parser.eat(exp!(Comma)) {
280            Some(parser.prev_token.span)
281        } else {
282            None
283        };
284
285        let arm = CfgSelectArm {
286            predicate,
287            arrow,
288            expr,
289            trailing_comma,
290        };
291
292        cfg_select_predicates.push(arm);
293    }
294    Some(cfg_select_predicates)
295}