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