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