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