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