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