2 use syntax::{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
111 .map_or(false, |first_stmt| match get_attrs_from_stmt(first_stmt) {
112 Some(attrs) => !attrs.is_empty(),
116 is_unsafe_block(block)
117 || block.stmts.len() > 1
119 || block_contains_comment(context, block)
120 || prefix.contains('\n')
123 fn veto_block(e: &ast::Expr) -> bool {
125 ast::ExprKind::Call(..)
126 | ast::ExprKind::Binary(..)
127 | ast::ExprKind::Cast(..)
128 | ast::ExprKind::Type(..)
129 | ast::ExprKind::Assign(..)
130 | ast::ExprKind::AssignOp(..)
131 | ast::ExprKind::Field(..)
132 | ast::ExprKind::Index(..)
133 | ast::ExprKind::Range(..)
134 | ast::ExprKind::Try(..) => true,
139 // Rewrite closure with a single expression wrapping its body with block.
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,
163 crate::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
164 Some(format!("{} {}", prefix, block))
167 // Rewrite closure with a single expression without wrapping its body with block.
168 fn rewrite_closure_expr(
171 context: &RewriteContext<'_>,
173 ) -> Option<String> {
174 fn allow_multi_line(expr: &ast::Expr) -> bool {
176 ast::ExprKind::Match(..)
177 | ast::ExprKind::Async(..)
178 | ast::ExprKind::Block(..)
179 | ast::ExprKind::TryBlock(..)
180 | ast::ExprKind::Loop(..)
181 | ast::ExprKind::Struct(..) => true,
183 ast::ExprKind::AddrOf(_, _, ref expr)
184 | ast::ExprKind::Box(ref expr)
185 | ast::ExprKind::Try(ref expr)
186 | ast::ExprKind::Unary(_, ref expr)
187 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
193 // When rewriting closure's body without block, we require it to fit in a single line
194 // unless it is a block-like expression or we are inside macro call.
195 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
196 || context.config.force_multiline_blocks();
197 expr.rewrite(context, shape)
199 if veto_multiline && rw.contains('\n') {
205 .map(|rw| format!("{} {}", prefix, rw))
208 // Rewrite closure whose body is block.
209 fn rewrite_closure_block(
212 context: &RewriteContext<'_>,
214 ) -> Option<String> {
215 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
218 // Return type is (prefix, extra_offset)
219 fn rewrite_closure_fn_decl(
220 capture: ast::CaptureBy,
221 asyncness: &ast::Async,
222 movability: ast::Movability,
223 fn_decl: &ast::FnDecl,
226 context: &RewriteContext<'_>,
228 ) -> Option<(String, usize)> {
229 let is_async = if asyncness.is_async() { "async " } else { "" };
230 let mover = if capture == ast::CaptureBy::Value {
235 let immovable = if movability == ast::Movability::Static {
240 // 4 = "|| {".len(), which is overconservative when the closure consists of
241 // a single expression.
242 let nested_shape = shape
243 .shrink_left(is_async.len() + mover.len() + immovable.len())?
247 let param_offset = nested_shape.indent + 1;
248 let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
249 let ret_str = fn_decl.output.rewrite(context, param_shape)?;
251 let param_items = itemize_list(
252 context.snippet_provider,
253 fn_decl.inputs.iter(),
256 |param| span_lo_for_param(param),
257 |param| span_hi_for_param(context, param),
258 |param| param.rewrite(context, param_shape),
259 context.snippet_provider.span_after(span, "|"),
263 let item_vec = param_items.collect::<Vec<_>>();
264 // 1 = space between parameters and return type.
265 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
266 let tactic = definitive_tactic(
268 ListTactic::HorizontalVertical,
272 let param_shape = match tactic {
273 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
277 let fmt = ListFormatting::new(param_shape, context.config)
279 .preserve_newline(true);
280 let list_str = write_list(&item_vec, &fmt)?;
281 let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
283 if !ret_str.is_empty() {
284 if prefix.contains('\n') {
286 prefix.push_str(¶m_offset.to_string(context.config));
290 prefix.push_str(&ret_str);
292 // 1 = space between `|...|` and body.
293 let extra_offset = last_line_width(&prefix) + 1;
295 Some((prefix, extra_offset))
298 // Rewriting closure which is placed at the end of the function call's arg.
299 // Returns `None` if the reformatted closure 'looks bad'.
300 pub(crate) fn rewrite_last_closure(
301 context: &RewriteContext<'_>,
304 ) -> Option<String> {
305 if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
308 let body = match body.kind {
309 ast::ExprKind::Block(ref block, _)
310 if !is_unsafe_block(block)
311 && !context.inside_macro()
312 && is_simple_block(context, block, Some(&body.attrs)) =>
314 stmt_expr(&block.stmts[0]).unwrap_or(body)
318 let (prefix, extra_offset) = rewrite_closure_fn_decl(
319 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
321 // If the closure goes multi line before its body, do not overflow the closure.
322 if prefix.contains('\n') {
326 let body_shape = shape.offset_left(extra_offset)?;
328 // We force to use block for the body of the closure for certain kinds of expressions.
329 if is_block_closure_forced(context, body) {
330 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
332 // If the expression can fit in a single line, we need not force block closure.
333 if body_str.lines().count() <= 7 {
334 match rewrite_closure_expr(body, &prefix, context, shape) {
335 Some(ref single_line_body_str)
336 if !single_line_body_str.contains('\n') =>
338 Some(single_line_body_str.clone())
349 // When overflowing the closure which consists of a single control flow expression,
350 // force to use block if its condition uses multi line.
351 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
352 cond.contains('\n') || cond.len() > body_shape.width
354 if is_multi_lined_cond {
355 return rewrite_closure_with_block(body, &prefix, context, body_shape);
358 // Seems fine, just format the closure in usual manner.
359 return expr.rewrite(context, shape);
364 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
365 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
367 .filter_map(OverflowableItem::to_expr)
368 .filter(|expr| match expr.kind {
369 ast::ExprKind::Closure(..) => true,
376 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
377 // If we are inside macro, we do not want to add or remove block from closure body.
378 if context.inside_macro() {
381 is_block_closure_forced_inner(expr, context.config.version())
385 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
387 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
388 ast::ExprKind::Loop(..) if version == Version::Two => true,
389 ast::ExprKind::AddrOf(_, _, ref expr)
390 | ast::ExprKind::Box(ref expr)
391 | ast::ExprKind::Try(ref expr)
392 | ast::ExprKind::Unary(_, ref expr)
393 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
398 /// Does this expression require a semicolon to be treated
399 /// as a statement? The negation of this: 'can this expression
400 /// be used as a statement without a semicolon' -- is used
401 /// as an early-bail-out in the parser so that, for instance,
402 /// if true {...} else {...}
404 /// isn't parsed as (if true {...} else {...} | x) | 5
405 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
406 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
408 ast::ExprKind::If(..)
409 | ast::ExprKind::Match(..)
410 | ast::ExprKind::Block(..)
411 | ast::ExprKind::While(..)
412 | ast::ExprKind::Loop(..)
413 | ast::ExprKind::ForLoop(..)
414 | ast::ExprKind::TryBlock(..) => false,