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