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