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