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