1 use rustc_ast::{ast, ptr};
4 use crate::attr::get_attrs_from_stmt;
5 use crate::config::lists::*;
6 use crate::config::Version;
7 use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
8 use crate::items::{span_hi_for_param, span_lo_for_param};
9 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
10 use crate::overflow::OverflowableItem;
11 use crate::rewrite::{Rewrite, RewriteContext};
12 use crate::shape::Shape;
13 use crate::source_map::SpanUtils;
14 use crate::types::rewrite_lifetime_param;
15 use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
17 // This module is pretty messy because of the rules around closures and blocks:
18 // FIXME - the below is probably no longer true in full.
19 // * if there is a return type, then there must be braces,
20 // * given a closure with braces, whether that is parsed to give an inner block
21 // or not depends on if there is a return type and if there are statements
23 // * if the first expression in the body ends with a block (i.e., is a
24 // statement without needing a semi-colon), then adding or removing braces
25 // can change whether it is treated as an expression or statement.
27 pub(crate) fn rewrite_closure(
28 binder: &ast::ClosureBinder,
29 capture: ast::CaptureBy,
30 is_async: &ast::Async,
31 movability: ast::Movability,
32 fn_decl: &ast::FnDecl,
35 context: &RewriteContext<'_>,
38 debug!("rewrite_closure {:?}", body);
40 let (prefix, extra_offset) = rewrite_closure_fn_decl(
41 binder, capture, is_async, movability, fn_decl, body, span, context, shape,
43 // 1 = space between `|...|` and body.
44 let body_shape = shape.offset_left(extra_offset)?;
46 if let ast::ExprKind::Block(ref block, _) = body.kind {
47 // The body of the closure is an empty block.
48 if block.stmts.is_empty() && !block_contains_comment(context, block) {
50 .rewrite(context, shape)
51 .map(|s| format!("{} {}", prefix, s));
54 let result = match fn_decl.output {
55 ast::FnRetTy::Default(_) if !context.inside_macro() => {
56 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
62 // Either we require a block, or tried without and failed.
63 rewrite_closure_block(block, &prefix, context, body_shape)
66 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
67 // The closure originally had a non-block expression, but we can't fit on
68 // one line, so we'll insert a block.
69 rewrite_closure_with_block(body, &prefix, context, body_shape)
74 fn try_rewrite_without_block(
77 context: &RewriteContext<'_>,
81 let expr = get_inner_expr(expr, prefix, context);
83 if is_block_closure_forced(context, expr) {
84 rewrite_closure_with_block(expr, prefix, context, shape)
86 rewrite_closure_expr(expr, prefix, context, body_shape)
90 fn get_inner_expr<'a>(
93 context: &RewriteContext<'_>,
95 if let ast::ExprKind::Block(ref block, _) = expr.kind {
96 if !needs_block(block, prefix, context) {
97 // block.stmts.len() == 1 except with `|| {{}}`;
98 // https://github.com/rust-lang/rustfmt/issues/3844
99 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
100 return get_inner_expr(expr, prefix, context);
108 // Figure out if a block is necessary.
109 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
110 let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
111 !get_attrs_from_stmt(first_stmt).is_empty()
114 is_unsafe_block(block)
115 || block.stmts.len() > 1
117 || block_contains_comment(context, block)
118 || prefix.contains('\n')
121 fn veto_block(e: &ast::Expr) -> bool {
123 ast::ExprKind::Call(..)
124 | ast::ExprKind::Binary(..)
125 | ast::ExprKind::Cast(..)
126 | ast::ExprKind::Type(..)
127 | ast::ExprKind::Assign(..)
128 | ast::ExprKind::AssignOp(..)
129 | ast::ExprKind::Field(..)
130 | ast::ExprKind::Index(..)
131 | ast::ExprKind::Range(..)
132 | ast::ExprKind::Try(..) => true,
137 // Rewrite closure with a single expression wrapping its body with block.
138 // || { #[attr] foo() } -> Block { #[attr] foo() }
139 fn rewrite_closure_with_block(
142 context: &RewriteContext<'_>,
144 ) -> Option<String> {
145 let left_most = left_most_sub_expr(body);
146 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
151 let block = ast::Block {
152 stmts: vec![ast::Stmt {
153 id: ast::NodeId::root(),
154 kind: ast::StmtKind::Expr(ptr::P(body.clone())),
157 id: ast::NodeId::root(),
158 rules: ast::BlockCheckMode::Default,
163 .map(|attr| attr.span.to(body.span))
164 .unwrap_or(body.span),
165 could_be_bare_literal: false,
167 let block = crate::expr::rewrite_block_with_visitor(
176 Some(format!("{} {}", prefix, block))
179 // Rewrite closure with a single expression without wrapping its body with block.
180 fn rewrite_closure_expr(
183 context: &RewriteContext<'_>,
185 ) -> Option<String> {
186 fn allow_multi_line(expr: &ast::Expr) -> bool {
188 ast::ExprKind::Match(..)
189 | ast::ExprKind::Async(..)
190 | ast::ExprKind::Block(..)
191 | ast::ExprKind::TryBlock(..)
192 | ast::ExprKind::Loop(..)
193 | ast::ExprKind::Struct(..) => true,
195 ast::ExprKind::AddrOf(_, _, ref expr)
196 | ast::ExprKind::Box(ref expr)
197 | ast::ExprKind::Try(ref expr)
198 | ast::ExprKind::Unary(_, ref expr)
199 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
205 // When rewriting closure's body without block, we require it to fit in a single line
206 // unless it is a block-like expression or we are inside macro call.
207 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
208 || context.config.force_multiline_blocks();
209 expr.rewrite(context, shape)
211 if veto_multiline && rw.contains('\n') {
217 .map(|rw| format!("{} {}", prefix, rw))
220 // Rewrite closure whose body is block.
221 fn rewrite_closure_block(
224 context: &RewriteContext<'_>,
226 ) -> Option<String> {
227 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
230 // Return type is (prefix, extra_offset)
231 fn rewrite_closure_fn_decl(
232 binder: &ast::ClosureBinder,
233 capture: ast::CaptureBy,
234 asyncness: &ast::Async,
235 movability: ast::Movability,
236 fn_decl: &ast::FnDecl,
239 context: &RewriteContext<'_>,
241 ) -> Option<(String, usize)> {
242 let binder = match binder {
243 ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
246 ast::ClosureBinder::For { generic_params, .. } => {
247 let lifetime_str = rewrite_lifetime_param(context, shape, generic_params)?;
248 format!("for<{lifetime_str}> ")
250 ast::ClosureBinder::NotPresent => "".to_owned(),
253 let immovable = if movability == ast::Movability::Static {
258 let is_async = if asyncness.is_async() { "async " } else { "" };
259 let mover = if capture == ast::CaptureBy::Value {
264 // 4 = "|| {".len(), which is overconservative when the closure consists of
265 // a single expression.
266 let nested_shape = shape
267 .shrink_left(binder.len() + immovable.len() + is_async.len() + mover.len())?
271 let param_offset = nested_shape.indent + 1;
272 let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
273 let ret_str = fn_decl.output.rewrite(context, param_shape)?;
275 let param_items = itemize_list(
276 context.snippet_provider,
277 fn_decl.inputs.iter(),
280 |param| span_lo_for_param(param),
281 |param| span_hi_for_param(context, param),
282 |param| param.rewrite(context, param_shape),
283 context.snippet_provider.span_after(span, "|"),
287 let item_vec = param_items.collect::<Vec<_>>();
288 // 1 = space between parameters and return type.
289 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
290 let tactic = definitive_tactic(
292 ListTactic::HorizontalVertical,
296 let param_shape = match tactic {
297 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
301 let fmt = ListFormatting::new(param_shape, context.config)
303 .preserve_newline(true);
304 let list_str = write_list(&item_vec, &fmt)?;
305 let mut prefix = format!("{}{}{}{}|{}|", binder, immovable, is_async, mover, list_str);
307 if !ret_str.is_empty() {
308 if prefix.contains('\n') {
310 prefix.push_str(¶m_offset.to_string(context.config));
314 prefix.push_str(&ret_str);
316 // 1 = space between `|...|` and body.
317 let extra_offset = last_line_width(&prefix) + 1;
319 Some((prefix, extra_offset))
322 // Rewriting closure which is placed at the end of the function call's arg.
323 // Returns `None` if the reformatted closure 'looks bad'.
324 pub(crate) fn rewrite_last_closure(
325 context: &RewriteContext<'_>,
328 ) -> Option<String> {
329 if let ast::ExprKind::Closure(
339 let body = match body.kind {
340 ast::ExprKind::Block(ref block, _)
341 if !is_unsafe_block(block)
342 && !context.inside_macro()
343 && is_simple_block(context, block, Some(&body.attrs)) =>
345 stmt_expr(&block.stmts[0]).unwrap_or(body)
349 let (prefix, extra_offset) = rewrite_closure_fn_decl(
350 binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape,
352 // If the closure goes multi line before its body, do not overflow the closure.
353 if prefix.contains('\n') {
357 let body_shape = shape.offset_left(extra_offset)?;
359 // We force to use block for the body of the closure for certain kinds of expressions.
360 if is_block_closure_forced(context, body) {
361 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
363 match fn_decl.output {
364 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
365 // If the expression can fit in a single line, we need not force block
366 // closure. However, if the closure has a return type, then we must
368 match rewrite_closure_expr(body, &prefix, context, shape) {
369 Some(single_line_body_str)
370 if !single_line_body_str.contains('\n') =>
383 // When overflowing the closure which consists of a single control flow expression,
384 // force to use block if its condition uses multi line.
385 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
386 cond.contains('\n') || cond.len() > body_shape.width
388 if is_multi_lined_cond {
389 return rewrite_closure_with_block(body, &prefix, context, body_shape);
392 // Seems fine, just format the closure in usual manner.
393 return expr.rewrite(context, shape);
398 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
399 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
401 .filter_map(OverflowableItem::to_expr)
402 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
407 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
408 // If we are inside macro, we do not want to add or remove block from closure body.
409 if context.inside_macro() {
412 is_block_closure_forced_inner(expr, context.config.version())
416 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
418 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
419 ast::ExprKind::Loop(..) if version == Version::Two => true,
420 ast::ExprKind::AddrOf(_, _, ref expr)
421 | ast::ExprKind::Box(ref expr)
422 | ast::ExprKind::Try(ref expr)
423 | ast::ExprKind::Unary(_, ref expr)
424 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
429 /// Does this expression require a semicolon to be treated
430 /// as a statement? The negation of this: 'can this expression
431 /// be used as a statement without a semicolon' -- is used
432 /// as an early-bail-out in the parser so that, for instance,
433 /// if true {...} else {...}
435 /// isn't parsed as (if true {...} else {...} | x) | 5
436 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
437 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
439 ast::ExprKind::If(..)
440 | ast::ExprKind::Match(..)
441 | ast::ExprKind::Block(..)
442 | ast::ExprKind::While(..)
443 | ast::ExprKind::Loop(..)
444 | ast::ExprKind::ForLoop(..)
445 | ast::ExprKind::TryBlock(..) => false,