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