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