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