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