]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/expr.rs
Add 'src/tools/rustfmt/' from commit '7872306edf2e11a69aaffb9434088fd66b46a863'
[rust.git] / src / tools / rustfmt / src / expr.rs
1 use std::borrow::Cow;
2 use std::cmp::min;
3
4 use itertools::Itertools;
5 use rustc_ast::token::{DelimToken, LitKind};
6 use rustc_ast::{ast, ptr};
7 use rustc_span::{BytePos, Span};
8
9 use crate::chains::rewrite_chain;
10 use crate::closures;
11 use crate::comment::{
12     combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
13     rewrite_missing_comment, CharClasses, FindUncommented,
14 };
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
17 use crate::lists::{
18     definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
19     struct_lit_tactic, write_list, ListFormatting, Separator,
20 };
21 use crate::macros::{rewrite_macro, MacroPosition};
22 use crate::matches::rewrite_match;
23 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
24 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::{Indent, Shape};
27 use crate::source_map::{LineRangeUtils, SpanUtils};
28 use crate::spanned::Spanned;
29 use crate::string::{rewrite_string, StringFormat};
30 use crate::types::{rewrite_path, PathContext};
31 use crate::utils::{
32     colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
33     last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr,
34     unicode_str_width, wrap_str,
35 };
36 use crate::vertical::rewrite_with_alignment;
37 use crate::visitor::FmtVisitor;
38
39 impl Rewrite for ast::Expr {
40     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
41         format_expr(self, ExprType::SubExpression, context, shape)
42     }
43 }
44
45 #[derive(Copy, Clone, PartialEq)]
46 pub(crate) enum ExprType {
47     Statement,
48     SubExpression,
49 }
50
51 pub(crate) fn format_expr(
52     expr: &ast::Expr,
53     expr_type: ExprType,
54     context: &RewriteContext<'_>,
55     shape: Shape,
56 ) -> Option<String> {
57     skip_out_of_file_lines_range!(context, expr.span);
58
59     if contains_skip(&*expr.attrs) {
60         return Some(context.snippet(expr.span()).to_owned());
61     }
62     let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
63         shape.sub_width(1)?
64     } else {
65         shape
66     };
67
68     let expr_rw = match expr.kind {
69         ast::ExprKind::Array(ref expr_vec) => rewrite_array(
70             "",
71             expr_vec.iter(),
72             expr.span,
73             context,
74             shape,
75             choose_separator_tactic(context, expr.span),
76             None,
77         ),
78         ast::ExprKind::Lit(ref l) => {
79             if let Some(expr_rw) = rewrite_literal(context, l, shape) {
80                 Some(expr_rw)
81             } else {
82                 if let LitKind::StrRaw(_) = l.token.kind {
83                     Some(context.snippet(l.span).trim().into())
84                 } else {
85                     None
86                 }
87             }
88         }
89         ast::ExprKind::Call(ref callee, ref args) => {
90             let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
91             let callee_str = callee.rewrite(context, shape)?;
92             rewrite_call(context, &callee_str, args, inner_span, shape)
93         }
94         ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
95         ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
96             // FIXME: format comments between operands and operator
97             rewrite_all_pairs(expr, shape, context).or_else(|| {
98                 rewrite_pair(
99                     &**lhs,
100                     &**rhs,
101                     PairParts::infix(&format!(" {} ", context.snippet(op.span))),
102                     context,
103                     shape,
104                     context.config.binop_separator(),
105                 )
106             })
107         }
108         ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
109         ast::ExprKind::Struct(ref struct_expr) => {
110             let ast::StructExpr { fields, path, rest } = &**struct_expr;
111             rewrite_struct_lit(context, path, fields, rest, &expr.attrs, expr.span, shape)
112         }
113         ast::ExprKind::Tup(ref items) => {
114             rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
115         }
116         ast::ExprKind::Let(..) => None,
117         ast::ExprKind::If(..)
118         | ast::ExprKind::ForLoop(..)
119         | ast::ExprKind::Loop(..)
120         | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
121             .and_then(|control_flow| control_flow.rewrite(context, shape)),
122         ast::ExprKind::ConstBlock(ref anon_const) => {
123             Some(format!("const {}", anon_const.rewrite(context, shape)?))
124         }
125         ast::ExprKind::Block(ref block, opt_label) => {
126             match expr_type {
127                 ExprType::Statement => {
128                     if is_unsafe_block(block) {
129                         rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
130                     } else if let rw @ Some(_) =
131                         rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
132                     {
133                         // Rewrite block without trying to put it in a single line.
134                         rw
135                     } else {
136                         let prefix = block_prefix(context, block, shape)?;
137
138                         rewrite_block_with_visitor(
139                             context,
140                             &prefix,
141                             block,
142                             Some(&expr.attrs),
143                             opt_label,
144                             shape,
145                             true,
146                         )
147                     }
148                 }
149                 ExprType::SubExpression => {
150                     rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
151                 }
152             }
153         }
154         ast::ExprKind::Match(ref cond, ref arms) => {
155             rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
156         }
157         ast::ExprKind::Path(ref qself, ref path) => {
158             rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
159         }
160         ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
161             rewrite_assignment(context, lhs, rhs, None, shape)
162         }
163         ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
164             rewrite_assignment(context, lhs, rhs, Some(op), shape)
165         }
166         ast::ExprKind::Continue(ref opt_label) => {
167             let id_str = match *opt_label {
168                 Some(label) => format!(" {}", label.ident),
169                 None => String::new(),
170             };
171             Some(format!("continue{}", id_str))
172         }
173         ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
174             let id_str = match *opt_label {
175                 Some(label) => format!(" {}", label.ident),
176                 None => String::new(),
177             };
178
179             if let Some(ref expr) = *opt_expr {
180                 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
181             } else {
182                 Some(format!("break{}", id_str))
183             }
184         }
185         ast::ExprKind::Yield(ref opt_expr) => {
186             if let Some(ref expr) = *opt_expr {
187                 rewrite_unary_prefix(context, "yield ", &**expr, shape)
188             } else {
189                 Some("yield".to_string())
190             }
191         }
192         ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
193             closures::rewrite_closure(
194                 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
195             )
196         }
197         ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
198             rewrite_chain(expr, context, shape)
199         }
200         ast::ExprKind::MacCall(ref mac) => {
201             rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
202                 wrap_str(
203                     context.snippet(expr.span).to_owned(),
204                     context.config.max_width(),
205                     shape,
206                 )
207             })
208         }
209         ast::ExprKind::Ret(None) => Some("return".to_owned()),
210         ast::ExprKind::Ret(Some(ref expr)) => {
211             rewrite_unary_prefix(context, "return ", &**expr, shape)
212         }
213         ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
214         ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
215             rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
216         }
217         ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
218             &**expr,
219             &**ty,
220             PairParts::infix(" as "),
221             context,
222             shape,
223             SeparatorPlace::Front,
224         ),
225         ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
226             &**expr,
227             &**ty,
228             PairParts::infix(": "),
229             context,
230             shape,
231             SeparatorPlace::Back,
232         ),
233         ast::ExprKind::Index(ref expr, ref index) => {
234             rewrite_index(&**expr, &**index, context, shape)
235         }
236         ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
237             &**expr,
238             &*repeats.value,
239             PairParts::new("[", "; ", "]"),
240             context,
241             shape,
242             SeparatorPlace::Back,
243         ),
244         ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
245             let delim = match limits {
246                 ast::RangeLimits::HalfOpen => "..",
247                 ast::RangeLimits::Closed => "..=",
248             };
249
250             fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
251                 match lhs.kind {
252                     ast::ExprKind::Lit(ref lit) => match lit.kind {
253                         ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
254                             context.snippet(lit.span).ends_with('.')
255                         }
256                         _ => false,
257                     },
258                     ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
259                     _ => false,
260                 }
261             }
262
263             fn needs_space_after_range(rhs: &ast::Expr) -> bool {
264                 match rhs.kind {
265                     // Don't format `.. ..` into `....`, which is invalid.
266                     //
267                     // This check is unnecessary for `lhs`, because a range
268                     // starting from another range needs parentheses as `(x ..) ..`
269                     // (`x .. ..` is a range from `x` to `..`).
270                     ast::ExprKind::Range(None, _, _) => true,
271                     _ => false,
272                 }
273             }
274
275             let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
276                 let space_if = |b: bool| if b { " " } else { "" };
277
278                 format!(
279                     "{}{}{}",
280                     lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
281                     delim,
282                     rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
283                 )
284             };
285
286             match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
287                 (Some(lhs), Some(rhs)) => {
288                     let sp_delim = if context.config.spaces_around_ranges() {
289                         format!(" {} ", delim)
290                     } else {
291                         default_sp_delim(Some(lhs), Some(rhs))
292                     };
293                     rewrite_pair(
294                         &*lhs,
295                         &*rhs,
296                         PairParts::infix(&sp_delim),
297                         context,
298                         shape,
299                         context.config.binop_separator(),
300                     )
301                 }
302                 (None, Some(rhs)) => {
303                     let sp_delim = if context.config.spaces_around_ranges() {
304                         format!("{} ", delim)
305                     } else {
306                         default_sp_delim(None, Some(rhs))
307                     };
308                     rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
309                 }
310                 (Some(lhs), None) => {
311                     let sp_delim = if context.config.spaces_around_ranges() {
312                         format!(" {}", delim)
313                     } else {
314                         default_sp_delim(Some(lhs), None)
315                     };
316                     rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
317                 }
318                 (None, None) => Some(delim.to_owned()),
319             }
320         }
321         // We do not format these expressions yet, but they should still
322         // satisfy our width restrictions.
323         // Style Guide RFC for InlineAsm variant pending
324         // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
325         ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
326             Some(context.snippet(expr.span).to_owned())
327         }
328         ast::ExprKind::TryBlock(ref block) => {
329             if let rw @ Some(_) =
330                 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
331             {
332                 rw
333             } else {
334                 // 9 = `try `
335                 let budget = shape.width.saturating_sub(9);
336                 Some(format!(
337                     "{}{}",
338                     "try ",
339                     rewrite_block(
340                         block,
341                         Some(&expr.attrs),
342                         None,
343                         context,
344                         Shape::legacy(budget, shape.indent)
345                     )?
346                 ))
347             }
348         }
349         ast::ExprKind::Async(capture_by, _node_id, ref block) => {
350             let mover = if capture_by == ast::CaptureBy::Value {
351                 "move "
352             } else {
353                 ""
354             };
355             if let rw @ Some(_) = rewrite_single_line_block(
356                 context,
357                 format!("{}{}", "async ", mover).as_str(),
358                 block,
359                 Some(&expr.attrs),
360                 None,
361                 shape,
362             ) {
363                 rw
364             } else {
365                 // 6 = `async `
366                 let budget = shape.width.saturating_sub(6);
367                 Some(format!(
368                     "{}{}{}",
369                     "async ",
370                     mover,
371                     rewrite_block(
372                         block,
373                         Some(&expr.attrs),
374                         None,
375                         context,
376                         Shape::legacy(budget, shape.indent)
377                     )?
378                 ))
379             }
380         }
381         ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
382         ast::ExprKind::Underscore => Some("_".to_owned()),
383         ast::ExprKind::Err => None,
384     };
385
386     expr_rw
387         .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
388         .and_then(|expr_str| {
389             let attrs = outer_attributes(&expr.attrs);
390             let attrs_str = attrs.rewrite(context, shape)?;
391             let span = mk_sp(
392                 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
393                 expr.span.lo(),
394             );
395             combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
396         })
397 }
398
399 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
400     name: &'a str,
401     exprs: impl Iterator<Item = &'a T>,
402     span: Span,
403     context: &'a RewriteContext<'_>,
404     shape: Shape,
405     force_separator_tactic: Option<SeparatorTactic>,
406     delim_token: Option<DelimToken>,
407 ) -> Option<String> {
408     overflow::rewrite_with_square_brackets(
409         context,
410         name,
411         exprs,
412         shape,
413         span,
414         force_separator_tactic,
415         delim_token,
416     )
417 }
418
419 fn rewrite_empty_block(
420     context: &RewriteContext<'_>,
421     block: &ast::Block,
422     attrs: Option<&[ast::Attribute]>,
423     label: Option<ast::Label>,
424     prefix: &str,
425     shape: Shape,
426 ) -> Option<String> {
427     if block_has_statements(&block) {
428         return None;
429     }
430
431     let label_str = rewrite_label(label);
432     if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
433         return None;
434     }
435
436     if !block_contains_comment(context, block) && shape.width >= 2 {
437         return Some(format!("{}{}{{}}", prefix, label_str));
438     }
439
440     // If a block contains only a single-line comment, then leave it on one line.
441     let user_str = context.snippet(block.span);
442     let user_str = user_str.trim();
443     if user_str.starts_with('{') && user_str.ends_with('}') {
444         let comment_str = user_str[1..user_str.len() - 1].trim();
445         if block.stmts.is_empty()
446             && !comment_str.contains('\n')
447             && !comment_str.starts_with("//")
448             && comment_str.len() + 4 <= shape.width
449         {
450             return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
451         }
452     }
453
454     None
455 }
456
457 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
458     Some(match block.rules {
459         ast::BlockCheckMode::Unsafe(..) => {
460             let snippet = context.snippet(block.span);
461             let open_pos = snippet.find_uncommented("{")?;
462             // Extract comment between unsafe and block start.
463             let trimmed = &snippet[6..open_pos].trim();
464
465             if !trimmed.is_empty() {
466                 // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
467                 let budget = shape.width.checked_sub(9)?;
468                 format!(
469                     "unsafe {} ",
470                     rewrite_comment(
471                         trimmed,
472                         true,
473                         Shape::legacy(budget, shape.indent + 7),
474                         context.config,
475                     )?
476                 )
477             } else {
478                 "unsafe ".to_owned()
479             }
480         }
481         ast::BlockCheckMode::Default => String::new(),
482     })
483 }
484
485 fn rewrite_single_line_block(
486     context: &RewriteContext<'_>,
487     prefix: &str,
488     block: &ast::Block,
489     attrs: Option<&[ast::Attribute]>,
490     label: Option<ast::Label>,
491     shape: Shape,
492 ) -> Option<String> {
493     if is_simple_block(context, block, attrs) {
494         let expr_shape = shape.offset_left(last_line_width(prefix))?;
495         let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
496         let label_str = rewrite_label(label);
497         let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
498         if result.len() <= shape.width && !result.contains('\n') {
499             return Some(result);
500         }
501     }
502     None
503 }
504
505 pub(crate) fn rewrite_block_with_visitor(
506     context: &RewriteContext<'_>,
507     prefix: &str,
508     block: &ast::Block,
509     attrs: Option<&[ast::Attribute]>,
510     label: Option<ast::Label>,
511     shape: Shape,
512     has_braces: bool,
513 ) -> Option<String> {
514     if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
515         return rw;
516     }
517
518     let mut visitor = FmtVisitor::from_context(context);
519     visitor.block_indent = shape.indent;
520     visitor.is_if_else_block = context.is_if_else_block();
521     match (block.rules, label) {
522         (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
523             let snippet = context.snippet(block.span);
524             let open_pos = snippet.find_uncommented("{")?;
525             visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
526         }
527         (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
528     }
529
530     let inner_attrs = attrs.map(inner_attributes);
531     let label_str = rewrite_label(label);
532     visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
533     let visitor_context = visitor.get_context();
534     context
535         .skipped_range
536         .borrow_mut()
537         .append(&mut visitor_context.skipped_range.borrow_mut());
538     Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
539 }
540
541 impl Rewrite for ast::Block {
542     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
543         rewrite_block(self, None, None, context, shape)
544     }
545 }
546
547 fn rewrite_block(
548     block: &ast::Block,
549     attrs: Option<&[ast::Attribute]>,
550     label: Option<ast::Label>,
551     context: &RewriteContext<'_>,
552     shape: Shape,
553 ) -> Option<String> {
554     let prefix = block_prefix(context, block, shape)?;
555
556     // shape.width is used only for the single line case: either the empty block `{}`,
557     // or an unsafe expression `unsafe { e }`.
558     if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
559         return rw;
560     }
561
562     let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
563     if let Some(ref result_str) = result {
564         if result_str.lines().count() <= 3 {
565             if let rw @ Some(_) =
566                 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
567             {
568                 return rw;
569             }
570         }
571     }
572
573     result
574 }
575
576 // Rewrite condition if the given expression has one.
577 pub(crate) fn rewrite_cond(
578     context: &RewriteContext<'_>,
579     expr: &ast::Expr,
580     shape: Shape,
581 ) -> Option<String> {
582     match expr.kind {
583         ast::ExprKind::Match(ref cond, _) => {
584             // `match `cond` {`
585             let cond_shape = match context.config.indent_style() {
586                 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
587                 IndentStyle::Block => shape.offset_left(8)?,
588             };
589             cond.rewrite(context, cond_shape)
590         }
591         _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
592             let alt_block_sep =
593                 String::from("\n") + &shape.indent.block_only().to_string(context.config);
594             control_flow
595                 .rewrite_cond(context, shape, &alt_block_sep)
596                 .and_then(|rw| Some(rw.0))
597         }),
598     }
599 }
600
601 // Abstraction over control flow expressions
602 #[derive(Debug)]
603 struct ControlFlow<'a> {
604     cond: Option<&'a ast::Expr>,
605     block: &'a ast::Block,
606     else_block: Option<&'a ast::Expr>,
607     label: Option<ast::Label>,
608     pat: Option<&'a ast::Pat>,
609     keyword: &'a str,
610     matcher: &'a str,
611     connector: &'a str,
612     allow_single_line: bool,
613     // HACK: `true` if this is an `if` expression in an `else if`.
614     nested_if: bool,
615     span: Span,
616 }
617
618 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
619     match expr.kind {
620         ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
621         _ => (None, expr),
622     }
623 }
624
625 // FIXME: Refactor this.
626 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
627     match expr.kind {
628         ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
629             let (pat, cond) = extract_pats_and_cond(cond);
630             Some(ControlFlow::new_if(
631                 cond,
632                 pat,
633                 if_block,
634                 else_block.as_ref().map(|e| &**e),
635                 expr_type == ExprType::SubExpression,
636                 false,
637                 expr.span,
638             ))
639         }
640         ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
641             Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
642         }
643         ast::ExprKind::Loop(ref block, label) => {
644             Some(ControlFlow::new_loop(block, label, expr.span))
645         }
646         ast::ExprKind::While(ref cond, ref block, label) => {
647             let (pat, cond) = extract_pats_and_cond(cond);
648             Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
649         }
650         _ => None,
651     }
652 }
653
654 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
655     pat.map_or("", |_| "let")
656 }
657
658 impl<'a> ControlFlow<'a> {
659     fn new_if(
660         cond: &'a ast::Expr,
661         pat: Option<&'a ast::Pat>,
662         block: &'a ast::Block,
663         else_block: Option<&'a ast::Expr>,
664         allow_single_line: bool,
665         nested_if: bool,
666         span: Span,
667     ) -> ControlFlow<'a> {
668         let matcher = choose_matcher(pat);
669         ControlFlow {
670             cond: Some(cond),
671             block,
672             else_block,
673             label: None,
674             pat,
675             keyword: "if",
676             matcher,
677             connector: " =",
678             allow_single_line,
679             nested_if,
680             span,
681         }
682     }
683
684     fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
685         ControlFlow {
686             cond: None,
687             block,
688             else_block: None,
689             label,
690             pat: None,
691             keyword: "loop",
692             matcher: "",
693             connector: "",
694             allow_single_line: false,
695             nested_if: false,
696             span,
697         }
698     }
699
700     fn new_while(
701         pat: Option<&'a ast::Pat>,
702         cond: &'a ast::Expr,
703         block: &'a ast::Block,
704         label: Option<ast::Label>,
705         span: Span,
706     ) -> ControlFlow<'a> {
707         let matcher = choose_matcher(pat);
708         ControlFlow {
709             cond: Some(cond),
710             block,
711             else_block: None,
712             label,
713             pat,
714             keyword: "while",
715             matcher,
716             connector: " =",
717             allow_single_line: false,
718             nested_if: false,
719             span,
720         }
721     }
722
723     fn new_for(
724         pat: &'a ast::Pat,
725         cond: &'a ast::Expr,
726         block: &'a ast::Block,
727         label: Option<ast::Label>,
728         span: Span,
729     ) -> ControlFlow<'a> {
730         ControlFlow {
731             cond: Some(cond),
732             block,
733             else_block: None,
734             label,
735             pat: Some(pat),
736             keyword: "for",
737             matcher: "",
738             connector: " in",
739             allow_single_line: false,
740             nested_if: false,
741             span,
742         }
743     }
744
745     fn rewrite_single_line(
746         &self,
747         pat_expr_str: &str,
748         context: &RewriteContext<'_>,
749         width: usize,
750     ) -> Option<String> {
751         assert!(self.allow_single_line);
752         let else_block = self.else_block?;
753         let fixed_cost = self.keyword.len() + "  {  } else {  }".len();
754
755         if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
756             if !is_simple_block(context, self.block, None)
757                 || !is_simple_block(context, else_node, None)
758                 || pat_expr_str.contains('\n')
759             {
760                 return None;
761             }
762
763             let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
764             let expr = &self.block.stmts[0];
765             let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
766
767             let new_width = new_width.checked_sub(if_str.len())?;
768             let else_expr = &else_node.stmts[0];
769             let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
770
771             if if_str.contains('\n') || else_str.contains('\n') {
772                 return None;
773             }
774
775             let result = format!(
776                 "{} {} {{ {} }} else {{ {} }}",
777                 self.keyword, pat_expr_str, if_str, else_str
778             );
779
780             if result.len() <= width {
781                 return Some(result);
782             }
783         }
784
785         None
786     }
787 }
788
789 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
790 /// shape's indent.
791 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
792     let mut leading_whitespaces = 0;
793     for c in pat_str.chars().rev() {
794         match c {
795             '\n' => break,
796             _ if c.is_whitespace() => leading_whitespaces += 1,
797             _ => leading_whitespaces = 0,
798         }
799     }
800     leading_whitespaces > start_column
801 }
802
803 impl<'a> ControlFlow<'a> {
804     fn rewrite_pat_expr(
805         &self,
806         context: &RewriteContext<'_>,
807         expr: &ast::Expr,
808         shape: Shape,
809         offset: usize,
810     ) -> Option<String> {
811         debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
812
813         let cond_shape = shape.offset_left(offset)?;
814         if let Some(pat) = self.pat {
815             let matcher = if self.matcher.is_empty() {
816                 self.matcher.to_owned()
817             } else {
818                 format!("{} ", self.matcher)
819             };
820             let pat_shape = cond_shape
821                 .offset_left(matcher.len())?
822                 .sub_width(self.connector.len())?;
823             let pat_string = pat.rewrite(context, pat_shape)?;
824             let comments_lo = context
825                 .snippet_provider
826                 .span_after(self.span, self.connector.trim());
827             let comments_span = mk_sp(comments_lo, expr.span.lo());
828             return rewrite_assign_rhs_with_comments(
829                 context,
830                 &format!("{}{}{}", matcher, pat_string, self.connector),
831                 expr,
832                 cond_shape,
833                 RhsTactics::Default,
834                 comments_span,
835                 true,
836             );
837         }
838
839         let expr_rw = expr.rewrite(context, cond_shape);
840         // The expression may (partially) fit on the current line.
841         // We do not allow splitting between `if` and condition.
842         if self.keyword == "if" || expr_rw.is_some() {
843             return expr_rw;
844         }
845
846         // The expression won't fit on the current line, jump to next.
847         let nested_shape = shape
848             .block_indent(context.config.tab_spaces())
849             .with_max_width(context.config);
850         let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
851         expr.rewrite(context, nested_shape)
852             .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
853     }
854
855     fn rewrite_cond(
856         &self,
857         context: &RewriteContext<'_>,
858         shape: Shape,
859         alt_block_sep: &str,
860     ) -> Option<(String, usize)> {
861         // Do not take the rhs overhead from the upper expressions into account
862         // when rewriting pattern.
863         let new_width = context.budget(shape.used_width());
864         let fresh_shape = Shape {
865             width: new_width,
866             ..shape
867         };
868         let constr_shape = if self.nested_if {
869             // We are part of an if-elseif-else chain. Our constraints are tightened.
870             // 7 = "} else " .len()
871             fresh_shape.offset_left(7)?
872         } else {
873             fresh_shape
874         };
875
876         let label_string = rewrite_label(self.label);
877         // 1 = space after keyword.
878         let offset = self.keyword.len() + label_string.len() + 1;
879
880         let pat_expr_string = match self.cond {
881             Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
882             None => String::new(),
883         };
884
885         let brace_overhead =
886             if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
887                 // 2 = ` {`
888                 2
889             } else {
890                 0
891             };
892         let one_line_budget = context
893             .config
894             .max_width()
895             .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
896         let force_newline_brace = (pat_expr_string.contains('\n')
897             || pat_expr_string.len() > one_line_budget)
898             && (!last_line_extendable(&pat_expr_string)
899                 || last_line_offsetted(shape.used_width(), &pat_expr_string));
900
901         // Try to format if-else on single line.
902         if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
903             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
904
905             if let Some(cond_str) = trial {
906                 if cond_str.len() <= context.config.single_line_if_else_max_width() {
907                     return Some((cond_str, 0));
908                 }
909             }
910         }
911
912         let cond_span = if let Some(cond) = self.cond {
913             cond.span
914         } else {
915             mk_sp(self.block.span.lo(), self.block.span.lo())
916         };
917
918         // `for event in event`
919         // Do not include label in the span.
920         let lo = self
921             .label
922             .map_or(self.span.lo(), |label| label.ident.span.hi());
923         let between_kwd_cond = mk_sp(
924             context
925                 .snippet_provider
926                 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
927             if self.pat.is_none() {
928                 cond_span.lo()
929             } else if self.matcher.is_empty() {
930                 self.pat.unwrap().span.lo()
931             } else {
932                 context
933                     .snippet_provider
934                     .span_before(self.span, self.matcher.trim())
935             },
936         );
937
938         let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
939
940         let after_cond_comment =
941             extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
942
943         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
944             ""
945         } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
946             || force_newline_brace
947         {
948             alt_block_sep
949         } else {
950             " "
951         };
952
953         let used_width = if pat_expr_string.contains('\n') {
954             last_line_width(&pat_expr_string)
955         } else {
956             // 2 = spaces after keyword and condition.
957             label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
958         };
959
960         Some((
961             format!(
962                 "{}{}{}{}{}",
963                 label_string,
964                 self.keyword,
965                 between_kwd_cond_comment.as_ref().map_or(
966                     if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
967                         ""
968                     } else {
969                         " "
970                     },
971                     |s| &**s,
972                 ),
973                 pat_expr_string,
974                 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
975             ),
976             used_width,
977         ))
978     }
979 }
980
981 impl<'a> Rewrite for ControlFlow<'a> {
982     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
983         debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
984
985         let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
986         let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
987         // If `used_width` is 0, it indicates that whole control flow is written in a single line.
988         if used_width == 0 {
989             return Some(cond_str);
990         }
991
992         let block_width = shape.width.saturating_sub(used_width);
993         // This is used only for the empty block case: `{}`. So, we use 1 if we know
994         // we should avoid the single line case.
995         let block_width = if self.else_block.is_some() || self.nested_if {
996             min(1, block_width)
997         } else {
998             block_width
999         };
1000         let block_shape = Shape {
1001             width: block_width,
1002             ..shape
1003         };
1004         let block_str = {
1005             let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1006             let result =
1007                 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1008             context.is_if_else_block.replace(old_val);
1009             result?
1010         };
1011
1012         let mut result = format!("{}{}", cond_str, block_str);
1013
1014         if let Some(else_block) = self.else_block {
1015             let shape = Shape::indented(shape.indent, context.config);
1016             let mut last_in_chain = false;
1017             let rewrite = match else_block.kind {
1018                 // If the else expression is another if-else expression, prevent it
1019                 // from being formatted on a single line.
1020                 // Note how we're passing the original shape, as the
1021                 // cost of "else" should not cascade.
1022                 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1023                     let (pats, cond) = extract_pats_and_cond(cond);
1024                     ControlFlow::new_if(
1025                         cond,
1026                         pats,
1027                         if_block,
1028                         next_else_block.as_ref().map(|e| &**e),
1029                         false,
1030                         true,
1031                         mk_sp(else_block.span.lo(), self.span.hi()),
1032                     )
1033                     .rewrite(context, shape)
1034                 }
1035                 _ => {
1036                     last_in_chain = true;
1037                     // When rewriting a block, the width is only used for single line
1038                     // blocks, passing 1 lets us avoid that.
1039                     let else_shape = Shape {
1040                         width: min(1, shape.width),
1041                         ..shape
1042                     };
1043                     format_expr(else_block, ExprType::Statement, context, else_shape)
1044                 }
1045             };
1046
1047             let between_kwd_else_block = mk_sp(
1048                 self.block.span.hi(),
1049                 context
1050                     .snippet_provider
1051                     .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1052             );
1053             let between_kwd_else_block_comment =
1054                 extract_comment(between_kwd_else_block, context, shape);
1055
1056             let after_else = mk_sp(
1057                 context
1058                     .snippet_provider
1059                     .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1060                 else_block.span.lo(),
1061             );
1062             let after_else_comment = extract_comment(after_else, context, shape);
1063
1064             let between_sep = match context.config.control_brace_style() {
1065                 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1066                     &*alt_block_sep
1067                 }
1068                 ControlBraceStyle::AlwaysSameLine => " ",
1069             };
1070             let after_sep = match context.config.control_brace_style() {
1071                 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1072                 _ => " ",
1073             };
1074
1075             result.push_str(&format!(
1076                 "{}else{}",
1077                 between_kwd_else_block_comment
1078                     .as_ref()
1079                     .map_or(between_sep, |s| &**s),
1080                 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1081             ));
1082             result.push_str(&rewrite?);
1083         }
1084
1085         Some(result)
1086     }
1087 }
1088
1089 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1090     match opt_label {
1091         Some(label) => Cow::from(format!("{}: ", label.ident)),
1092         None => Cow::from(""),
1093     }
1094 }
1095
1096 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1097     match rewrite_missing_comment(span, shape, context) {
1098         Some(ref comment) if !comment.is_empty() => Some(format!(
1099             "{indent}{}{indent}",
1100             comment,
1101             indent = shape.indent.to_string_with_newline(context.config)
1102         )),
1103         _ => None,
1104     }
1105 }
1106
1107 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1108     contains_comment(context.snippet(block.span))
1109 }
1110
1111 // Checks that a block contains no statements, an expression and no comments or
1112 // attributes.
1113 // FIXME: incorrectly returns false when comment is contained completely within
1114 // the expression.
1115 pub(crate) fn is_simple_block(
1116     context: &RewriteContext<'_>,
1117     block: &ast::Block,
1118     attrs: Option<&[ast::Attribute]>,
1119 ) -> bool {
1120     block.stmts.len() == 1
1121         && stmt_is_expr(&block.stmts[0])
1122         && !block_contains_comment(context, block)
1123         && attrs.map_or(true, |a| a.is_empty())
1124 }
1125
1126 /// Checks whether a block contains at most one statement or expression, and no
1127 /// comments or attributes.
1128 pub(crate) fn is_simple_block_stmt(
1129     context: &RewriteContext<'_>,
1130     block: &ast::Block,
1131     attrs: Option<&[ast::Attribute]>,
1132 ) -> bool {
1133     block.stmts.len() <= 1
1134         && !block_contains_comment(context, block)
1135         && attrs.map_or(true, |a| a.is_empty())
1136 }
1137
1138 fn block_has_statements(block: &ast::Block) -> bool {
1139     block
1140         .stmts
1141         .iter()
1142         .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1143 }
1144
1145 /// Checks whether a block contains no statements, expressions, comments, or
1146 /// inner attributes.
1147 pub(crate) fn is_empty_block(
1148     context: &RewriteContext<'_>,
1149     block: &ast::Block,
1150     attrs: Option<&[ast::Attribute]>,
1151 ) -> bool {
1152     !block_has_statements(&block)
1153         && !block_contains_comment(context, block)
1154         && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1155 }
1156
1157 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1158     match stmt.kind {
1159         ast::StmtKind::Expr(..) => true,
1160         _ => false,
1161     }
1162 }
1163
1164 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1165     if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1166         true
1167     } else {
1168         false
1169     }
1170 }
1171
1172 pub(crate) fn rewrite_literal(
1173     context: &RewriteContext<'_>,
1174     l: &ast::Lit,
1175     shape: Shape,
1176 ) -> Option<String> {
1177     match l.kind {
1178         ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1179         _ => wrap_str(
1180             context.snippet(l.span).to_owned(),
1181             context.config.max_width(),
1182             shape,
1183         ),
1184     }
1185 }
1186
1187 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1188     let string_lit = context.snippet(span);
1189
1190     if !context.config.format_strings() {
1191         if string_lit
1192             .lines()
1193             .dropping_back(1)
1194             .all(|line| line.ends_with('\\'))
1195             && context.config.version() == Version::Two
1196         {
1197             return Some(string_lit.to_owned());
1198         } else {
1199             return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1200         }
1201     }
1202
1203     // Remove the quote characters.
1204     let str_lit = &string_lit[1..string_lit.len() - 1];
1205
1206     rewrite_string(
1207         str_lit,
1208         &StringFormat::new(shape.visual_indent(0), context.config),
1209         shape.width.saturating_sub(2),
1210     )
1211 }
1212
1213 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1214     if context.inside_macro() {
1215         if span_ends_with_comma(context, span) {
1216             Some(SeparatorTactic::Always)
1217         } else {
1218             Some(SeparatorTactic::Never)
1219         }
1220     } else {
1221         None
1222     }
1223 }
1224
1225 pub(crate) fn rewrite_call(
1226     context: &RewriteContext<'_>,
1227     callee: &str,
1228     args: &[ptr::P<ast::Expr>],
1229     span: Span,
1230     shape: Shape,
1231 ) -> Option<String> {
1232     overflow::rewrite_with_parens(
1233         context,
1234         callee,
1235         args.iter(),
1236         shape,
1237         span,
1238         context.config.fn_call_width(),
1239         choose_separator_tactic(context, span),
1240     )
1241 }
1242
1243 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1244     match expr.kind {
1245         ast::ExprKind::Lit(..) => true,
1246         ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1247         ast::ExprKind::AddrOf(_, _, ref expr)
1248         | ast::ExprKind::Box(ref expr)
1249         | ast::ExprKind::Cast(ref expr, _)
1250         | ast::ExprKind::Field(ref expr, _)
1251         | ast::ExprKind::Try(ref expr)
1252         | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1253         ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1254         ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1255             is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1256         }
1257         _ => false,
1258     }
1259 }
1260
1261 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1262     lists.iter().all(OverflowableItem::is_simple)
1263 }
1264
1265 pub(crate) fn can_be_overflowed_expr(
1266     context: &RewriteContext<'_>,
1267     expr: &ast::Expr,
1268     args_len: usize,
1269 ) -> bool {
1270     match expr.kind {
1271         _ if !expr.attrs.is_empty() => false,
1272         ast::ExprKind::Match(..) => {
1273             (context.use_block_indent() && args_len == 1)
1274                 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1275                 || context.config.overflow_delimited_expr()
1276         }
1277         ast::ExprKind::If(..)
1278         | ast::ExprKind::ForLoop(..)
1279         | ast::ExprKind::Loop(..)
1280         | ast::ExprKind::While(..) => {
1281             context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1282         }
1283
1284         // Handle always block-like expressions
1285         ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1286
1287         // Handle `[]` and `{}`-like expressions
1288         ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1289             context.config.overflow_delimited_expr()
1290                 || (context.use_block_indent() && args_len == 1)
1291         }
1292         ast::ExprKind::MacCall(ref mac) => {
1293             match (
1294                 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
1295                 context.config.overflow_delimited_expr(),
1296             ) {
1297                 (Some(ast::MacDelimiter::Bracket), true)
1298                 | (Some(ast::MacDelimiter::Brace), true) => true,
1299                 _ => context.use_block_indent() && args_len == 1,
1300             }
1301         }
1302
1303         // Handle parenthetical expressions
1304         ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1305             context.use_block_indent() && args_len == 1
1306         }
1307
1308         // Handle unary-like expressions
1309         ast::ExprKind::AddrOf(_, _, ref expr)
1310         | ast::ExprKind::Box(ref expr)
1311         | ast::ExprKind::Try(ref expr)
1312         | ast::ExprKind::Unary(_, ref expr)
1313         | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1314         _ => false,
1315     }
1316 }
1317
1318 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1319     match expr.kind {
1320         ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1321         ast::ExprKind::AddrOf(_, _, ref expr)
1322         | ast::ExprKind::Box(ref expr)
1323         | ast::ExprKind::Try(ref expr)
1324         | ast::ExprKind::Unary(_, ref expr)
1325         | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1326         _ => false,
1327     }
1328 }
1329
1330 /// Returns `true` if a function call or a method call represented by the given span ends with a
1331 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1332 /// comma from macro can potentially break the code.
1333 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1334     let mut result: bool = Default::default();
1335     let mut prev_char: char = Default::default();
1336     let closing_delimiters = &[')', '}', ']'];
1337
1338     for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1339         match c {
1340             _ if kind.is_comment() || c.is_whitespace() => continue,
1341             c if closing_delimiters.contains(&c) => {
1342                 result &= !closing_delimiters.contains(&prev_char);
1343             }
1344             ',' => result = true,
1345             _ => result = false,
1346         }
1347         prev_char = c;
1348     }
1349
1350     result
1351 }
1352
1353 fn rewrite_paren(
1354     context: &RewriteContext<'_>,
1355     mut subexpr: &ast::Expr,
1356     shape: Shape,
1357     mut span: Span,
1358 ) -> Option<String> {
1359     debug!("rewrite_paren, shape: {:?}", shape);
1360
1361     // Extract comments within parens.
1362     let mut pre_span;
1363     let mut post_span;
1364     let mut pre_comment;
1365     let mut post_comment;
1366     let remove_nested_parens = context.config.remove_nested_parens();
1367     loop {
1368         // 1 = "(" or ")"
1369         pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1370         post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1371         pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1372         post_comment = rewrite_missing_comment(post_span, shape, context)?;
1373
1374         // Remove nested parens if there are no comments.
1375         if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1376             if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1377                 span = subexpr.span;
1378                 subexpr = subsubexpr;
1379                 continue;
1380             }
1381         }
1382
1383         break;
1384     }
1385
1386     // 1 = `(` and `)`
1387     let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1388     let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1389     let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1390     if fits_single_line {
1391         Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1392     } else {
1393         rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1394     }
1395 }
1396
1397 fn rewrite_paren_in_multi_line(
1398     context: &RewriteContext<'_>,
1399     subexpr: &ast::Expr,
1400     shape: Shape,
1401     pre_span: Span,
1402     post_span: Span,
1403 ) -> Option<String> {
1404     let nested_indent = shape.indent.block_indent(context.config);
1405     let nested_shape = Shape::indented(nested_indent, context.config);
1406     let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1407     let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1408     let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1409
1410     let mut result = String::with_capacity(subexpr_str.len() * 2);
1411     result.push('(');
1412     if !pre_comment.is_empty() {
1413         result.push_str(&nested_indent.to_string_with_newline(context.config));
1414         result.push_str(&pre_comment);
1415     }
1416     result.push_str(&nested_indent.to_string_with_newline(context.config));
1417     result.push_str(&subexpr_str);
1418     if !post_comment.is_empty() {
1419         result.push_str(&nested_indent.to_string_with_newline(context.config));
1420         result.push_str(&post_comment);
1421     }
1422     result.push_str(&shape.indent.to_string_with_newline(context.config));
1423     result.push(')');
1424
1425     Some(result)
1426 }
1427
1428 fn rewrite_index(
1429     expr: &ast::Expr,
1430     index: &ast::Expr,
1431     context: &RewriteContext<'_>,
1432     shape: Shape,
1433 ) -> Option<String> {
1434     let expr_str = expr.rewrite(context, shape)?;
1435
1436     let offset = last_line_width(&expr_str) + 1;
1437     let rhs_overhead = shape.rhs_overhead(context.config);
1438     let index_shape = if expr_str.contains('\n') {
1439         Shape::legacy(context.config.max_width(), shape.indent)
1440             .offset_left(offset)
1441             .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1442     } else {
1443         match context.config.indent_style() {
1444             IndentStyle::Block => shape
1445                 .offset_left(offset)
1446                 .and_then(|shape| shape.sub_width(1)),
1447             IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1448         }
1449     };
1450     let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1451
1452     // Return if index fits in a single line.
1453     match orig_index_rw {
1454         Some(ref index_str) if !index_str.contains('\n') => {
1455             return Some(format!("{}[{}]", expr_str, index_str));
1456         }
1457         _ => (),
1458     }
1459
1460     // Try putting index on the next line and see if it fits in a single line.
1461     let indent = shape.indent.block_indent(context.config);
1462     let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1463     let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1464     let new_index_rw = index.rewrite(context, index_shape);
1465     match (orig_index_rw, new_index_rw) {
1466         (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1467             "{}{}[{}]",
1468             expr_str,
1469             indent.to_string_with_newline(context.config),
1470             new_index_str,
1471         )),
1472         (None, Some(ref new_index_str)) => Some(format!(
1473             "{}{}[{}]",
1474             expr_str,
1475             indent.to_string_with_newline(context.config),
1476             new_index_str,
1477         )),
1478         (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1479         _ => None,
1480     }
1481 }
1482
1483 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1484     !has_base && fields.iter().all(|field| !field.is_shorthand)
1485 }
1486
1487 fn rewrite_struct_lit<'a>(
1488     context: &RewriteContext<'_>,
1489     path: &ast::Path,
1490     fields: &'a [ast::ExprField],
1491     struct_rest: &ast::StructRest,
1492     attrs: &[ast::Attribute],
1493     span: Span,
1494     shape: Shape,
1495 ) -> Option<String> {
1496     debug!("rewrite_struct_lit: shape {:?}", shape);
1497
1498     enum StructLitField<'a> {
1499         Regular(&'a ast::ExprField),
1500         Base(&'a ast::Expr),
1501         Rest(&'a Span),
1502     }
1503
1504     // 2 = " {".len()
1505     let path_shape = shape.sub_width(2)?;
1506     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1507
1508     let has_base = match struct_rest {
1509         ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1510         ast::StructRest::Rest(_) if fields.is_empty() => {
1511             return Some(format!("{} {{ .. }}", path_str));
1512         }
1513         ast::StructRest::Base(_) => true,
1514         _ => false,
1515     };
1516
1517     // Foo { a: Foo } - indent is +3, width is -5.
1518     let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1519
1520     let one_line_width = h_shape.map_or(0, |shape| shape.width);
1521     let body_lo = context.snippet_provider.span_after(span, "{");
1522     let fields_str = if struct_lit_can_be_aligned(fields, has_base)
1523         && context.config.struct_field_align_threshold() > 0
1524     {
1525         rewrite_with_alignment(
1526             fields,
1527             context,
1528             v_shape,
1529             mk_sp(body_lo, span.hi()),
1530             one_line_width,
1531         )?
1532     } else {
1533         let field_iter = fields.iter().map(StructLitField::Regular).chain(
1534             match struct_rest {
1535                 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1536                 ast::StructRest::Rest(span) => Some(StructLitField::Rest(span)),
1537                 ast::StructRest::None => None,
1538             }
1539             .into_iter(),
1540         );
1541
1542         let span_lo = |item: &StructLitField<'_>| match *item {
1543             StructLitField::Regular(field) => field.span().lo(),
1544             StructLitField::Base(expr) => {
1545                 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1546                 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1547                 let pos = snippet.find_uncommented("..").unwrap();
1548                 last_field_hi + BytePos(pos as u32)
1549             }
1550             StructLitField::Rest(span) => span.lo(),
1551         };
1552         let span_hi = |item: &StructLitField<'_>| match *item {
1553             StructLitField::Regular(field) => field.span().hi(),
1554             StructLitField::Base(expr) => expr.span.hi(),
1555             StructLitField::Rest(span) => span.hi(),
1556         };
1557         let rewrite = |item: &StructLitField<'_>| match *item {
1558             StructLitField::Regular(field) => {
1559                 // The 1 taken from the v_budget is for the comma.
1560                 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1561             }
1562             StructLitField::Base(expr) => {
1563                 // 2 = ..
1564                 expr.rewrite(context, v_shape.offset_left(2)?)
1565                     .map(|s| format!("..{}", s))
1566             }
1567             StructLitField::Rest(_) => Some("..".to_owned()),
1568         };
1569
1570         let items = itemize_list(
1571             context.snippet_provider,
1572             field_iter,
1573             "}",
1574             ",",
1575             span_lo,
1576             span_hi,
1577             rewrite,
1578             body_lo,
1579             span.hi(),
1580             false,
1581         );
1582         let item_vec = items.collect::<Vec<_>>();
1583
1584         let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1585         let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1586
1587         let ends_with_comma = span_ends_with_comma(context, span);
1588         let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1589
1590         let fmt = struct_lit_formatting(
1591             nested_shape,
1592             tactic,
1593             context,
1594             force_no_trailing_comma
1595                 || has_base
1596                 || !context.use_block_indent()
1597                 || matches!(struct_rest, ast::StructRest::Rest(_)),
1598         );
1599
1600         write_list(&item_vec, &fmt)?
1601     };
1602
1603     let fields_str =
1604         wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1605     Some(format!("{} {{{}}}", path_str, fields_str))
1606
1607     // FIXME if context.config.indent_style() == Visual, but we run out
1608     // of space, we should fall back to BlockIndent.
1609 }
1610
1611 pub(crate) fn wrap_struct_field(
1612     context: &RewriteContext<'_>,
1613     attrs: &[ast::Attribute],
1614     fields_str: &str,
1615     shape: Shape,
1616     nested_shape: Shape,
1617     one_line_width: usize,
1618 ) -> Option<String> {
1619     let should_vertical = context.config.indent_style() == IndentStyle::Block
1620         && (fields_str.contains('\n')
1621             || !context.config.struct_lit_single_line()
1622             || fields_str.len() > one_line_width);
1623
1624     let inner_attrs = &inner_attributes(attrs);
1625     if inner_attrs.is_empty() {
1626         if should_vertical {
1627             Some(format!(
1628                 "{}{}{}",
1629                 nested_shape.indent.to_string_with_newline(context.config),
1630                 fields_str,
1631                 shape.indent.to_string_with_newline(context.config)
1632             ))
1633         } else {
1634             // One liner or visual indent.
1635             Some(format!(" {} ", fields_str))
1636         }
1637     } else {
1638         Some(format!(
1639             "{}{}{}{}{}",
1640             nested_shape.indent.to_string_with_newline(context.config),
1641             inner_attrs.rewrite(context, shape)?,
1642             nested_shape.indent.to_string_with_newline(context.config),
1643             fields_str,
1644             shape.indent.to_string_with_newline(context.config)
1645         ))
1646     }
1647 }
1648
1649 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1650     colon_spaces(config)
1651 }
1652
1653 pub(crate) fn rewrite_field(
1654     context: &RewriteContext<'_>,
1655     field: &ast::ExprField,
1656     shape: Shape,
1657     prefix_max_width: usize,
1658 ) -> Option<String> {
1659     if contains_skip(&field.attrs) {
1660         return Some(context.snippet(field.span()).to_owned());
1661     }
1662     let mut attrs_str = field.attrs.rewrite(context, shape)?;
1663     if !attrs_str.is_empty() {
1664         attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1665     };
1666     let name = context.snippet(field.ident.span);
1667     if field.is_shorthand {
1668         Some(attrs_str + name)
1669     } else {
1670         let mut separator = String::from(struct_lit_field_separator(context.config));
1671         for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1672             separator.push(' ');
1673         }
1674         let overhead = name.len() + separator.len();
1675         let expr_shape = shape.offset_left(overhead)?;
1676         let expr = field.expr.rewrite(context, expr_shape);
1677
1678         match expr {
1679             Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1680                 Some(attrs_str + name)
1681             }
1682             Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1683             None => {
1684                 let expr_offset = shape.indent.block_indent(context.config);
1685                 let expr = field
1686                     .expr
1687                     .rewrite(context, Shape::indented(expr_offset, context.config));
1688                 expr.map(|s| {
1689                     format!(
1690                         "{}{}:\n{}{}",
1691                         attrs_str,
1692                         name,
1693                         expr_offset.to_string(context.config),
1694                         s
1695                     )
1696                 })
1697             }
1698         }
1699     }
1700 }
1701
1702 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1703     context: &RewriteContext<'_>,
1704     mut items: impl Iterator<Item = &'a T>,
1705     span: Span,
1706     shape: Shape,
1707     is_singleton_tuple: bool,
1708 ) -> Option<String> {
1709     // In case of length 1, need a trailing comma
1710     debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1711     if is_singleton_tuple {
1712         // 3 = "(" + ",)"
1713         let nested_shape = shape.sub_width(3)?.visual_indent(1);
1714         return items
1715             .next()
1716             .unwrap()
1717             .rewrite(context, nested_shape)
1718             .map(|s| format!("({},)", s));
1719     }
1720
1721     let list_lo = context.snippet_provider.span_after(span, "(");
1722     let nested_shape = shape.sub_width(2)?.visual_indent(1);
1723     let items = itemize_list(
1724         context.snippet_provider,
1725         items,
1726         ")",
1727         ",",
1728         |item| item.span().lo(),
1729         |item| item.span().hi(),
1730         |item| item.rewrite(context, nested_shape),
1731         list_lo,
1732         span.hi() - BytePos(1),
1733         false,
1734     );
1735     let item_vec: Vec<_> = items.collect();
1736     let tactic = definitive_tactic(
1737         &item_vec,
1738         ListTactic::HorizontalVertical,
1739         Separator::Comma,
1740         nested_shape.width,
1741     );
1742     let fmt = ListFormatting::new(nested_shape, context.config)
1743         .tactic(tactic)
1744         .ends_with_newline(false);
1745     let list_str = write_list(&item_vec, &fmt)?;
1746
1747     Some(format!("({})", list_str))
1748 }
1749
1750 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1751     context: &'a RewriteContext<'_>,
1752     items: impl Iterator<Item = &'a T>,
1753     span: Span,
1754     shape: Shape,
1755     is_singleton_tuple: bool,
1756 ) -> Option<String> {
1757     debug!("rewrite_tuple {:?}", shape);
1758     if context.use_block_indent() {
1759         // We use the same rule as function calls for rewriting tuples.
1760         let force_tactic = if context.inside_macro() {
1761             if span_ends_with_comma(context, span) {
1762                 Some(SeparatorTactic::Always)
1763             } else {
1764                 Some(SeparatorTactic::Never)
1765             }
1766         } else if is_singleton_tuple {
1767             Some(SeparatorTactic::Always)
1768         } else {
1769             None
1770         };
1771         overflow::rewrite_with_parens(
1772             context,
1773             "",
1774             items,
1775             shape,
1776             span,
1777             context.config.fn_call_width(),
1778             force_tactic,
1779         )
1780     } else {
1781         rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1782     }
1783 }
1784
1785 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1786     context: &RewriteContext<'_>,
1787     prefix: &str,
1788     rewrite: &R,
1789     shape: Shape,
1790 ) -> Option<String> {
1791     rewrite
1792         .rewrite(context, shape.offset_left(prefix.len())?)
1793         .map(|r| format!("{}{}", prefix, r))
1794 }
1795
1796 // FIXME: this is probably not correct for multi-line Rewrites. we should
1797 // subtract suffix.len() from the last line budget, not the first!
1798 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1799     context: &RewriteContext<'_>,
1800     suffix: &str,
1801     rewrite: &R,
1802     shape: Shape,
1803 ) -> Option<String> {
1804     rewrite
1805         .rewrite(context, shape.sub_width(suffix.len())?)
1806         .map(|mut r| {
1807             r.push_str(suffix);
1808             r
1809         })
1810 }
1811
1812 fn rewrite_unary_op(
1813     context: &RewriteContext<'_>,
1814     op: ast::UnOp,
1815     expr: &ast::Expr,
1816     shape: Shape,
1817 ) -> Option<String> {
1818     // For some reason, an UnOp is not spanned like BinOp!
1819     rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1820 }
1821
1822 fn rewrite_assignment(
1823     context: &RewriteContext<'_>,
1824     lhs: &ast::Expr,
1825     rhs: &ast::Expr,
1826     op: Option<&ast::BinOp>,
1827     shape: Shape,
1828 ) -> Option<String> {
1829     let operator_str = match op {
1830         Some(op) => context.snippet(op.span),
1831         None => "=",
1832     };
1833
1834     // 1 = space between lhs and operator.
1835     let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1836     let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1837
1838     rewrite_assign_rhs(context, lhs_str, rhs, shape)
1839 }
1840
1841 /// Controls where to put the rhs.
1842 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1843 pub(crate) enum RhsTactics {
1844     /// Use heuristics.
1845     Default,
1846     /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1847     ForceNextLineWithoutIndent,
1848     /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1849     /// did not work.
1850     AllowOverflow,
1851 }
1852
1853 // The left hand side must contain everything up to, and including, the
1854 // assignment operator.
1855 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1856     context: &RewriteContext<'_>,
1857     lhs: S,
1858     ex: &R,
1859     shape: Shape,
1860 ) -> Option<String> {
1861     rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1862 }
1863
1864 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1865     context: &RewriteContext<'_>,
1866     lhs: &str,
1867     ex: &R,
1868     shape: Shape,
1869     rhs_tactics: RhsTactics,
1870 ) -> Option<String> {
1871     let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1872         shape.indent.width()
1873     } else {
1874         0
1875     });
1876     // 1 = space between operator and rhs.
1877     let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1878         width: 0,
1879         offset: shape.offset + last_line_width + 1,
1880         ..shape
1881     });
1882     let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1883         lhs.trim_end().len() > offset + 1
1884     } else {
1885         false
1886     };
1887
1888     choose_rhs(
1889         context,
1890         ex,
1891         orig_shape,
1892         ex.rewrite(context, orig_shape),
1893         rhs_tactics,
1894         has_rhs_comment,
1895     )
1896 }
1897
1898 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1899     context: &RewriteContext<'_>,
1900     lhs: S,
1901     ex: &R,
1902     shape: Shape,
1903     rhs_tactics: RhsTactics,
1904 ) -> Option<String> {
1905     let lhs = lhs.into();
1906     let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
1907     Some(lhs + &rhs)
1908 }
1909
1910 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
1911     context: &RewriteContext<'_>,
1912     lhs: S,
1913     ex: &R,
1914     shape: Shape,
1915     rhs_tactics: RhsTactics,
1916     between_span: Span,
1917     allow_extend: bool,
1918 ) -> Option<String> {
1919     let lhs = lhs.into();
1920     let contains_comment = contains_comment(context.snippet(between_span));
1921     let shape = if contains_comment {
1922         shape.block_left(context.config.tab_spaces())?
1923     } else {
1924         shape
1925     };
1926     let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
1927
1928     if contains_comment {
1929         let rhs = rhs.trim_start();
1930         combine_strs_with_missing_comments(context, &lhs, &rhs, between_span, shape, allow_extend)
1931     } else {
1932         Some(lhs + &rhs)
1933     }
1934 }
1935
1936 fn choose_rhs<R: Rewrite>(
1937     context: &RewriteContext<'_>,
1938     expr: &R,
1939     shape: Shape,
1940     orig_rhs: Option<String>,
1941     rhs_tactics: RhsTactics,
1942     has_rhs_comment: bool,
1943 ) -> Option<String> {
1944     match orig_rhs {
1945         Some(ref new_str)
1946             if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1947         {
1948             Some(format!(" {}", new_str))
1949         }
1950         _ => {
1951             // Expression did not fit on the same line as the identifier.
1952             // Try splitting the line and see if that works better.
1953             let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1954             let new_rhs = expr.rewrite(context, new_shape);
1955             let new_indent_str = &shape
1956                 .indent
1957                 .block_indent(context.config)
1958                 .to_string_with_newline(context.config);
1959             let before_space_str = if has_rhs_comment { "" } else { " " };
1960
1961             match (orig_rhs, new_rhs) {
1962                 (Some(ref orig_rhs), Some(ref new_rhs))
1963                     if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1964                         .is_none() =>
1965                 {
1966                     Some(format!("{}{}", before_space_str, orig_rhs))
1967                 }
1968                 (Some(ref orig_rhs), Some(ref new_rhs))
1969                     if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1970                 {
1971                     Some(format!("{}{}", new_indent_str, new_rhs))
1972                 }
1973                 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1974                 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1975                     let shape = shape.infinite_width();
1976                     expr.rewrite(context, shape)
1977                         .map(|s| format!("{}{}", before_space_str, s))
1978                 }
1979                 (None, None) => None,
1980                 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
1981             }
1982         }
1983     }
1984 }
1985
1986 fn shape_from_rhs_tactic(
1987     context: &RewriteContext<'_>,
1988     shape: Shape,
1989     rhs_tactic: RhsTactics,
1990 ) -> Option<Shape> {
1991     match rhs_tactic {
1992         RhsTactics::ForceNextLineWithoutIndent => shape
1993             .with_max_width(context.config)
1994             .sub_width(shape.indent.width()),
1995         RhsTactics::Default | RhsTactics::AllowOverflow => {
1996             Shape::indented(shape.indent.block_indent(context.config), context.config)
1997                 .sub_width(shape.rhs_overhead(context.config))
1998         }
1999     }
2000 }
2001
2002 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2003 /// original's line formatting.
2004 ///
2005 /// It is considered better if:
2006 /// 1. the tactic is ForceNextLineWithoutIndent
2007 /// 2. next_line_rhs doesn't have newlines
2008 /// 3. the original line has more newlines than next_line_rhs
2009 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2010 ///    doesn't
2011 pub(crate) fn prefer_next_line(
2012     orig_rhs: &str,
2013     next_line_rhs: &str,
2014     rhs_tactics: RhsTactics,
2015 ) -> bool {
2016     rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2017         || !next_line_rhs.contains('\n')
2018         || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2019         || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2020         || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2021         || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2022 }
2023
2024 fn rewrite_expr_addrof(
2025     context: &RewriteContext<'_>,
2026     borrow_kind: ast::BorrowKind,
2027     mutability: ast::Mutability,
2028     expr: &ast::Expr,
2029     shape: Shape,
2030 ) -> Option<String> {
2031     let operator_str = match (mutability, borrow_kind) {
2032         (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2033         (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2034         (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2035         (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2036     };
2037     rewrite_unary_prefix(context, operator_str, expr, shape)
2038 }
2039
2040 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2041     match expr.kind {
2042         ast::ExprKind::MethodCall(..) => true,
2043         ast::ExprKind::AddrOf(_, _, ref expr)
2044         | ast::ExprKind::Box(ref expr)
2045         | ast::ExprKind::Cast(ref expr, _)
2046         | ast::ExprKind::Try(ref expr)
2047         | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2048         _ => false,
2049     }
2050 }
2051
2052 #[cfg(test)]
2053 mod test {
2054     use super::last_line_offsetted;
2055
2056     #[test]
2057     fn test_last_line_offsetted() {
2058         let lines = "one\n    two";
2059         assert_eq!(last_line_offsetted(2, lines), true);
2060         assert_eq!(last_line_offsetted(4, lines), false);
2061         assert_eq!(last_line_offsetted(6, lines), false);
2062
2063         let lines = "one    two";
2064         assert_eq!(last_line_offsetted(2, lines), false);
2065         assert_eq!(last_line_offsetted(0, lines), false);
2066
2067         let lines = "\ntwo";
2068         assert_eq!(last_line_offsetted(2, lines), false);
2069         assert_eq!(last_line_offsetted(0, lines), false);
2070
2071         let lines = "one\n    two      three";
2072         assert_eq!(last_line_offsetted(2, lines), true);
2073         let lines = "one\n two      three";
2074         assert_eq!(last_line_offsetted(2, lines), false);
2075     }
2076 }