1 use syntax::source_map::Span;
2 use syntax::{ast, ptr};
4 use crate::config::lists::*;
5 use crate::config::Version;
6 use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
7 use crate::items::{span_hi_for_param, span_lo_for_param};
8 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
9 use crate::overflow::OverflowableItem;
10 use crate::rewrite::{Rewrite, RewriteContext};
11 use crate::shape::Shape;
12 use crate::source_map::SpanUtils;
13 use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
15 // This module is pretty messy because of the rules around closures and blocks:
16 // FIXME - the below is probably no longer true in full.
17 // * if there is a return type, then there must be braces,
18 // * given a closure with braces, whether that is parsed to give an inner block
19 // or not depends on if there is a return type and if there are statements
21 // * if the first expression in the body ends with a block (i.e., is a
22 // statement without needing a semi-colon), then adding or removing braces
23 // can change whether it is treated as an expression or statement.
25 pub(crate) fn rewrite_closure(
26 capture: ast::CaptureBy,
27 is_async: &ast::IsAsync,
28 movability: ast::Movability,
29 fn_decl: &ast::FnDecl,
32 context: &RewriteContext<'_>,
35 debug!("rewrite_closure {:?}", body);
37 let (prefix, extra_offset) = rewrite_closure_fn_decl(
38 capture, is_async, movability, fn_decl, body, span, context, shape,
40 // 1 = space between `|...|` and body.
41 let body_shape = shape.offset_left(extra_offset)?;
43 if let ast::ExprKind::Block(ref block, _) = body.kind {
44 // The body of the closure is an empty block.
45 if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
47 .rewrite(context, shape)
48 .map(|s| format!("{} {}", prefix, s));
51 let result = match fn_decl.output {
52 ast::FunctionRetTy::Default(_) if !context.inside_macro() => {
53 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
59 // Either we require a block, or tried without and failed.
60 rewrite_closure_block(block, &prefix, context, body_shape)
63 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
64 // The closure originally had a non-block expression, but we can't fit on
65 // one line, so we'll insert a block.
66 rewrite_closure_with_block(body, &prefix, context, body_shape)
71 fn try_rewrite_without_block(
74 context: &RewriteContext<'_>,
78 let expr = get_inner_expr(expr, prefix, context);
80 if is_block_closure_forced(context, expr) {
81 rewrite_closure_with_block(expr, prefix, context, shape)
83 rewrite_closure_expr(expr, prefix, context, body_shape)
87 fn get_inner_expr<'a>(
90 context: &RewriteContext<'_>,
92 if let ast::ExprKind::Block(ref block, _) = expr.kind {
93 if !needs_block(block, prefix, context) {
94 // block.stmts.len() == 1 except with `|| {{}}`;
95 // https://github.com/rust-lang/rustfmt/issues/3844
96 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
97 return get_inner_expr(expr, prefix, context);
105 // Figure out if a block is necessary.
106 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
107 is_unsafe_block(block)
108 || block.stmts.len() > 1
109 || block_contains_comment(block, context.source_map)
110 || prefix.contains('\n')
113 fn veto_block(e: &ast::Expr) -> bool {
115 ast::ExprKind::Call(..)
116 | ast::ExprKind::Binary(..)
117 | ast::ExprKind::Cast(..)
118 | ast::ExprKind::Type(..)
119 | ast::ExprKind::Assign(..)
120 | ast::ExprKind::AssignOp(..)
121 | ast::ExprKind::Field(..)
122 | ast::ExprKind::Index(..)
123 | ast::ExprKind::Range(..)
124 | ast::ExprKind::Try(..) => true,
129 // Rewrite closure with a single expression wrapping its body with block.
130 fn rewrite_closure_with_block(
133 context: &RewriteContext<'_>,
135 ) -> Option<String> {
136 let left_most = left_most_sub_expr(body);
137 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
142 let block = ast::Block {
143 stmts: vec![ast::Stmt {
144 id: ast::NodeId::root(),
145 kind: ast::StmtKind::Expr(ptr::P(body.clone())),
148 id: ast::NodeId::root(),
149 rules: ast::BlockCheckMode::Default,
153 crate::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
154 Some(format!("{} {}", prefix, block))
157 // Rewrite closure with a single expression without wrapping its body with block.
158 fn rewrite_closure_expr(
161 context: &RewriteContext<'_>,
163 ) -> Option<String> {
164 fn allow_multi_line(expr: &ast::Expr) -> bool {
166 ast::ExprKind::Match(..)
167 | ast::ExprKind::Block(..)
168 | ast::ExprKind::TryBlock(..)
169 | ast::ExprKind::Loop(..)
170 | ast::ExprKind::Struct(..) => true,
172 ast::ExprKind::AddrOf(_, ref expr)
173 | ast::ExprKind::Box(ref expr)
174 | ast::ExprKind::Try(ref expr)
175 | ast::ExprKind::Unary(_, ref expr)
176 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
182 // When rewriting closure's body without block, we require it to fit in a single line
183 // unless it is a block-like expression or we are inside macro call.
184 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
185 || context.config.force_multiline_blocks();
186 expr.rewrite(context, shape)
188 if veto_multiline && rw.contains('\n') {
194 .map(|rw| format!("{} {}", prefix, rw))
197 // Rewrite closure whose body is block.
198 fn rewrite_closure_block(
201 context: &RewriteContext<'_>,
203 ) -> Option<String> {
204 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
207 // Return type is (prefix, extra_offset)
208 fn rewrite_closure_fn_decl(
209 capture: ast::CaptureBy,
210 asyncness: &ast::IsAsync,
211 movability: ast::Movability,
212 fn_decl: &ast::FnDecl,
215 context: &RewriteContext<'_>,
217 ) -> Option<(String, usize)> {
218 let is_async = if asyncness.is_async() { "async " } else { "" };
219 let mover = if capture == ast::CaptureBy::Value {
224 let immovable = if movability == ast::Movability::Static {
229 // 4 = "|| {".len(), which is overconservative when the closure consists of
230 // a single expression.
231 let nested_shape = shape
232 .shrink_left(is_async.len() + mover.len() + immovable.len())?
236 let param_offset = nested_shape.indent + 1;
237 let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
238 let ret_str = fn_decl.output.rewrite(context, param_shape)?;
240 let param_items = itemize_list(
241 context.snippet_provider,
242 fn_decl.inputs.iter(),
245 |param| span_lo_for_param(param),
246 |param| span_hi_for_param(context, param),
247 |param| param.rewrite(context, param_shape),
248 context.snippet_provider.span_after(span, "|"),
252 let item_vec = param_items.collect::<Vec<_>>();
253 // 1 = space between parameters and return type.
254 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
255 let tactic = definitive_tactic(
257 ListTactic::HorizontalVertical,
261 let param_shape = match tactic {
262 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
266 let fmt = ListFormatting::new(param_shape, context.config)
268 .preserve_newline(true);
269 let list_str = write_list(&item_vec, &fmt)?;
270 let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
272 if !ret_str.is_empty() {
273 if prefix.contains('\n') {
275 prefix.push_str(¶m_offset.to_string(context.config));
279 prefix.push_str(&ret_str);
281 // 1 = space between `|...|` and body.
282 let extra_offset = last_line_width(&prefix) + 1;
284 Some((prefix, extra_offset))
287 // Rewriting closure which is placed at the end of the function call's arg.
288 // Returns `None` if the reformatted closure 'looks bad'.
289 pub(crate) fn rewrite_last_closure(
290 context: &RewriteContext<'_>,
293 ) -> Option<String> {
294 if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
297 let body = match body.kind {
298 ast::ExprKind::Block(ref block, _)
299 if !is_unsafe_block(block)
300 && !context.inside_macro()
301 && is_simple_block(block, Some(&body.attrs), context.source_map) =>
303 stmt_expr(&block.stmts[0]).unwrap_or(body)
307 let (prefix, extra_offset) = rewrite_closure_fn_decl(
308 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
310 // If the closure goes multi line before its body, do not overflow the closure.
311 if prefix.contains('\n') {
315 let body_shape = shape.offset_left(extra_offset)?;
317 // We force to use block for the body of the closure for certain kinds of expressions.
318 if is_block_closure_forced(context, body) {
319 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
321 // If the expression can fit in a single line, we need not force block closure.
322 if body_str.lines().count() <= 7 {
323 match rewrite_closure_expr(body, &prefix, context, shape) {
324 Some(ref single_line_body_str)
325 if !single_line_body_str.contains('\n') =>
327 Some(single_line_body_str.clone())
338 // When overflowing the closure which consists of a single control flow expression,
339 // force to use block if its condition uses multi line.
340 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
341 cond.contains('\n') || cond.len() > body_shape.width
343 if is_multi_lined_cond {
344 return rewrite_closure_with_block(body, &prefix, context, body_shape);
347 // Seems fine, just format the closure in usual manner.
348 return expr.rewrite(context, shape);
353 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
354 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
356 .filter_map(OverflowableItem::to_expr)
357 .filter(|expr| match expr.kind {
358 ast::ExprKind::Closure(..) => true,
365 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
366 // If we are inside macro, we do not want to add or remove block from closure body.
367 if context.inside_macro() {
370 is_block_closure_forced_inner(expr, context.config.version())
374 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
376 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
377 ast::ExprKind::Loop(..) if version == Version::Two => true,
378 ast::ExprKind::AddrOf(_, ref expr)
379 | ast::ExprKind::Box(ref expr)
380 | ast::ExprKind::Try(ref expr)
381 | ast::ExprKind::Unary(_, ref expr)
382 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
387 /// Does this expression require a semicolon to be treated
388 /// as a statement? The negation of this: 'can this expression
389 /// be used as a statement without a semicolon' -- is used
390 /// as an early-bail-out in the parser so that, for instance,
391 /// if true {...} else {...}
393 /// isn't parsed as (if true {...} else {...} | x) | 5
394 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
395 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
397 ast::ExprKind::If(..)
398 | ast::ExprKind::Match(..)
399 | ast::ExprKind::Block(..)
400 | ast::ExprKind::While(..)
401 | ast::ExprKind::Loop(..)
402 | ast::ExprKind::ForLoop(..)
403 | ast::ExprKind::TryBlock(..) => false,