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