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