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