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::{ast, ptr};
12 use syntax::codemap::Span;
13 use syntax::parse::classify;
15 use codemap::SpanUtils;
16 use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond, ToExpr};
17 use items::{span_hi_for_arg, span_lo_for_arg};
18 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
19 ListTactic, Separator, SeparatorPlace, SeparatorTactic};
20 use rewrite::{Rewrite, RewriteContext};
22 use utils::{last_line_width, left_most_sub_expr, stmt_expr};
24 // This module is pretty messy because of the rules around closures and blocks:
25 // FIXME - the below is probably no longer true in full.
26 // * if there is a return type, then there must be braces,
27 // * given a closure with braces, whether that is parsed to give an inner block
28 // or not depends on if there is a return type and if there are statements
30 // * if the first expression in the body ends with a block (i.e., is a
31 // statement without needing a semi-colon), then adding or removing braces
32 // can change whether it is treated as an expression or statement.
34 pub fn rewrite_closure(
35 capture: ast::CaptureBy,
36 fn_decl: &ast::FnDecl,
39 context: &RewriteContext,
42 debug!("rewrite_closure {:?}", body);
44 let (prefix, extra_offset) =
45 rewrite_closure_fn_decl(capture, fn_decl, body, span, context, shape)?;
46 // 1 = space between `|...|` and body.
47 let body_shape = shape.offset_left(extra_offset)?;
49 if let ast::ExprKind::Block(ref block) = body.node {
50 // The body of the closure is an empty block.
51 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
52 return Some(format!("{} {{}}", prefix));
55 let result = match fn_decl.output {
56 ast::FunctionRetTy::Default(_) => {
57 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
63 // Either we require a block, or tried without and failed.
64 rewrite_closure_block(block, &prefix, context, body_shape)
67 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
68 // The closure originally had a non-block expression, but we can't fit on
69 // one line, so we'll insert a block.
70 rewrite_closure_with_block(body, &prefix, context, body_shape)
75 fn try_rewrite_without_block(
78 context: &RewriteContext,
82 let expr = get_inner_expr(expr, prefix, context);
84 if is_block_closure_forced(context, expr) {
85 rewrite_closure_with_block(expr, prefix, context, shape)
87 rewrite_closure_expr(expr, prefix, context, body_shape)
91 fn get_inner_expr<'a>(
94 context: &RewriteContext,
96 if let ast::ExprKind::Block(ref block) = expr.node {
97 if !needs_block(block, prefix, context) {
98 // block.stmts.len() == 1
99 if let Some(expr) = stmt_expr(&block.stmts[0]) {
100 return get_inner_expr(expr, prefix, context);
108 // Figure out if a block is necessary.
109 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
110 is_unsafe_block(block) || block.stmts.len() > 1
111 || block_contains_comment(block, context.codemap) || prefix.contains('\n')
114 // Rewrite closure with a single expression wrapping its body with block.
115 fn rewrite_closure_with_block(
118 context: &RewriteContext,
120 ) -> Option<String> {
121 let left_most = left_most_sub_expr(body);
122 let veto_block = left_most != body && !classify::expr_requires_semi_to_be_stmt(left_most);
127 let block = ast::Block {
130 id: ast::NodeId::new(0),
131 node: ast::StmtKind::Expr(ptr::P(body.clone())),
135 id: ast::NodeId::new(0),
136 rules: ast::BlockCheckMode::Default,
139 let block = ::expr::rewrite_block_with_visitor(context, "", &block, shape, false)?;
140 Some(format!("{} {}", prefix, block))
143 // Rewrite closure with a single expression without wrapping its body with block.
144 fn rewrite_closure_expr(
147 context: &RewriteContext,
149 ) -> Option<String> {
150 fn allow_multi_line(expr: &ast::Expr) -> bool {
152 ast::ExprKind::Match(..)
153 | ast::ExprKind::Block(..)
154 | ast::ExprKind::Catch(..)
155 | ast::ExprKind::Loop(..)
156 | ast::ExprKind::Struct(..) => true,
158 ast::ExprKind::AddrOf(_, ref expr)
159 | ast::ExprKind::Box(ref expr)
160 | ast::ExprKind::Try(ref expr)
161 | ast::ExprKind::Unary(_, ref expr)
162 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
168 // When rewriting closure's body without block, we require it to fit in a single line
169 // unless it is a block-like expression or we are inside macro call.
170 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro)
171 || context.config.force_multiline_blocks();
172 expr.rewrite(context, shape)
174 if veto_multiline && rw.contains('\n') {
180 .map(|rw| format!("{} {}", prefix, rw))
183 // Rewrite closure whose body is block.
184 fn rewrite_closure_block(
187 context: &RewriteContext,
189 ) -> Option<String> {
190 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
193 // Return type is (prefix, extra_offset)
194 fn rewrite_closure_fn_decl(
195 capture: ast::CaptureBy,
196 fn_decl: &ast::FnDecl,
199 context: &RewriteContext,
201 ) -> Option<(String, usize)> {
202 let mover = if capture == ast::CaptureBy::Value {
207 // 4 = "|| {".len(), which is overconservative when the closure consists of
208 // a single expression.
209 let nested_shape = shape.shrink_left(mover.len())?.sub_width(4)?;
212 let argument_offset = nested_shape.indent + 1;
213 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
214 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
216 let arg_items = itemize_list(
218 fn_decl.inputs.iter(),
221 |arg| span_lo_for_arg(arg),
222 |arg| span_hi_for_arg(context, arg),
223 |arg| arg.rewrite(context, arg_shape),
224 context.codemap.span_after(span, "|"),
228 let item_vec = arg_items.collect::<Vec<_>>();
229 // 1 = space between arguments and return type.
230 let horizontal_budget = nested_shape
232 .checked_sub(ret_str.len() + 1)
234 let tactic = definitive_tactic(
236 ListTactic::HorizontalVertical,
240 let arg_shape = match tactic {
241 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
245 let fmt = ListFormatting {
248 trailing_separator: SeparatorTactic::Never,
249 separator_place: SeparatorPlace::Back,
251 ends_with_newline: false,
252 preserve_newline: true,
253 config: context.config,
255 let list_str = write_list(&item_vec, &fmt)?;
256 let mut prefix = format!("{}|{}|", mover, list_str);
258 if !ret_str.is_empty() {
259 if prefix.contains('\n') {
261 prefix.push_str(&argument_offset.to_string(context.config));
265 prefix.push_str(&ret_str);
267 // 1 = space between `|...|` and body.
268 let extra_offset = last_line_width(&prefix) + 1;
270 Some((prefix, extra_offset))
273 // Rewriting closure which is placed at the end of the function call's arg.
274 // Returns `None` if the reformatted closure 'looks bad'.
275 pub fn rewrite_last_closure(
276 context: &RewriteContext,
279 ) -> Option<String> {
280 if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
281 let body = match body.node {
282 ast::ExprKind::Block(ref block)
283 if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
285 stmt_expr(&block.stmts[0]).unwrap_or(body)
289 let (prefix, extra_offset) =
290 rewrite_closure_fn_decl(capture, fn_decl, body, expr.span, context, shape)?;
291 // If the closure goes multi line before its body, do not overflow the closure.
292 if prefix.contains('\n') {
296 let body_shape = shape.offset_left(extra_offset)?;
298 // We force to use block for the body of the closure for certain kinds of expressions.
299 if is_block_closure_forced(context, body) {
300 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
302 // If the expression can fit in a single line, we need not force block closure.
303 if body_str.lines().count() <= 7 {
304 match rewrite_closure_expr(body, &prefix, context, shape) {
305 Some(ref single_line_body_str)
306 if !single_line_body_str.contains('\n') =>
308 Some(single_line_body_str.clone())
319 // When overflowing the closure which consists of a single control flow expression,
320 // force to use block if its condition uses multi line.
321 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
322 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
324 if is_multi_lined_cond {
325 return rewrite_closure_with_block(body, &prefix, context, body_shape);
328 // Seems fine, just format the closure in usual manner.
329 return expr.rewrite(context, shape);
334 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
335 pub fn args_have_many_closure<T>(args: &[&T]) -> bool
342 .map(|e| match e.node {
343 ast::ExprKind::Closure(..) => true,
351 fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {
352 // If we are inside macro, we do not want to add or remove block from closure body.
353 if context.inside_macro {
356 is_block_closure_forced_inner(expr)
360 fn is_block_closure_forced_inner(expr: &ast::Expr) -> bool {
362 ast::ExprKind::If(..)
363 | ast::ExprKind::IfLet(..)
364 | ast::ExprKind::While(..)
365 | ast::ExprKind::WhileLet(..)
366 | ast::ExprKind::ForLoop(..) => true,
367 ast::ExprKind::AddrOf(_, ref expr)
368 | ast::ExprKind::Box(ref expr)
369 | ast::ExprKind::Try(ref expr)
370 | ast::ExprKind::Unary(_, ref expr)
371 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr),