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