]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Merge pull request #2117 from adeschamps/issue-2103
[rust.git] / src / expr.rs
1 // Copyright 2015 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 std::cmp::min;
12 use std::borrow::Cow;
13 use std::iter::{repeat, ExactSizeIterator};
14
15 use syntax::{ast, ptr};
16 use syntax::codemap::{BytePos, CodeMap, Span};
17 use syntax::parse::classify;
18
19 use spanned::Spanned;
20 use chains::rewrite_chain;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23               rewrite_comment, rewrite_missing_comment, FindUncommented};
24 use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
25 use items::{span_hi_for_arg, span_lo_for_arg};
26 use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
27             struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
28             ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
29 use macros::{rewrite_macro, MacroArg, MacroPosition};
30 use patterns::{can_be_overflowed_pat, TuplePatField};
31 use rewrite::{Rewrite, RewriteContext};
32 use shape::{Indent, Shape};
33 use string::{rewrite_string, StringFormat};
34 use types::{can_be_overflowed_type, rewrite_path, PathContext};
35 use utils::{colon_spaces, contains_skip, extra_offset, first_line_width, inner_attributes,
36             last_line_extendable, last_line_width, left_most_sub_expr, mk_sp, outer_attributes,
37             paren_overhead, ptr_vec_to_ref_vec, semicolon_for_stmt, stmt_expr,
38             trimmed_last_line_width};
39 use vertical::rewrite_with_alignment;
40 use visitor::FmtVisitor;
41
42 impl Rewrite for ast::Expr {
43     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
44         format_expr(self, ExprType::SubExpression, context, shape)
45     }
46 }
47
48 #[derive(Copy, Clone, PartialEq)]
49 pub enum ExprType {
50     Statement,
51     SubExpression,
52 }
53
54 pub fn format_expr(
55     expr: &ast::Expr,
56     expr_type: ExprType,
57     context: &RewriteContext,
58     shape: Shape,
59 ) -> Option<String> {
60     skip_out_of_file_lines_range!(context, expr.span);
61
62     if contains_skip(&*expr.attrs) {
63         return Some(context.snippet(expr.span()));
64     }
65
66     let expr_rw = match expr.node {
67         ast::ExprKind::Array(ref expr_vec) => rewrite_array(
68             expr_vec.iter().map(|e| &**e),
69             mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi()),
70             context,
71             shape,
72             false,
73         ),
74         ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
75         ast::ExprKind::Call(ref callee, ref args) => {
76             let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
77             let callee_str = callee.rewrite(context, shape)?;
78             rewrite_call(context, &callee_str, &args, inner_span, shape)
79         }
80         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
81         ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
82             // FIXME: format comments between operands and operator
83             rewrite_pair(
84                 &**lhs,
85                 &**rhs,
86                 "",
87                 &format!(" {} ", context.snippet(op.span)),
88                 "",
89                 context,
90                 shape,
91                 context.config.binop_separator(),
92             )
93         }
94         ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
95         ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
96             context,
97             path,
98             fields,
99             base.as_ref().map(|e| &**e),
100             expr.span,
101             shape,
102         ),
103         ast::ExprKind::Tup(ref items) => {
104             rewrite_tuple(context, &ptr_vec_to_ref_vec(&items), expr.span, shape)
105         }
106         ast::ExprKind::If(..) |
107         ast::ExprKind::IfLet(..) |
108         ast::ExprKind::ForLoop(..) |
109         ast::ExprKind::Loop(..) |
110         ast::ExprKind::While(..) |
111         ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
112             .and_then(|control_flow| control_flow.rewrite(context, shape)),
113         ast::ExprKind::Block(ref block) => {
114             match expr_type {
115                 ExprType::Statement => {
116                     if is_unsafe_block(block) {
117                         block.rewrite(context, shape)
118                     } else if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
119                         // Rewrite block without trying to put it in a single line.
120                         rw
121                     } else {
122                         let prefix = block_prefix(context, block, shape)?;
123                         rewrite_block_with_visitor(context, &prefix, block, shape)
124                     }
125                 }
126                 ExprType::SubExpression => block.rewrite(context, shape),
127             }
128         }
129         ast::ExprKind::Match(ref cond, ref arms) => {
130             rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
131         }
132         ast::ExprKind::Path(ref qself, ref path) => {
133             rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
134         }
135         ast::ExprKind::Assign(ref lhs, ref rhs) => {
136             rewrite_assignment(context, lhs, rhs, None, shape)
137         }
138         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
139             rewrite_assignment(context, lhs, rhs, Some(op), shape)
140         }
141         ast::ExprKind::Continue(ref opt_ident) => {
142             let id_str = match *opt_ident {
143                 Some(ident) => format!(" {}", ident.node),
144                 None => String::new(),
145             };
146             Some(format!("continue{}", id_str))
147         }
148         ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
149             let id_str = match *opt_ident {
150                 Some(ident) => format!(" {}", ident.node),
151                 None => String::new(),
152             };
153
154             if let Some(ref expr) = *opt_expr {
155                 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
156             } else {
157                 Some(format!("break{}", id_str))
158             }
159         }
160         ast::ExprKind::Yield(ref opt_expr) => if let Some(ref expr) = *opt_expr {
161             rewrite_unary_prefix(context, "yield ", &**expr, shape)
162         } else {
163             Some("yield".to_string())
164         },
165         ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
166             rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
167         }
168         ast::ExprKind::Try(..) |
169         ast::ExprKind::Field(..) |
170         ast::ExprKind::TupField(..) |
171         ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
172         ast::ExprKind::Mac(ref mac) => {
173             // Failure to rewrite a macro should not imply failure to
174             // rewrite the expression.
175             rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
176                 .or_else(|| Some(context.snippet(expr.span)))
177         }
178         ast::ExprKind::Ret(None) => Some("return".to_owned()),
179         ast::ExprKind::Ret(Some(ref expr)) => {
180             rewrite_unary_prefix(context, "return ", &**expr, shape)
181         }
182         ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
183         ast::ExprKind::AddrOf(mutability, ref expr) => {
184             rewrite_expr_addrof(context, mutability, expr, shape)
185         }
186         ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
187             &**expr,
188             &**ty,
189             "",
190             " as ",
191             "",
192             context,
193             shape,
194             SeparatorPlace::Front,
195         ),
196         ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
197             &**expr,
198             &**ty,
199             "",
200             ": ",
201             "",
202             context,
203             shape,
204             SeparatorPlace::Back,
205         ),
206         ast::ExprKind::Index(ref expr, ref index) => {
207             rewrite_index(&**expr, &**index, context, shape)
208         }
209         ast::ExprKind::Repeat(ref expr, ref repeats) => {
210             let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
211                 ("[ ", " ]")
212             } else {
213                 ("[", "]")
214             };
215             rewrite_pair(
216                 &**expr,
217                 &**repeats,
218                 lbr,
219                 "; ",
220                 rbr,
221                 context,
222                 shape,
223                 SeparatorPlace::Back,
224             )
225         }
226         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
227             let delim = match limits {
228                 ast::RangeLimits::HalfOpen => "..",
229                 ast::RangeLimits::Closed => "..=",
230             };
231
232             fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
233                 match lhs.node {
234                     ast::ExprKind::Lit(ref lit) => match lit.node {
235                         ast::LitKind::FloatUnsuffixed(..) => {
236                             context.snippet(lit.span).ends_with('.')
237                         }
238                         _ => false,
239                     },
240                     _ => false,
241                 }
242             }
243
244             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
245                 (Some(lhs), Some(rhs)) => {
246                     let sp_delim = if context.config.spaces_around_ranges() {
247                         format!(" {} ", delim)
248                     } else if needs_space_before_range(context, lhs) {
249                         format!(" {}", delim)
250                     } else {
251                         delim.into()
252                     };
253                     rewrite_pair(
254                         &*lhs,
255                         &*rhs,
256                         "",
257                         &sp_delim,
258                         "",
259                         context,
260                         shape,
261                         SeparatorPlace::Front,
262                     )
263                 }
264                 (None, Some(rhs)) => {
265                     let sp_delim = if context.config.spaces_around_ranges() {
266                         format!("{} ", delim)
267                     } else {
268                         delim.into()
269                     };
270                     rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
271                 }
272                 (Some(lhs), None) => {
273                     let sp_delim = if context.config.spaces_around_ranges() {
274                         format!(" {}", delim)
275                     } else {
276                         delim.into()
277                     };
278                     rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
279                 }
280                 (None, None) => Some(delim.into()),
281             }
282         }
283         // We do not format these expressions yet, but they should still
284         // satisfy our width restrictions.
285         ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => {
286             Some(context.snippet(expr.span))
287         }
288         ast::ExprKind::Catch(ref block) => {
289             if let rw @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape) {
290                 rw
291             } else {
292                 // 9 = `do catch `
293                 let budget = shape.width.checked_sub(9).unwrap_or(0);
294                 Some(format!(
295                     "{}{}",
296                     "do catch ",
297                     block.rewrite(context, Shape::legacy(budget, shape.indent))?
298                 ))
299             }
300         }
301     };
302
303     expr_rw
304         .and_then(|expr_str| {
305             recover_comment_removed(expr_str, expr.span, context)
306         })
307         .and_then(|expr_str| {
308             let attrs = outer_attributes(&expr.attrs);
309             let attrs_str = attrs.rewrite(context, shape)?;
310             let span = mk_sp(
311                 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
312                 expr.span.lo(),
313             );
314             combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
315         })
316 }
317
318 pub fn rewrite_pair<LHS, RHS>(
319     lhs: &LHS,
320     rhs: &RHS,
321     prefix: &str,
322     infix: &str,
323     suffix: &str,
324     context: &RewriteContext,
325     shape: Shape,
326     separator_place: SeparatorPlace,
327 ) -> Option<String>
328 where
329     LHS: Rewrite,
330     RHS: Rewrite,
331 {
332     let lhs_overhead = match separator_place {
333         SeparatorPlace::Back => shape.used_width() + prefix.len() + infix.trim_right().len(),
334         SeparatorPlace::Front => shape.used_width(),
335     };
336     let lhs_shape = Shape {
337         width: context.budget(lhs_overhead),
338         ..shape
339     };
340     let lhs_result = lhs.rewrite(context, lhs_shape)
341         .map(|lhs_str| format!("{}{}", prefix, lhs_str))?;
342
343     // Try to the both lhs and rhs on the same line.
344     let rhs_orig_result = shape
345         .offset_left(last_line_width(&lhs_result) + infix.len())
346         .and_then(|s| s.sub_width(suffix.len()))
347         .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
348     if let Some(ref rhs_result) = rhs_orig_result {
349         // If the rhs looks like block expression, we allow it to stay on the same line
350         // with the lhs even if it is multi-lined.
351         let allow_same_line = rhs_result
352             .lines()
353             .next()
354             .map(|first_line| first_line.ends_with('{'))
355             .unwrap_or(false);
356         if !rhs_result.contains('\n') || allow_same_line {
357             let one_line_width = last_line_width(&lhs_result) + infix.len()
358                 + first_line_width(&rhs_result) + suffix.len();
359             if one_line_width <= shape.width {
360                 return Some(format!("{}{}{}{}", lhs_result, infix, rhs_result, suffix));
361             }
362         }
363     }
364
365     // We have to use multiple lines.
366     // Re-evaluate the rhs because we have more space now:
367     let mut rhs_shape = match context.config.control_style() {
368         Style::Legacy => shape
369             .sub_width(suffix.len() + prefix.len())?
370             .visual_indent(prefix.len()),
371         Style::Rfc => {
372             // Try to calculate the initial constraint on the right hand side.
373             let rhs_overhead = shape.rhs_overhead(context.config);
374             Shape::indented(shape.indent.block_indent(context.config), context.config)
375                 .sub_width(rhs_overhead)?
376         }
377     };
378     let infix = match separator_place {
379         SeparatorPlace::Back => infix.trim_right(),
380         SeparatorPlace::Front => infix.trim_left(),
381     };
382     if separator_place == SeparatorPlace::Front {
383         rhs_shape = rhs_shape.offset_left(infix.len())?;
384     }
385     let rhs_result = rhs.rewrite(context, rhs_shape)?;
386     match separator_place {
387         SeparatorPlace::Back => Some(format!(
388             "{}{}\n{}{}{}",
389             lhs_result,
390             infix,
391             rhs_shape.indent.to_string(context.config),
392             rhs_result,
393             suffix
394         )),
395         SeparatorPlace::Front => Some(format!(
396             "{}\n{}{}{}{}",
397             lhs_result,
398             rhs_shape.indent.to_string(context.config),
399             infix,
400             rhs_result,
401             suffix
402         )),
403     }
404 }
405
406 pub fn rewrite_array<'a, I>(
407     expr_iter: I,
408     span: Span,
409     context: &RewriteContext,
410     shape: Shape,
411     trailing_comma: bool,
412 ) -> Option<String>
413 where
414     I: Iterator<Item = &'a ast::Expr>,
415 {
416     let bracket_size = if context.config.spaces_within_square_brackets() {
417         2 // "[ "
418     } else {
419         1 // "["
420     };
421
422     let nested_shape = match context.config.array_layout() {
423         IndentStyle::Block => shape
424             .block()
425             .block_indent(context.config.tab_spaces())
426             .with_max_width(context.config)
427             .sub_width(1)?,
428         IndentStyle::Visual => shape
429             .visual_indent(bracket_size)
430             .sub_width(bracket_size * 2)?,
431     };
432
433     let items = itemize_list(
434         context.codemap,
435         expr_iter,
436         "]",
437         |item| item.span.lo(),
438         |item| item.span.hi(),
439         |item| item.rewrite(context, nested_shape),
440         span.lo(),
441         span.hi(),
442         false,
443     ).collect::<Vec<_>>();
444
445     if items.is_empty() {
446         if context.config.spaces_within_square_brackets() {
447             return Some("[ ]".to_string());
448         } else {
449             return Some("[]".to_string());
450         }
451     }
452
453     let has_long_item = items
454         .iter()
455         .any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
456
457     let mut tactic = match context.config.array_layout() {
458         IndentStyle::Block => {
459             // FIXME wrong shape in one-line case
460             match shape.width.checked_sub(2 * bracket_size) {
461                 Some(width) => {
462                     let tactic =
463                         ListTactic::LimitedHorizontalVertical(context.config.array_width());
464                     definitive_tactic(&items, tactic, Separator::Comma, width)
465                 }
466                 None => DefinitiveListTactic::Vertical,
467             }
468         }
469         IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
470             definitive_tactic(
471                 &items,
472                 ListTactic::LimitedHorizontalVertical(context.config.array_width()),
473                 Separator::Comma,
474                 nested_shape.width,
475             )
476         } else {
477             DefinitiveListTactic::Mixed
478         },
479     };
480     let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
481     if context.config.array_horizontal_layout_threshold() > 0
482         && items.len() > context.config.array_horizontal_layout_threshold()
483     {
484         tactic = DefinitiveListTactic::Mixed;
485     }
486
487     let fmt = ListFormatting {
488         tactic: tactic,
489         separator: ",",
490         trailing_separator: if trailing_comma {
491             SeparatorTactic::Always
492         } else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
493             SeparatorTactic::Never
494         } else {
495             SeparatorTactic::Vertical
496         },
497         separator_place: SeparatorPlace::Back,
498         shape: nested_shape,
499         ends_with_newline: ends_with_newline,
500         preserve_newline: false,
501         config: context.config,
502     };
503     let list_str = write_list(&items, &fmt)?;
504
505     let result = if context.config.array_layout() == IndentStyle::Visual
506         || tactic == DefinitiveListTactic::Horizontal
507     {
508         if context.config.spaces_within_square_brackets() && !list_str.is_empty() {
509             format!("[ {} ]", list_str)
510         } else {
511             format!("[{}]", list_str)
512         }
513     } else {
514         format!(
515             "[\n{}{}\n{}]",
516             nested_shape.indent.to_string(context.config),
517             list_str,
518             shape.block().indent.to_string(context.config)
519         )
520     };
521
522     Some(result)
523 }
524
525 // Return type is (prefix, extra_offset)
526 fn rewrite_closure_fn_decl(
527     capture: ast::CaptureBy,
528     fn_decl: &ast::FnDecl,
529     body: &ast::Expr,
530     span: Span,
531     context: &RewriteContext,
532     shape: Shape,
533 ) -> Option<(String, usize)> {
534     let mover = if capture == ast::CaptureBy::Value {
535         "move "
536     } else {
537         ""
538     };
539     // 4 = "|| {".len(), which is overconservative when the closure consists of
540     // a single expression.
541     let nested_shape = shape.shrink_left(mover.len())?.sub_width(4)?;
542
543     // 1 = |
544     let argument_offset = nested_shape.indent + 1;
545     let arg_shape = nested_shape.offset_left(1)?.visual_indent(0);
546     let ret_str = fn_decl.output.rewrite(context, arg_shape)?;
547
548     let arg_items = itemize_list(
549         context.codemap,
550         fn_decl.inputs.iter(),
551         "|",
552         |arg| span_lo_for_arg(arg),
553         |arg| span_hi_for_arg(context, arg),
554         |arg| arg.rewrite(context, arg_shape),
555         context.codemap.span_after(span, "|"),
556         body.span.lo(),
557         false,
558     );
559     let item_vec = arg_items.collect::<Vec<_>>();
560     // 1 = space between arguments and return type.
561     let horizontal_budget = nested_shape
562         .width
563         .checked_sub(ret_str.len() + 1)
564         .unwrap_or(0);
565     let tactic = definitive_tactic(
566         &item_vec,
567         ListTactic::HorizontalVertical,
568         Separator::Comma,
569         horizontal_budget,
570     );
571     let arg_shape = match tactic {
572         DefinitiveListTactic::Horizontal => arg_shape.sub_width(ret_str.len() + 1)?,
573         _ => arg_shape,
574     };
575
576     let fmt = ListFormatting {
577         tactic: tactic,
578         separator: ",",
579         trailing_separator: SeparatorTactic::Never,
580         separator_place: SeparatorPlace::Back,
581         shape: arg_shape,
582         ends_with_newline: false,
583         preserve_newline: true,
584         config: context.config,
585     };
586     let list_str = write_list(&item_vec, &fmt)?;
587     let mut prefix = format!("{}|{}|", mover, list_str);
588
589     if !ret_str.is_empty() {
590         if prefix.contains('\n') {
591             prefix.push('\n');
592             prefix.push_str(&argument_offset.to_string(context.config));
593         } else {
594             prefix.push(' ');
595         }
596         prefix.push_str(&ret_str);
597     }
598     // 1 = space between `|...|` and body.
599     let extra_offset = last_line_width(&prefix) + 1;
600
601     Some((prefix, extra_offset))
602 }
603
604 // This functions is pretty messy because of the rules around closures and blocks:
605 // FIXME - the below is probably no longer true in full.
606 //   * if there is a return type, then there must be braces,
607 //   * given a closure with braces, whether that is parsed to give an inner block
608 //     or not depends on if there is a return type and if there are statements
609 //     in that block,
610 //   * if the first expression in the body ends with a block (i.e., is a
611 //     statement without needing a semi-colon), then adding or removing braces
612 //     can change whether it is treated as an expression or statement.
613 fn rewrite_closure(
614     capture: ast::CaptureBy,
615     fn_decl: &ast::FnDecl,
616     body: &ast::Expr,
617     span: Span,
618     context: &RewriteContext,
619     shape: Shape,
620 ) -> Option<String> {
621     let (prefix, extra_offset) =
622         rewrite_closure_fn_decl(capture, fn_decl, body, span, context, shape)?;
623     // 1 = space between `|...|` and body.
624     let body_shape = shape.offset_left(extra_offset)?;
625
626     if let ast::ExprKind::Block(ref block) = body.node {
627         // The body of the closure is an empty block.
628         if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
629             return Some(format!("{} {{}}", prefix));
630         }
631
632         // Figure out if the block is necessary.
633         let needs_block = is_unsafe_block(block) || block.stmts.len() > 1 || context.inside_macro
634             || block_contains_comment(block, context.codemap)
635             || prefix.contains('\n');
636
637         let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
638             true
639         } else {
640             false
641         };
642         if no_return_type && !needs_block {
643             // block.stmts.len() == 1
644             if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
645                 if let Some(rw) = if is_block_closure_forced(expr) {
646                     rewrite_closure_with_block(context, shape, &prefix, expr)
647                 } else {
648                     rewrite_closure_expr(expr, &prefix, context, body_shape)
649                 } {
650                     return Some(rw);
651                 }
652             }
653         }
654
655         // Either we require a block, or tried without and failed.
656         rewrite_closure_block(block, &prefix, context, body_shape)
657     } else {
658         rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
659             // The closure originally had a non-block expression, but we can't fit on
660             // one line, so we'll insert a block.
661             rewrite_closure_with_block(context, body_shape, &prefix, body)
662         })
663     }
664 }
665
666 // Rewrite closure with a single expression wrapping its body with block.
667 fn rewrite_closure_with_block(
668     context: &RewriteContext,
669     shape: Shape,
670     prefix: &str,
671     body: &ast::Expr,
672 ) -> Option<String> {
673     let block = ast::Block {
674         stmts: vec![
675             ast::Stmt {
676                 id: ast::NodeId::new(0),
677                 node: ast::StmtKind::Expr(ptr::P(body.clone())),
678                 span: body.span,
679             },
680         ],
681         id: ast::NodeId::new(0),
682         rules: ast::BlockCheckMode::Default,
683         span: body.span,
684     };
685     rewrite_closure_block(&block, prefix, context, shape)
686 }
687
688 // Rewrite closure with a single expression without wrapping its body with block.
689 fn rewrite_closure_expr(
690     expr: &ast::Expr,
691     prefix: &str,
692     context: &RewriteContext,
693     shape: Shape,
694 ) -> Option<String> {
695     let mut rewrite = expr.rewrite(context, shape);
696     if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
697         rewrite = and_one_line(rewrite);
698     }
699     rewrite = rewrite.and_then(|rw| {
700         if context.config.multiline_closure_forces_block() && rw.contains('\n') {
701             None
702         } else {
703             Some(rw)
704         }
705     });
706     rewrite.map(|rw| format!("{} {}", prefix, rw))
707 }
708
709 // Rewrite closure whose body is block.
710 fn rewrite_closure_block(
711     block: &ast::Block,
712     prefix: &str,
713     context: &RewriteContext,
714     shape: Shape,
715 ) -> Option<String> {
716     // Start with visual indent, then fall back to block indent if the
717     // closure is large.
718     let block_threshold = context.config.closure_block_indent_threshold();
719     if block_threshold >= 0 {
720         if let Some(block_str) = block.rewrite(context, shape) {
721             if block_str.matches('\n').count() <= block_threshold as usize
722                 && !need_block_indent(&block_str, shape)
723             {
724                 return Some(format!("{} {}", prefix, block_str));
725             }
726         }
727     }
728
729     // The body of the closure is big enough to be block indented, that
730     // means we must re-format.
731     let block_shape = shape.block();
732     let block_str = block.rewrite(context, block_shape)?;
733     Some(format!("{} {}", prefix, block_str))
734 }
735
736 fn and_one_line(x: Option<String>) -> Option<String> {
737     x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
738 }
739
740 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
741     debug!("nop_block_collapse {:?} {}", block_str, budget);
742     block_str.map(|block_str| {
743         if block_str.starts_with('{') && budget >= 2
744             && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
745         {
746             "{}".to_owned()
747         } else {
748             block_str.to_owned()
749         }
750     })
751 }
752
753 fn rewrite_empty_block(
754     context: &RewriteContext,
755     block: &ast::Block,
756     shape: Shape,
757 ) -> Option<String> {
758     if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
759     {
760         return Some("{}".to_owned());
761     }
762
763     // If a block contains only a single-line comment, then leave it on one line.
764     let user_str = context.snippet(block.span);
765     let user_str = user_str.trim();
766     if user_str.starts_with('{') && user_str.ends_with('}') {
767         let comment_str = user_str[1..user_str.len() - 1].trim();
768         if block.stmts.is_empty() && !comment_str.contains('\n') && !comment_str.starts_with("//")
769             && comment_str.len() + 4 <= shape.width
770         {
771             return Some(format!("{{ {} }}", comment_str));
772         }
773     }
774
775     None
776 }
777
778 fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
779     Some(match block.rules {
780         ast::BlockCheckMode::Unsafe(..) => {
781             let snippet = context.snippet(block.span);
782             let open_pos = snippet.find_uncommented("{")?;
783             // Extract comment between unsafe and block start.
784             let trimmed = &snippet[6..open_pos].trim();
785
786             if !trimmed.is_empty() {
787                 // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
788                 let budget = shape.width.checked_sub(9)?;
789                 format!(
790                     "unsafe {} ",
791                     rewrite_comment(
792                         trimmed,
793                         true,
794                         Shape::legacy(budget, shape.indent + 7),
795                         context.config,
796                     )?
797                 )
798             } else {
799                 "unsafe ".to_owned()
800             }
801         }
802         ast::BlockCheckMode::Default => String::new(),
803     })
804 }
805
806 fn rewrite_single_line_block(
807     context: &RewriteContext,
808     prefix: &str,
809     block: &ast::Block,
810     shape: Shape,
811 ) -> Option<String> {
812     if is_simple_block(block, context.codemap) {
813         let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
814         let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
815         let result = format!("{}{{ {} }}", prefix, expr_str);
816         if result.len() <= shape.width && !result.contains('\n') {
817             return Some(result);
818         }
819     }
820     None
821 }
822
823 fn rewrite_block_with_visitor(
824     context: &RewriteContext,
825     prefix: &str,
826     block: &ast::Block,
827     shape: Shape,
828 ) -> Option<String> {
829     if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
830         return rw;
831     }
832
833     let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
834     visitor.block_indent = shape.indent;
835     visitor.is_if_else_block = context.is_if_else_block;
836     match block.rules {
837         ast::BlockCheckMode::Unsafe(..) => {
838             let snippet = context.snippet(block.span);
839             let open_pos = snippet.find_uncommented("{")?;
840             visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
841         }
842         ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo(),
843     }
844
845     visitor.visit_block(block, None);
846     Some(format!("{}{}", prefix, visitor.buffer))
847 }
848
849 impl Rewrite for ast::Block {
850     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
851         // shape.width is used only for the single line case: either the empty block `{}`,
852         // or an unsafe expression `unsafe { e }`.
853         if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
854             return rw;
855         }
856
857         let prefix = block_prefix(context, self, shape)?;
858
859         let result = rewrite_block_with_visitor(context, &prefix, self, shape);
860         if let Some(ref result_str) = result {
861             if result_str.lines().count() <= 3 {
862                 if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
863                     return rw;
864                 }
865             }
866         }
867
868         result
869     }
870 }
871
872 impl Rewrite for ast::Stmt {
873     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
874         skip_out_of_file_lines_range!(context, self.span());
875
876         let result = match self.node {
877             ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
878             ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
879                 let suffix = if semicolon_for_stmt(context, self) {
880                     ";"
881                 } else {
882                     ""
883                 };
884
885                 let shape = shape.sub_width(suffix.len())?;
886                 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
887             }
888             ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
889         };
890         result.and_then(|res| recover_comment_removed(res, self.span(), context))
891     }
892 }
893
894 // Rewrite condition if the given expression has one.
895 fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
896     match expr.node {
897         ast::ExprKind::Match(ref cond, _) => {
898             // `match `cond` {`
899             let cond_shape = match context.config.control_style() {
900                 Style::Legacy => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
901                 Style::Rfc => shape.offset_left(8)?,
902             };
903             cond.rewrite(context, cond_shape)
904         }
905         _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
906             let alt_block_sep =
907                 String::from("\n") + &shape.indent.block_only().to_string(context.config);
908             control_flow
909                 .rewrite_cond(context, shape, &alt_block_sep)
910                 .and_then(|rw| Some(rw.0))
911         }),
912     }
913 }
914
915 // Abstraction over control flow expressions
916 #[derive(Debug)]
917 struct ControlFlow<'a> {
918     cond: Option<&'a ast::Expr>,
919     block: &'a ast::Block,
920     else_block: Option<&'a ast::Expr>,
921     label: Option<ast::SpannedIdent>,
922     pat: Option<&'a ast::Pat>,
923     keyword: &'a str,
924     matcher: &'a str,
925     connector: &'a str,
926     allow_single_line: bool,
927     // True if this is an `if` expression in an `else if` :-( hacky
928     nested_if: bool,
929     span: Span,
930 }
931
932 fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
933     match expr.node {
934         ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
935             cond,
936             None,
937             if_block,
938             else_block.as_ref().map(|e| &**e),
939             expr_type == ExprType::SubExpression,
940             false,
941             expr.span,
942         )),
943         ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
944             Some(ControlFlow::new_if(
945                 cond,
946                 Some(pat),
947                 if_block,
948                 else_block.as_ref().map(|e| &**e),
949                 expr_type == ExprType::SubExpression,
950                 false,
951                 expr.span,
952             ))
953         }
954         ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
955             Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
956         }
957         ast::ExprKind::Loop(ref block, label) => {
958             Some(ControlFlow::new_loop(block, label, expr.span))
959         }
960         ast::ExprKind::While(ref cond, ref block, label) => {
961             Some(ControlFlow::new_while(None, cond, block, label, expr.span))
962         }
963         ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
964             ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
965         ),
966         _ => None,
967     }
968 }
969
970 impl<'a> ControlFlow<'a> {
971     fn new_if(
972         cond: &'a ast::Expr,
973         pat: Option<&'a ast::Pat>,
974         block: &'a ast::Block,
975         else_block: Option<&'a ast::Expr>,
976         allow_single_line: bool,
977         nested_if: bool,
978         span: Span,
979     ) -> ControlFlow<'a> {
980         ControlFlow {
981             cond: Some(cond),
982             block: block,
983             else_block: else_block,
984             label: None,
985             pat: pat,
986             keyword: "if",
987             matcher: match pat {
988                 Some(..) => "let",
989                 None => "",
990             },
991             connector: " =",
992             allow_single_line: allow_single_line,
993             nested_if: nested_if,
994             span: span,
995         }
996     }
997
998     fn new_loop(
999         block: &'a ast::Block,
1000         label: Option<ast::SpannedIdent>,
1001         span: Span,
1002     ) -> ControlFlow<'a> {
1003         ControlFlow {
1004             cond: None,
1005             block: block,
1006             else_block: None,
1007             label: label,
1008             pat: None,
1009             keyword: "loop",
1010             matcher: "",
1011             connector: "",
1012             allow_single_line: false,
1013             nested_if: false,
1014             span: span,
1015         }
1016     }
1017
1018     fn new_while(
1019         pat: Option<&'a ast::Pat>,
1020         cond: &'a ast::Expr,
1021         block: &'a ast::Block,
1022         label: Option<ast::SpannedIdent>,
1023         span: Span,
1024     ) -> ControlFlow<'a> {
1025         ControlFlow {
1026             cond: Some(cond),
1027             block: block,
1028             else_block: None,
1029             label: label,
1030             pat: pat,
1031             keyword: "while",
1032             matcher: match pat {
1033                 Some(..) => "let",
1034                 None => "",
1035             },
1036             connector: " =",
1037             allow_single_line: false,
1038             nested_if: false,
1039             span: span,
1040         }
1041     }
1042
1043     fn new_for(
1044         pat: &'a ast::Pat,
1045         cond: &'a ast::Expr,
1046         block: &'a ast::Block,
1047         label: Option<ast::SpannedIdent>,
1048         span: Span,
1049     ) -> ControlFlow<'a> {
1050         ControlFlow {
1051             cond: Some(cond),
1052             block: block,
1053             else_block: None,
1054             label: label,
1055             pat: Some(pat),
1056             keyword: "for",
1057             matcher: "",
1058             connector: " in",
1059             allow_single_line: false,
1060             nested_if: false,
1061             span: span,
1062         }
1063     }
1064
1065     fn rewrite_single_line(
1066         &self,
1067         pat_expr_str: &str,
1068         context: &RewriteContext,
1069         width: usize,
1070     ) -> Option<String> {
1071         assert!(self.allow_single_line);
1072         let else_block = self.else_block?;
1073         let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
1074
1075         if let ast::ExprKind::Block(ref else_node) = else_block.node {
1076             if !is_simple_block(self.block, context.codemap)
1077                 || !is_simple_block(else_node, context.codemap)
1078                 || pat_expr_str.contains('\n')
1079             {
1080                 return None;
1081             }
1082
1083             let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
1084             let expr = &self.block.stmts[0];
1085             let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
1086
1087             let new_width = new_width.checked_sub(if_str.len())?;
1088             let else_expr = &else_node.stmts[0];
1089             let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
1090
1091             if if_str.contains('\n') || else_str.contains('\n') {
1092                 return None;
1093             }
1094
1095             let result = format!(
1096                 "{} {} {{ {} }} else {{ {} }}",
1097                 self.keyword,
1098                 pat_expr_str,
1099                 if_str,
1100                 else_str
1101             );
1102
1103             if result.len() <= width {
1104                 return Some(result);
1105             }
1106         }
1107
1108         None
1109     }
1110 }
1111
1112 impl<'a> ControlFlow<'a> {
1113     fn rewrite_cond(
1114         &self,
1115         context: &RewriteContext,
1116         shape: Shape,
1117         alt_block_sep: &str,
1118     ) -> Option<(String, usize)> {
1119         // Do not take the rhs overhead from the upper expressions into account
1120         // when rewriting pattern.
1121         let new_width = context
1122             .config
1123             .max_width()
1124             .checked_sub(shape.used_width())
1125             .unwrap_or(0);
1126         let fresh_shape = Shape {
1127             width: new_width,
1128             ..shape
1129         };
1130         let constr_shape = if self.nested_if {
1131             // We are part of an if-elseif-else chain. Our constraints are tightened.
1132             // 7 = "} else " .len()
1133             fresh_shape.offset_left(7)?
1134         } else {
1135             fresh_shape
1136         };
1137
1138         let label_string = rewrite_label(self.label);
1139         // 1 = space after keyword.
1140         let offset = self.keyword.len() + label_string.len() + 1;
1141
1142         let pat_expr_string = match self.cond {
1143             Some(cond) => {
1144                 let cond_shape = match context.config.control_style() {
1145                     Style::Legacy => constr_shape.shrink_left(offset)?,
1146                     Style::Rfc => constr_shape.offset_left(offset)?,
1147                 };
1148                 rewrite_pat_expr(
1149                     context,
1150                     self.pat,
1151                     cond,
1152                     self.matcher,
1153                     self.connector,
1154                     self.keyword,
1155                     cond_shape,
1156                 )?
1157             }
1158             None => String::new(),
1159         };
1160
1161         let brace_overhead =
1162             if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
1163                 // 2 = ` {`
1164                 2
1165             } else {
1166                 0
1167             };
1168         let one_line_budget = context
1169             .config
1170             .max_width()
1171             .checked_sub(constr_shape.used_width() + offset + brace_overhead)
1172             .unwrap_or(0);
1173         let force_newline_brace = context.config.control_style() == Style::Rfc
1174             && (pat_expr_string.contains('\n') || pat_expr_string.len() > one_line_budget)
1175             && !last_line_extendable(&pat_expr_string);
1176
1177         // Try to format if-else on single line.
1178         if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
1179             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
1180
1181             if let Some(cond_str) = trial {
1182                 if cond_str.len() <= context.config.single_line_if_else_max_width() {
1183                     return Some((cond_str, 0));
1184                 }
1185             }
1186         }
1187
1188         let cond_span = if let Some(cond) = self.cond {
1189             cond.span
1190         } else {
1191             mk_sp(self.block.span.lo(), self.block.span.lo())
1192         };
1193
1194         // `for event in event`
1195         // Do not include label in the span.
1196         let lo = self.label.map_or(self.span.lo(), |label| label.span.hi());
1197         let between_kwd_cond = mk_sp(
1198             context
1199                 .codemap
1200                 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
1201             self.pat.map_or(cond_span.lo(), |p| {
1202                 if self.matcher.is_empty() {
1203                     p.span.lo()
1204                 } else {
1205                     context.codemap.span_before(self.span, self.matcher.trim())
1206                 }
1207             }),
1208         );
1209
1210         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
1211
1212         let after_cond_comment =
1213             extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1214
1215         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1216             ""
1217         } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1218             || force_newline_brace
1219         {
1220             alt_block_sep
1221         } else {
1222             " "
1223         };
1224
1225         let used_width = if pat_expr_string.contains('\n') {
1226             last_line_width(&pat_expr_string)
1227         } else {
1228             // 2 = spaces after keyword and condition.
1229             label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1230         };
1231
1232         Some((
1233             format!(
1234                 "{}{}{}{}{}",
1235                 label_string,
1236                 self.keyword,
1237                 between_kwd_cond_comment.as_ref().map_or(
1238                     if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1239                         ""
1240                     } else {
1241                         " "
1242                     },
1243                     |s| &**s,
1244                 ),
1245                 pat_expr_string,
1246                 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1247             ),
1248             used_width,
1249         ))
1250     }
1251 }
1252
1253 impl<'a> Rewrite for ControlFlow<'a> {
1254     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1255         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1256
1257         let alt_block_sep =
1258             String::from("\n") + &shape.indent.block_only().to_string(context.config);
1259         let (cond_str, used_width) = self.rewrite_cond(context, shape, &alt_block_sep)?;
1260         // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1261         if used_width == 0 {
1262             return Some(cond_str);
1263         }
1264
1265         let block_width = shape.width.checked_sub(used_width).unwrap_or(0);
1266         // This is used only for the empty block case: `{}`. So, we use 1 if we know
1267         // we should avoid the single line case.
1268         let block_width = if self.else_block.is_some() || self.nested_if {
1269             min(1, block_width)
1270         } else {
1271             block_width
1272         };
1273         let block_shape = Shape {
1274             width: block_width,
1275             ..shape
1276         };
1277         let mut block_context = context.clone();
1278         block_context.is_if_else_block = self.else_block.is_some();
1279         let block_str = rewrite_block_with_visitor(&block_context, "", self.block, block_shape)?;
1280
1281         let mut result = format!("{}{}", cond_str, block_str);
1282
1283         if let Some(else_block) = self.else_block {
1284             let shape = Shape::indented(shape.indent, context.config);
1285             let mut last_in_chain = false;
1286             let rewrite = match else_block.node {
1287                 // If the else expression is another if-else expression, prevent it
1288                 // from being formatted on a single line.
1289                 // Note how we're passing the original shape, as the
1290                 // cost of "else" should not cascade.
1291                 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1292                     ControlFlow::new_if(
1293                         cond,
1294                         Some(pat),
1295                         if_block,
1296                         next_else_block.as_ref().map(|e| &**e),
1297                         false,
1298                         true,
1299                         mk_sp(else_block.span.lo(), self.span.hi()),
1300                     ).rewrite(context, shape)
1301                 }
1302                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1303                     ControlFlow::new_if(
1304                         cond,
1305                         None,
1306                         if_block,
1307                         next_else_block.as_ref().map(|e| &**e),
1308                         false,
1309                         true,
1310                         mk_sp(else_block.span.lo(), self.span.hi()),
1311                     ).rewrite(context, shape)
1312                 }
1313                 _ => {
1314                     last_in_chain = true;
1315                     // When rewriting a block, the width is only used for single line
1316                     // blocks, passing 1 lets us avoid that.
1317                     let else_shape = Shape {
1318                         width: min(1, shape.width),
1319                         ..shape
1320                     };
1321                     format_expr(else_block, ExprType::Statement, context, else_shape)
1322                 }
1323             };
1324
1325             let between_kwd_else_block = mk_sp(
1326                 self.block.span.hi(),
1327                 context
1328                     .codemap
1329                     .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1330             );
1331             let between_kwd_else_block_comment =
1332                 extract_comment(between_kwd_else_block, context, shape);
1333
1334             let after_else = mk_sp(
1335                 context
1336                     .codemap
1337                     .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1338                 else_block.span.lo(),
1339             );
1340             let after_else_comment = extract_comment(after_else, context, shape);
1341
1342             let between_sep = match context.config.control_brace_style() {
1343                 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1344                     &*alt_block_sep
1345                 }
1346                 ControlBraceStyle::AlwaysSameLine => " ",
1347             };
1348             let after_sep = match context.config.control_brace_style() {
1349                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1350                 _ => " ",
1351             };
1352
1353             result.push_str(&format!(
1354                 "{}else{}",
1355                 between_kwd_else_block_comment
1356                     .as_ref()
1357                     .map_or(between_sep, |s| &**s),
1358                 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1359             ));
1360             result.push_str(&rewrite?);
1361         }
1362
1363         Some(result)
1364     }
1365 }
1366
1367 fn rewrite_label(label: Option<ast::SpannedIdent>) -> Cow<'static, str> {
1368     match label {
1369         Some(ident) => Cow::from(format!("{}: ", ident.node)),
1370         None => Cow::from(""),
1371     }
1372 }
1373
1374 fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1375     match rewrite_missing_comment(span, shape, context) {
1376         Some(ref comment) if !comment.is_empty() => Some(format!(
1377             "\n{indent}{}\n{indent}",
1378             comment,
1379             indent = shape.indent.to_string(context.config)
1380         )),
1381         _ => None,
1382     }
1383 }
1384
1385 fn block_contains_comment(block: &ast::Block, codemap: &CodeMap) -> bool {
1386     let snippet = codemap.span_to_snippet(block.span).unwrap();
1387     contains_comment(&snippet)
1388 }
1389
1390 // Checks that a block contains no statements, an expression and no comments.
1391 // FIXME: incorrectly returns false when comment is contained completely within
1392 // the expression.
1393 pub fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1394     (block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0])
1395         && !block_contains_comment(block, codemap))
1396 }
1397
1398 /// Checks whether a block contains at most one statement or expression, and no comments.
1399 pub fn is_simple_block_stmt(block: &ast::Block, codemap: &CodeMap) -> bool {
1400     block.stmts.len() <= 1 && !block_contains_comment(block, codemap)
1401 }
1402
1403 /// Checks whether a block contains no statements, expressions, or comments.
1404 pub fn is_empty_block(block: &ast::Block, codemap: &CodeMap) -> bool {
1405     block.stmts.is_empty() && !block_contains_comment(block, codemap)
1406 }
1407
1408 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1409     match stmt.node {
1410         ast::StmtKind::Expr(..) => true,
1411         _ => false,
1412     }
1413 }
1414
1415 fn is_unsafe_block(block: &ast::Block) -> bool {
1416     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1417         true
1418     } else {
1419         false
1420     }
1421 }
1422
1423 // A simple wrapper type against ast::Arm. Used inside write_list().
1424 struct ArmWrapper<'a> {
1425     pub arm: &'a ast::Arm,
1426     // True if the arm is the last one in match expression. Used to decide on whether we should add
1427     // trailing comma to the match arm when `config.trailing_comma() == Never`.
1428     pub is_last: bool,
1429 }
1430
1431 impl<'a> ArmWrapper<'a> {
1432     pub fn new(arm: &'a ast::Arm, is_last: bool) -> ArmWrapper<'a> {
1433         ArmWrapper { arm, is_last }
1434     }
1435 }
1436
1437 impl<'a> Rewrite for ArmWrapper<'a> {
1438     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1439         rewrite_match_arm(context, self.arm, shape, self.is_last)
1440     }
1441 }
1442
1443 fn rewrite_match(
1444     context: &RewriteContext,
1445     cond: &ast::Expr,
1446     arms: &[ast::Arm],
1447     shape: Shape,
1448     span: Span,
1449     attrs: &[ast::Attribute],
1450 ) -> Option<String> {
1451     // Do not take the rhs overhead from the upper expressions into account
1452     // when rewriting match condition.
1453     let cond_shape = Shape {
1454         width: context.budget(shape.used_width()),
1455         ..shape
1456     };
1457     // 6 = `match `
1458     let cond_shape = match context.config.control_style() {
1459         Style::Legacy => cond_shape.shrink_left(6)?,
1460         Style::Rfc => cond_shape.offset_left(6)?,
1461     };
1462     let cond_str = cond.rewrite(context, cond_shape)?;
1463     let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1464     let block_sep = match context.config.control_brace_style() {
1465         ControlBraceStyle::AlwaysNextLine => &alt_block_sep,
1466         _ if last_line_extendable(&cond_str) => " ",
1467         // 2 = ` {`
1468         _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => &alt_block_sep,
1469         _ => " ",
1470     };
1471
1472     let nested_indent_str = shape
1473         .indent
1474         .block_indent(context.config)
1475         .to_string(context.config);
1476     // Inner attributes.
1477     let inner_attrs = &inner_attributes(attrs);
1478     let inner_attrs_str = if inner_attrs.is_empty() {
1479         String::new()
1480     } else {
1481         inner_attrs
1482             .rewrite(context, shape)
1483             .map(|s| format!("{}{}\n", nested_indent_str, s))?
1484     };
1485
1486     let open_brace_pos = if inner_attrs.is_empty() {
1487         let hi = if arms.is_empty() {
1488             span.hi()
1489         } else {
1490             arms[0].span().lo()
1491         };
1492         context.codemap.span_after(mk_sp(cond.span.hi(), hi), "{")
1493     } else {
1494         inner_attrs[inner_attrs.len() - 1].span().hi()
1495     };
1496
1497     let arm_indent_str = if context.config.indent_match_arms() {
1498         nested_indent_str
1499     } else {
1500         shape.indent.to_string(context.config)
1501     };
1502
1503     if arms.is_empty() {
1504         let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
1505         if snippet.trim().is_empty() {
1506             Some(format!("match {} {{}}", cond_str))
1507         } else {
1508             // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
1509             Some(context.snippet(span))
1510         }
1511     } else {
1512         Some(format!(
1513             "match {}{}{{\n{}{}{}\n{}}}",
1514             cond_str,
1515             block_sep,
1516             inner_attrs_str,
1517             arm_indent_str,
1518             rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
1519             shape.indent.to_string(context.config),
1520         ))
1521     }
1522 }
1523
1524 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
1525     if is_last && config.trailing_comma() == SeparatorTactic::Never {
1526         ""
1527     } else if config.match_block_trailing_comma() {
1528         ","
1529     } else if let ast::ExprKind::Block(ref block) = body.node {
1530         if let ast::BlockCheckMode::Default = block.rules {
1531             ""
1532         } else {
1533             ","
1534         }
1535     } else {
1536         ","
1537     }
1538 }
1539
1540 fn rewrite_match_arms(
1541     context: &RewriteContext,
1542     arms: &[ast::Arm],
1543     shape: Shape,
1544     span: Span,
1545     open_brace_pos: BytePos,
1546 ) -> Option<String> {
1547     let arm_shape = if context.config.indent_match_arms() {
1548         shape.block_indent(context.config.tab_spaces())
1549     } else {
1550         shape.block_indent(0)
1551     }.with_max_width(context.config);
1552
1553     let arm_len = arms.len();
1554     let is_last_iter = repeat(false)
1555         .take(arm_len.checked_sub(1).unwrap_or(0))
1556         .chain(repeat(true));
1557     let items = itemize_list(
1558         context.codemap,
1559         arms.iter()
1560             .zip(is_last_iter)
1561             .map(|(arm, is_last)| ArmWrapper::new(arm, is_last)),
1562         "}",
1563         |arm| arm.arm.span().lo(),
1564         |arm| arm.arm.span().hi(),
1565         |arm| arm.rewrite(context, arm_shape),
1566         open_brace_pos,
1567         span.hi(),
1568         false,
1569     );
1570     let arms_vec: Vec<_> = items.collect();
1571     let fmt = ListFormatting {
1572         tactic: DefinitiveListTactic::Vertical,
1573         // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1574         separator: "",
1575         trailing_separator: SeparatorTactic::Never,
1576         separator_place: SeparatorPlace::Back,
1577         shape: arm_shape,
1578         ends_with_newline: true,
1579         preserve_newline: true,
1580         config: context.config,
1581     };
1582
1583     write_list(&arms_vec, &fmt)
1584 }
1585
1586 fn rewrite_match_arm(
1587     context: &RewriteContext,
1588     arm: &ast::Arm,
1589     shape: Shape,
1590     is_last: bool,
1591 ) -> Option<String> {
1592     let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
1593         if contains_skip(&arm.attrs) {
1594             let (_, body) = flatten_arm_body(context, &arm.body);
1595             // `arm.span()` does not include trailing comma, add it manually.
1596             return Some(format!(
1597                 "{}{}",
1598                 context.snippet(arm.span()),
1599                 arm_comma(context.config, body, is_last),
1600             ));
1601         }
1602         (
1603             mk_sp(
1604                 arm.attrs[arm.attrs.len() - 1].span.hi(),
1605                 arm.pats[0].span.lo(),
1606             ),
1607             arm.attrs.rewrite(context, shape)?,
1608         )
1609     } else {
1610         (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
1611     };
1612     let pats_str =
1613         rewrite_match_pattern(context, &arm.pats, &arm.guard, shape).and_then(|pats_str| {
1614             combine_strs_with_missing_comments(
1615                 context,
1616                 &attrs_str,
1617                 &pats_str,
1618                 missing_span,
1619                 shape,
1620                 false,
1621             )
1622         })?;
1623     rewrite_match_body(
1624         context,
1625         &arm.body,
1626         &pats_str,
1627         shape,
1628         arm.guard.is_some(),
1629         is_last,
1630     )
1631 }
1632
1633 fn rewrite_match_pattern(
1634     context: &RewriteContext,
1635     pats: &[ptr::P<ast::Pat>],
1636     guard: &Option<ptr::P<ast::Expr>>,
1637     shape: Shape,
1638 ) -> Option<String> {
1639     // Patterns
1640     // 5 = ` => {`
1641     let pat_shape = shape.sub_width(5)?;
1642
1643     let pat_strs = pats.iter()
1644         .map(|p| p.rewrite(context, pat_shape))
1645         .collect::<Option<Vec<_>>>()?;
1646
1647     let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1648     let tactic = definitive_tactic(
1649         &items,
1650         ListTactic::HorizontalVertical,
1651         Separator::VerticalBar,
1652         pat_shape.width,
1653     );
1654     let fmt = ListFormatting {
1655         tactic: tactic,
1656         separator: " |",
1657         trailing_separator: SeparatorTactic::Never,
1658         separator_place: context.config.match_pattern_separator_break_point(),
1659         shape: pat_shape,
1660         ends_with_newline: false,
1661         preserve_newline: false,
1662         config: context.config,
1663     };
1664     let pats_str = write_list(&items, &fmt)?;
1665
1666     // Guard
1667     let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
1668
1669     Some(format!("{}{}", pats_str, guard_str))
1670 }
1671
1672 // (extend, body)
1673 // @extend: true if the arm body can be put next to `=>`
1674 // @body: flattened body, if the body is block with a single expression
1675 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
1676     match body.node {
1677         ast::ExprKind::Block(ref block)
1678             if !is_unsafe_block(block) && is_simple_block(block, context.codemap) =>
1679         {
1680             if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
1681                 (
1682                     !context.config.multiline_match_arm_forces_block()
1683                         && expr.can_be_overflowed(context, 1),
1684                     &**expr,
1685                 )
1686             } else {
1687                 (false, &*body)
1688             }
1689         }
1690         _ => (
1691             !context.config.multiline_match_arm_forces_block()
1692                 && body.can_be_overflowed(context, 1),
1693             &*body,
1694         ),
1695     }
1696 }
1697
1698 fn rewrite_match_body(
1699     context: &RewriteContext,
1700     body: &ptr::P<ast::Expr>,
1701     pats_str: &str,
1702     shape: Shape,
1703     has_guard: bool,
1704     is_last: bool,
1705 ) -> Option<String> {
1706     let (extend, body) = flatten_arm_body(context, body);
1707     let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
1708         (true, is_empty_block(block, context.codemap))
1709     } else {
1710         (false, false)
1711     };
1712     let extend = if context.config.match_arm_forces_newline() {
1713         is_block
1714     } else {
1715         extend
1716     };
1717
1718     let comma = arm_comma(context.config, body, is_last);
1719     let alt_block_sep = String::from("\n") + &shape.indent.block_only().to_string(context.config);
1720     let alt_block_sep = alt_block_sep.as_str();
1721
1722     let combine_orig_body = |body_str: &str| {
1723         let block_sep = match context.config.control_brace_style() {
1724             ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
1725             _ => " ",
1726         };
1727
1728         Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
1729     };
1730
1731     let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
1732     let next_line_indent = if is_block {
1733         if is_empty_block {
1734             shape.indent.block_indent(context.config)
1735         } else {
1736             shape.indent
1737         }
1738     } else {
1739         shape.indent.block_indent(context.config)
1740     };
1741     let combine_next_line_body = |body_str: &str| {
1742         if is_block {
1743             return Some(format!(
1744                 "{} =>\n{}{}",
1745                 pats_str,
1746                 next_line_indent.to_string(context.config),
1747                 body_str
1748             ));
1749         }
1750
1751         let indent_str = shape.indent.to_string(context.config);
1752         let nested_indent_str = next_line_indent.to_string(context.config);
1753         let (body_prefix, body_suffix) = if context.config.wrap_match_arms() {
1754             let comma = if context.config.match_block_trailing_comma() {
1755                 ","
1756             } else {
1757                 ""
1758             };
1759             ("{", format!("\n{}}}{}", indent_str, comma))
1760         } else {
1761             ("", String::from(","))
1762         };
1763
1764         let block_sep = match context.config.control_brace_style() {
1765             ControlBraceStyle::AlwaysNextLine => format!("{}{}\n", alt_block_sep, body_prefix),
1766             _ if body_prefix.is_empty() => "\n".to_owned(),
1767             _ if forbid_same_line => format!("{}{}\n", alt_block_sep, body_prefix),
1768             _ => format!(" {}\n", body_prefix),
1769         } + &nested_indent_str;
1770
1771         Some(format!(
1772             "{} =>{}{}{}",
1773             pats_str,
1774             block_sep,
1775             body_str,
1776             body_suffix
1777         ))
1778     };
1779
1780     // Let's try and get the arm body on the same line as the condition.
1781     // 4 = ` => `.len()
1782     let orig_body_shape = shape
1783         .offset_left(extra_offset(pats_str, shape) + 4)
1784         .and_then(|shape| shape.sub_width(comma.len()));
1785     let orig_body = if let Some(body_shape) = orig_body_shape {
1786         let rewrite = nop_block_collapse(
1787             format_expr(body, ExprType::Statement, context, body_shape),
1788             body_shape.width,
1789         );
1790
1791         match rewrite {
1792             Some(ref body_str)
1793                 if !forbid_same_line && !context.config.match_arm_forces_newline()
1794                     && (is_block
1795                         || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
1796             {
1797                 return combine_orig_body(body_str);
1798             }
1799             _ => rewrite,
1800         }
1801     } else {
1802         None
1803     };
1804     let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
1805
1806     // Try putting body on the next line and see if it looks better.
1807     let next_line_body_shape = Shape::indented(next_line_indent, context.config);
1808     let next_line_body = nop_block_collapse(
1809         format_expr(body, ExprType::Statement, context, next_line_body_shape),
1810         next_line_body_shape.width,
1811     );
1812     match (orig_body, next_line_body) {
1813         (Some(ref orig_str), Some(ref next_line_str))
1814             if forbid_same_line || prefer_next_line(orig_str, next_line_str) =>
1815         {
1816             combine_next_line_body(next_line_str)
1817         }
1818         (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
1819             combine_orig_body(orig_str)
1820         }
1821         (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
1822             combine_next_line_body(next_line_str)
1823         }
1824         (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
1825         (None, None) => None,
1826         (Some(ref orig_str), _) => combine_orig_body(orig_str),
1827     }
1828 }
1829
1830 // The `if ...` guard on a match arm.
1831 fn rewrite_guard(
1832     context: &RewriteContext,
1833     guard: &Option<ptr::P<ast::Expr>>,
1834     shape: Shape,
1835     // The amount of space used up on this line for the pattern in
1836     // the arm (excludes offset).
1837     pattern_width: usize,
1838 ) -> Option<String> {
1839     if let Some(ref guard) = *guard {
1840         // First try to fit the guard string on the same line as the pattern.
1841         // 4 = ` if `, 5 = ` => {`
1842         let cond_shape = shape
1843             .offset_left(pattern_width + 4)
1844             .and_then(|s| s.sub_width(5));
1845         if let Some(cond_shape) = cond_shape {
1846             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1847                 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
1848                     return Some(format!(" if {}", cond_str));
1849                 }
1850             }
1851         }
1852
1853         // Not enough space to put the guard after the pattern, try a newline.
1854         // 3 = `if `, 5 = ` => {`
1855         let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
1856             .offset_left(3)
1857             .and_then(|s| s.sub_width(5));
1858         if let Some(cond_shape) = cond_shape {
1859             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
1860                 return Some(format!(
1861                     "\n{}if {}",
1862                     cond_shape.indent.to_string(context.config),
1863                     cond_str
1864                 ));
1865             }
1866         }
1867
1868         None
1869     } else {
1870         Some(String::new())
1871     }
1872 }
1873
1874 fn rewrite_pat_expr(
1875     context: &RewriteContext,
1876     pat: Option<&ast::Pat>,
1877     expr: &ast::Expr,
1878     matcher: &str,
1879     // Connecting piece between pattern and expression,
1880     // *without* trailing space.
1881     connector: &str,
1882     keyword: &str,
1883     shape: Shape,
1884 ) -> Option<String> {
1885     debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
1886     if let Some(pat) = pat {
1887         let matcher = if matcher.is_empty() {
1888             matcher.to_owned()
1889         } else {
1890             format!("{} ", matcher)
1891         };
1892         let pat_shape = shape
1893             .offset_left(matcher.len())?
1894             .sub_width(connector.len())?;
1895         let pat_string = pat.rewrite(context, pat_shape)?;
1896         let result = format!("{}{}{}", matcher, pat_string, connector);
1897         return rewrite_assign_rhs(context, result, expr, shape);
1898     }
1899
1900     let expr_rw = expr.rewrite(context, shape);
1901     // The expression may (partially) fit on the current line.
1902     // We do not allow splitting between `if` and condition.
1903     if keyword == "if" || expr_rw.is_some() {
1904         return expr_rw;
1905     }
1906
1907     // The expression won't fit on the current line, jump to next.
1908     let nested_shape = shape
1909         .block_indent(context.config.tab_spaces())
1910         .with_max_width(context.config);
1911     let nested_indent_str = nested_shape.indent.to_string(context.config);
1912     expr.rewrite(context, nested_shape)
1913         .map(|expr_rw| format!("\n{}{}", nested_indent_str, expr_rw))
1914 }
1915
1916 pub fn rewrite_literal(context: &RewriteContext, l: &ast::Lit, shape: Shape) -> Option<String> {
1917     match l.node {
1918         ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1919         _ => Some(context.snippet(l.span)),
1920     }
1921 }
1922
1923 fn rewrite_string_lit(context: &RewriteContext, span: Span, shape: Shape) -> Option<String> {
1924     let string_lit = context.snippet(span);
1925
1926     if !context.config.format_strings() && !context.config.force_format_strings() {
1927         if string_lit
1928             .lines()
1929             .rev()
1930             .skip(1)
1931             .all(|line| line.ends_with('\\'))
1932         {
1933             let new_indent = shape.visual_indent(1).indent;
1934             return Some(String::from(
1935                 string_lit
1936                     .lines()
1937                     .map(|line| {
1938                         format!(
1939                             "{}{}",
1940                             new_indent.to_string(context.config),
1941                             line.trim_left()
1942                         )
1943                     })
1944                     .collect::<Vec<_>>()
1945                     .join("\n")
1946                     .trim_left(),
1947             ));
1948         } else {
1949             return Some(string_lit);
1950         }
1951     }
1952
1953     if !context.config.force_format_strings()
1954         && !string_requires_rewrite(context, span, &string_lit, shape)
1955     {
1956         return Some(string_lit);
1957     }
1958
1959     // Remove the quote characters.
1960     let str_lit = &string_lit[1..string_lit.len() - 1];
1961
1962     rewrite_string(
1963         str_lit,
1964         &StringFormat::new(shape.visual_indent(0), context.config),
1965         None,
1966     )
1967 }
1968
1969 fn string_requires_rewrite(
1970     context: &RewriteContext,
1971     span: Span,
1972     string: &str,
1973     shape: Shape,
1974 ) -> bool {
1975     if context.codemap.lookup_char_pos(span.lo()).col.0 != shape.indent.width() {
1976         return true;
1977     }
1978
1979     for (i, line) in string.lines().enumerate() {
1980         if i == 0 {
1981             if line.len() > shape.width {
1982                 return true;
1983             }
1984         } else if line.len() > shape.width + shape.indent.width() {
1985             return true;
1986         }
1987     }
1988
1989     false
1990 }
1991
1992 pub fn rewrite_call(
1993     context: &RewriteContext,
1994     callee: &str,
1995     args: &[ptr::P<ast::Expr>],
1996     span: Span,
1997     shape: Shape,
1998 ) -> Option<String> {
1999     let force_trailing_comma = if context.inside_macro {
2000         span_ends_with_comma(context, span)
2001     } else {
2002         false
2003     };
2004     rewrite_call_inner(
2005         context,
2006         callee,
2007         &ptr_vec_to_ref_vec(&args),
2008         span,
2009         shape,
2010         context.config.fn_call_width(),
2011         force_trailing_comma,
2012     )
2013 }
2014
2015 pub fn rewrite_call_inner<'a, T>(
2016     context: &RewriteContext,
2017     callee_str: &str,
2018     args: &[&T],
2019     span: Span,
2020     shape: Shape,
2021     args_max_width: usize,
2022     force_trailing_comma: bool,
2023 ) -> Option<String>
2024 where
2025     T: Rewrite + Spanned + ToExpr + 'a,
2026 {
2027     // 2 = `( `, 1 = `(`
2028     let paren_overhead = if context.config.spaces_within_parens() {
2029         2
2030     } else {
2031         1
2032     };
2033     let used_width = extra_offset(callee_str, shape);
2034     let one_line_width = shape.width.checked_sub(used_width + 2 * paren_overhead)?;
2035
2036     let nested_shape = shape_from_fn_call_style(
2037         context,
2038         shape,
2039         used_width + 2 * paren_overhead,
2040         used_width + paren_overhead,
2041     )?;
2042
2043     let span_lo = context.codemap.span_after(span, "(");
2044     let args_span = mk_sp(span_lo, span.hi());
2045
2046     let (extendable, list_str) = rewrite_call_args(
2047         context,
2048         args,
2049         args_span,
2050         nested_shape,
2051         one_line_width,
2052         args_max_width,
2053         force_trailing_comma,
2054     )?;
2055
2056     if !context.use_block_indent() && need_block_indent(&list_str, nested_shape) && !extendable {
2057         let mut new_context = context.clone();
2058         new_context.use_block = true;
2059         return rewrite_call_inner(
2060             &new_context,
2061             callee_str,
2062             args,
2063             span,
2064             shape,
2065             args_max_width,
2066             force_trailing_comma,
2067         );
2068     }
2069
2070     let args_shape = shape.sub_width(last_line_width(callee_str))?;
2071     Some(format!(
2072         "{}{}",
2073         callee_str,
2074         wrap_args_with_parens(context, &list_str, extendable, args_shape, nested_shape)
2075     ))
2076 }
2077
2078 fn need_block_indent(s: &str, shape: Shape) -> bool {
2079     s.lines().skip(1).any(|s| {
2080         s.find(|c| !char::is_whitespace(c))
2081             .map_or(false, |w| w + 1 < shape.indent.width())
2082     })
2083 }
2084
2085 fn rewrite_call_args<'a, T>(
2086     context: &RewriteContext,
2087     args: &[&T],
2088     span: Span,
2089     shape: Shape,
2090     one_line_width: usize,
2091     args_max_width: usize,
2092     force_trailing_comma: bool,
2093 ) -> Option<(bool, String)>
2094 where
2095     T: Rewrite + Spanned + ToExpr + 'a,
2096 {
2097     let items = itemize_list(
2098         context.codemap,
2099         args.iter(),
2100         ")",
2101         |item| item.span().lo(),
2102         |item| item.span().hi(),
2103         |item| item.rewrite(context, shape),
2104         span.lo(),
2105         span.hi(),
2106         true,
2107     );
2108     let mut item_vec: Vec<_> = items.collect();
2109
2110     // Try letting the last argument overflow to the next line with block
2111     // indentation. If its first line fits on one line with the other arguments,
2112     // we format the function arguments horizontally.
2113     let tactic = try_overflow_last_arg(
2114         context,
2115         &mut item_vec,
2116         &args[..],
2117         shape,
2118         one_line_width,
2119         args_max_width,
2120     );
2121
2122     let fmt = ListFormatting {
2123         tactic: tactic,
2124         separator: ",",
2125         trailing_separator: if force_trailing_comma {
2126             SeparatorTactic::Always
2127         } else if context.inside_macro || !context.use_block_indent() {
2128             SeparatorTactic::Never
2129         } else {
2130             context.config.trailing_comma()
2131         },
2132         separator_place: SeparatorPlace::Back,
2133         shape: shape,
2134         ends_with_newline: context.use_block_indent() && tactic == DefinitiveListTactic::Vertical,
2135         preserve_newline: false,
2136         config: context.config,
2137     };
2138
2139     write_list(&item_vec, &fmt).map(|args_str| {
2140         (tactic != DefinitiveListTactic::Vertical, args_str)
2141     })
2142 }
2143
2144 fn try_overflow_last_arg<'a, T>(
2145     context: &RewriteContext,
2146     item_vec: &mut Vec<ListItem>,
2147     args: &[&T],
2148     shape: Shape,
2149     one_line_width: usize,
2150     args_max_width: usize,
2151 ) -> DefinitiveListTactic
2152 where
2153     T: Rewrite + Spanned + ToExpr + 'a,
2154 {
2155     let overflow_last = can_be_overflowed(context, args);
2156
2157     // Replace the last item with its first line to see if it fits with
2158     // first arguments.
2159     let placeholder = if overflow_last {
2160         let mut context = context.clone();
2161         if let Some(expr) = args[args.len() - 1].to_expr() {
2162             if let ast::ExprKind::MethodCall(..) = expr.node {
2163                 context.force_one_line_chain = true;
2164             }
2165         }
2166         last_arg_shape(&context, item_vec, shape, args_max_width).and_then(|arg_shape| {
2167             rewrite_last_arg_with_overflow(&context, args, &mut item_vec[args.len() - 1], arg_shape)
2168         })
2169     } else {
2170         None
2171     };
2172
2173     let mut tactic = definitive_tactic(
2174         &*item_vec,
2175         ListTactic::LimitedHorizontalVertical(args_max_width),
2176         Separator::Comma,
2177         one_line_width,
2178     );
2179
2180     // Replace the stub with the full overflowing last argument if the rewrite
2181     // succeeded and its first line fits with the other arguments.
2182     match (overflow_last, tactic, placeholder) {
2183         (true, DefinitiveListTactic::Horizontal, placeholder @ Some(..)) => {
2184             item_vec[args.len() - 1].item = placeholder;
2185         }
2186         _ if args.len() >= 1 => {
2187             item_vec[args.len() - 1].item = args.last()
2188                 .and_then(|last_arg| last_arg.rewrite(context, shape));
2189             // Use horizontal layout for a function with a single argument as long as
2190             // everything fits in a single line.
2191             if args.len() == 1
2192                 && args_max_width != 0 // Vertical layout is forced.
2193                 && !item_vec[0].has_comment()
2194                 && !item_vec[0].inner_as_ref().contains('\n')
2195                 && ::lists::total_item_width(&item_vec[0]) <= one_line_width
2196             {
2197                 tactic = DefinitiveListTactic::Horizontal;
2198             } else {
2199                 tactic = definitive_tactic(
2200                     &*item_vec,
2201                     ListTactic::LimitedHorizontalVertical(args_max_width),
2202                     Separator::Comma,
2203                     one_line_width,
2204                 );
2205             }
2206         }
2207         _ => (),
2208     }
2209
2210     tactic
2211 }
2212
2213 fn last_arg_shape(
2214     context: &RewriteContext,
2215     items: &[ListItem],
2216     shape: Shape,
2217     args_max_width: usize,
2218 ) -> Option<Shape> {
2219     let overhead = items.iter().rev().skip(1).fold(0, |acc, i| {
2220         acc + i.item.as_ref().map_or(0, |s| first_line_width(s))
2221     });
2222     let max_width = min(args_max_width, shape.width);
2223     let arg_indent = if context.use_block_indent() {
2224         shape.block().indent.block_unindent(context.config)
2225     } else {
2226         shape.block().indent
2227     };
2228     Some(Shape {
2229         width: max_width.checked_sub(overhead)?,
2230         indent: arg_indent,
2231         offset: 0,
2232     })
2233 }
2234
2235 // Rewriting closure which is placed at the end of the function call's arg.
2236 // Returns `None` if the reformatted closure 'looks bad'.
2237 fn rewrite_last_closure(
2238     context: &RewriteContext,
2239     expr: &ast::Expr,
2240     shape: Shape,
2241 ) -> Option<String> {
2242     if let ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) = expr.node {
2243         let body = match body.node {
2244             ast::ExprKind::Block(ref block) if is_simple_block(block, context.codemap) => {
2245                 stmt_expr(&block.stmts[0]).unwrap_or(body)
2246             }
2247             _ => body,
2248         };
2249         let (prefix, extra_offset) =
2250             rewrite_closure_fn_decl(capture, fn_decl, body, expr.span, context, shape)?;
2251         // If the closure goes multi line before its body, do not overflow the closure.
2252         if prefix.contains('\n') {
2253             return None;
2254         }
2255         // If we are inside macro, we do not want to add or remove block from closure body.
2256         if context.inside_macro {
2257             return expr.rewrite(context, shape);
2258         }
2259
2260         let body_shape = shape.offset_left(extra_offset)?;
2261
2262         // We force to use block for the body of the closure for certain kinds of expressions.
2263         if is_block_closure_forced(body) {
2264             return rewrite_closure_with_block(context, body_shape, &prefix, body).and_then(
2265                 |body_str| {
2266                     // If the expression can fit in a single line, we need not force block closure.
2267                     if body_str.lines().count() <= 7 {
2268                         match rewrite_closure_expr(body, &prefix, context, shape) {
2269                             Some(ref single_line_body_str)
2270                                 if !single_line_body_str.contains('\n') =>
2271                             {
2272                                 Some(single_line_body_str.clone())
2273                             }
2274                             _ => Some(body_str),
2275                         }
2276                     } else {
2277                         Some(body_str)
2278                     }
2279                 },
2280             );
2281         }
2282
2283         // When overflowing the closure which consists of a single control flow expression,
2284         // force to use block if its condition uses multi line.
2285         let is_multi_lined_cond = rewrite_cond(context, body, body_shape)
2286             .map(|cond| cond.contains('\n') || cond.len() > body_shape.width)
2287             .unwrap_or(false);
2288         if is_multi_lined_cond {
2289             return rewrite_closure_with_block(context, body_shape, &prefix, body);
2290         }
2291
2292         // Seems fine, just format the closure in usual manner.
2293         return expr.rewrite(context, shape);
2294     }
2295     None
2296 }
2297
2298 fn is_block_closure_forced(expr: &ast::Expr) -> bool {
2299     match expr.node {
2300         ast::ExprKind::If(..) |
2301         ast::ExprKind::IfLet(..) |
2302         ast::ExprKind::Loop(..) |
2303         ast::ExprKind::While(..) |
2304         ast::ExprKind::WhileLet(..) |
2305         ast::ExprKind::ForLoop(..) => true,
2306         ast::ExprKind::AddrOf(_, ref expr) |
2307         ast::ExprKind::Box(ref expr) |
2308         ast::ExprKind::Try(ref expr) |
2309         ast::ExprKind::Unary(_, ref expr) |
2310         ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced(expr),
2311         _ => false,
2312     }
2313 }
2314
2315 fn rewrite_last_arg_with_overflow<'a, T>(
2316     context: &RewriteContext,
2317     args: &[&T],
2318     last_item: &mut ListItem,
2319     shape: Shape,
2320 ) -> Option<String>
2321 where
2322     T: Rewrite + Spanned + ToExpr + 'a,
2323 {
2324     let last_arg = args[args.len() - 1];
2325     let rewrite = if let Some(expr) = last_arg.to_expr() {
2326         match expr.node {
2327             // When overflowing the closure which consists of a single control flow expression,
2328             // force to use block if its condition uses multi line.
2329             ast::ExprKind::Closure(..) => {
2330                 // If the argument consists of multiple closures, we do not overflow
2331                 // the last closure.
2332                 if args_have_many_closure(args) {
2333                     None
2334                 } else {
2335                     rewrite_last_closure(context, expr, shape)
2336                 }
2337             }
2338             _ => expr.rewrite(context, shape),
2339         }
2340     } else {
2341         last_arg.rewrite(context, shape)
2342     };
2343
2344     if let Some(rewrite) = rewrite {
2345         let rewrite_first_line = Some(rewrite[..first_line_width(&rewrite)].to_owned());
2346         last_item.item = rewrite_first_line;
2347         Some(rewrite)
2348     } else {
2349         None
2350     }
2351 }
2352
2353 /// Returns true if the given vector of arguments has more than one `ast::ExprKind::Closure`.
2354 fn args_have_many_closure<T>(args: &[&T]) -> bool
2355 where
2356     T: ToExpr,
2357 {
2358     args.iter()
2359         .filter(|arg| {
2360             arg.to_expr()
2361                 .map(|e| match e.node {
2362                     ast::ExprKind::Closure(..) => true,
2363                     _ => false,
2364                 })
2365                 .unwrap_or(false)
2366         })
2367         .count() > 1
2368 }
2369
2370 fn can_be_overflowed<'a, T>(context: &RewriteContext, args: &[&T]) -> bool
2371 where
2372     T: Rewrite + Spanned + ToExpr + 'a,
2373 {
2374     args.last()
2375         .map_or(false, |x| x.can_be_overflowed(context, args.len()))
2376 }
2377
2378 pub fn can_be_overflowed_expr(context: &RewriteContext, expr: &ast::Expr, args_len: usize) -> bool {
2379     match expr.node {
2380         ast::ExprKind::Match(..) => {
2381             (context.use_block_indent() && args_len == 1)
2382                 || (context.config.fn_call_style() == IndentStyle::Visual && args_len > 1)
2383         }
2384         ast::ExprKind::If(..) |
2385         ast::ExprKind::IfLet(..) |
2386         ast::ExprKind::ForLoop(..) |
2387         ast::ExprKind::Loop(..) |
2388         ast::ExprKind::While(..) |
2389         ast::ExprKind::WhileLet(..) => {
2390             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
2391         }
2392         ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => {
2393             context.use_block_indent()
2394                 || context.config.fn_call_style() == IndentStyle::Visual && args_len > 1
2395         }
2396         ast::ExprKind::Array(..) |
2397         ast::ExprKind::Call(..) |
2398         ast::ExprKind::Mac(..) |
2399         ast::ExprKind::MethodCall(..) |
2400         ast::ExprKind::Struct(..) |
2401         ast::ExprKind::Tup(..) => context.use_block_indent() && args_len == 1,
2402         ast::ExprKind::AddrOf(_, ref expr) |
2403         ast::ExprKind::Box(ref expr) |
2404         ast::ExprKind::Try(ref expr) |
2405         ast::ExprKind::Unary(_, ref expr) |
2406         ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
2407         _ => false,
2408     }
2409 }
2410
2411 pub fn wrap_args_with_parens(
2412     context: &RewriteContext,
2413     args_str: &str,
2414     is_extendable: bool,
2415     shape: Shape,
2416     nested_shape: Shape,
2417 ) -> String {
2418     if !context.use_block_indent()
2419         || (context.inside_macro && !args_str.contains('\n')
2420             && args_str.len() + paren_overhead(context) <= shape.width) || is_extendable
2421     {
2422         if context.config.spaces_within_parens() && !args_str.is_empty() {
2423             format!("( {} )", args_str)
2424         } else {
2425             format!("({})", args_str)
2426         }
2427     } else {
2428         format!(
2429             "(\n{}{}\n{})",
2430             nested_shape.indent.to_string(context.config),
2431             args_str,
2432             shape.block().indent.to_string(context.config)
2433         )
2434     }
2435 }
2436
2437 /// Return true if a function call or a method call represented by the given span ends with a
2438 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2439 /// comma from macro can potentially break the code.
2440 fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2441     let mut encountered_closing_paren = false;
2442     for c in context.snippet(span).chars().rev() {
2443         match c {
2444             ',' => return true,
2445             ')' => if encountered_closing_paren {
2446                 return false;
2447             } else {
2448                 encountered_closing_paren = true;
2449             },
2450             _ if c.is_whitespace() => continue,
2451             _ => return false,
2452         }
2453     }
2454     false
2455 }
2456
2457 fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {
2458     debug!("rewrite_paren, shape: {:?}", shape);
2459     let total_paren_overhead = paren_overhead(context);
2460     let paren_overhead = total_paren_overhead / 2;
2461     let sub_shape = shape
2462         .offset_left(paren_overhead)
2463         .and_then(|s| s.sub_width(paren_overhead))?;
2464
2465     let paren_wrapper = |s: &str| if context.config.spaces_within_parens() && !s.is_empty() {
2466         format!("( {} )", s)
2467     } else {
2468         format!("({})", s)
2469     };
2470
2471     let subexpr_str = subexpr.rewrite(context, sub_shape)?;
2472     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
2473
2474     if subexpr_str.contains('\n')
2475         || first_line_width(&subexpr_str) + total_paren_overhead <= shape.width
2476     {
2477         Some(paren_wrapper(&subexpr_str))
2478     } else {
2479         None
2480     }
2481 }
2482
2483 fn rewrite_index(
2484     expr: &ast::Expr,
2485     index: &ast::Expr,
2486     context: &RewriteContext,
2487     shape: Shape,
2488 ) -> Option<String> {
2489     let expr_str = expr.rewrite(context, shape)?;
2490
2491     let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
2492         ("[ ", " ]")
2493     } else {
2494         ("[", "]")
2495     };
2496
2497     let offset = last_line_width(&expr_str) + lbr.len();
2498     let rhs_overhead = shape.rhs_overhead(context.config);
2499     let index_shape = if expr_str.contains('\n') {
2500         Shape::legacy(context.config.max_width(), shape.indent)
2501             .offset_left(offset)
2502             .and_then(|shape| shape.sub_width(rbr.len() + rhs_overhead))
2503     } else {
2504         shape.visual_indent(offset).sub_width(offset + rbr.len())
2505     };
2506     let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
2507
2508     // Return if index fits in a single line.
2509     match orig_index_rw {
2510         Some(ref index_str) if !index_str.contains('\n') => {
2511             return Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr));
2512         }
2513         _ => (),
2514     }
2515
2516     // Try putting index on the next line and see if it fits in a single line.
2517     let indent = shape.indent.block_indent(context.config);
2518     let index_shape = Shape::indented(indent, context.config).offset_left(lbr.len())?;
2519     let index_shape = index_shape.sub_width(rbr.len() + rhs_overhead)?;
2520     let new_index_rw = index.rewrite(context, index_shape);
2521     match (orig_index_rw, new_index_rw) {
2522         (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
2523             "{}\n{}{}{}{}",
2524             expr_str,
2525             indent.to_string(context.config),
2526             lbr,
2527             new_index_str,
2528             rbr
2529         )),
2530         (None, Some(ref new_index_str)) => Some(format!(
2531             "{}\n{}{}{}{}",
2532             expr_str,
2533             indent.to_string(context.config),
2534             lbr,
2535             new_index_str,
2536             rbr
2537         )),
2538         (Some(ref index_str), _) => Some(format!("{}{}{}{}", expr_str, lbr, index_str, rbr)),
2539         _ => None,
2540     }
2541 }
2542
2543 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: &Option<&ast::Expr>) -> bool {
2544     if base.is_some() {
2545         return false;
2546     }
2547
2548     fields.iter().all(|field| !field.is_shorthand)
2549 }
2550
2551 fn rewrite_struct_lit<'a>(
2552     context: &RewriteContext,
2553     path: &ast::Path,
2554     fields: &'a [ast::Field],
2555     base: Option<&'a ast::Expr>,
2556     span: Span,
2557     shape: Shape,
2558 ) -> Option<String> {
2559     debug!("rewrite_struct_lit: shape {:?}", shape);
2560
2561     enum StructLitField<'a> {
2562         Regular(&'a ast::Field),
2563         Base(&'a ast::Expr),
2564     }
2565
2566     // 2 = " {".len()
2567     let path_shape = shape.sub_width(2)?;
2568     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
2569
2570     if fields.is_empty() && base.is_none() {
2571         return Some(format!("{} {{}}", path_str));
2572     }
2573
2574     // Foo { a: Foo } - indent is +3, width is -5.
2575     let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
2576
2577     let one_line_width = h_shape.map_or(0, |shape| shape.width);
2578     let body_lo = context.codemap.span_after(span, "{");
2579     let fields_str = if struct_lit_can_be_aligned(fields, &base)
2580         && context.config.struct_field_align_threshold() > 0
2581     {
2582         rewrite_with_alignment(
2583             fields,
2584             context,
2585             shape,
2586             mk_sp(body_lo, span.hi()),
2587             one_line_width,
2588         )?
2589     } else {
2590         let field_iter = fields
2591             .into_iter()
2592             .map(StructLitField::Regular)
2593             .chain(base.into_iter().map(StructLitField::Base));
2594
2595         let span_lo = |item: &StructLitField| match *item {
2596             StructLitField::Regular(field) => field.span().lo(),
2597             StructLitField::Base(expr) => {
2598                 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
2599                 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
2600                 let pos = snippet.find_uncommented("..").unwrap();
2601                 last_field_hi + BytePos(pos as u32)
2602             }
2603         };
2604         let span_hi = |item: &StructLitField| match *item {
2605             StructLitField::Regular(field) => field.span().hi(),
2606             StructLitField::Base(expr) => expr.span.hi(),
2607         };
2608         let rewrite = |item: &StructLitField| match *item {
2609             StructLitField::Regular(field) => {
2610                 // The 1 taken from the v_budget is for the comma.
2611                 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
2612             }
2613             StructLitField::Base(expr) => {
2614                 // 2 = ..
2615                 expr.rewrite(context, v_shape.offset_left(2)?)
2616                     .map(|s| format!("..{}", s))
2617             }
2618         };
2619
2620         let items = itemize_list(
2621             context.codemap,
2622             field_iter,
2623             "}",
2624             span_lo,
2625             span_hi,
2626             rewrite,
2627             body_lo,
2628             span.hi(),
2629             false,
2630         );
2631         let item_vec = items.collect::<Vec<_>>();
2632
2633         let tactic = struct_lit_tactic(h_shape, context, &item_vec);
2634         let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
2635         let fmt = struct_lit_formatting(nested_shape, tactic, context, base.is_some());
2636
2637         write_list(&item_vec, &fmt)?
2638     };
2639
2640     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
2641     Some(format!("{} {{{}}}", path_str, fields_str))
2642
2643     // FIXME if context.config.struct_lit_style() == Visual, but we run out
2644     // of space, we should fall back to BlockIndent.
2645 }
2646
2647 pub fn wrap_struct_field(
2648     context: &RewriteContext,
2649     fields_str: &str,
2650     shape: Shape,
2651     nested_shape: Shape,
2652     one_line_width: usize,
2653 ) -> String {
2654     if context.config.struct_lit_style() == IndentStyle::Block
2655         && (fields_str.contains('\n')
2656             || context.config.struct_lit_multiline_style() == MultilineStyle::ForceMulti
2657             || fields_str.len() > one_line_width)
2658     {
2659         format!(
2660             "\n{}{}\n{}",
2661             nested_shape.indent.to_string(context.config),
2662             fields_str,
2663             shape.indent.to_string(context.config)
2664         )
2665     } else {
2666         // One liner or visual indent.
2667         format!(" {} ", fields_str)
2668     }
2669 }
2670
2671 pub fn struct_lit_field_separator(config: &Config) -> &str {
2672     colon_spaces(
2673         config.space_before_struct_lit_field_colon(),
2674         config.space_after_struct_lit_field_colon(),
2675     )
2676 }
2677
2678 pub fn rewrite_field(
2679     context: &RewriteContext,
2680     field: &ast::Field,
2681     shape: Shape,
2682     prefix_max_width: usize,
2683 ) -> Option<String> {
2684     if contains_skip(&field.attrs) {
2685         return Some(context.snippet(field.span()));
2686     }
2687     let name = &field.ident.node.to_string();
2688     if field.is_shorthand {
2689         Some(name.to_string())
2690     } else {
2691         let mut separator = String::from(struct_lit_field_separator(context.config));
2692         for _ in 0..prefix_max_width.checked_sub(name.len()).unwrap_or(0) {
2693             separator.push(' ');
2694         }
2695         let overhead = name.len() + separator.len();
2696         let expr_shape = shape.offset_left(overhead)?;
2697         let expr = field.expr.rewrite(context, expr_shape);
2698
2699         let mut attrs_str = field.attrs.rewrite(context, shape)?;
2700         if !attrs_str.is_empty() {
2701             attrs_str.push_str(&format!("\n{}", shape.indent.to_string(context.config)));
2702         };
2703
2704         match expr {
2705             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
2706             None => {
2707                 let expr_offset = shape.indent.block_indent(context.config);
2708                 let expr = field
2709                     .expr
2710                     .rewrite(context, Shape::indented(expr_offset, context.config));
2711                 expr.map(|s| {
2712                     format!(
2713                         "{}{}:\n{}{}",
2714                         attrs_str,
2715                         name,
2716                         expr_offset.to_string(context.config),
2717                         s
2718                     )
2719                 })
2720             }
2721         }
2722     }
2723 }
2724
2725 fn shape_from_fn_call_style(
2726     context: &RewriteContext,
2727     shape: Shape,
2728     overhead: usize,
2729     offset: usize,
2730 ) -> Option<Shape> {
2731     if context.use_block_indent() {
2732         // 1 = ","
2733         shape
2734             .block()
2735             .block_indent(context.config.tab_spaces())
2736             .with_max_width(context.config)
2737             .sub_width(1)
2738     } else {
2739         shape.visual_indent(offset).sub_width(overhead)
2740     }
2741 }
2742
2743 fn rewrite_tuple_in_visual_indent_style<'a, T>(
2744     context: &RewriteContext,
2745     items: &[&T],
2746     span: Span,
2747     shape: Shape,
2748 ) -> Option<String>
2749 where
2750     T: Rewrite + Spanned + ToExpr + 'a,
2751 {
2752     let mut items = items.iter();
2753     // In case of length 1, need a trailing comma
2754     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
2755     if items.len() == 1 {
2756         // 3 = "(" + ",)"
2757         let nested_shape = shape.sub_width(3)?.visual_indent(1);
2758         return items
2759             .next()
2760             .unwrap()
2761             .rewrite(context, nested_shape)
2762             .map(|s| {
2763                 if context.config.spaces_within_parens() {
2764                     format!("( {}, )", s)
2765                 } else {
2766                     format!("({},)", s)
2767                 }
2768             });
2769     }
2770
2771     let list_lo = context.codemap.span_after(span, "(");
2772     let nested_shape = shape.sub_width(2)?.visual_indent(1);
2773     let items = itemize_list(
2774         context.codemap,
2775         items,
2776         ")",
2777         |item| item.span().lo(),
2778         |item| item.span().hi(),
2779         |item| item.rewrite(context, nested_shape),
2780         list_lo,
2781         span.hi() - BytePos(1),
2782         false,
2783     );
2784     let item_vec: Vec<_> = items.collect();
2785     let tactic = definitive_tactic(
2786         &item_vec,
2787         ListTactic::HorizontalVertical,
2788         Separator::Comma,
2789         nested_shape.width,
2790     );
2791     let fmt = ListFormatting {
2792         tactic: tactic,
2793         separator: ",",
2794         trailing_separator: SeparatorTactic::Never,
2795         separator_place: SeparatorPlace::Back,
2796         shape: shape,
2797         ends_with_newline: false,
2798         preserve_newline: false,
2799         config: context.config,
2800     };
2801     let list_str = write_list(&item_vec, &fmt)?;
2802
2803     if context.config.spaces_within_parens() && !list_str.is_empty() {
2804         Some(format!("( {} )", list_str))
2805     } else {
2806         Some(format!("({})", list_str))
2807     }
2808 }
2809
2810 pub fn rewrite_tuple<'a, T>(
2811     context: &RewriteContext,
2812     items: &[&T],
2813     span: Span,
2814     shape: Shape,
2815 ) -> Option<String>
2816 where
2817     T: Rewrite + Spanned + ToExpr + 'a,
2818 {
2819     debug!("rewrite_tuple {:?}", shape);
2820     if context.use_block_indent() {
2821         // We use the same rule as function calls for rewriting tuples.
2822         let force_trailing_comma = if context.inside_macro {
2823             span_ends_with_comma(context, span)
2824         } else {
2825             items.len() == 1
2826         };
2827         rewrite_call_inner(
2828             context,
2829             &String::new(),
2830             items,
2831             span,
2832             shape,
2833             context.config.fn_call_width(),
2834             force_trailing_comma,
2835         )
2836     } else {
2837         rewrite_tuple_in_visual_indent_style(context, items, span, shape)
2838     }
2839 }
2840
2841 pub fn rewrite_unary_prefix<R: Rewrite>(
2842     context: &RewriteContext,
2843     prefix: &str,
2844     rewrite: &R,
2845     shape: Shape,
2846 ) -> Option<String> {
2847     rewrite
2848         .rewrite(context, shape.offset_left(prefix.len())?)
2849         .map(|r| format!("{}{}", prefix, r))
2850 }
2851
2852 // FIXME: this is probably not correct for multi-line Rewrites. we should
2853 // subtract suffix.len() from the last line budget, not the first!
2854 pub fn rewrite_unary_suffix<R: Rewrite>(
2855     context: &RewriteContext,
2856     suffix: &str,
2857     rewrite: &R,
2858     shape: Shape,
2859 ) -> Option<String> {
2860     rewrite
2861         .rewrite(context, shape.sub_width(suffix.len())?)
2862         .map(|mut r| {
2863             r.push_str(suffix);
2864             r
2865         })
2866 }
2867
2868 fn rewrite_unary_op(
2869     context: &RewriteContext,
2870     op: &ast::UnOp,
2871     expr: &ast::Expr,
2872     shape: Shape,
2873 ) -> Option<String> {
2874     // For some reason, an UnOp is not spanned like BinOp!
2875     let operator_str = match *op {
2876         ast::UnOp::Deref => "*",
2877         ast::UnOp::Not => "!",
2878         ast::UnOp::Neg => "-",
2879     };
2880     rewrite_unary_prefix(context, operator_str, expr, shape)
2881 }
2882
2883 fn rewrite_assignment(
2884     context: &RewriteContext,
2885     lhs: &ast::Expr,
2886     rhs: &ast::Expr,
2887     op: Option<&ast::BinOp>,
2888     shape: Shape,
2889 ) -> Option<String> {
2890     let operator_str = match op {
2891         Some(op) => context.snippet(op.span),
2892         None => "=".to_owned(),
2893     };
2894
2895     // 1 = space between lhs and operator.
2896     let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
2897     let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
2898
2899     rewrite_assign_rhs(context, lhs_str, rhs, shape)
2900 }
2901
2902 // The left hand side must contain everything up to, and including, the
2903 // assignment operator.
2904 pub fn rewrite_assign_rhs<S: Into<String>>(
2905     context: &RewriteContext,
2906     lhs: S,
2907     ex: &ast::Expr,
2908     shape: Shape,
2909 ) -> Option<String> {
2910     let lhs = lhs.into();
2911     let last_line_width = last_line_width(&lhs) - if lhs.contains('\n') {
2912         shape.indent.width()
2913     } else {
2914         0
2915     };
2916     // 1 = space between operator and rhs.
2917     let orig_shape = shape.offset_left(last_line_width + 1)?;
2918     let rhs = choose_rhs(context, ex, orig_shape, ex.rewrite(context, orig_shape))?;
2919     Some(lhs + &rhs)
2920 }
2921
2922 fn choose_rhs(
2923     context: &RewriteContext,
2924     expr: &ast::Expr,
2925     shape: Shape,
2926     orig_rhs: Option<String>,
2927 ) -> Option<String> {
2928     match orig_rhs {
2929         Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
2930             Some(format!(" {}", new_str))
2931         }
2932         _ => {
2933             // Expression did not fit on the same line as the identifier.
2934             // Try splitting the line and see if that works better.
2935             let new_shape = Shape::indented(
2936                 shape.block().indent.block_indent(context.config),
2937                 context.config,
2938             ).sub_width(shape.rhs_overhead(context.config))?;
2939             let new_rhs = expr.rewrite(context, new_shape);
2940             let new_indent_str = &new_shape.indent.to_string(context.config);
2941
2942             match (orig_rhs, new_rhs) {
2943                 (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs) => {
2944                     Some(format!("\n{}{}", new_indent_str, new_rhs))
2945                 }
2946                 (None, Some(ref new_rhs)) => Some(format!("\n{}{}", new_indent_str, new_rhs)),
2947                 (None, None) => None,
2948                 (Some(ref orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2949             }
2950         }
2951     }
2952 }
2953
2954 fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str) -> bool {
2955     fn count_line_breaks(src: &str) -> usize {
2956         src.chars().filter(|&x| x == '\n').count()
2957     }
2958
2959     !next_line_rhs.contains('\n')
2960         || count_line_breaks(orig_rhs) > count_line_breaks(next_line_rhs) + 1
2961 }
2962
2963 fn rewrite_expr_addrof(
2964     context: &RewriteContext,
2965     mutability: ast::Mutability,
2966     expr: &ast::Expr,
2967     shape: Shape,
2968 ) -> Option<String> {
2969     let operator_str = match mutability {
2970         ast::Mutability::Immutable => "&",
2971         ast::Mutability::Mutable => "&mut ",
2972     };
2973     rewrite_unary_prefix(context, operator_str, expr, shape)
2974 }
2975
2976 pub trait ToExpr {
2977     fn to_expr(&self) -> Option<&ast::Expr>;
2978     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool;
2979 }
2980
2981 impl ToExpr for ast::Expr {
2982     fn to_expr(&self) -> Option<&ast::Expr> {
2983         Some(self)
2984     }
2985
2986     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2987         can_be_overflowed_expr(context, self, len)
2988     }
2989 }
2990
2991 impl ToExpr for ast::Ty {
2992     fn to_expr(&self) -> Option<&ast::Expr> {
2993         None
2994     }
2995
2996     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
2997         can_be_overflowed_type(context, self, len)
2998     }
2999 }
3000
3001 impl<'a> ToExpr for TuplePatField<'a> {
3002     fn to_expr(&self) -> Option<&ast::Expr> {
3003         None
3004     }
3005
3006     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3007         can_be_overflowed_pat(context, self, len)
3008     }
3009 }
3010
3011 impl<'a> ToExpr for ast::StructField {
3012     fn to_expr(&self) -> Option<&ast::Expr> {
3013         None
3014     }
3015
3016     fn can_be_overflowed(&self, _: &RewriteContext, _: usize) -> bool {
3017         false
3018     }
3019 }
3020
3021 impl<'a> ToExpr for MacroArg {
3022     fn to_expr(&self) -> Option<&ast::Expr> {
3023         match *self {
3024             MacroArg::Expr(ref expr) => Some(expr),
3025             _ => None,
3026         }
3027     }
3028
3029     fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3030         match *self {
3031             MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
3032             MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
3033             MacroArg::Pat(..) => false,
3034         }
3035     }
3036 }