1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use syntax::parse::classify;
12 use syntax::source_map::Span;
13 use syntax::{ast, ptr};
15 use crate::config::lists::*;
16 use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
17 use crate::items::{span_hi_for_arg, span_lo_for_arg};
18 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
19 use crate::overflow::OverflowableItem;
20 use crate::rewrite::{Rewrite, RewriteContext};
21 use crate::shape::Shape;
22 use crate::source_map::SpanUtils;
23 use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
25 // This module is pretty messy because of the rules around closures and blocks:
26 // FIXME - the below is probably no longer true in full.
27 // * if there is a return type, then there must be braces,
28 // * given a closure with braces, whether that is parsed to give an inner block
29 // or not depends on if there is a return type and if there are statements
31 // * if the first expression in the body ends with a block (i.e., is a
32 // statement without needing a semi-colon), then adding or removing braces
33 // can change whether it is treated as an expression or statement.
35 pub fn rewrite_closure(
36 capture: ast::CaptureBy,
37 asyncness: ast::IsAsync,
38 movability: ast::Movability,
39 fn_decl: &ast::FnDecl,
42 context: &RewriteContext,
45 debug!("rewrite_closure {:?}", body);
47 let (prefix, extra_offset) = rewrite_closure_fn_decl(
48 capture, asyncness, movability, fn_decl, body, span, context, shape,
50 // 1 = space between `|...|` and body.
51 let body_shape = shape.offset_left(extra_offset)?;
53 if let ast::ExprKind::Block(ref block, _) = body.node {
54 // The body of the closure is an empty block.
55 if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
57 .rewrite(context, shape)
58 .map(|s| format!("{} {}", prefix, s));
61 let result = match fn_decl.output {
62 ast::FunctionRetTy::Default(_) if !context.inside_macro() => {
63 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
69 // Either we require a block, or tried without and failed.
70 rewrite_closure_block(block, &prefix, context, body_shape)
73 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
74 // The closure originally had a non-block expression, but we can't fit on
75 // one line, so we'll insert a block.
76 rewrite_closure_with_block(body, &prefix, context, body_shape)
81 fn try_rewrite_without_block(
84 context: &RewriteContext,
88 let expr = get_inner_expr(expr, prefix, context);
90 if is_block_closure_forced(context, expr) {
91 rewrite_closure_with_block(expr, prefix, context, shape)
93 rewrite_closure_expr(expr, prefix, context, body_shape)
97 fn get_inner_expr<'a>(
100 context: &RewriteContext,
102 if let ast::ExprKind::Block(ref block, _) = expr.node {
103 if !needs_block(block, prefix, context) {
104 // block.stmts.len() == 1
105 if let Some(expr) = stmt_expr(&block.stmts[0]) {
106 return get_inner_expr(expr, prefix, context);
114 // Figure out if a block is necessary.
115 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
116 is_unsafe_block(block)
117 || block.stmts.len() > 1
118 || block_contains_comment(block, context.source_map)
119 || prefix.contains('\n')
122 fn veto_block(e: &ast::Expr) -> bool {
124 ast::ExprKind::Call(..)
125 | ast::ExprKind::Binary(..)
126 | ast::ExprKind::Cast(..)
127 | ast::ExprKind::Type(..)
128 | ast::ExprKind::Assign(..)
129 | ast::ExprKind::AssignOp(..)
130 | ast::ExprKind::Field(..)
131 | ast::ExprKind::Index(..)
132 | ast::ExprKind::Range(..)
133 | ast::ExprKind::Try(..) => true,
138 // Rewrite closure with a single expression wrapping its body with block.
139 fn rewrite_closure_with_block(
142 context: &RewriteContext,
144 ) -> Option<String> {
145 let left_most = left_most_sub_expr(body);
146 let veto_block = veto_block(body) && !classify::expr_requires_semi_to_be_stmt(left_most);
151 let block = ast::Block {
152 stmts: vec![ast::Stmt {
153 id: ast::NodeId::root(),
154 node: ast::StmtKind::Expr(ptr::P(body.clone())),
157 id: ast::NodeId::root(),
158 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::Block(..)
178 | ast::ExprKind::TryBlock(..)
179 | ast::ExprKind::Loop(..)
180 | ast::ExprKind::Struct(..) => true,
182 ast::ExprKind::AddrOf(_, ref expr)
183 | ast::ExprKind::Box(ref expr)
184 | ast::ExprKind::Try(ref expr)
185 | ast::ExprKind::Unary(_, ref expr)
186 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
192 // When rewriting closure's body without block, we require it to fit in a single line
193 // unless it is a block-like expression or we are inside macro call.
194 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
195 || context.config.force_multiline_blocks();
196 expr.rewrite(context, shape)
198 if veto_multiline && rw.contains('\n') {
204 .map(|rw| format!("{} {}", prefix, rw))
207 // Rewrite closure whose body is block.
208 fn rewrite_closure_block(
211 context: &RewriteContext,
213 ) -> Option<String> {
214 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
217 // Return type is (prefix, extra_offset)
218 fn rewrite_closure_fn_decl(
219 capture: ast::CaptureBy,
220 asyncness: ast::IsAsync,
221 movability: ast::Movability,
222 fn_decl: &ast::FnDecl,
225 context: &RewriteContext,
227 ) -> Option<(String, usize)> {
228 let is_async = if asyncness.is_async() { "async " } else { "" };
229 let mover = if capture == ast::CaptureBy::Value {
234 let immovable = if movability == ast::Movability::Static {
239 // 4 = "|| {".len(), which is overconservative when the closure consists of
240 // a single expression.
241 let nested_shape = shape
242 .shrink_left(is_async.len() + mover.len() + immovable.len())?
246 let argument_offset = nested_shape.indent + 1;
247 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
248 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
250 let arg_items = itemize_list(
251 context.snippet_provider,
252 fn_decl.inputs.iter(),
255 |arg| span_lo_for_arg(arg),
256 |arg| span_hi_for_arg(context, arg),
257 |arg| arg.rewrite(context, arg_shape),
258 context.snippet_provider.span_after(span, "|"),
262 let item_vec = arg_items.collect::<Vec<_>>();
263 // 1 = space between arguments and return type.
264 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
265 let tactic = definitive_tactic(
267 ListTactic::HorizontalVertical,
271 let arg_shape = match tactic {
272 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
276 let fmt = ListFormatting::new(arg_shape, context.config)
278 .preserve_newline(true);
279 let list_str = write_list(&item_vec, &fmt)?;
280 let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
282 if !ret_str.is_empty() {
283 if prefix.contains('\n') {
285 prefix.push_str(&argument_offset.to_string(context.config));
289 prefix.push_str(&ret_str);
291 // 1 = space between `|...|` and body.
292 let extra_offset = last_line_width(&prefix) + 1;
294 Some((prefix, extra_offset))
297 // Rewriting closure which is placed at the end of the function call's arg.
298 // Returns `None` if the reformatted closure 'looks bad'.
299 pub fn rewrite_last_closure(
300 context: &RewriteContext,
303 ) -> Option<String> {
304 if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
307 let body = match body.node {
308 ast::ExprKind::Block(ref block, _)
309 if !is_unsafe_block(block)
310 && !context.inside_macro()
311 && is_simple_block(block, Some(&body.attrs), context.source_map) =>
313 stmt_expr(&block.stmts[0]).unwrap_or(body)
317 let (prefix, extra_offset) = rewrite_closure_fn_decl(
318 capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
320 // If the closure goes multi line before its body, do not overflow the closure.
321 if prefix.contains('\n') {
325 let body_shape = shape.offset_left(extra_offset)?;
327 // We force to use block for the body of the closure for certain kinds of expressions.
328 if is_block_closure_forced(context, body) {
329 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
331 // If the expression can fit in a single line, we need not force block closure.
332 if body_str.lines().count() <= 7 {
333 match rewrite_closure_expr(body, &prefix, context, shape) {
334 Some(ref single_line_body_str)
335 if !single_line_body_str.contains('\n') =>
337 Some(single_line_body_str.clone())
348 // When overflowing the closure which consists of a single control flow expression,
349 // force to use block if its condition uses multi line.
350 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
351 cond.contains('\n') || cond.len() > body_shape.width
353 if is_multi_lined_cond {
354 return rewrite_closure_with_block(body, &prefix, context, body_shape);
357 // Seems fine, just format the closure in usual manner.
358 return expr.rewrite(context, shape);
363 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
364 pub fn args_have_many_closure(args: &[OverflowableItem]) -> bool {
366 .filter_map(|arg| arg.to_expr())
367 .filter(|expr| match expr.node {
368 ast::ExprKind::Closure(..) => true,
375 fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {
376 // If we are inside macro, we do not want to add or remove block from closure body.
377 if context.inside_macro() {
380 is_block_closure_forced_inner(expr)
384 fn is_block_closure_forced_inner(expr: &ast::Expr) -> bool {
386 ast::ExprKind::If(..)
387 | ast::ExprKind::IfLet(..)
388 | ast::ExprKind::While(..)
389 | ast::ExprKind::WhileLet(..)
390 | ast::ExprKind::ForLoop(..) => true,
391 ast::ExprKind::AddrOf(_, ref expr)
392 | ast::ExprKind::Box(ref expr)
393 | ast::ExprKind::Try(ref expr)
394 | ast::ExprKind::Unary(_, ref expr)
395 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr),