1 use syntax::parse::classify;
2 use syntax::source_map::Span;
3 use syntax::{ast, ptr};
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_arg, span_lo_for_arg};
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 fn rewrite_closure(
27 capture: ast::CaptureBy,
28 asyncness: ast::IsAsync,
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, asyncness, 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.node {
45 // The body of the closure is an empty block.
46 if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
48 .rewrite(context, shape)
49 .map(|s| format!("{} {}", prefix, s));
52 let result = match fn_decl.output {
53 ast::FunctionRetTy::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.node {
94 if !needs_block(block, prefix, context) {
95 // block.stmts.len() == 1
96 if let Some(expr) = stmt_expr(&block.stmts[0]) {
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) && !classify::expr_requires_semi_to_be_stmt(left_most);
142 let block = ast::Block {
143 stmts: vec![ast::Stmt {
144 id: ast::NodeId::root(),
145 node: 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 argument_offset = nested_shape.indent + 1;
237 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
238 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
240 let arg_items = itemize_list(
241 context.snippet_provider,
242 fn_decl.inputs.iter(),
245 |arg| span_lo_for_arg(arg),
246 |arg| span_hi_for_arg(context, arg),
247 |arg| arg.rewrite(context, arg_shape),
248 context.snippet_provider.span_after(span, "|"),
252 let item_vec = arg_items.collect::<Vec<_>>();
253 // 1 = space between arguments 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 arg_shape = match tactic {
262 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
266 let fmt = ListFormatting::new(arg_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(&argument_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 fn rewrite_last_closure(
290 context: &RewriteContext<'_>,
293 ) -> Option<String> {
294 if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
297 let body = match body.node {
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, asyncness, 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 fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
356 .filter_map(|arg| arg.to_expr())
357 .filter(|expr| match expr.node {
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(..)
377 | ast::ExprKind::IfLet(..)
378 | ast::ExprKind::While(..)
379 | ast::ExprKind::WhileLet(..)
380 | ast::ExprKind::ForLoop(..) => true,
381 ast::ExprKind::Loop(..) if version == Version::Two => true,
382 ast::ExprKind::AddrOf(_, ref expr)
383 | ast::ExprKind::Box(ref expr)
384 | ast::ExprKind::Try(ref expr)
385 | ast::ExprKind::Unary(_, ref expr)
386 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),