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