]> git.lizzy.rs Git - rust.git/blob - src/closures.rs
Merge pull request #3472 from devinalvaro/add-print-current-config
[rust.git] / src / closures.rs
1 use syntax::parse::classify;
2 use syntax::source_map::Span;
3 use syntax::{ast, ptr};
4
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_arg, span_lo_for_arg};
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 fn rewrite_closure(
27     capture: ast::CaptureBy,
28     asyncness: ast::IsAsync,
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, asyncness, 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.node {
45         // The body of the closure is an empty block.
46         if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
47             return body
48                 .rewrite(context, shape)
49                 .map(|s| format!("{} {}", prefix, s));
50         }
51
52         let result = match fn_decl.output {
53             ast::FunctionRetTy::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.node {
94         if !needs_block(block, prefix, context) {
95             // block.stmts.len() == 1
96             if let Some(expr) = stmt_expr(&block.stmts[0]) {
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.node {
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) && !classify::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             node: 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.node {
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 argument_offset = nested_shape.indent + 1;
237     let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
238     let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
239
240     let arg_items = itemize_list(
241         context.snippet_provider,
242         fn_decl.inputs.iter(),
243         "|",
244         ",",
245         |arg| span_lo_for_arg(arg),
246         |arg| span_hi_for_arg(context, arg),
247         |arg| arg.rewrite(context, arg_shape),
248         context.snippet_provider.span_after(span, "|"),
249         body.span.lo(),
250         false,
251     );
252     let item_vec = arg_items.collect::<Vec<_>>();
253     // 1 = space between arguments 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 arg_shape = match tactic {
262         DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
263         _ => arg_shape,
264     };
265
266     let fmt = ListFormatting::new(arg_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(&argument_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 fn rewrite_last_closure(
290     context: &RewriteContext<'_>,
291     expr: &ast::Expr,
292     shape: Shape,
293 ) -> Option<String> {
294     if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
295         expr.node
296     {
297         let body = match body.node {
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, asyncness, 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 fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
355     args.iter()
356         .filter_map(|arg| arg.to_expr())
357         .filter(|expr| match expr.node {
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.node {
376         ast::ExprKind::If(..)
377         | ast::ExprKind::IfLet(..)
378         | ast::ExprKind::While(..)
379         | ast::ExprKind::WhileLet(..)
380         | ast::ExprKind::ForLoop(..) => true,
381         ast::ExprKind::Loop(..) if version == Version::Two => true,
382         ast::ExprKind::AddrOf(_, ref expr)
383         | ast::ExprKind::Box(ref expr)
384         | ast::ExprKind::Try(ref expr)
385         | ast::ExprKind::Unary(_, ref expr)
386         | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, version),
387         _ => false,
388     }
389 }