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