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