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