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