Skip to main content

rustfmt_nightly/
closures.rs

1use rustc_ast::{Label, ast};
2use rustc_span::Span;
3use thin_vec::thin_vec;
4use tracing::debug;
5
6use crate::attr::get_attrs_from_stmt;
7use crate::config::StyleEdition;
8use crate::config::lists::*;
9use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
10use crate::items::{span_hi_for_param, span_lo_for_param};
11use crate::lists::{ListFormatting, Separator, definitive_tactic, itemize_list, write_list};
12use crate::overflow::OverflowableItem;
13use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
14use crate::shape::Shape;
15use crate::source_map::SpanUtils;
16use crate::types::rewrite_bound_params;
17use crate::utils::{NodeIdExt, last_line_width, left_most_sub_expr, stmt_expr};
18
19// This module is pretty messy because of the rules around closures and blocks:
20// FIXME - the below is probably no longer true in full.
21//   * if there is a return type, then there must be braces,
22//   * given a closure with braces, whether that is parsed to give an inner block
23//     or not depends on if there is a return type and if there are statements
24//     in that block,
25//   * if the first expression in the body ends with a block (i.e., is a
26//     statement without needing a semi-colon), then adding or removing braces
27//     can change whether it is treated as an expression or statement.
28
29pub(crate) fn rewrite_closure(
30    binder: &ast::ClosureBinder,
31    constness: ast::Const,
32    capture: ast::CaptureBy,
33    coroutine_kind: &Option<ast::CoroutineKind>,
34    movability: ast::Movability,
35    fn_decl: &ast::FnDecl,
36    body: &ast::Expr,
37    span: Span,
38    context: &RewriteContext<'_>,
39    shape: Shape,
40) -> RewriteResult {
41    debug!("rewrite_closure {:?}", body);
42
43    let (prefix, extra_offset) = rewrite_closure_fn_decl(
44        binder,
45        constness,
46        capture,
47        coroutine_kind,
48        movability,
49        fn_decl,
50        body,
51        span,
52        context,
53        shape,
54    )?;
55    // 1 = space between `|...|` and body.
56    let body_shape = shape.offset_left(extra_offset, span)?;
57
58    if let ast::ExprKind::Block(ref block, _) = body.kind {
59        // The body of the closure is an empty block.
60        if block.stmts.is_empty() && !block_contains_comment(context, block) {
61            return body
62                .rewrite_result(context, shape)
63                .map(|s| format!("{} {}", prefix, s));
64        }
65
66        let result = match fn_decl.output {
67            ast::FnRetTy::Default(_) if !context.inside_macro() => {
68                try_rewrite_without_block(body, &prefix, context, shape, body_shape)
69            }
70            _ => Err(RewriteError::Unknown),
71        };
72
73        result.or_else(|_| {
74            // Either we require a block, or tried without and failed.
75            rewrite_closure_block(body, &prefix, context, body_shape)
76        })
77    } else {
78        rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|_| {
79            // The closure originally had a non-block expression, but we can't fit on
80            // one line, so we'll insert a block.
81            rewrite_closure_with_block(body, &prefix, context, body_shape)
82        })
83    }
84}
85
86fn try_rewrite_without_block(
87    expr: &ast::Expr,
88    prefix: &str,
89    context: &RewriteContext<'_>,
90    shape: Shape,
91    body_shape: Shape,
92) -> RewriteResult {
93    let expr = get_inner_expr(expr, prefix, context);
94
95    if is_block_closure_forced(context, expr) {
96        rewrite_closure_with_block(expr, prefix, context, shape)
97    } else {
98        rewrite_closure_expr(expr, prefix, context, body_shape)
99    }
100}
101
102fn get_inner_expr<'a>(
103    expr: &'a ast::Expr,
104    prefix: &str,
105    context: &RewriteContext<'_>,
106) -> &'a ast::Expr {
107    if let ast::ExprKind::Block(ref block, ref label) = expr.kind {
108        if !needs_block(block, label, prefix, context) {
109            // block.stmts.len() == 1 except with `|| {{}}`;
110            // https://github.com/rust-lang/rustfmt/issues/3844
111            if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
112                return get_inner_expr(expr, prefix, context);
113            }
114        }
115    }
116
117    expr
118}
119
120// Figure out if a block is necessary.
121fn needs_block(
122    block: &ast::Block,
123    label: &Option<Label>,
124    prefix: &str,
125    context: &RewriteContext<'_>,
126) -> bool {
127    let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
128        !get_attrs_from_stmt(first_stmt).is_empty()
129    });
130
131    is_unsafe_block(block)
132        || block.stmts.len() > 1
133        || has_attributes
134        || block_contains_comment(context, block)
135        || prefix.contains('\n')
136        || label.is_some()
137}
138
139fn veto_block(e: &ast::Expr) -> bool {
140    match e.kind {
141        ast::ExprKind::Call(..)
142        | ast::ExprKind::Binary(..)
143        | ast::ExprKind::Cast(..)
144        | ast::ExprKind::Type(..)
145        | ast::ExprKind::Assign(..)
146        | ast::ExprKind::AssignOp(..)
147        | ast::ExprKind::Field(..)
148        | ast::ExprKind::Index(..)
149        | ast::ExprKind::Range(..)
150        | ast::ExprKind::Try(..) => true,
151        _ => false,
152    }
153}
154
155// Rewrite closure with a single expression wrapping its body with block.
156// || { #[attr] foo() } -> Block { #[attr] foo() }
157fn rewrite_closure_with_block(
158    body: &ast::Expr,
159    prefix: &str,
160    context: &RewriteContext<'_>,
161    shape: Shape,
162) -> RewriteResult {
163    let left_most = left_most_sub_expr(body);
164    let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
165    if veto_block {
166        return Err(RewriteError::Unknown);
167    }
168
169    let block = ast::Block {
170        stmts: thin_vec![ast::Stmt {
171            id: ast::NodeId::root(),
172            kind: ast::StmtKind::Expr(Box::new(body.clone())),
173            span: body.span,
174        }],
175        id: ast::NodeId::root(),
176        rules: ast::BlockCheckMode::Default,
177        span: body
178            .attrs
179            .first()
180            .map(|attr| attr.span.to(body.span))
181            .unwrap_or(body.span),
182    };
183    let block = crate::expr::rewrite_block_with_visitor(
184        context,
185        "",
186        &block,
187        Some(&body.attrs),
188        None,
189        shape,
190        false,
191    )?;
192    Ok(format!("{prefix} {block}"))
193}
194
195// Rewrite closure with a single expression without wrapping its body with block.
196fn rewrite_closure_expr(
197    expr: &ast::Expr,
198    prefix: &str,
199    context: &RewriteContext<'_>,
200    shape: Shape,
201) -> RewriteResult {
202    fn allow_multi_line(expr: &ast::Expr) -> bool {
203        match expr.kind {
204            ast::ExprKind::Match(..)
205            | ast::ExprKind::Gen(..)
206            | ast::ExprKind::Block(..)
207            | ast::ExprKind::TryBlock(..)
208            | ast::ExprKind::Loop(..)
209            | ast::ExprKind::Struct(..) => true,
210
211            ast::ExprKind::AddrOf(_, _, ref expr)
212            | ast::ExprKind::Try(ref expr)
213            | ast::ExprKind::Unary(_, ref expr)
214            | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
215
216            _ => false,
217        }
218    }
219
220    // When rewriting closure's body without block, we require it to fit in a single line
221    // unless it is a block-like expression or we are inside macro call.
222    let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
223        || context.config.force_multiline_blocks();
224    expr.rewrite_result(context, shape)
225        .and_then(|rw| {
226            if veto_multiline && rw.contains('\n') {
227                Err(RewriteError::Unknown)
228            } else {
229                Ok(rw)
230            }
231        })
232        .map(|rw| format!("{} {}", prefix, rw))
233}
234
235// Rewrite closure whose body is block.
236fn rewrite_closure_block(
237    block: &ast::Expr,
238    prefix: &str,
239    context: &RewriteContext<'_>,
240    shape: Shape,
241) -> RewriteResult {
242    debug_assert!(
243        matches!(block.kind, ast::ExprKind::Block(..)),
244        "expected a block expression"
245    );
246
247    Ok(format!(
248        "{} {}",
249        prefix,
250        block.rewrite_result(context, shape)?
251    ))
252}
253
254// Return type is (prefix, extra_offset)
255fn rewrite_closure_fn_decl(
256    binder: &ast::ClosureBinder,
257    constness: ast::Const,
258    capture: ast::CaptureBy,
259    coroutine_kind: &Option<ast::CoroutineKind>,
260    movability: ast::Movability,
261    fn_decl: &ast::FnDecl,
262    body: &ast::Expr,
263    span: Span,
264    context: &RewriteContext<'_>,
265    shape: Shape,
266) -> Result<(String, usize), RewriteError> {
267    let binder = match binder {
268        ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
269            "for<> ".to_owned()
270        }
271        ast::ClosureBinder::For { generic_params, .. } => {
272            let lifetime_str =
273                rewrite_bound_params(context, shape, generic_params).unknown_error()?;
274            format!("for<{lifetime_str}> ")
275        }
276        ast::ClosureBinder::NotPresent => "".to_owned(),
277    };
278
279    let const_ = if matches!(constness, ast::Const::Yes(_)) {
280        "const "
281    } else {
282        ""
283    };
284
285    let immovable = if movability == ast::Movability::Static {
286        "static "
287    } else {
288        ""
289    };
290    let coro = match coroutine_kind {
291        Some(ast::CoroutineKind::Async { .. }) => "async ",
292        Some(ast::CoroutineKind::Gen { .. }) => "gen ",
293        Some(ast::CoroutineKind::AsyncGen { .. }) => "async gen ",
294        None => "",
295    };
296    let capture_str = match capture {
297        ast::CaptureBy::Value { .. } => "move ",
298        ast::CaptureBy::Use { .. } => "use ",
299        ast::CaptureBy::Ref => "",
300    };
301    // 4 = "|| {".len(), which is overconservative when the closure consists of
302    // a single expression.
303    let offset = binder.len() + const_.len() + immovable.len() + coro.len() + capture_str.len();
304    let nested_shape = shape.shrink_left(offset, span)?.sub_width(4, span)?;
305
306    // 1 = |
307    let param_offset = nested_shape.indent + 1;
308    let param_shape = nested_shape.offset_left(1, span)?.visual_indent(0);
309    let ret_str = fn_decl.output.rewrite_result(context, param_shape)?;
310
311    let param_items = itemize_list(
312        context.snippet_provider,
313        fn_decl.inputs.iter(),
314        "|",
315        ",",
316        |param| span_lo_for_param(param),
317        |param| span_hi_for_param(context, param),
318        |param| param.rewrite_result(context, param_shape),
319        context.snippet_provider.span_after(span, "|"),
320        body.span.lo(),
321        false,
322    );
323    let item_vec = param_items.collect::<Vec<_>>();
324    // 1 = space between parameters and return type.
325    let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
326    let tactic = definitive_tactic(
327        &item_vec,
328        ListTactic::HorizontalVertical,
329        Separator::Comma,
330        horizontal_budget,
331    );
332    let param_shape = match tactic {
333        DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1, span)?,
334        _ => param_shape,
335    };
336
337    let fmt = ListFormatting::new(param_shape, context.config)
338        .tactic(tactic)
339        .preserve_newline(true);
340    let list_str = write_list(&item_vec, &fmt)?;
341    let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|");
342
343    if !ret_str.is_empty() {
344        if prefix.contains('\n') {
345            prefix.push('\n');
346            prefix.push_str(&param_offset.to_string(context.config));
347        } else {
348            prefix.push(' ');
349        }
350        prefix.push_str(&ret_str);
351    }
352    // 1 = space between `|...|` and body.
353    let extra_offset = last_line_width(&prefix) + 1;
354
355    Ok((prefix, extra_offset))
356}
357
358// Rewriting closure which is placed at the end of the function call's arg.
359// Returns `None` if the reformatted closure 'looks bad'.
360pub(crate) fn rewrite_last_closure(
361    context: &RewriteContext<'_>,
362    expr: &ast::Expr,
363    shape: Shape,
364) -> RewriteResult {
365    debug!("rewrite_last_closure {:?}", expr);
366
367    if let ast::ExprKind::Closure(ref closure) = expr.kind {
368        let ast::Closure {
369            ref binder,
370            constness,
371            capture_clause,
372            ref coroutine_kind,
373            movability,
374            ref fn_decl,
375            ref body,
376            fn_decl_span: _,
377            fn_arg_span: _,
378        } = **closure;
379        let body = match body.kind {
380            ast::ExprKind::Block(ref block, ref label)
381                if !is_unsafe_block(block)
382                    && !context.inside_macro()
383                    && is_simple_block(context, block, Some(&body.attrs))
384                    && label.is_none() =>
385            {
386                stmt_expr(&block.stmts[0]).unwrap_or(body)
387            }
388            _ => body,
389        };
390        let (prefix, extra_offset) = rewrite_closure_fn_decl(
391            binder,
392            constness,
393            capture_clause,
394            coroutine_kind,
395            movability,
396            fn_decl,
397            body,
398            expr.span,
399            context,
400            shape,
401        )?;
402        // If the closure goes multi line before its body, do not overflow the closure.
403        if prefix.contains('\n') {
404            return Err(RewriteError::Unknown);
405        }
406
407        let body_shape = shape.offset_left(extra_offset, expr.span)?;
408
409        // We force to use block for the body of the closure for certain kinds of expressions.
410        if is_block_closure_forced(context, body) {
411            return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
412                |body_str| {
413                    match fn_decl.output {
414                        ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
415                            // If the expression can fit in a single line, we need not force block
416                            // closure.  However, if the closure has a return type, then we must
417                            // keep the blocks.
418                            match rewrite_closure_expr(body, &prefix, context, shape) {
419                                Ok(single_line_body_str)
420                                    if !single_line_body_str.contains('\n') =>
421                                {
422                                    single_line_body_str
423                                }
424                                _ => body_str,
425                            }
426                        }
427                        _ => body_str,
428                    }
429                },
430            );
431        }
432
433        // When overflowing the closure which consists of a single control flow expression,
434        // force to use block if its condition uses multi line.
435        let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
436            cond.contains('\n') || cond.len() > body_shape.width
437        });
438        if is_multi_lined_cond {
439            return rewrite_closure_with_block(body, &prefix, context, body_shape);
440        }
441
442        // Seems fine, just format the closure in usual manner.
443        return expr.rewrite_result(context, shape);
444    }
445    Err(RewriteError::Unknown)
446}
447
448/// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
449pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
450    args.iter()
451        .filter_map(OverflowableItem::to_expr)
452        .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
453        .count()
454        > 1
455}
456
457fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
458    // If we are inside macro, we do not want to add or remove block from closure body.
459    if context.inside_macro() {
460        false
461    } else {
462        is_block_closure_forced_inner(expr, context.config.style_edition())
463    }
464}
465
466fn is_block_closure_forced_inner(expr: &ast::Expr, style_edition: StyleEdition) -> bool {
467    match expr.kind {
468        ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
469        ast::ExprKind::Loop(..) if style_edition >= StyleEdition::Edition2024 => true,
470        ast::ExprKind::AddrOf(_, _, ref expr)
471        | ast::ExprKind::Try(ref expr)
472        | ast::ExprKind::Unary(_, ref expr)
473        | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, style_edition),
474        _ => false,
475    }
476}
477
478/// Does this expression require a semicolon to be treated
479/// as a statement? The negation of this: 'can this expression
480/// be used as a statement without a semicolon' -- is used
481/// as an early-bail-out in the parser so that, for instance,
482///     if true {...} else {...}
483///      |x| 5
484/// isn't parsed as (if true {...} else {...} | x) | 5
485// From https://github.com/rust-lang/rust/blob/HEAD/src/libsyntax/parse/classify.rs.
486fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
487    match e.kind {
488        ast::ExprKind::If(..)
489        | ast::ExprKind::Match(..)
490        | ast::ExprKind::Block(..)
491        | ast::ExprKind::While(..)
492        | ast::ExprKind::Loop(..)
493        | ast::ExprKind::ForLoop { .. }
494        | ast::ExprKind::TryBlock(..) => false,
495        _ => true,
496    }
497}