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