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