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