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