]> git.lizzy.rs Git - rust.git/blob - src/closures.rs
9412992171680ca9db9aaadc604c24bbdefb6863
[rust.git] / src / closures.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use syntax::{ast, ptr};
12 use syntax::codemap::Span;
13 use syntax::parse::classify;
14
15 use codemap::SpanUtils;
16 use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond, ToExpr};
17 use items::{span_hi_for_arg, span_lo_for_arg};
18 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
19             ListTactic, Separator, SeparatorPlace, SeparatorTactic};
20 use rewrite::{Rewrite, RewriteContext};
21 use shape::Shape;
22 use utils::{last_line_width, left_most_sub_expr, stmt_expr};
23
24 // This module is pretty messy because of the rules around closures and blocks:
25 // FIXME - the below is probably no longer true in full.
26 //   * if there is a return type, then there must be braces,
27 //   * given a closure with braces, whether that is parsed to give an inner block
28 //     or not depends on if there is a return type and if there are statements
29 //     in that block,
30 //   * if the first expression in the body ends with a block (i.e., is a
31 //     statement without needing a semi-colon), then adding or removing braces
32 //     can change whether it is treated as an expression or statement.
33
34
35 pub fn rewrite_closure(
36     capture: ast::CaptureBy,
37     fn_decl: &ast::FnDecl,
38     body: &ast::Expr,
39     span: Span,
40     context: &RewriteContext,
41     shape: Shape,
42 ) -> Option<String> {
43     debug!("rewrite_closure {:?}", body);
44
45     let (prefix, extra_offset) =
46         rewrite_closure_fn_decl(capture, fn_decl, body, span, context, shape)?;
47     // 1 = space between `|...|` and body.
48     let body_shape = shape.offset_left(extra_offset)?;
49
50     if let ast::ExprKind::Block(ref block) = body.node {
51         try_rewrite_without_block(block, fn_decl, &prefix, context, shape, body_shape).or_else(|| {
52             // Either we require a block, or tried without and failed.
53             rewrite_closure_block(block, &prefix, context, body_shape)
54         })
55     } else {
56         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
57             // The closure originally had a non-block expression, but we can't fit on
58             // one line, so we'll insert a block.
59             rewrite_closure_with_block(body, &prefix, context, body_shape)
60         })
61     }
62 }
63
64 fn try_rewrite_without_block(
65     block: &ast::Block,
66     fn_decl: &ast::FnDecl,
67     prefix: &str,
68     context: &RewriteContext,
69     shape: Shape,
70     body_shape: Shape,
71 ) -> Option<String> {
72     // The body of the closure is an empty block.
73     if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
74         return Some(format!("{} {{}}", prefix));
75     }
76
77     match fn_decl.output {
78         ast::FunctionRetTy::Default(_) => {}
79         _ => return None,
80     }
81
82     get_inner_expr(block, prefix, context).and_then(|expr| {
83         return if is_block_closure_forced(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
91 fn get_inner_expr<'a>(
92     block: &'a ast::Block,
93     prefix: &str,
94     context: &RewriteContext,
95 ) -> Option<&'a ast::Expr> {
96     if !needs_block(block, prefix, context) {
97         // block.stmts.len() == 1
98         stmt_expr(&block.stmts[0])
99     } else {
100         None
101     }
102 }
103
104 // Figure out if a block is necessary.
105 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
106     is_unsafe_block(block) || block.stmts.len() > 1 || context.inside_macro
107         || block_contains_comment(block, context.codemap) || prefix.contains('\n')
108 }
109
110 // Rewrite closure with a single expression wrapping its body with block.
111 fn rewrite_closure_with_block(
112     body: &ast::Expr,
113     prefix: &str,
114     context: &RewriteContext,
115     shape: Shape,
116 ) -> Option<String> {
117     let block = ast::Block {
118         stmts: vec![
119             ast::Stmt {
120                 id: ast::NodeId::new(0),
121                 node: ast::StmtKind::Expr(ptr::P(body.clone())),
122                 span: body.span,
123             },
124         ],
125         id: ast::NodeId::new(0),
126         rules: ast::BlockCheckMode::Default,
127         span: body.span,
128     };
129     rewrite_closure_block(&block, prefix, context, shape)
130 }
131
132 // Rewrite closure with a single expression without wrapping its body with block.
133 fn rewrite_closure_expr(
134     expr: &ast::Expr,
135     prefix: &str,
136     context: &RewriteContext,
137     shape: Shape,
138 ) -> Option<String> {
139     let mut rewrite = expr.rewrite(context, shape);
140     if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
141         rewrite = and_one_line(rewrite);
142     }
143     rewrite = rewrite.and_then(|rw| {
144         if context.config.multiline_closure_forces_block() && rw.contains('\n') {
145             None
146         } else {
147             Some(rw)
148         }
149     });
150     rewrite.map(|rw| format!("{} {}", prefix, rw))
151 }
152
153 // Rewrite closure whose body is block.
154 fn rewrite_closure_block(
155     block: &ast::Block,
156     prefix: &str,
157     context: &RewriteContext,
158     shape: Shape,
159 ) -> Option<String> {
160     let block_shape = shape.block();
161     let block_str = block.rewrite(context, block_shape)?;
162     Some(format!("{} {}", prefix, block_str))
163 }
164
165 // Return type is (prefix, extra_offset)
166 fn rewrite_closure_fn_decl(
167     capture: ast::CaptureBy,
168     fn_decl: &ast::FnDecl,
169     body: &ast::Expr,
170     span: Span,
171     context: &RewriteContext,
172     shape: Shape,
173 ) -> Option<(String, usize)> {
174     let mover = if capture == ast::CaptureBy::Value {
175         "move "
176     } else {
177         ""
178     };
179     // 4 = "|| {".len(), which is overconservative when the closure consists of
180     // a single expression.
181     let nested_shape = shape.shrink_left(mover.len())?.sub_width(4)?;
182
183     // 1 = |
184     let argument_offset = nested_shape.indent + 1;
185     let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
186     let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
187
188     let arg_items = itemize_list(
189         context.codemap,
190         fn_decl.inputs.iter(),
191         "|",
192         |arg| span_lo_for_arg(arg),
193         |arg| span_hi_for_arg(context, arg),
194         |arg| arg.rewrite(context, arg_shape),
195         context.codemap.span_after(span, "|"),
196         body.span.lo(),
197         false,
198     );
199     let item_vec = arg_items.collect::<Vec<_>>();
200     // 1 = space between arguments and return type.
201     let horizontal_budget = nested_shape
202         .width
203         .checked_sub(ret_str.len() + 1)
204         .unwrap_or(0);
205     let tactic = definitive_tactic(
206         &item_vec,
207         ListTactic::HorizontalVertical,
208         Separator::Comma,
209         horizontal_budget,
210     );
211     let arg_shape = match tactic {
212         DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
213         _ => arg_shape,
214     };
215
216     let fmt = ListFormatting {
217         tactic: tactic,
218         separator: ",",
219         trailing_separator: SeparatorTactic::Never,
220         separator_place: SeparatorPlace::Back,
221         shape: arg_shape,
222         ends_with_newline: false,
223         preserve_newline: true,
224         config: context.config,
225     };
226     let list_str = write_list(&item_vec, &fmt)?;
227     let mut prefix = format!("{}|{}|", mover, list_str);
228
229     if !ret_str.is_empty() {
230         if prefix.contains('\n') {
231             prefix.push('\n');
232             prefix.push_str(&argument_offset.to_string(context.config));
233         } else {
234             prefix.push(' ');
235         }
236         prefix.push_str(&ret_str);
237     }
238     // 1 = space between `|...|` and body.
239     let extra_offset = last_line_width(&prefix) + 1;
240
241     Some((prefix, extra_offset))
242 }
243
244 // Rewriting closure which is placed at the end of the function call's arg.
245 // Returns `None` if the reformatted closure 'looks bad'.
246 pub fn rewrite_last_closure(
247     context: &RewriteContext,
248     expr: &ast::Expr,
249     shape: Shape,
250 ) -> Option<String> {
251     if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
252         let body = match body.node {
253             ast::ExprKind::Block(ref block) if is_simple_block(block, context.codemap) => {
254                 stmt_expr(&block.stmts[0]).unwrap_or(body)
255             }
256             _ => body,
257         };
258         let (prefix, extra_offset) =
259             rewrite_closure_fn_decl(capture, fn_decl, body, expr.span, context, shape)?;
260         // If the closure goes multi line before its body, do not overflow the closure.
261         if prefix.contains('\n') {
262             return None;
263         }
264         // If we are inside macro, we do not want to add or remove block from closure body.
265         if context.inside_macro {
266             return expr.rewrite(context, shape);
267         }
268
269         let body_shape = shape.offset_left(extra_offset)?;
270
271         // We force to use block for the body of the closure for certain kinds of expressions.
272         if is_block_closure_forced(body) {
273             return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
274                 |body_str| {
275                     // If the expression can fit in a single line, we need not force block closure.
276                     if body_str.lines().count() <= 7 {
277                         match rewrite_closure_expr(body, &prefix, context, shape) {
278                             Some(ref single_line_body_str)
279                                 if !single_line_body_str.contains('\n') =>
280                             {
281                                 Some(single_line_body_str.clone())
282                             }
283                             _ => Some(body_str),
284                         }
285                     } else {
286                         Some(body_str)
287                     }
288                 },
289             );
290         }
291
292         // When overflowing the closure which consists of a single control flow expression,
293         // force to use block if its condition uses multi line.
294         let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
295             .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
296             .unwrap_or(false);
297         if is_multi_lined_cond {
298             return rewrite_closure_with_block(body, &prefix, context, body_shape);
299         }
300
301         // Seems fine, just format the closure in usual manner.
302         return expr.rewrite(context, shape);
303     }
304     None
305 }
306
307 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
308 pub fn args_have_many_closure<T>(args: &[&T]) -> bool
309 where
310     T: ToExpr,
311 {
312     args.iter()
313         .filter(|arg| {
314             arg.to_expr()
315                 .map(|e| match e.node {
316                     ast::ExprKind::Closure(..) => true,
317                     _ => false,
318                 })
319                 .unwrap_or(false)
320         })
321         .count() > 1
322 }
323
324 fn is_block_closure_forced(expr: &ast::Expr) -> bool {
325     match expr.node {
326         ast::ExprKind::If(..) |
327         ast::ExprKind::IfLet(..) |
328         ast::ExprKind::Loop(..) |
329         ast::ExprKind::While(..) |
330         ast::ExprKind::WhileLet(..) |
331         ast::ExprKind::ForLoop(..) => true,
332         ast::ExprKind::AddrOf(_, ref expr) |
333         ast::ExprKind::Box(ref expr) |
334         ast::ExprKind::Try(ref expr) |
335         ast::ExprKind::Unary(_, ref expr) |
336         ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced(expr),
337         _ => false,
338     }
339 }
340
341 fn and_one_line(x: Option<String>) -> Option<String> {
342     x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
343 }