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