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