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