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