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