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