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