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