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