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