]> git.lizzy.rs Git - rust.git/blob - src/closures.rs
Merge pull request #2838 from nrc/chains
[rust.git] / src / closures.rs
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.
4 //
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.
10
11 use config::lists::*;
12 use syntax::codemap::Span;
13 use syntax::parse::classify;
14 use syntax::{ast, ptr};
15
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};
21 use shape::Shape;
22 use utils::{last_line_width, left_most_sub_expr, stmt_expr};
23
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
29 //     in that block,
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.
33
34 pub fn rewrite_closure(
35     capture: ast::CaptureBy,
36     asyncness: ast::IsAsync,
37     movability: ast::Movability,
38     fn_decl: &ast::FnDecl,
39     body: &ast::Expr,
40     span: Span,
41     context: &RewriteContext,
42     shape: Shape,
43 ) -> Option<String> {
44     debug!("rewrite_closure {:?}", body);
45
46     let (prefix, extra_offset) = rewrite_closure_fn_decl(
47         capture, asyncness, movability, fn_decl, body, span, context, shape,
48     )?;
49     // 1 = space between `|...|` and body.
50     let body_shape = shape.offset_left(extra_offset)?;
51
52     if let ast::ExprKind::Block(ref block, _) = body.node {
53         // The body of the closure is an empty block.
54         if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
55             return body
56                 .rewrite(context, shape)
57                 .map(|s| format!("{} {}", prefix, s));
58         }
59
60         let result = match fn_decl.output {
61             ast::FunctionRetTy::Default(_) => {
62                 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
63             }
64             _ => None,
65         };
66
67         result.or_else(|| {
68             // Either we require a block, or tried without and failed.
69             rewrite_closure_block(block, &prefix, context, body_shape)
70         })
71     } else {
72         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
73             // The closure originally had a non-block expression, but we can't fit on
74             // one line, so we'll insert a block.
75             rewrite_closure_with_block(body, &prefix, context, body_shape)
76         })
77     }
78 }
79
80 fn try_rewrite_without_block(
81     expr: &ast::Expr,
82     prefix: &str,
83     context: &RewriteContext,
84     shape: Shape,
85     body_shape: Shape,
86 ) -> Option<String> {
87     let expr = get_inner_expr(expr, prefix, context);
88
89     if is_block_closure_forced(context, expr) {
90         rewrite_closure_with_block(expr, prefix, context, shape)
91     } else {
92         rewrite_closure_expr(expr, prefix, context, body_shape)
93     }
94 }
95
96 fn get_inner_expr<'a>(
97     expr: &'a ast::Expr,
98     prefix: &str,
99     context: &RewriteContext,
100 ) -> &'a ast::Expr {
101     if let ast::ExprKind::Block(ref block, _) = expr.node {
102         if !needs_block(block, prefix, context) {
103             // block.stmts.len() == 1
104             if let Some(expr) = stmt_expr(&block.stmts[0]) {
105                 return get_inner_expr(expr, prefix, context);
106             }
107         }
108     }
109
110     expr
111 }
112
113 // Figure out if a block is necessary.
114 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
115     is_unsafe_block(block)
116         || block.stmts.len() > 1
117         || block_contains_comment(block, context.codemap)
118         || prefix.contains('\n')
119 }
120
121 fn veto_block(e: &ast::Expr) -> bool {
122     match e.node {
123         ast::ExprKind::Call(..)
124         | ast::ExprKind::Binary(..)
125         | ast::ExprKind::Cast(..)
126         | ast::ExprKind::Type(..)
127         | ast::ExprKind::Assign(..)
128         | ast::ExprKind::AssignOp(..)
129         | ast::ExprKind::Field(..)
130         | ast::ExprKind::Index(..)
131         | ast::ExprKind::Range(..)
132         | ast::ExprKind::Try(..) => true,
133         _ => false,
134     }
135 }
136
137 // Rewrite closure with a single expression wrapping its body with block.
138 fn rewrite_closure_with_block(
139     body: &ast::Expr,
140     prefix: &str,
141     context: &RewriteContext,
142     shape: Shape,
143 ) -> Option<String> {
144     let left_most = left_most_sub_expr(body);
145     let veto_block = veto_block(body) && !classify::expr_requires_semi_to_be_stmt(left_most);
146     if veto_block {
147         return None;
148     }
149
150     let block = ast::Block {
151         stmts: vec![ast::Stmt {
152             id: ast::NodeId::new(0),
153             node: ast::StmtKind::Expr(ptr::P(body.clone())),
154             span: body.span,
155         }],
156         id: ast::NodeId::new(0),
157         rules: ast::BlockCheckMode::Default,
158         span: body.span,
159         recovered: false,
160     };
161     let block = ::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
162     Some(format!("{} {}", prefix, block))
163 }
164
165 // Rewrite closure with a single expression without wrapping its body with block.
166 fn rewrite_closure_expr(
167     expr: &ast::Expr,
168     prefix: &str,
169     context: &RewriteContext,
170     shape: Shape,
171 ) -> Option<String> {
172     fn allow_multi_line(expr: &ast::Expr) -> bool {
173         match expr.node {
174             ast::ExprKind::Match(..)
175             | ast::ExprKind::Block(..)
176             | ast::ExprKind::Catch(..)
177             | ast::ExprKind::Loop(..)
178             | ast::ExprKind::Struct(..) => true,
179
180             ast::ExprKind::AddrOf(_, ref expr)
181             | ast::ExprKind::Box(ref expr)
182             | ast::ExprKind::Try(ref expr)
183             | ast::ExprKind::Unary(_, ref expr)
184             | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
185
186             _ => false,
187         }
188     }
189
190     // When rewriting closure's body without block, we require it to fit in a single line
191     // unless it is a block-like expression or we are inside macro call.
192     let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
193         || context.config.force_multiline_blocks();
194     expr.rewrite(context, shape)
195         .and_then(|rw| {
196             if veto_multiline && rw.contains('\n') {
197                 None
198             } else {
199                 Some(rw)
200             }
201         }).map(|rw| format!("{} {}", prefix, rw))
202 }
203
204 // Rewrite closure whose body is block.
205 fn rewrite_closure_block(
206     block: &ast::Block,
207     prefix: &str,
208     context: &RewriteContext,
209     shape: Shape,
210 ) -> Option<String> {
211     Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
212 }
213
214 // Return type is (prefix, extra_offset)
215 fn rewrite_closure_fn_decl(
216     capture: ast::CaptureBy,
217     asyncness: ast::IsAsync,
218     movability: ast::Movability,
219     fn_decl: &ast::FnDecl,
220     body: &ast::Expr,
221     span: Span,
222     context: &RewriteContext,
223     shape: Shape,
224 ) -> Option<(String, usize)> {
225     let is_async = if asyncness.is_async() { "async " } else { "" };
226     let mover = if capture == ast::CaptureBy::Value {
227         "move "
228     } else {
229         ""
230     };
231     let immovable = if movability == ast::Movability::Static {
232         "static "
233     } else {
234         ""
235     };
236     // 4 = "|| {".len(), which is overconservative when the closure consists of
237     // a single expression.
238     let nested_shape = shape
239         .shrink_left(is_async.len() + mover.len() + immovable.len())?
240         .sub_width(4)?;
241
242     // 1 = |
243     let argument_offset = nested_shape.indent + 1;
244     let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
245     let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
246
247     let arg_items = itemize_list(
248         context.snippet_provider,
249         fn_decl.inputs.iter(),
250         "|",
251         ",",
252         |arg| span_lo_for_arg(arg),
253         |arg| span_hi_for_arg(context, arg),
254         |arg| arg.rewrite(context, arg_shape),
255         context.snippet_provider.span_after(span, "|"),
256         body.span.lo(),
257         false,
258     );
259     let item_vec = arg_items.collect::<Vec<_>>();
260     // 1 = space between arguments and return type.
261     let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
262     let tactic = definitive_tactic(
263         &item_vec,
264         ListTactic::HorizontalVertical,
265         Separator::Comma,
266         horizontal_budget,
267     );
268     let arg_shape = match tactic {
269         DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
270         _ => arg_shape,
271     };
272
273     let fmt = ListFormatting {
274         tactic,
275         separator: ",",
276         trailing_separator: SeparatorTactic::Never,
277         separator_place: SeparatorPlace::Back,
278         shape: arg_shape,
279         ends_with_newline: false,
280         preserve_newline: true,
281         nested: false,
282         config: context.config,
283     };
284     let list_str = write_list(&item_vec, &fmt)?;
285     let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
286
287     if !ret_str.is_empty() {
288         if prefix.contains('\n') {
289             prefix.push('\n');
290             prefix.push_str(&argument_offset.to_string(context.config));
291         } else {
292             prefix.push(' ');
293         }
294         prefix.push_str(&ret_str);
295     }
296     // 1 = space between `|...|` and body.
297     let extra_offset = last_line_width(&prefix) + 1;
298
299     Some((prefix, extra_offset))
300 }
301
302 // Rewriting closure which is placed at the end of the function call's arg.
303 // Returns `None` if the reformatted closure 'looks bad'.
304 pub fn rewrite_last_closure(
305     context: &RewriteContext,
306     expr: &ast::Expr,
307     shape: Shape,
308 ) -> Option<String> {
309     if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
310         expr.node
311     {
312         let body = match body.node {
313             ast::ExprKind::Block(ref block, _)
314                 if !is_unsafe_block(block)
315                     && is_simple_block(block, Some(&body.attrs), context.codemap) =>
316             {
317                 stmt_expr(&block.stmts[0]).unwrap_or(body)
318             }
319             _ => body,
320         };
321         let (prefix, extra_offset) = rewrite_closure_fn_decl(
322             capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
323         )?;
324         // If the closure goes multi line before its body, do not overflow the closure.
325         if prefix.contains('\n') {
326             return None;
327         }
328
329         let body_shape = shape.offset_left(extra_offset)?;
330
331         // We force to use block for the body of the closure for certain kinds of expressions.
332         if is_block_closure_forced(context, body) {
333             return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
334                 |body_str| {
335                     // If the expression can fit in a single line, we need not force block closure.
336                     if body_str.lines().count() <= 7 {
337                         match rewrite_closure_expr(body, &prefix, context, shape) {
338                             Some(ref single_line_body_str)
339                                 if !single_line_body_str.contains('\n') =>
340                             {
341                                 Some(single_line_body_str.clone())
342                             }
343                             _ => Some(body_str),
344                         }
345                     } else {
346                         Some(body_str)
347                     }
348                 },
349             );
350         }
351
352         // When overflowing the closure which consists of a single control flow expression,
353         // force to use block if its condition uses multi line.
354         let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
355             .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
356             .unwrap_or(false);
357         if is_multi_lined_cond {
358             return rewrite_closure_with_block(body, &prefix, context, body_shape);
359         }
360
361         // Seems fine, just format the closure in usual manner.
362         return expr.rewrite(context, shape);
363     }
364     None
365 }
366
367 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
368 pub fn args_have_many_closure<T>(args: &[&T]) -> bool
369 where
370     T: ToExpr,
371 {
372     args.iter()
373         .filter(|arg| {
374             arg.to_expr()
375                 .map(|e| match e.node {
376                     ast::ExprKind::Closure(..) => true,
377                     _ => false,
378                 }).unwrap_or(false)
379         }).count()
380         > 1
381 }
382
383 fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {
384     // If we are inside macro, we do not want to add or remove block from closure body.
385     if context.inside_macro() {
386         false
387     } else {
388         is_block_closure_forced_inner(expr)
389     }
390 }
391
392 fn is_block_closure_forced_inner(expr: &ast::Expr) -> bool {
393     match expr.node {
394         ast::ExprKind::If(..)
395         | ast::ExprKind::IfLet(..)
396         | ast::ExprKind::While(..)
397         | ast::ExprKind::WhileLet(..)
398         | ast::ExprKind::ForLoop(..) => true,
399         ast::ExprKind::AddrOf(_, ref expr)
400         | ast::ExprKind::Box(ref expr)
401         | ast::ExprKind::Try(ref expr)
402         | ast::ExprKind::Unary(_, ref expr)
403         | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr),
404         _ => false,
405     }
406 }