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