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