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