]> git.lizzy.rs Git - rust.git/blob - src/closures.rs
Cargo update (#3559)
[rust.git] / src / closures.rs
1 use syntax::source_map::Span;
2 use syntax::{ast, ptr};
3
4 use crate::config::lists::*;
5 use crate::config::Version;
6 use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
7 use crate::items::{span_hi_for_arg, span_lo_for_arg};
8 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
9 use crate::overflow::OverflowableItem;
10 use crate::rewrite::{Rewrite, RewriteContext};
11 use crate::shape::Shape;
12 use crate::source_map::SpanUtils;
13 use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
14
15 // This module is pretty messy because of the rules around closures and blocks:
16 // FIXME - the below is probably no longer true in full.
17 //   * if there is a return type, then there must be braces,
18 //   * given a closure with braces, whether that is parsed to give an inner block
19 //     or not depends on if there is a return type and if there are statements
20 //     in that block,
21 //   * if the first expression in the body ends with a block (i.e., is a
22 //     statement without needing a semi-colon), then adding or removing braces
23 //     can change whether it is treated as an expression or statement.
24
25 pub(crate) fn rewrite_closure(
26     capture: ast::CaptureBy,
27     is_async: &ast::IsAsync,
28     movability: ast::Movability,
29     fn_decl: &ast::FnDecl,
30     body: &ast::Expr,
31     span: Span,
32     context: &RewriteContext<'_>,
33     shape: Shape,
34 ) -> Option<String> {
35     debug!("rewrite_closure {:?}", body);
36
37     let (prefix, extra_offset) = rewrite_closure_fn_decl(
38         capture, is_async, movability, fn_decl, body, span, context, shape,
39     )?;
40     // 1 = space between `|...|` and body.
41     let body_shape = shape.offset_left(extra_offset)?;
42
43     if let ast::ExprKind::Block(ref block, _) = body.node {
44         // The body of the closure is an empty block.
45         if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
46             return body
47                 .rewrite(context, shape)
48                 .map(|s| format!("{} {}", prefix, s));
49         }
50
51         let result = match fn_decl.output {
52             ast::FunctionRetTy::Default(_) if !context.inside_macro() => {
53                 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
54             }
55             _ => None,
56         };
57
58         result.or_else(|| {
59             // Either we require a block, or tried without and failed.
60             rewrite_closure_block(block, &prefix, context, body_shape)
61         })
62     } else {
63         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
64             // The closure originally had a non-block expression, but we can't fit on
65             // one line, so we'll insert a block.
66             rewrite_closure_with_block(body, &prefix, context, body_shape)
67         })
68     }
69 }
70
71 fn try_rewrite_without_block(
72     expr: &ast::Expr,
73     prefix: &str,
74     context: &RewriteContext<'_>,
75     shape: Shape,
76     body_shape: Shape,
77 ) -> Option<String> {
78     let expr = get_inner_expr(expr, prefix, context);
79
80     if is_block_closure_forced(context, expr) {
81         rewrite_closure_with_block(expr, prefix, context, shape)
82     } else {
83         rewrite_closure_expr(expr, prefix, context, body_shape)
84     }
85 }
86
87 fn get_inner_expr<'a>(
88     expr: &'a ast::Expr,
89     prefix: &str,
90     context: &RewriteContext<'_>,
91 ) -> &'a ast::Expr {
92     if let ast::ExprKind::Block(ref block, _) = expr.node {
93         if !needs_block(block, prefix, context) {
94             // block.stmts.len() == 1
95             if let Some(expr) = stmt_expr(&block.stmts[0]) {
96                 return get_inner_expr(expr, prefix, context);
97             }
98         }
99     }
100
101     expr
102 }
103
104 // Figure out if a block is necessary.
105 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
106     is_unsafe_block(block)
107         || block.stmts.len() > 1
108         || block_contains_comment(block, context.source_map)
109         || prefix.contains('\n')
110 }
111
112 fn veto_block(e: &ast::Expr) -> bool {
113     match e.node {
114         ast::ExprKind::Call(..)
115         | ast::ExprKind::Binary(..)
116         | ast::ExprKind::Cast(..)
117         | ast::ExprKind::Type(..)
118         | ast::ExprKind::Assign(..)
119         | ast::ExprKind::AssignOp(..)
120         | ast::ExprKind::Field(..)
121         | ast::ExprKind::Index(..)
122         | ast::ExprKind::Range(..)
123         | ast::ExprKind::Try(..) => true,
124         _ => false,
125     }
126 }
127
128 // Rewrite closure with a single expression wrapping its body with block.
129 fn rewrite_closure_with_block(
130     body: &ast::Expr,
131     prefix: &str,
132     context: &RewriteContext<'_>,
133     shape: Shape,
134 ) -> Option<String> {
135     let left_most = left_most_sub_expr(body);
136     let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
137     if veto_block {
138         return None;
139     }
140
141     let block = ast::Block {
142         stmts: vec![ast::Stmt {
143             id: ast::NodeId::root(),
144             node: ast::StmtKind::Expr(ptr::P(body.clone())),
145             span: body.span,
146         }],
147         id: ast::NodeId::root(),
148         rules: ast::BlockCheckMode::Default,
149         span: body.span,
150     };
151     let block =
152         crate::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
153     Some(format!("{} {}", prefix, block))
154 }
155
156 // Rewrite closure with a single expression without wrapping its body with block.
157 fn rewrite_closure_expr(
158     expr: &ast::Expr,
159     prefix: &str,
160     context: &RewriteContext<'_>,
161     shape: Shape,
162 ) -> Option<String> {
163     fn allow_multi_line(expr: &ast::Expr) -> bool {
164         match expr.node {
165             ast::ExprKind::Match(..)
166             | ast::ExprKind::Block(..)
167             | ast::ExprKind::TryBlock(..)
168             | ast::ExprKind::Loop(..)
169             | ast::ExprKind::Struct(..) => true,
170
171             ast::ExprKind::AddrOf(_, ref expr)
172             | ast::ExprKind::Box(ref expr)
173             | ast::ExprKind::Try(ref expr)
174             | ast::ExprKind::Unary(_, ref expr)
175             | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
176
177             _ => false,
178         }
179     }
180
181     // When rewriting closure's body without block, we require it to fit in a single line
182     // unless it is a block-like expression or we are inside macro call.
183     let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
184         || context.config.force_multiline_blocks();
185     expr.rewrite(context, shape)
186         .and_then(|rw| {
187             if veto_multiline && rw.contains('\n') {
188                 None
189             } else {
190                 Some(rw)
191             }
192         })
193         .map(|rw| format!("{} {}", prefix, rw))
194 }
195
196 // Rewrite closure whose body is block.
197 fn rewrite_closure_block(
198     block: &ast::Block,
199     prefix: &str,
200     context: &RewriteContext<'_>,
201     shape: Shape,
202 ) -> Option<String> {
203     Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
204 }
205
206 // Return type is (prefix, extra_offset)
207 fn rewrite_closure_fn_decl(
208     capture: ast::CaptureBy,
209     asyncness: &ast::IsAsync,
210     movability: ast::Movability,
211     fn_decl: &ast::FnDecl,
212     body: &ast::Expr,
213     span: Span,
214     context: &RewriteContext<'_>,
215     shape: Shape,
216 ) -> Option<(String, usize)> {
217     let is_async = if asyncness.is_async() { "async " } else { "" };
218     let mover = if capture == ast::CaptureBy::Value {
219         "move "
220     } else {
221         ""
222     };
223     let immovable = if movability == ast::Movability::Static {
224         "static "
225     } else {
226         ""
227     };
228     // 4 = "|| {".len(), which is overconservative when the closure consists of
229     // a single expression.
230     let nested_shape = shape
231         .shrink_left(is_async.len() + mover.len() + immovable.len())?
232         .sub_width(4)?;
233
234     // 1 = |
235     let argument_offset = nested_shape.indent + 1;
236     let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
237     let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
238
239     let arg_items = itemize_list(
240         context.snippet_provider,
241         fn_decl.inputs.iter(),
242         "|",
243         ",",
244         |arg| span_lo_for_arg(arg),
245         |arg| span_hi_for_arg(context, arg),
246         |arg| arg.rewrite(context, arg_shape),
247         context.snippet_provider.span_after(span, "|"),
248         body.span.lo(),
249         false,
250     );
251     let item_vec = arg_items.collect::<Vec<_>>();
252     // 1 = space between arguments and return type.
253     let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
254     let tactic = definitive_tactic(
255         &item_vec,
256         ListTactic::HorizontalVertical,
257         Separator::Comma,
258         horizontal_budget,
259     );
260     let arg_shape = match tactic {
261         DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
262         _ => arg_shape,
263     };
264
265     let fmt = ListFormatting::new(arg_shape, context.config)
266         .tactic(tactic)
267         .preserve_newline(true);
268     let list_str = write_list(&item_vec, &fmt)?;
269     let mut prefix = format!("{}{}{}|{}|", is_async, 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(crate) fn rewrite_last_closure(
289     context: &RewriteContext<'_>,
290     expr: &ast::Expr,
291     shape: Shape,
292 ) -> Option<String> {
293     if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
294         expr.node
295     {
296         let body = match body.node {
297             ast::ExprKind::Block(ref block, _)
298                 if !is_unsafe_block(block)
299                     && !context.inside_macro()
300                     && is_simple_block(block, Some(&body.attrs), context.source_map) =>
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, is_async, 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).map_or(false, |cond| {
340             cond.contains('\n') || cond.len() > body_shape.width
341         });
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(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
354     args.iter()
355         .filter_map(OverflowableItem::to_expr)
356         .filter(|expr| match expr.node {
357             ast::ExprKind::Closure(..) => true,
358             _ => false,
359         })
360         .count()
361         > 1
362 }
363
364 fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
365     // If we are inside macro, we do not want to add or remove block from closure body.
366     if context.inside_macro() {
367         false
368     } else {
369         is_block_closure_forced_inner(expr, context.config.version())
370     }
371 }
372
373 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
374     match expr.node {
375         ast::ExprKind::If(..)
376         | ast::ExprKind::IfLet(..)
377         | ast::ExprKind::While(..)
378         | ast::ExprKind::WhileLet(..)
379         | ast::ExprKind::ForLoop(..) => true,
380         ast::ExprKind::Loop(..) if version == Version::Two => 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, version),
386         _ => false,
387     }
388 }
389
390 /// Does this expression require a semicolon to be treated
391 /// as a statement? The negation of this: 'can this expression
392 /// be used as a statement without a semicolon' -- is used
393 /// as an early-bail-out in the parser so that, for instance,
394 ///     if true {...} else {...}
395 ///      |x| 5
396 /// isn't parsed as (if true {...} else {...} | x) | 5
397 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
398 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
399     match e.node {
400         ast::ExprKind::If(..)
401         | ast::ExprKind::IfLet(..)
402         | ast::ExprKind::Match(..)
403         | ast::ExprKind::Block(..)
404         | ast::ExprKind::While(..)
405         | ast::ExprKind::WhileLet(..)
406         | ast::ExprKind::Loop(..)
407         | ast::ExprKind::ForLoop(..)
408         | ast::ExprKind::TryBlock(..) => false,
409         _ => true,
410     }
411 }