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 constness: ast::Const,
30 capture: ast::CaptureBy,
31 is_async: &ast::Async,
32 movability: ast::Movability,
33 fn_decl: &ast::FnDecl,
36 context: &RewriteContext<'_>,
39 debug!("rewrite_closure {:?}", body);
41 let (prefix, extra_offset) = rewrite_closure_fn_decl(
42 binder, constness, capture, is_async, movability, fn_decl, body, span, context, shape,
44 // 1 = space between `|...|` and body.
45 let body_shape = shape.offset_left(extra_offset)?;
47 if let ast::ExprKind::Block(ref block, _) = body.kind {
48 // The body of the closure is an empty block.
49 if block.stmts.is_empty() && !block_contains_comment(context, block) {
51 .rewrite(context, shape)
52 .map(|s| format!("{} {}", prefix, s));
55 let result = match fn_decl.output {
56 ast::FnRetTy::Default(_) if !context.inside_macro() => {
57 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
63 // Either we require a block, or tried without and failed.
64 rewrite_closure_block(block, &prefix, context, body_shape)
67 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
68 // The closure originally had a non-block expression, but we can't fit on
69 // one line, so we'll insert a block.
70 rewrite_closure_with_block(body, &prefix, context, body_shape)
75 fn try_rewrite_without_block(
78 context: &RewriteContext<'_>,
82 let expr = get_inner_expr(expr, prefix, context);
84 if is_block_closure_forced(context, expr) {
85 rewrite_closure_with_block(expr, prefix, context, shape)
87 rewrite_closure_expr(expr, prefix, context, body_shape)
91 fn get_inner_expr<'a>(
94 context: &RewriteContext<'_>,
96 if let ast::ExprKind::Block(ref block, _) = expr.kind {
97 if !needs_block(block, prefix, context) {
98 // block.stmts.len() == 1 except with `|| {{}}`;
99 // https://github.com/rust-lang/rustfmt/issues/3844
100 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
101 return get_inner_expr(expr, prefix, context);
109 // Figure out if a block is necessary.
110 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
111 let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
112 !get_attrs_from_stmt(first_stmt).is_empty()
115 is_unsafe_block(block)
116 || block.stmts.len() > 1
118 || block_contains_comment(context, block)
119 || prefix.contains('\n')
122 fn veto_block(e: &ast::Expr) -> bool {
124 ast::ExprKind::Call(..)
125 | ast::ExprKind::Binary(..)
126 | ast::ExprKind::Cast(..)
127 | ast::ExprKind::Type(..)
128 | ast::ExprKind::Assign(..)
129 | ast::ExprKind::AssignOp(..)
130 | ast::ExprKind::Field(..)
131 | ast::ExprKind::Index(..)
132 | ast::ExprKind::Range(..)
133 | ast::ExprKind::Try(..) => true,
138 // Rewrite closure with a single expression wrapping its body with block.
139 // || { #[attr] foo() } -> Block { #[attr] foo() }
140 fn rewrite_closure_with_block(
143 context: &RewriteContext<'_>,
145 ) -> Option<String> {
146 let left_most = left_most_sub_expr(body);
147 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
152 let block = ast::Block {
153 stmts: vec![ast::Stmt {
154 id: ast::NodeId::root(),
155 kind: ast::StmtKind::Expr(ptr::P(body.clone())),
158 id: ast::NodeId::root(),
159 rules: ast::BlockCheckMode::Default,
164 .map(|attr| attr.span.to(body.span))
165 .unwrap_or(body.span),
166 could_be_bare_literal: false,
168 let block = crate::expr::rewrite_block_with_visitor(
177 Some(format!("{} {}", prefix, block))
180 // Rewrite closure with a single expression without wrapping its body with block.
181 fn rewrite_closure_expr(
184 context: &RewriteContext<'_>,
186 ) -> Option<String> {
187 fn allow_multi_line(expr: &ast::Expr) -> bool {
189 ast::ExprKind::Match(..)
190 | ast::ExprKind::Async(..)
191 | ast::ExprKind::Block(..)
192 | ast::ExprKind::TryBlock(..)
193 | ast::ExprKind::Loop(..)
194 | ast::ExprKind::Struct(..) => true,
196 ast::ExprKind::AddrOf(_, _, ref expr)
197 | ast::ExprKind::Box(ref expr)
198 | ast::ExprKind::Try(ref expr)
199 | ast::ExprKind::Unary(_, ref expr)
200 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
206 // When rewriting closure's body without block, we require it to fit in a single line
207 // unless it is a block-like expression or we are inside macro call.
208 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
209 || context.config.force_multiline_blocks();
210 expr.rewrite(context, shape)
212 if veto_multiline && rw.contains('\n') {
218 .map(|rw| format!("{} {}", prefix, rw))
221 // Rewrite closure whose body is block.
222 fn rewrite_closure_block(
225 context: &RewriteContext<'_>,
227 ) -> Option<String> {
228 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
231 // Return type is (prefix, extra_offset)
232 fn rewrite_closure_fn_decl(
233 binder: &ast::ClosureBinder,
234 constness: ast::Const,
235 capture: ast::CaptureBy,
236 asyncness: &ast::Async,
237 movability: ast::Movability,
238 fn_decl: &ast::FnDecl,
241 context: &RewriteContext<'_>,
243 ) -> Option<(String, usize)> {
244 let binder = match binder {
245 ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
248 ast::ClosureBinder::For { generic_params, .. } => {
249 let lifetime_str = rewrite_lifetime_param(context, shape, generic_params)?;
250 format!("for<{lifetime_str}> ")
252 ast::ClosureBinder::NotPresent => "".to_owned(),
255 let const_ = if matches!(constness, ast::Const::Yes(_)) {
261 let immovable = if movability == ast::Movability::Static {
266 let is_async = if asyncness.is_async() { "async " } else { "" };
267 let mover = if capture == ast::CaptureBy::Value {
272 // 4 = "|| {".len(), which is overconservative when the closure consists of
273 // a single expression.
274 let nested_shape = shape
275 .shrink_left(binder.len() + const_.len() + immovable.len() + is_async.len() + mover.len())?
279 let param_offset = nested_shape.indent + 1;
280 let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
281 let ret_str = fn_decl.output.rewrite(context, param_shape)?;
283 let param_items = itemize_list(
284 context.snippet_provider,
285 fn_decl.inputs.iter(),
288 |param| span_lo_for_param(param),
289 |param| span_hi_for_param(context, param),
290 |param| param.rewrite(context, param_shape),
291 context.snippet_provider.span_after(span, "|"),
295 let item_vec = param_items.collect::<Vec<_>>();
296 // 1 = space between parameters and return type.
297 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
298 let tactic = definitive_tactic(
300 ListTactic::HorizontalVertical,
304 let param_shape = match tactic {
305 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
309 let fmt = ListFormatting::new(param_shape, context.config)
311 .preserve_newline(true);
312 let list_str = write_list(&item_vec, &fmt)?;
313 let mut prefix = format!(
315 binder, const_, immovable, is_async, mover, list_str
318 if !ret_str.is_empty() {
319 if prefix.contains('\n') {
321 prefix.push_str(¶m_offset.to_string(context.config));
325 prefix.push_str(&ret_str);
327 // 1 = space between `|...|` and body.
328 let extra_offset = last_line_width(&prefix) + 1;
330 Some((prefix, extra_offset))
333 // Rewriting closure which is placed at the end of the function call's arg.
334 // Returns `None` if the reformatted closure 'looks bad'.
335 pub(crate) fn rewrite_last_closure(
336 context: &RewriteContext<'_>,
339 ) -> Option<String> {
340 if let ast::ExprKind::Closure(ref closure) = expr.kind {
352 let body = match body.kind {
353 ast::ExprKind::Block(ref block, _)
354 if !is_unsafe_block(block)
355 && !context.inside_macro()
356 && is_simple_block(context, block, Some(&body.attrs)) =>
358 stmt_expr(&block.stmts[0]).unwrap_or(body)
362 let (prefix, extra_offset) = rewrite_closure_fn_decl(
374 // If the closure goes multi line before its body, do not overflow the closure.
375 if prefix.contains('\n') {
379 let body_shape = shape.offset_left(extra_offset)?;
381 // We force to use block for the body of the closure for certain kinds of expressions.
382 if is_block_closure_forced(context, body) {
383 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
385 match fn_decl.output {
386 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
387 // If the expression can fit in a single line, we need not force block
388 // closure. However, if the closure has a return type, then we must
390 match rewrite_closure_expr(body, &prefix, context, shape) {
391 Some(single_line_body_str)
392 if !single_line_body_str.contains('\n') =>
405 // When overflowing the closure which consists of a single control flow expression,
406 // force to use block if its condition uses multi line.
407 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
408 cond.contains('\n') || cond.len() > body_shape.width
410 if is_multi_lined_cond {
411 return rewrite_closure_with_block(body, &prefix, context, body_shape);
414 // Seems fine, just format the closure in usual manner.
415 return expr.rewrite(context, shape);
420 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
421 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
423 .filter_map(OverflowableItem::to_expr)
424 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
429 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
430 // If we are inside macro, we do not want to add or remove block from closure body.
431 if context.inside_macro() {
434 is_block_closure_forced_inner(expr, context.config.version())
438 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
440 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
441 ast::ExprKind::Loop(..) if version == Version::Two => true,
442 ast::ExprKind::AddrOf(_, _, ref expr)
443 | ast::ExprKind::Box(ref expr)
444 | ast::ExprKind::Try(ref expr)
445 | ast::ExprKind::Unary(_, ref expr)
446 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
451 /// Does this expression require a semicolon to be treated
452 /// as a statement? The negation of this: 'can this expression
453 /// be used as a statement without a semicolon' -- is used
454 /// as an early-bail-out in the parser so that, for instance,
455 /// if true {...} else {...}
457 /// isn't parsed as (if true {...} else {...} | x) | 5
458 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
459 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
461 ast::ExprKind::If(..)
462 | ast::ExprKind::Match(..)
463 | ast::ExprKind::Block(..)
464 | ast::ExprKind::While(..)
465 | ast::ExprKind::Loop(..)
466 | ast::ExprKind::ForLoop(..)
467 | ast::ExprKind::TryBlock(..) => false,