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