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