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