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