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