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.
12 use syntax::codemap::Span;
13 use syntax::parse::classify;
14 use syntax::{ast, ptr};
16 use codemap::SpanUtils;
17 use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond, ToExpr};
18 use items::{span_hi_for_arg, span_lo_for_arg};
19 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
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 movability: ast::Movability,
37 fn_decl: &ast::FnDecl,
40 context: &RewriteContext,
43 debug!("rewrite_closure {:?}", body);
45 let (prefix, extra_offset) =
46 rewrite_closure_fn_decl(capture, movability, fn_decl, body, span, context, shape)?;
47 // 1 = space between `|...|` and body.
48 let body_shape = shape.offset_left(extra_offset)?;
50 if let ast::ExprKind::Block(ref block) = body.node {
51 // The body of the closure is an empty block.
52 if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
53 return body.rewrite(context, shape)
54 .map(|s| format!("{} {}", prefix, s));
57 let result = match fn_decl.output {
58 ast::FunctionRetTy::Default(_) => {
59 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
65 // Either we require a block, or tried without and failed.
66 rewrite_closure_block(block, &prefix, context, body_shape)
69 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
70 // The closure originally had a non-block expression, but we can't fit on
71 // one line, so we'll insert a block.
72 rewrite_closure_with_block(body, &prefix, context, body_shape)
77 fn try_rewrite_without_block(
80 context: &RewriteContext,
84 let expr = get_inner_expr(expr, prefix, context);
86 if is_block_closure_forced(context, expr) {
87 rewrite_closure_with_block(expr, prefix, context, shape)
89 rewrite_closure_expr(expr, prefix, context, body_shape)
93 fn get_inner_expr<'a>(
96 context: &RewriteContext,
98 if let ast::ExprKind::Block(ref block) = expr.node {
99 if !needs_block(block, prefix, context) {
100 // block.stmts.len() == 1
101 if let Some(expr) = stmt_expr(&block.stmts[0]) {
102 return get_inner_expr(expr, prefix, context);
110 // Figure out if a block is necessary.
111 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
112 is_unsafe_block(block) || block.stmts.len() > 1
113 || block_contains_comment(block, context.codemap) || prefix.contains('\n')
116 // Rewrite closure with a single expression wrapping its body with block.
117 fn rewrite_closure_with_block(
120 context: &RewriteContext,
122 ) -> Option<String> {
123 let left_most = left_most_sub_expr(body);
124 let veto_block = left_most != body && !classify::expr_requires_semi_to_be_stmt(left_most);
129 let block = ast::Block {
132 id: ast::NodeId::new(0),
133 node: ast::StmtKind::Expr(ptr::P(body.clone())),
137 id: ast::NodeId::new(0),
138 rules: ast::BlockCheckMode::Default,
142 let block = ::expr::rewrite_block_with_visitor(context, "", &block, None, shape, false)?;
143 Some(format!("{} {}", prefix, block))
146 // Rewrite closure with a single expression without wrapping its body with block.
147 fn rewrite_closure_expr(
150 context: &RewriteContext,
152 ) -> Option<String> {
153 fn allow_multi_line(expr: &ast::Expr) -> bool {
155 ast::ExprKind::Match(..)
156 | ast::ExprKind::Block(..)
157 | ast::ExprKind::Catch(..)
158 | ast::ExprKind::Loop(..)
159 | ast::ExprKind::Struct(..) => true,
161 ast::ExprKind::AddrOf(_, ref expr)
162 | ast::ExprKind::Box(ref expr)
163 | ast::ExprKind::Try(ref expr)
164 | ast::ExprKind::Unary(_, ref expr)
165 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
171 // When rewriting closure's body without block, we require it to fit in a single line
172 // unless it is a block-like expression or we are inside macro call.
173 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro)
174 || context.config.force_multiline_blocks();
175 expr.rewrite(context, shape)
177 if veto_multiline && rw.contains('\n') {
183 .map(|rw| format!("{} {}", prefix, rw))
186 // Rewrite closure whose body is block.
187 fn rewrite_closure_block(
190 context: &RewriteContext,
192 ) -> Option<String> {
193 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
196 // Return type is (prefix, extra_offset)
197 fn rewrite_closure_fn_decl(
198 capture: ast::CaptureBy,
199 movability: ast::Movability,
200 fn_decl: &ast::FnDecl,
203 context: &RewriteContext,
205 ) -> Option<(String, usize)> {
206 let mover = if capture == ast::CaptureBy::Value {
212 let immovable = if movability == ast::Movability::Static {
217 // 4 = "|| {".len(), which is overconservative when the closure consists of
218 // a single expression.
219 let nested_shape = shape
220 .shrink_left(mover.len() + immovable.len())?
224 let argument_offset = nested_shape.indent + 1;
225 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
226 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
228 let arg_items = itemize_list(
229 context.snippet_provider,
230 fn_decl.inputs.iter(),
233 |arg| span_lo_for_arg(arg),
234 |arg| span_hi_for_arg(context, arg),
235 |arg| arg.rewrite(context, arg_shape),
236 context.snippet_provider.span_after(span, "|"),
240 let item_vec = arg_items.collect::<Vec<_>>();
241 // 1 = space between arguments and return type.
242 let horizontal_budget = nested_shape
244 .checked_sub(ret_str.len() + 1)
246 let tactic = definitive_tactic(
248 ListTactic::HorizontalVertical,
252 let arg_shape = match tactic {
253 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
257 let fmt = ListFormatting {
260 trailing_separator: SeparatorTactic::Never,
261 separator_place: SeparatorPlace::Back,
263 ends_with_newline: false,
264 preserve_newline: true,
265 config: context.config,
267 let list_str = write_list(&item_vec, &fmt)?;
268 let mut prefix = format!("{}{}|{}|", immovable, mover, list_str);
270 if !ret_str.is_empty() {
271 if prefix.contains('\n') {
273 prefix.push_str(&argument_offset.to_string(context.config));
277 prefix.push_str(&ret_str);
279 // 1 = space between `|...|` and body.
280 let extra_offset = last_line_width(&prefix) + 1;
282 Some((prefix, extra_offset))
285 // Rewriting closure which is placed at the end of the function call's arg.
286 // Returns `None` if the reformatted closure 'looks bad'.
287 pub fn rewrite_last_closure(
288 context: &RewriteContext,
291 ) -> Option<String> {
292 if let ast::ExprKind::Closure(capture, movability, ref fn_decl, ref body, _) = expr.node {
293 let body = match body.node {
294 ast::ExprKind::Block(ref block)
295 if !is_unsafe_block(block)
296 && is_simple_block(block, Some(&body.attrs), context.codemap) =>
298 stmt_expr(&block.stmts[0]).unwrap_or(body)
302 let (prefix, extra_offset) = rewrite_closure_fn_decl(
311 // If the closure goes multi line before its body, do not overflow the closure.
312 if prefix.contains('\n') {
316 let body_shape = shape.offset_left(extra_offset)?;
318 // We force to use block for the body of the closure for certain kinds of expressions.
319 if is_block_closure_forced(context, body) {
320 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
322 // If the expression can fit in a single line, we need not force block closure.
323 if body_str.lines().count() <= 7 {
324 match rewrite_closure_expr(body, &prefix, context, shape) {
325 Some(ref single_line_body_str)
326 if !single_line_body_str.contains('\n') =>
328 Some(single_line_body_str.clone())
339 // When overflowing the closure which consists of a single control flow expression,
340 // force to use block if its condition uses multi line.
341 let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
342 .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
344 if is_multi_lined_cond {
345 return rewrite_closure_with_block(body, &prefix, context, body_shape);
348 // Seems fine, just format the closure in usual manner.
349 return expr.rewrite(context, shape);
354 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
355 pub fn args_have_many_closure<T>(args: &[&T]) -> bool
362 .map(|e| match e.node {
363 ast::ExprKind::Closure(..) => true,
371 fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {
372 // If we are inside macro, we do not want to add or remove block from closure body.
373 if context.inside_macro {
376 is_block_closure_forced_inner(expr)
380 fn is_block_closure_forced_inner(expr: &ast::Expr) -> bool {
382 ast::ExprKind::If(..)
383 | ast::ExprKind::IfLet(..)
384 | ast::ExprKind::While(..)
385 | ast::ExprKind::WhileLet(..)
386 | ast::ExprKind::ForLoop(..) => true,
387 ast::ExprKind::AddrOf(_, ref expr)
388 | ast::ExprKind::Box(ref expr)
389 | ast::ExprKind::Try(ref expr)
390 | ast::ExprKind::Unary(_, ref expr)
391 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr),