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