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