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