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