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