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