]> git.lizzy.rs Git - rust.git/blob - src/closures.rs
5e2f01053f111131cf31639cb221ad95c7b44e38
[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     asyncness: ast::IsAsync,
37     movability: ast::Movability,
38     fn_decl: &ast::FnDecl,
39     body: &ast::Expr,
40     span: Span,
41     context: &RewriteContext,
42     shape: Shape,
43 ) -> Option<String> {
44     debug!("rewrite_closure {:?}", body);
45
46     let (prefix, extra_offset) = rewrite_closure_fn_decl(
47         capture, asyncness, movability, fn_decl, body, span, context, shape,
48     )?;
49     // 1 = space between `|...|` and body.
50     let body_shape = shape.offset_left(extra_offset)?;
51
52     if let ast::ExprKind::Block(ref block, _) = body.node {
53         // The body of the closure is an empty block.
54         if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
55             return body
56                 .rewrite(context, shape)
57                 .map(|s| format!("{} {}", prefix, s));
58         }
59
60         let result = match fn_decl.output {
61             ast::FunctionRetTy::Default(_) => {
62                 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
63             }
64             _ => None,
65         };
66
67         result.or_else(|| {
68             // Either we require a block, or tried without and failed.
69             rewrite_closure_block(block, &prefix, context, body_shape)
70         })
71     } else {
72         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
73             // The closure originally had a non-block expression, but we can't fit on
74             // one line, so we'll insert a block.
75             rewrite_closure_with_block(body, &prefix, context, body_shape)
76         })
77     }
78 }
79
80 fn try_rewrite_without_block(
81     expr: &ast::Expr,
82     prefix: &str,
83     context: &RewriteContext,
84     shape: Shape,
85     body_shape: Shape,
86 ) -> Option<String> {
87     let expr = get_inner_expr(expr, prefix, context);
88
89     if is_block_closure_forced(context, expr) {
90         rewrite_closure_with_block(expr, prefix, context, shape)
91     } else {
92         rewrite_closure_expr(expr, prefix, context, body_shape)
93     }
94 }
95
96 fn get_inner_expr<'a>(
97     expr: &'a ast::Expr,
98     prefix: &str,
99     context: &RewriteContext,
100 ) -> &'a ast::Expr {
101     if let ast::ExprKind::Block(ref block, _) = expr.node {
102         if !needs_block(block, prefix, context) {
103             // block.stmts.len() == 1
104             if let Some(expr) = stmt_expr(&block.stmts[0]) {
105                 return get_inner_expr(expr, prefix, context);
106             }
107         }
108     }
109
110     expr
111 }
112
113 // Figure out if a block is necessary.
114 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
115     is_unsafe_block(block)
116         || block.stmts.len() > 1
117         || block_contains_comment(block, context.codemap)
118         || prefix.contains('\n')
119 }
120
121 // Rewrite closure with a single expression wrapping its body with block.
122 fn rewrite_closure_with_block(
123     body: &ast::Expr,
124     prefix: &str,
125     context: &RewriteContext,
126     shape: Shape,
127 ) -> Option<String> {
128     let left_most = left_most_sub_expr(body);
129     let veto_block = left_most != body && !classify::expr_requires_semi_to_be_stmt(left_most);
130     if veto_block {
131         return None;
132     }
133
134     let block = ast::Block {
135         stmts: vec![ast::Stmt {
136             id: ast::NodeId::new(0),
137             node: ast::StmtKind::Expr(ptr::P(body.clone())),
138             span: body.span,
139         }],
140         id: ast::NodeId::new(0),
141         rules: ast::BlockCheckMode::Default,
142         span: body.span,
143         recovered: false,
144     };
145     let block = ::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
146     Some(format!("{} {}", prefix, block))
147 }
148
149 // Rewrite closure with a single expression without wrapping its body with block.
150 fn rewrite_closure_expr(
151     expr: &ast::Expr,
152     prefix: &str,
153     context: &RewriteContext,
154     shape: Shape,
155 ) -> Option<String> {
156     fn allow_multi_line(expr: &ast::Expr) -> bool {
157         match expr.node {
158             ast::ExprKind::Match(..)
159             | ast::ExprKind::Block(..)
160             | ast::ExprKind::Catch(..)
161             | ast::ExprKind::Loop(..)
162             | ast::ExprKind::Struct(..) => true,
163
164             ast::ExprKind::AddrOf(_, ref expr)
165             | ast::ExprKind::Box(ref expr)
166             | ast::ExprKind::Try(ref expr)
167             | ast::ExprKind::Unary(_, ref expr)
168             | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
169
170             _ => false,
171         }
172     }
173
174     // When rewriting closure's body without block, we require it to fit in a single line
175     // unless it is a block-like expression or we are inside macro call.
176     let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
177         || context.config.force_multiline_blocks();
178     expr.rewrite(context, shape)
179         .and_then(|rw| {
180             if veto_multiline && rw.contains('\n') {
181                 None
182             } else {
183                 Some(rw)
184             }
185         })
186         .map(|rw| format!("{} {}", prefix, rw))
187 }
188
189 // Rewrite closure whose body is block.
190 fn rewrite_closure_block(
191     block: &ast::Block,
192     prefix: &str,
193     context: &RewriteContext,
194     shape: Shape,
195 ) -> Option<String> {
196     Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
197 }
198
199 // Return type is (prefix, extra_offset)
200 fn rewrite_closure_fn_decl(
201     capture: ast::CaptureBy,
202     asyncness: ast::IsAsync,
203     movability: ast::Movability,
204     fn_decl: &ast::FnDecl,
205     body: &ast::Expr,
206     span: Span,
207     context: &RewriteContext,
208     shape: Shape,
209 ) -> Option<(String, usize)> {
210     let is_async = if asyncness.is_async() { "async " } else { "" };
211     let mover = if capture == ast::CaptureBy::Value {
212         "move "
213     } else {
214         ""
215     };
216     let immovable = if movability == ast::Movability::Static {
217         "static "
218     } else {
219         ""
220     };
221     // 4 = "|| {".len(), which is overconservative when the closure consists of
222     // a single expression.
223     let nested_shape = shape
224         .shrink_left(is_async.len() + mover.len() + immovable.len())?
225         .sub_width(4)?;
226
227     // 1 = |
228     let argument_offset = nested_shape.indent + 1;
229     let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
230     let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
231
232     let arg_items = itemize_list(
233         context.snippet_provider,
234         fn_decl.inputs.iter(),
235         "|",
236         ",",
237         |arg| span_lo_for_arg(arg),
238         |arg| span_hi_for_arg(context, arg),
239         |arg| arg.rewrite(context, arg_shape),
240         context.snippet_provider.span_after(span, "|"),
241         body.span.lo(),
242         false,
243     );
244     let item_vec = arg_items.collect::<Vec<_>>();
245     // 1 = space between arguments and return type.
246     let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
247     let tactic = definitive_tactic(
248         &item_vec,
249         ListTactic::HorizontalVertical,
250         Separator::Comma,
251         horizontal_budget,
252     );
253     let arg_shape = match tactic {
254         DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
255         _ => arg_shape,
256     };
257
258     let fmt = ListFormatting {
259         tactic,
260         separator: ",",
261         trailing_separator: SeparatorTactic::Never,
262         separator_place: SeparatorPlace::Back,
263         shape: arg_shape,
264         ends_with_newline: false,
265         preserve_newline: true,
266         nested: false,
267         config: context.config,
268     };
269     let list_str = write_list(&item_vec, &fmt)?;
270     let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
271
272     if !ret_str.is_empty() {
273         if prefix.contains('\n') {
274             prefix.push('\n');
275             prefix.push_str(&argument_offset.to_string(context.config));
276         } else {
277             prefix.push(' ');
278         }
279         prefix.push_str(&ret_str);
280     }
281     // 1 = space between `|...|` and body.
282     let extra_offset = last_line_width(&prefix) + 1;
283
284     Some((prefix, extra_offset))
285 }
286
287 // Rewriting closure which is placed at the end of the function call's arg.
288 // Returns `None` if the reformatted closure 'looks bad'.
289 pub fn rewrite_last_closure(
290     context: &RewriteContext,
291     expr: &ast::Expr,
292     shape: Shape,
293 ) -> Option<String> {
294     if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
295         expr.node
296     {
297         let body = match body.node {
298             ast::ExprKind::Block(ref block, _)
299                 if !is_unsafe_block(block)
300                     && is_simple_block(block, Some(&body.attrs), context.codemap) =>
301             {
302                 stmt_expr(&block.stmts[0]).unwrap_or(body)
303             }
304             _ => body,
305         };
306         let (prefix, extra_offset) = rewrite_closure_fn_decl(
307             capture, asyncness, movability, fn_decl, body, expr.span, context, 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 }