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