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