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