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