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_arg, span_lo_for_arg};
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.node {
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.node {
93 if !needs_block(block, prefix, context) {
94 // block.stmts.len() == 1
95 if let Some(expr) = stmt_expr(&block.stmts[0]) {
96 return get_inner_expr(expr, prefix, context);
104 // Figure out if a block is necessary.
105 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
106 is_unsafe_block(block)
107 || block.stmts.len() > 1
108 || block_contains_comment(block, context.source_map)
109 || prefix.contains('\n')
112 fn veto_block(e: &ast::Expr) -> bool {
114 ast::ExprKind::Call(..)
115 | ast::ExprKind::Binary(..)
116 | ast::ExprKind::Cast(..)
117 | ast::ExprKind::Type(..)
118 | ast::ExprKind::Assign(..)
119 | ast::ExprKind::AssignOp(..)
120 | ast::ExprKind::Field(..)
121 | ast::ExprKind::Index(..)
122 | ast::ExprKind::Range(..)
123 | ast::ExprKind::Try(..) => true,
128 // Rewrite closure with a single expression wrapping its body with block.
129 fn rewrite_closure_with_block(
132 context: &RewriteContext<'_>,
134 ) -> Option<String> {
135 let left_most = left_most_sub_expr(body);
136 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
141 let block = ast::Block {
142 stmts: vec![ast::Stmt {
143 id: ast::NodeId::root(),
144 node: ast::StmtKind::Expr(ptr::P(body.clone())),
147 id: ast::NodeId::root(),
148 rules: ast::BlockCheckMode::Default,
152 crate::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
153 Some(format!("{} {}", prefix, block))
156 // Rewrite closure with a single expression without wrapping its body with block.
157 fn rewrite_closure_expr(
160 context: &RewriteContext<'_>,
162 ) -> Option<String> {
163 fn allow_multi_line(expr: &ast::Expr) -> bool {
165 ast::ExprKind::Match(..)
166 | ast::ExprKind::Block(..)
167 | ast::ExprKind::TryBlock(..)
168 | ast::ExprKind::Loop(..)
169 | ast::ExprKind::Struct(..) => true,
171 ast::ExprKind::AddrOf(_, ref expr)
172 | ast::ExprKind::Box(ref expr)
173 | ast::ExprKind::Try(ref expr)
174 | ast::ExprKind::Unary(_, ref expr)
175 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
181 // When rewriting closure's body without block, we require it to fit in a single line
182 // unless it is a block-like expression or we are inside macro call.
183 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
184 || context.config.force_multiline_blocks();
185 expr.rewrite(context, shape)
187 if veto_multiline && rw.contains('\n') {
193 .map(|rw| format!("{} {}", prefix, rw))
196 // Rewrite closure whose body is block.
197 fn rewrite_closure_block(
200 context: &RewriteContext<'_>,
202 ) -> Option<String> {
203 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
206 // Return type is (prefix, extra_offset)
207 fn rewrite_closure_fn_decl(
208 capture: ast::CaptureBy,
209 asyncness: &ast::IsAsync,
210 movability: ast::Movability,
211 fn_decl: &ast::FnDecl,
214 context: &RewriteContext<'_>,
216 ) -> Option<(String, usize)> {
217 let is_async = if asyncness.is_async() { "async " } else { "" };
218 let mover = if capture == ast::CaptureBy::Value {
223 let immovable = if movability == ast::Movability::Static {
228 // 4 = "|| {".len(), which is overconservative when the closure consists of
229 // a single expression.
230 let nested_shape = shape
231 .shrink_left(is_async.len() + mover.len() + immovable.len())?
235 let argument_offset = nested_shape.indent + 1;
236 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
237 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
239 let arg_items = itemize_list(
240 context.snippet_provider,
241 fn_decl.inputs.iter(),
244 |arg| span_lo_for_arg(arg),
245 |arg| span_hi_for_arg(context, arg),
246 |arg| arg.rewrite(context, arg_shape),
247 context.snippet_provider.span_after(span, "|"),
251 let item_vec = arg_items.collect::<Vec<_>>();
252 // 1 = space between arguments and return type.
253 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
254 let tactic = definitive_tactic(
256 ListTactic::HorizontalVertical,
260 let arg_shape = match tactic {
261 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
265 let fmt = ListFormatting::new(arg_shape, context.config)
267 .preserve_newline(true);
268 let list_str = write_list(&item_vec, &fmt)?;
269 let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
271 if !ret_str.is_empty() {
272 if prefix.contains('\n') {
274 prefix.push_str(&argument_offset.to_string(context.config));
278 prefix.push_str(&ret_str);
280 // 1 = space between `|...|` and body.
281 let extra_offset = last_line_width(&prefix) + 1;
283 Some((prefix, extra_offset))
286 // Rewriting closure which is placed at the end of the function call's arg.
287 // Returns `None` if the reformatted closure 'looks bad'.
288 pub(crate) fn rewrite_last_closure(
289 context: &RewriteContext<'_>,
292 ) -> Option<String> {
293 if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
296 let body = match body.node {
297 ast::ExprKind::Block(ref block, _)
298 if !is_unsafe_block(block)
299 && !context.inside_macro()
300 && is_simple_block(block, Some(&body.attrs), context.source_map) =>
302 stmt_expr(&block.stmts[0]).unwrap_or(body)
306 let (prefix, extra_offset) = rewrite_closure_fn_decl(
307 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
309 // If the closure goes multi line before its body, do not overflow the closure.
310 if prefix.contains('\n') {
314 let body_shape = shape.offset_left(extra_offset)?;
316 // We force to use block for the body of the closure for certain kinds of expressions.
317 if is_block_closure_forced(context, body) {
318 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
320 // If the expression can fit in a single line, we need not force block closure.
321 if body_str.lines().count() <= 7 {
322 match rewrite_closure_expr(body, &prefix, context, shape) {
323 Some(ref single_line_body_str)
324 if !single_line_body_str.contains('\n') =>
326 Some(single_line_body_str.clone())
337 // When overflowing the closure which consists of a single control flow expression,
338 // force to use block if its condition uses multi line.
339 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
340 cond.contains('\n') || cond.len() > body_shape.width
342 if is_multi_lined_cond {
343 return rewrite_closure_with_block(body, &prefix, context, body_shape);
346 // Seems fine, just format the closure in usual manner.
347 return expr.rewrite(context, shape);
352 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
353 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
355 .filter_map(OverflowableItem::to_expr)
356 .filter(|expr| match expr.node {
357 ast::ExprKind::Closure(..) => true,
364 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
365 // If we are inside macro, we do not want to add or remove block from closure body.
366 if context.inside_macro() {
369 is_block_closure_forced_inner(expr, context.config.version())
373 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
375 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
376 ast::ExprKind::Loop(..) if version == Version::Two => true,
377 ast::ExprKind::AddrOf(_, ref expr)
378 | ast::ExprKind::Box(ref expr)
379 | ast::ExprKind::Try(ref expr)
380 | ast::ExprKind::Unary(_, ref expr)
381 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
386 /// Does this expression require a semicolon to be treated
387 /// as a statement? The negation of this: 'can this expression
388 /// be used as a statement without a semicolon' -- is used
389 /// as an early-bail-out in the parser so that, for instance,
390 /// if true {...} else {...}
392 /// isn't parsed as (if true {...} else {...} | x) | 5
393 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
394 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
396 ast::ExprKind::If(..)
397 | ast::ExprKind::Match(..)
398 | ast::ExprKind::Block(..)
399 | ast::ExprKind::While(..)
400 | ast::ExprKind::Loop(..)
401 | ast::ExprKind::ForLoop(..)
402 | ast::ExprKind::TryBlock(..) => false,