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