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