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