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