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