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.
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.
12 use syntax::parse::classify;
13 use syntax::source_map::Span;
14 use syntax::{ast, ptr};
16 use expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
17 use items::{span_hi_for_arg, span_lo_for_arg};
18 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
19 use overflow::OverflowableItem;
20 use rewrite::{Rewrite, RewriteContext};
22 use source_map::SpanUtils;
23 use utils::{last_line_width, left_most_sub_expr, stmt_expr};
25 // This module is pretty messy because of the rules around closures and blocks:
26 // FIXME - the below is probably no longer true in full.
27 // * if there is a return type, then there must be braces,
28 // * given a closure with braces, whether that is parsed to give an inner block
29 // or not depends on if there is a return type and if there are statements
31 // * if the first expression in the body ends with a block (i.e., is a
32 // statement without needing a semi-colon), then adding or removing braces
33 // can change whether it is treated as an expression or statement.
35 pub fn rewrite_closure(
36 capture: ast::CaptureBy,
37 asyncness: ast::IsAsync,
38 movability: ast::Movability,
39 fn_decl: &ast::FnDecl,
42 context: &RewriteContext,
45 debug!("rewrite_closure {:?}", body);
47 let (prefix, extra_offset) = rewrite_closure_fn_decl(
48 capture, asyncness, movability, fn_decl, body, span, context, shape,
50 // 1 = space between `|...|` and body.
51 let body_shape = shape.offset_left(extra_offset)?;
53 if let ast::ExprKind::Block(ref block, _) = body.node {
54 // The body of the closure is an empty block.
55 if block.stmts.is_empty() && !block_contains_comment(block, context.source_map) {
57 .rewrite(context, shape)
58 .map(|s| format!("{} {}", prefix, s));
61 let result = match fn_decl.output {
62 ast::FunctionRetTy::Default(_) => {
63 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
69 // Either we require a block, or tried without and failed.
70 rewrite_closure_block(block, &prefix, context, body_shape)
73 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
74 // The closure originally had a non-block expression, but we can't fit on
75 // one line, so we'll insert a block.
76 rewrite_closure_with_block(body, &prefix, context, body_shape)
81 fn try_rewrite_without_block(
84 context: &RewriteContext,
88 let expr = get_inner_expr(expr, prefix, context);
90 if is_block_closure_forced(context, expr) {
91 rewrite_closure_with_block(expr, prefix, context, shape)
93 rewrite_closure_expr(expr, prefix, context, body_shape)
97 fn get_inner_expr<'a>(
100 context: &RewriteContext,
102 if let ast::ExprKind::Block(ref block, _) = expr.node {
103 if !needs_block(block, prefix, context) {
104 // block.stmts.len() == 1
105 if let Some(expr) = stmt_expr(&block.stmts[0]) {
106 return get_inner_expr(expr, prefix, context);
114 // Figure out if a block is necessary.
115 fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext) -> bool {
116 is_unsafe_block(block)
117 || block.stmts.len() > 1
118 || block_contains_comment(block, context.source_map)
119 || prefix.contains('\n')
122 fn veto_block(e: &ast::Expr) -> bool {
124 ast::ExprKind::Call(..)
125 | ast::ExprKind::Binary(..)
126 | ast::ExprKind::Cast(..)
127 | ast::ExprKind::Type(..)
128 | ast::ExprKind::Assign(..)
129 | ast::ExprKind::AssignOp(..)
130 | ast::ExprKind::Field(..)
131 | ast::ExprKind::Index(..)
132 | ast::ExprKind::Range(..)
133 | ast::ExprKind::Try(..) => true,
138 // Rewrite closure with a single expression wrapping its body with block.
139 fn rewrite_closure_with_block(
142 context: &RewriteContext,
144 ) -> Option<String> {
145 let left_most = left_most_sub_expr(body);
146 let veto_block = veto_block(body) && !classify::expr_requires_semi_to_be_stmt(left_most);
151 let block = ast::Block {
152 stmts: vec![ast::Stmt {
153 id: ast::NodeId::new(0),
154 node: ast::StmtKind::Expr(ptr::P(body.clone())),
157 id: ast::NodeId::new(0),
158 rules: ast::BlockCheckMode::Default,
162 let block = ::expr::rewrite_block_with_visitor(context, "", &block, None, None, shape, false)?;
163 Some(format!("{} {}", prefix, block))
166 // Rewrite closure with a single expression without wrapping its body with block.
167 fn rewrite_closure_expr(
170 context: &RewriteContext,
172 ) -> Option<String> {
173 fn allow_multi_line(expr: &ast::Expr) -> bool {
175 ast::ExprKind::Match(..)
176 | ast::ExprKind::Block(..)
177 | ast::ExprKind::TryBlock(..)
178 | ast::ExprKind::Loop(..)
179 | ast::ExprKind::Struct(..) => true,
181 ast::ExprKind::AddrOf(_, ref expr)
182 | ast::ExprKind::Box(ref expr)
183 | ast::ExprKind::Try(ref expr)
184 | ast::ExprKind::Unary(_, ref expr)
185 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
191 // When rewriting closure's body without block, we require it to fit in a single line
192 // unless it is a block-like expression or we are inside macro call.
193 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
194 || context.config.force_multiline_blocks();
195 expr.rewrite(context, shape)
197 if veto_multiline && rw.contains('\n') {
203 .map(|rw| format!("{} {}", prefix, rw))
206 // Rewrite closure whose body is block.
207 fn rewrite_closure_block(
210 context: &RewriteContext,
212 ) -> Option<String> {
213 Some(format!("{} {}", prefix, block.rewrite(context, shape)?))
216 // Return type is (prefix, extra_offset)
217 fn rewrite_closure_fn_decl(
218 capture: ast::CaptureBy,
219 asyncness: ast::IsAsync,
220 movability: ast::Movability,
221 fn_decl: &ast::FnDecl,
224 context: &RewriteContext,
226 ) -> Option<(String, usize)> {
227 let is_async = if asyncness.is_async() { "async " } else { "" };
228 let mover = if capture == ast::CaptureBy::Value {
233 let immovable = if movability == ast::Movability::Static {
238 // 4 = "|| {".len(), which is overconservative when the closure consists of
239 // a single expression.
240 let nested_shape = shape
241 .shrink_left(is_async.len() + mover.len() + immovable.len())?
245 let argument_offset = nested_shape.indent + 1;
246 let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
247 let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
249 let arg_items = itemize_list(
250 context.snippet_provider,
251 fn_decl.inputs.iter(),
254 |arg| span_lo_for_arg(arg),
255 |arg| span_hi_for_arg(context, arg),
256 |arg| arg.rewrite(context, arg_shape),
257 context.snippet_provider.span_after(span, "|"),
261 let item_vec = arg_items.collect::<Vec<_>>();
262 // 1 = space between arguments and return type.
263 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
264 let tactic = definitive_tactic(
266 ListTactic::HorizontalVertical,
270 let arg_shape = match tactic {
271 DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
275 let fmt = ListFormatting::new(arg_shape, context.config)
277 .preserve_newline(true);
278 let list_str = write_list(&item_vec, &fmt)?;
279 let mut prefix = format!("{}{}{}|{}|", is_async, immovable, mover, list_str);
281 if !ret_str.is_empty() {
282 if prefix.contains('\n') {
284 prefix.push_str(&argument_offset.to_string(context.config));
288 prefix.push_str(&ret_str);
290 // 1 = space between `|...|` and body.
291 let extra_offset = last_line_width(&prefix) + 1;
293 Some((prefix, extra_offset))
296 // Rewriting closure which is placed at the end of the function call's arg.
297 // Returns `None` if the reformatted closure 'looks bad'.
298 pub fn rewrite_last_closure(
299 context: &RewriteContext,
302 ) -> Option<String> {
303 if let ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) =
306 let body = match body.node {
307 ast::ExprKind::Block(ref block, _)
308 if !is_unsafe_block(block)
309 && is_simple_block(block, Some(&body.attrs), context.source_map) =>
311 stmt_expr(&block.stmts[0]).unwrap_or(body)
315 let (prefix, extra_offset) = rewrite_closure_fn_decl(
316 capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
318 // If the closure goes multi line before its body, do not overflow the closure.
319 if prefix.contains('\n') {
323 let body_shape = shape.offset_left(extra_offset)?;
325 // We force to use block for the body of the closure for certain kinds of expressions.
326 if is_block_closure_forced(context, body) {
327 return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
329 // If the expression can fit in a single line, we need not force block closure.
330 if body_str.lines().count() <= 7 {
331 match rewrite_closure_expr(body, &prefix, context, shape) {
332 Some(ref single_line_body_str)
333 if !single_line_body_str.contains('\n') =>
335 Some(single_line_body_str.clone())
346 // When overflowing the closure which consists of a single control flow expression,
347 // force to use block if its condition uses multi line.
348 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
349 cond.contains('\n') || cond.len() > body_shape.width
351 if is_multi_lined_cond {
352 return rewrite_closure_with_block(body, &prefix, context, body_shape);
355 // Seems fine, just format the closure in usual manner.
356 return expr.rewrite(context, shape);
361 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
362 pub fn args_have_many_closure(args: &[OverflowableItem]) -> bool {
364 .filter_map(|arg| arg.to_expr())
365 .filter(|expr| match expr.node {
366 ast::ExprKind::Closure(..) => true,
373 fn is_block_closure_forced(context: &RewriteContext, expr: &ast::Expr) -> bool {
374 // If we are inside macro, we do not want to add or remove block from closure body.
375 if context.inside_macro() {
378 is_block_closure_forced_inner(expr)
382 fn is_block_closure_forced_inner(expr: &ast::Expr) -> bool {
384 ast::ExprKind::If(..)
385 | ast::ExprKind::IfLet(..)
386 | ast::ExprKind::While(..)
387 | ast::ExprKind::WhileLet(..)
388 | ast::ExprKind::ForLoop(..) => 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),