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