]> git.lizzy.rs Git - rust.git/blob - src/closures.rs
fix panic on closure with empty block expr (#3846)
[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_param, span_lo_for_param};
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.kind {
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.kind {
93         if !needs_block(block, prefix, context) {
94             // block.stmts.len() == 1 except with `|| {{}}`;
95             // https://github.com/rust-lang/rustfmt/issues/3844
96             if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
97                 return get_inner_expr(expr, prefix, context);
98             }
99         }
100     }
101
102     expr
103 }
104
105 // Figure out if a block is necessary.
106 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
107     is_unsafe_block(block)
108         || block.stmts.len() > 1
109         || block_contains_comment(block, context.source_map)
110         || prefix.contains('\n')
111 }
112
113 fn veto_block(e: &ast::Expr) -> bool {
114     match e.kind {
115         ast::ExprKind::Call(..)
116         | ast::ExprKind::Binary(..)
117         | ast::ExprKind::Cast(..)
118         | ast::ExprKind::Type(..)
119         | ast::ExprKind::Assign(..)
120         | ast::ExprKind::AssignOp(..)
121         | ast::ExprKind::Field(..)
122         | ast::ExprKind::Index(..)
123         | ast::ExprKind::Range(..)
124         | ast::ExprKind::Try(..) => true,
125         _ => false,
126     }
127 }
128
129 // Rewrite closure with a single expression wrapping its body with block.
130 fn rewrite_closure_with_block(
131     body: &ast::Expr,
132     prefix: &str,
133     context: &RewriteContext<'_>,
134     shape: Shape,
135 ) -> Option<String> {
136     let left_most = left_most_sub_expr(body);
137     let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
138     if veto_block {
139         return None;
140     }
141
142     let block = ast::Block {
143         stmts: vec![ast::Stmt {
144             id: ast::NodeId::root(),
145             kind: ast::StmtKind::Expr(ptr::P(body.clone())),
146             span: body.span,
147         }],
148         id: ast::NodeId::root(),
149         rules: ast::BlockCheckMode::Default,
150         span: body.span,
151     };
152     let block =
153         crate::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
154     Some(format!("{} {}", prefix, block))
155 }
156
157 // Rewrite closure with a single expression without wrapping its body with block.
158 fn rewrite_closure_expr(
159     expr: &ast::Expr,
160     prefix: &str,
161     context: &RewriteContext<'_>,
162     shape: Shape,
163 ) -> Option<String> {
164     fn allow_multi_line(expr: &ast::Expr) -> bool {
165         match expr.kind {
166             ast::ExprKind::Match(..)
167             | ast::ExprKind::Block(..)
168             | ast::ExprKind::TryBlock(..)
169             | ast::ExprKind::Loop(..)
170             | ast::ExprKind::Struct(..) => true,
171
172             ast::ExprKind::AddrOf(_, ref expr)
173             | ast::ExprKind::Box(ref expr)
174             | ast::ExprKind::Try(ref expr)
175             | ast::ExprKind::Unary(_, ref expr)
176             | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
177
178             _ => false,
179         }
180     }
181
182     // When rewriting closure's body without block, we require it to fit in a single line
183     // unless it is a block-like expression or we are inside macro call.
184     let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
185         || context.config.force_multiline_blocks();
186     expr.rewrite(context, shape)
187         .and_then(|rw| {
188             if veto_multiline && rw.contains('\n') {
189                 None
190             } else {
191                 Some(rw)
192             }
193         })
194         .map(|rw| format!("{} {}", prefix, rw))
195 }
196
197 // Rewrite closure whose body is block.
198 fn rewrite_closure_block(
199     block: &ast::Block,
200     prefix: &str,
201     context: &RewriteContext<'_>,
202     shape: Shape,
203 ) -> Option<String> {
204     Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
205 }
206
207 // Return type is (prefix, extra_offset)
208 fn rewrite_closure_fn_decl(
209     capture: ast::CaptureBy,
210     asyncness: &ast::IsAsync,
211     movability: ast::Movability,
212     fn_decl: &ast::FnDecl,
213     body: &ast::Expr,
214     span: Span,
215     context: &RewriteContext<'_>,
216     shape: Shape,
217 ) -> Option<(String, usize)> {
218     let is_async = if asyncness.is_async() { "async " } else { "" };
219     let mover = if capture == ast::CaptureBy::Value {
220         "move "
221     } else {
222         ""
223     };
224     let immovable = if movability == ast::Movability::Static {
225         "static "
226     } else {
227         ""
228     };
229     // 4 = "|| {".len(), which is overconservative when the closure consists of
230     // a single expression.
231     let nested_shape = shape
232         .shrink_left(is_async.len() + mover.len() + immovable.len())?
233         .sub_width(4)?;
234
235     // 1 = |
236     let param_offset = nested_shape.indent + 1;
237     let param_shape = nested_shape.offset_left(1)?.visual_indent(0);
238     let ret_str = fn_decl.output.rewrite(context, param_shape)?;
239
240     let param_items = itemize_list(
241         context.snippet_provider,
242         fn_decl.inputs.iter(),
243         "|",
244         ",",
245         |param| span_lo_for_param(param),
246         |param| span_hi_for_param(context, param),
247         |param| param.rewrite(context, param_shape),
248         context.snippet_provider.span_after(span, "|"),
249         body.span.lo(),
250         false,
251     );
252     let item_vec = param_items.collect::<Vec<_>>();
253     // 1 = space between parameters and return type.
254     let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
255     let tactic = definitive_tactic(
256         &item_vec,
257         ListTactic::HorizontalVertical,
258         Separator::Comma,
259         horizontal_budget,
260     );
261     let param_shape = match tactic {
262         DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1)?,
263         _ => param_shape,
264     };
265
266     let fmt = ListFormatting::new(param_shape, context.config)
267         .tactic(tactic)
268         .preserve_newline(true);
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(&param_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(crate) fn rewrite_last_closure(
290     context: &RewriteContext<'_>,
291     expr: &ast::Expr,
292     shape: Shape,
293 ) -> Option<String> {
294     if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) =
295         expr.kind
296     {
297         let body = match body.kind {
298             ast::ExprKind::Block(ref block, _)
299                 if !is_unsafe_block(block)
300                     && !context.inside_macro()
301                     && is_simple_block(block, Some(&body.attrs), context.source_map) =>
302             {
303                 stmt_expr(&block.stmts[0]).unwrap_or(body)
304             }
305             _ => body,
306         };
307         let (prefix, extra_offset) = rewrite_closure_fn_decl(
308             capture, is_async, movability, fn_decl, body, expr.span, context, shape,
309         )?;
310         // If the closure goes multi line before its body, do not overflow the closure.
311         if prefix.contains('\n') {
312             return None;
313         }
314
315         let body_shape = shape.offset_left(extra_offset)?;
316
317         // We force to use block for the body of the closure for certain kinds of expressions.
318         if is_block_closure_forced(context, body) {
319             return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
320                 |body_str| {
321                     // If the expression can fit in a single line, we need not force block closure.
322                     if body_str.lines().count() <= 7 {
323                         match rewrite_closure_expr(body, &prefix, context, shape) {
324                             Some(ref single_line_body_str)
325                                 if !single_line_body_str.contains('\n') =>
326                             {
327                                 Some(single_line_body_str.clone())
328                             }
329                             _ => Some(body_str),
330                         }
331                     } else {
332                         Some(body_str)
333                     }
334                 },
335             );
336         }
337
338         // When overflowing the closure which consists of a single control flow expression,
339         // force to use block if its condition uses multi line.
340         let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
341             cond.contains('\n') || cond.len() > body_shape.width
342         });
343         if is_multi_lined_cond {
344             return rewrite_closure_with_block(body, &prefix, context, body_shape);
345         }
346
347         // Seems fine, just format the closure in usual manner.
348         return expr.rewrite(context, shape);
349     }
350     None
351 }
352
353 /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
354 pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
355     args.iter()
356         .filter_map(OverflowableItem::to_expr)
357         .filter(|expr| match expr.kind {
358             ast::ExprKind::Closure(..) => true,
359             _ => false,
360         })
361         .count()
362         > 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, context.config.version())
371     }
372 }
373
374 fn is_block_closure_forced_inner(expr: &ast::Expr, version: Version) -> bool {
375     match expr.kind {
376         ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop(..) => true,
377         ast::ExprKind::Loop(..) if version == Version::Two => true,
378         ast::ExprKind::AddrOf(_, ref expr)
379         | ast::ExprKind::Box(ref expr)
380         | ast::ExprKind::Try(ref expr)
381         | ast::ExprKind::Unary(_, ref expr)
382         | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
383         _ => false,
384     }
385 }
386
387 /// Does this expression require a semicolon to be treated
388 /// as a statement? The negation of this: 'can this expression
389 /// be used as a statement without a semicolon' -- is used
390 /// as an early-bail-out in the parser so that, for instance,
391 ///     if true {...} else {...}
392 ///      |x| 5
393 /// isn't parsed as (if true {...} else {...} | x) | 5
394 // From https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/classify.rs.
395 fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
396     match e.kind {
397         ast::ExprKind::If(..)
398         | ast::ExprKind::Match(..)
399         | ast::ExprKind::Block(..)
400         | ast::ExprKind::While(..)
401         | ast::ExprKind::Loop(..)
402         | ast::ExprKind::ForLoop(..)
403         | ast::ExprKind::TryBlock(..) => false,
404         _ => true,
405     }
406 }