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