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