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::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
16 // This module is pretty messy because of the rules around closures and blocks:
17 // FIXME - the below is probably no longer true in full.
18 // * if there is a return type, then there must be braces,
19 // * given a closure with braces, whether that is parsed to give an inner block
20 // or not depends on if there is a return type and if there are statements
22 // * if the first expression in the body ends with a block (i.e., is a
23 // statement without needing a semi-colon), then adding or removing braces
24 // can change whether it is treated as an expression or statement.
26 pub(crate) fn rewrite_closure(
27 capture: ast::CaptureBy,
28 is_async: &ast::Async,
29 movability: ast::Movability,
30 fn_decl: &ast::FnDecl,
33 context: &RewriteContext<'_>,
36 debug!("rewrite_closure {:?}", body);
38 let (prefix, extra_offset) = rewrite_closure_fn_decl(
39 capture, is_async, movability, fn_decl, body, span, context, shape,
41 // 1 = space between `|...|` and body.
42 let body_shape = shape.offset_left(extra_offset)?;
44 if let ast::ExprKind::Block(ref block, _) = body.kind {
45 // The body of the closure is an empty block.
46 if block.stmts.is_empty() && !block_contains_comment(context, block) {
48 .rewrite(context, shape)
49 .map(|s| format!("{} {}", prefix, s));
52 let result = match fn_decl.output {
53 ast::FnRetTy::Default(_) if !context.inside_macro() => {
54 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
60 // Either we require a block, or tried without and failed.
61 rewrite_closure_block(block, &prefix, context, body_shape)
64 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
65 // The closure originally had a non-block expression, but we can't fit on
66 // one line, so we'll insert a block.
67 rewrite_closure_with_block(body, &prefix, context, body_shape)
72 fn try_rewrite_without_block(
75 context: &RewriteContext<'_>,
79 let expr = get_inner_expr(expr, prefix, context);
81 if is_block_closure_forced(context, expr) {
82 rewrite_closure_with_block(expr, prefix, context, shape)
84 rewrite_closure_expr(expr, prefix, context, body_shape)
88 fn get_inner_expr<'a>(
91 context: &RewriteContext<'_>,
93 if let ast::ExprKind::Block(ref block, _) = expr.kind {
94 if !needs_block(block, prefix, context) {
95 // block.stmts.len() == 1 except with `|| {{}}`;
96 // https://github.com/rust-lang/rustfmt/issues/3844
97 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
98 return get_inner_expr(expr, prefix, context);
106 // Figure out if a block is necessary.
107 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
108 let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
109 !get_attrs_from_stmt(first_stmt).is_empty()
112 is_unsafe_block(block)
113 || block.stmts.len() > 1
115 || block_contains_comment(context, block)
116 || prefix.contains('\n')
119 fn veto_block(e: &ast::Expr) -> bool {
121 ast::ExprKind::Call(..)
122 | ast::ExprKind::Binary(..)
123 | ast::ExprKind::Cast(..)
124 | ast::ExprKind::Type(..)
125 | ast::ExprKind::Assign(..)
126 | ast::ExprKind::AssignOp(..)
127 | ast::ExprKind::Field(..)
128 | ast::ExprKind::Index(..)
129 | ast::ExprKind::Range(..)
130 | ast::ExprKind::Try(..) => true,
135 // Rewrite closure with a single expression wrapping its body with block.
136 // || { #[attr] foo() } -> Block { #[attr] foo() }
137 fn rewrite_closure_with_block(
140 context: &RewriteContext<'_>,
142 ) -> Option<String> {
143 let left_most = left_most_sub_expr(body);
144 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
149 let block = ast::Block {
150 stmts: vec![ast::Stmt {
151 id: ast::NodeId::root(),
152 kind: ast::StmtKind::Expr(ptr::P(body.clone())),
155 id: ast::NodeId::root(),
156 rules: ast::BlockCheckMode::Default,
161 .map(|attr| attr.span.to(body.span))
162 .unwrap_or(body.span),
163 could_be_bare_literal: false,
165 let block = crate::expr::rewrite_block_with_visitor(
174 Some(format!("{} {}", prefix, block))
177 // Rewrite closure with a single expression without wrapping its body with block.
178 fn rewrite_closure_expr(
181 context: &RewriteContext<'_>,
183 ) -> Option<String> {
184 fn allow_multi_line(expr: &ast::Expr) -> bool {
186 ast::ExprKind::Match(..)
187 | ast::ExprKind::Async(..)
188 | ast::ExprKind::Block(..)
189 | ast::ExprKind::TryBlock(..)
190 | ast::ExprKind::Loop(..)
191 | ast::ExprKind::Struct(..) => true,
193 ast::ExprKind::AddrOf(_, _, ref expr)
194 | ast::ExprKind::Box(ref expr)
195 | ast::ExprKind::Try(ref expr)
196 | ast::ExprKind::Unary(_, ref expr)
197 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
203 // When rewriting closure's body without block, we require it to fit in a single line
204 // unless it is a block-like expression or we are inside macro call.
205 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
206 || context.config.force_multiline_blocks();
207 expr.rewrite(context, shape)
209 if veto_multiline && rw.contains('\n') {
215 .map(|rw| format!("{} {}", prefix, rw))
218 // Rewrite closure whose body is block.
219 fn rewrite_closure_block(
222 context: &RewriteContext<'_>,
224 ) -> Option<String> {
225 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
228 // Return type is (prefix, extra_offset)
229 fn rewrite_closure_fn_decl(
230 capture: ast::CaptureBy,
231 asyncness: &ast::Async,
232 movability: ast::Movability,
233 fn_decl: &ast::FnDecl,
236 context: &RewriteContext<'_>,
238 ) -> Option<(String, usize)> {
239 let immovable = if movability == ast::Movability::Static {
244 let is_async = if asyncness.is_async() { "async " } else { "" };
245 let mover = if capture == ast::CaptureBy::Value {
250 // 4 = "|| {".len(), which is overconservative when the closure consists of
251 // a single expression.
252 let nested_shape = shape
253 .shrink_left(immovable.len() + is_async.len() + mover.len())?
257 let param_offset = nested_shape.indent + 1;
258 let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
259 let ret_str = fn_decl.output.rewrite(context, param_shape)?;
261 let param_items = itemize_list(
262 context.snippet_provider,
263 fn_decl.inputs.iter(),
266 |param| span_lo_for_param(param),
267 |param| span_hi_for_param(context, param),
268 |param| param.rewrite(context, param_shape),
269 context.snippet_provider.span_after(span, "|"),
273 let item_vec = param_items.collect::<Vec<_>>();
274 // 1 = space between parameters and return type.
275 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
276 let tactic = definitive_tactic(
278 ListTactic::HorizontalVertical,
282 let param_shape = match tactic {
283 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
287 let fmt = ListFormatting::new(param_shape, context.config)
289 .preserve_newline(true);
290 let list_str = write_list(&item_vec, &fmt)?;
291 let mut prefix = format!("{}{}{}|{}|", immovable, is_async, mover, list_str);
293 if !ret_str.is_empty() {
294 if prefix.contains('\n') {
296 prefix.push_str(¶m_offset.to_string(context.config));
300 prefix.push_str(&ret_str);
302 // 1 = space between `|...|` and body.
303 let extra_offset = last_line_width(&prefix) + 1;
305 Some((prefix, extra_offset))
308 // Rewriting closure which is placed at the end of the function call's arg.
309 // Returns `None` if the reformatted closure 'looks bad'.
310 pub(crate) fn rewrite_last_closure(
311 context: &RewriteContext<'_>,
314 ) -> Option<String> {
315 if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
318 let body = match body.kind {
319 ast::ExprKind::Block(ref block, _)
320 if !is_unsafe_block(block)
321 && !context.inside_macro()
322 && is_simple_block(context, block, Some(&body.attrs)) =>
324 stmt_expr(&block.stmts[0]).unwrap_or(body)
328 let (prefix, extra_offset) = rewrite_closure_fn_decl(
329 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
331 // If the closure goes multi line before its body, do not overflow the closure.
332 if prefix.contains('\n') {
336 let body_shape = shape.offset_left(extra_offset)?;
338 // We force to use block for the body of the closure for certain kinds of expressions.
339 if is_block_closure_forced(context, body) {
340 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
342 match fn_decl.output {
343 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
344 // If the expression can fit in a single line, we need not force block
345 // closure. However, if the closure has a return type, then we must
347 match rewrite_closure_expr(body, &prefix, context, shape) {
348 Some(single_line_body_str)
349 if !single_line_body_str.contains('\n') =>
362 // When overflowing the closure which consists of a single control flow expression,
363 // force to use block if its condition uses multi line.
364 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
365 cond.contains('\n') || cond.len() > body_shape.width
367 if is_multi_lined_cond {
368 return rewrite_closure_with_block(body, &prefix, context, body_shape);
371 // Seems fine, just format the closure in usual manner.
372 return expr.rewrite(context, shape);
377 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
378 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
380 .filter_map(OverflowableItem::to_expr)
381 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
386 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
387 // If we are inside macro, we do not want to add or remove block from closure body.
388 if context.inside_macro() {
391 is_block_closure_forced_inner(expr, context.config.version())
395 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
397 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
398 ast::ExprKind::Loop(..) if version == Version::Two => true,
399 ast::ExprKind::AddrOf(_, _, ref expr)
400 | ast::ExprKind::Box(ref expr)
401 | ast::ExprKind::Try(ref expr)
402 | ast::ExprKind::Unary(_, ref expr)
403 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
408 /// Does this expression require a semicolon to be treated
409 /// as a statement? The negation of this: 'can this expression
410 /// be used as a statement without a semicolon' -- is used
411 /// as an early-bail-out in the parser so that, for instance,
412 /// if true {...} else {...}
414 /// isn't parsed as (if true {...} else {...} | x) | 5
415 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
416 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
418 ast::ExprKind::If(..)
419 | ast::ExprKind::Match(..)
420 | ast::ExprKind::Block(..)
421 | ast::ExprKind::While(..)
422 | ast::ExprKind::Loop(..)
423 | ast::ExprKind::ForLoop(..)
424 | ast::ExprKind::TryBlock(..) => false,