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