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