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