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