5 use itertools::Itertools;
6 use syntax::parse::token::DelimToken;
7 use syntax::source_map::{BytePos, SourceMap, Span};
8 use syntax::{ast, ptr};
10 use crate::chains::rewrite_chain;
13 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
14 rewrite_missing_comment, CharClasses, FindUncommented,
16 use crate::config::lists::*;
17 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
19 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
20 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
22 use crate::macros::{rewrite_macro, MacroPosition};
23 use crate::matches::rewrite_match;
24 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
25 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
26 use crate::patterns::is_short_pattern;
27 use crate::rewrite::{Rewrite, RewriteContext};
28 use crate::shape::{Indent, Shape};
29 use crate::source_map::{LineRangeUtils, SpanUtils};
30 use crate::spanned::Spanned;
31 use crate::string::{rewrite_string, StringFormat};
32 use crate::types::{rewrite_path, PathContext};
34 colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
35 last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
36 semicolon_for_expr, unicode_str_width, wrap_str,
38 use crate::vertical::rewrite_with_alignment;
39 use crate::visitor::FmtVisitor;
41 impl Rewrite for ast::Expr {
42 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
43 format_expr(self, ExprType::SubExpression, context, shape)
47 #[derive(Copy, Clone, PartialEq)]
48 pub(crate) enum ExprType {
53 pub(crate) fn format_expr(
56 context: &RewriteContext<'_>,
59 skip_out_of_file_lines_range!(context, expr.span);
61 if contains_skip(&*expr.attrs) {
62 return Some(context.snippet(expr.span()).to_owned());
64 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
70 let expr_rw = match expr.node {
71 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
77 choose_separator_tactic(context, expr.span),
80 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
81 ast::ExprKind::Call(ref callee, ref args) => {
82 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
83 let callee_str = callee.rewrite(context, shape)?;
84 rewrite_call(context, &callee_str, args, inner_span, shape)
86 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
87 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
88 // FIXME: format comments between operands and operator
89 rewrite_all_pairs(expr, shape, context).or_else(|| {
93 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
96 context.config.binop_separator(),
100 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
101 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
105 base.as_ref().map(|e| &**e),
110 ast::ExprKind::Tup(ref items) => {
111 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
113 ast::ExprKind::Let(..) => None,
114 ast::ExprKind::If(..)
115 | ast::ExprKind::ForLoop(..)
116 | ast::ExprKind::Loop(..)
117 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
118 .and_then(|control_flow| control_flow.rewrite(context, shape)),
119 ast::ExprKind::Block(ref block, opt_label) => {
121 ExprType::Statement => {
122 if is_unsafe_block(block) {
123 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
124 } else if let rw @ Some(_) =
125 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
127 // Rewrite block without trying to put it in a single line.
130 let prefix = block_prefix(context, block, shape)?;
132 rewrite_block_with_visitor(
143 ExprType::SubExpression => {
144 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
148 ast::ExprKind::Match(ref cond, ref arms) => {
149 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
151 ast::ExprKind::Path(ref qself, ref path) => {
152 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
154 ast::ExprKind::Assign(ref lhs, ref rhs) => {
155 rewrite_assignment(context, lhs, rhs, None, shape)
157 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
158 rewrite_assignment(context, lhs, rhs, Some(op), shape)
160 ast::ExprKind::Continue(ref opt_label) => {
161 let id_str = match *opt_label {
162 Some(label) => format!(" {}", label.ident),
163 None => String::new(),
165 Some(format!("continue{}", id_str))
167 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
168 let id_str = match *opt_label {
169 Some(label) => format!(" {}", label.ident),
170 None => String::new(),
173 if let Some(ref expr) = *opt_expr {
174 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
176 Some(format!("break{}", id_str))
179 ast::ExprKind::Yield(ref opt_expr) => {
180 if let Some(ref expr) = *opt_expr {
181 rewrite_unary_prefix(context, "yield ", &**expr, shape)
183 Some("yield".to_string())
186 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
187 closures::rewrite_closure(
188 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
191 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
192 rewrite_chain(expr, context, shape)
194 ast::ExprKind::Mac(ref mac) => {
195 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
197 context.snippet(expr.span).to_owned(),
198 context.config.max_width(),
203 ast::ExprKind::Ret(None) => Some("return".to_owned()),
204 ast::ExprKind::Ret(Some(ref expr)) => {
205 rewrite_unary_prefix(context, "return ", &**expr, shape)
207 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
208 ast::ExprKind::AddrOf(mutability, ref expr) => {
209 rewrite_expr_addrof(context, mutability, expr, shape)
211 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
214 PairParts::infix(" as "),
217 SeparatorPlace::Front,
219 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
222 PairParts::infix(": "),
225 SeparatorPlace::Back,
227 ast::ExprKind::Index(ref expr, ref index) => {
228 rewrite_index(&**expr, &**index, context, shape)
230 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
233 PairParts::new("[", "; ", "]"),
236 SeparatorPlace::Back,
238 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
239 let delim = match limits {
240 ast::RangeLimits::HalfOpen => "..",
241 ast::RangeLimits::Closed => "..=",
244 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
246 ast::ExprKind::Lit(ref lit) => match lit.node {
247 ast::LitKind::FloatUnsuffixed(..) => {
248 context.snippet(lit.span).ends_with('.')
256 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
258 // Don't format `.. ..` into `....`, which is invalid.
260 // This check is unnecessary for `lhs`, because a range
261 // starting from another range needs parentheses as `(x ..) ..`
262 // (`x .. ..` is a range from `x` to `..`).
263 ast::ExprKind::Range(None, _, _) => true,
268 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
269 let space_if = |b: bool| if b { " " } else { "" };
273 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
275 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
279 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
280 (Some(lhs), Some(rhs)) => {
281 let sp_delim = if context.config.spaces_around_ranges() {
282 format!(" {} ", delim)
284 default_sp_delim(Some(lhs), Some(rhs))
289 PairParts::infix(&sp_delim),
292 context.config.binop_separator(),
295 (None, Some(rhs)) => {
296 let sp_delim = if context.config.spaces_around_ranges() {
297 format!("{} ", delim)
299 default_sp_delim(None, Some(rhs))
301 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
303 (Some(lhs), None) => {
304 let sp_delim = if context.config.spaces_around_ranges() {
305 format!(" {}", delim)
307 default_sp_delim(Some(lhs), None)
309 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
311 (None, None) => Some(delim.to_owned()),
314 // We do not format these expressions yet, but they should still
315 // satisfy our width restrictions.
316 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
317 ast::ExprKind::TryBlock(ref block) => {
318 if let rw @ Some(_) =
319 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
324 let budget = shape.width.saturating_sub(9);
333 Shape::legacy(budget, shape.indent)
338 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
339 let mover = if capture_by == ast::CaptureBy::Value {
344 if let rw @ Some(_) = rewrite_single_line_block(
346 format!("{}{}", "async ", mover).as_str(),
355 let budget = shape.width.saturating_sub(6);
365 Shape::legacy(budget, shape.indent)
370 ast::ExprKind::Await(ast::AwaitOrigin::FieldLike, _) => rewrite_chain(expr, context, shape),
371 ast::ExprKind::Await(ast::AwaitOrigin::MacroLike, ref nested) => {
372 overflow::rewrite_with_parens(
378 context.config.max_width(),
382 ast::ExprKind::Err => None,
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)?;
391 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
394 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
398 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
400 exprs: impl Iterator<Item = &'a T>,
402 context: &'a RewriteContext<'_>,
404 force_separator_tactic: Option<SeparatorTactic>,
405 delim_token: Option<DelimToken>,
406 ) -> Option<String> {
407 overflow::rewrite_with_square_brackets(
413 force_separator_tactic,
418 fn rewrite_empty_block(
419 context: &RewriteContext<'_>,
421 attrs: Option<&[ast::Attribute]>,
422 label: Option<ast::Label>,
425 ) -> Option<String> {
426 if !block.stmts.is_empty() {
430 let label_str = rewrite_label(label);
431 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
435 if !block_contains_comment(block, context.source_map) && shape.width >= 2 {
436 return Some(format!("{}{}{{}}", prefix, label_str));
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
449 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
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();
464 if !trimmed.is_empty() {
465 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
466 let budget = shape.width.checked_sub(9)?;
472 Shape::legacy(budget, shape.indent + 7),
480 ast::BlockCheckMode::Default => String::new(),
484 fn rewrite_single_line_block(
485 context: &RewriteContext<'_>,
488 attrs: Option<&[ast::Attribute]>,
489 label: Option<ast::Label>,
491 ) -> Option<String> {
492 if is_simple_block(block, attrs, context.source_map) {
493 let expr_shape = shape.offset_left(last_line_width(prefix))?;
494 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
495 let label_str = rewrite_label(label);
496 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
497 if result.len() <= shape.width && !result.contains('\n') {
504 pub(crate) fn rewrite_block_with_visitor(
505 context: &RewriteContext<'_>,
508 attrs: Option<&[ast::Attribute]>,
509 label: Option<ast::Label>,
512 ) -> Option<String> {
513 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
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)
526 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
529 let inner_attrs = attrs.map(inner_attributes);
530 let label_str = rewrite_label(label);
531 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
532 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
535 impl Rewrite for ast::Block {
536 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
537 rewrite_block(self, None, None, context, shape)
543 attrs: Option<&[ast::Attribute]>,
544 label: Option<ast::Label>,
545 context: &RewriteContext<'_>,
547 ) -> Option<String> {
548 let prefix = block_prefix(context, block, shape)?;
550 // shape.width is used only for the single line case: either the empty block `{}`,
551 // or an unsafe expression `unsafe { e }`.
552 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
556 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
557 if let Some(ref result_str) = result {
558 if result_str.lines().count() <= 3 {
559 if let rw @ Some(_) =
560 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
570 // Rewrite condition if the given expression has one.
571 pub(crate) fn rewrite_cond(
572 context: &RewriteContext<'_>,
575 ) -> Option<String> {
577 ast::ExprKind::Match(ref cond, _) => {
579 let cond_shape = match context.config.indent_style() {
580 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
581 IndentStyle::Block => shape.offset_left(8)?,
583 cond.rewrite(context, cond_shape)
585 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
587 String::from("\n") + &shape.indent.block_only().to_string(context.config);
589 .rewrite_cond(context, shape, &alt_block_sep)
590 .and_then(|rw| Some(rw.0))
595 // Abstraction over control flow expressions
597 struct ControlFlow<'a> {
598 cond: Option<&'a ast::Expr>,
599 block: &'a ast::Block,
600 else_block: Option<&'a ast::Expr>,
601 label: Option<ast::Label>,
602 pats: Vec<&'a ast::Pat>,
606 allow_single_line: bool,
607 // HACK: `true` if this is an `if` expression in an `else if`.
612 fn extract_pats_and_cond(expr: &ast::Expr) -> (Vec<&ast::Pat>, &ast::Expr) {
614 ast::ExprKind::Let(ref pats, ref cond) => (ptr_vec_to_ref_vec(pats), cond),
619 // FIXME: Refactor this.
620 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
622 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
623 let (pats, cond) = extract_pats_and_cond(cond);
624 Some(ControlFlow::new_if(
628 else_block.as_ref().map(|e| &**e),
629 expr_type == ExprType::SubExpression,
634 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
635 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
637 ast::ExprKind::Loop(ref block, label) => {
638 Some(ControlFlow::new_loop(block, label, expr.span))
640 ast::ExprKind::While(ref cond, ref block, label) => {
641 let (pats, cond) = extract_pats_and_cond(cond);
642 Some(ControlFlow::new_while(pats, cond, block, label, expr.span))
648 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
649 if pats.is_empty() { "" } else { "let" }
652 impl<'a> ControlFlow<'a> {
655 pats: Vec<&'a ast::Pat>,
656 block: &'a ast::Block,
657 else_block: Option<&'a ast::Expr>,
658 allow_single_line: bool,
661 ) -> ControlFlow<'a> {
662 let matcher = choose_matcher(&pats);
678 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
688 allow_single_line: false,
695 pats: Vec<&'a ast::Pat>,
697 block: &'a ast::Block,
698 label: Option<ast::Label>,
700 ) -> ControlFlow<'a> {
701 let matcher = choose_matcher(&pats);
711 allow_single_line: false,
720 block: &'a ast::Block,
721 label: Option<ast::Label>,
723 ) -> ControlFlow<'a> {
733 allow_single_line: false,
739 fn rewrite_single_line(
742 context: &RewriteContext<'_>,
744 ) -> Option<String> {
745 assert!(self.allow_single_line);
746 let else_block = self.else_block?;
747 let fixed_cost = self.keyword.len() + " { } else { }".len();
749 if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
750 if !is_simple_block(self.block, None, context.source_map)
751 || !is_simple_block(else_node, None, context.source_map)
752 || pat_expr_str.contains('\n')
757 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
758 let expr = &self.block.stmts[0];
759 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
761 let new_width = new_width.checked_sub(if_str.len())?;
762 let else_expr = &else_node.stmts[0];
763 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
765 if if_str.contains('\n') || else_str.contains('\n') {
769 let result = format!(
770 "{} {} {{ {} }} else {{ {} }}",
771 self.keyword, pat_expr_str, if_str, else_str
774 if result.len() <= width {
783 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
785 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
786 let mut leading_whitespaces = 0;
787 for c in pat_str.chars().rev() {
790 _ if c.is_whitespace() => leading_whitespaces += 1,
791 _ => leading_whitespaces = 0,
794 leading_whitespaces > start_column
797 impl<'a> ControlFlow<'a> {
800 context: &RewriteContext<'_>,
804 ) -> Option<String> {
805 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
807 let cond_shape = shape.offset_left(offset)?;
808 if !self.pats.is_empty() {
809 let matcher = if self.matcher.is_empty() {
810 self.matcher.to_owned()
812 format!("{} ", self.matcher)
814 let pat_shape = cond_shape
815 .offset_left(matcher.len())?
816 .sub_width(self.connector.len())?;
817 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
818 let result = format!("{}{}{}", matcher, pat_string, self.connector);
819 return rewrite_assign_rhs(context, result, expr, cond_shape);
822 let expr_rw = expr.rewrite(context, cond_shape);
823 // The expression may (partially) fit on the current line.
824 // We do not allow splitting between `if` and condition.
825 if self.keyword == "if" || expr_rw.is_some() {
829 // The expression won't fit on the current line, jump to next.
830 let nested_shape = shape
831 .block_indent(context.config.tab_spaces())
832 .with_max_width(context.config);
833 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
834 expr.rewrite(context, nested_shape)
835 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
840 context: &RewriteContext<'_>,
843 ) -> Option<(String, usize)> {
844 // Do not take the rhs overhead from the upper expressions into account
845 // when rewriting pattern.
846 let new_width = context.budget(shape.used_width());
847 let fresh_shape = Shape {
851 let constr_shape = if self.nested_if {
852 // We are part of an if-elseif-else chain. Our constraints are tightened.
853 // 7 = "} else " .len()
854 fresh_shape.offset_left(7)?
859 let label_string = rewrite_label(self.label);
860 // 1 = space after keyword.
861 let offset = self.keyword.len() + label_string.len() + 1;
863 let pat_expr_string = match self.cond {
864 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
865 None => String::new(),
869 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
875 let one_line_budget = context
878 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
879 let force_newline_brace = (pat_expr_string.contains('\n')
880 || pat_expr_string.len() > one_line_budget)
881 && (!last_line_extendable(&pat_expr_string)
882 || last_line_offsetted(shape.used_width(), &pat_expr_string));
884 // Try to format if-else on single line.
885 if self.allow_single_line
889 .single_line_if_else_max_width
892 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
894 if let Some(cond_str) = trial {
899 .single_line_if_else_max_width
901 return Some((cond_str, 0));
906 let cond_span = if let Some(cond) = self.cond {
909 mk_sp(self.block.span.lo(), self.block.span.lo())
912 // `for event in event`
913 // Do not include label in the span.
916 .map_or(self.span.lo(), |label| label.ident.span.hi());
917 let between_kwd_cond = mk_sp(
920 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
921 if self.pats.is_empty() {
923 } else if self.matcher.is_empty() {
924 self.pats[0].span.lo()
928 .span_before(self.span, self.matcher.trim())
932 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
934 let after_cond_comment =
935 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
937 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
939 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
940 || force_newline_brace
947 let used_width = if pat_expr_string.contains('\n') {
948 last_line_width(&pat_expr_string)
950 // 2 = spaces after keyword and condition.
951 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
959 between_kwd_cond_comment.as_ref().map_or(
960 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
968 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
975 impl<'a> Rewrite for ControlFlow<'a> {
976 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
977 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
979 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
980 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
981 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
983 return Some(cond_str);
986 let block_width = shape.width.saturating_sub(used_width);
987 // This is used only for the empty block case: `{}`. So, we use 1 if we know
988 // we should avoid the single line case.
989 let block_width = if self.else_block.is_some() || self.nested_if {
994 let block_shape = Shape {
999 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1001 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1002 context.is_if_else_block.replace(old_val);
1006 let mut result = format!("{}{}", cond_str, block_str);
1008 if let Some(else_block) = self.else_block {
1009 let shape = Shape::indented(shape.indent, context.config);
1010 let mut last_in_chain = false;
1011 let rewrite = match else_block.node {
1012 // If the else expression is another if-else expression, prevent it
1013 // from being formatted on a single line.
1014 // Note how we're passing the original shape, as the
1015 // cost of "else" should not cascade.
1016 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1017 let (pats, cond) = extract_pats_and_cond(cond);
1018 ControlFlow::new_if(
1022 next_else_block.as_ref().map(|e| &**e),
1025 mk_sp(else_block.span.lo(), self.span.hi()),
1027 .rewrite(context, shape)
1030 last_in_chain = true;
1031 // When rewriting a block, the width is only used for single line
1032 // blocks, passing 1 lets us avoid that.
1033 let else_shape = Shape {
1034 width: min(1, shape.width),
1037 format_expr(else_block, ExprType::Statement, context, else_shape)
1041 let between_kwd_else_block = mk_sp(
1042 self.block.span.hi(),
1045 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1047 let between_kwd_else_block_comment =
1048 extract_comment(between_kwd_else_block, context, shape);
1050 let after_else = mk_sp(
1053 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1054 else_block.span.lo(),
1056 let after_else_comment = extract_comment(after_else, context, shape);
1058 let between_sep = match context.config.control_brace_style() {
1059 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1062 ControlBraceStyle::AlwaysSameLine => " ",
1064 let after_sep = match context.config.control_brace_style() {
1065 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1069 result.push_str(&format!(
1071 between_kwd_else_block_comment
1073 .map_or(between_sep, |s| &**s),
1074 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1076 result.push_str(&rewrite?);
1083 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1085 Some(label) => Cow::from(format!("{}: ", label.ident)),
1086 None => Cow::from(""),
1090 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1091 match rewrite_missing_comment(span, shape, context) {
1092 Some(ref comment) if !comment.is_empty() => Some(format!(
1093 "{indent}{}{indent}",
1095 indent = shape.indent.to_string_with_newline(context.config)
1101 pub(crate) fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1102 let snippet = source_map.span_to_snippet(block.span).unwrap();
1103 contains_comment(&snippet)
1106 // Checks that a block contains no statements, an expression and no comments or
1108 // FIXME: incorrectly returns false when comment is contained completely within
1110 pub(crate) fn is_simple_block(
1112 attrs: Option<&[ast::Attribute]>,
1113 source_map: &SourceMap,
1115 (block.stmts.len() == 1
1116 && stmt_is_expr(&block.stmts[0])
1117 && !block_contains_comment(block, source_map)
1118 && attrs.map_or(true, |a| a.is_empty()))
1121 /// Checks whether a block contains at most one statement or expression, and no
1122 /// comments or attributes.
1123 pub(crate) fn is_simple_block_stmt(
1125 attrs: Option<&[ast::Attribute]>,
1126 source_map: &SourceMap,
1128 block.stmts.len() <= 1
1129 && !block_contains_comment(block, source_map)
1130 && attrs.map_or(true, |a| a.is_empty())
1133 /// Checks whether a block contains no statements, expressions, comments, or
1134 /// inner attributes.
1135 pub(crate) fn is_empty_block(
1137 attrs: Option<&[ast::Attribute]>,
1138 source_map: &SourceMap,
1140 block.stmts.is_empty()
1141 && !block_contains_comment(block, source_map)
1142 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1145 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1147 ast::StmtKind::Expr(..) => true,
1152 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1153 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1160 pub(crate) fn rewrite_multiple_patterns(
1161 context: &RewriteContext<'_>,
1164 ) -> Option<String> {
1167 .map(|p| p.rewrite(context, shape))
1168 .collect::<Option<Vec<_>>>()?;
1170 let use_mixed_layout = pats
1172 .zip(pat_strs.iter())
1173 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1174 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1175 let tactic = if use_mixed_layout {
1176 DefinitiveListTactic::Mixed
1180 ListTactic::HorizontalVertical,
1181 Separator::VerticalBar,
1185 let fmt = ListFormatting::new(shape, context.config)
1188 .separator_place(context.config.binop_separator())
1189 .ends_with_newline(false);
1190 write_list(&items, &fmt)
1193 pub(crate) fn rewrite_literal(
1194 context: &RewriteContext<'_>,
1197 ) -> Option<String> {
1199 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1201 context.snippet(l.span).to_owned(),
1202 context.config.max_width(),
1208 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1209 let string_lit = context.snippet(span);
1211 if !context.config.format_strings() {
1215 .all(|line| line.ends_with('\\'))
1217 let new_indent = shape.visual_indent(1).indent;
1218 let indented_string_lit = String::from(
1224 new_indent.to_string(context.config),
1228 .collect::<Vec<_>>()
1232 return if context.config.version() == Version::Two {
1233 Some(indented_string_lit)
1235 wrap_str(indented_string_lit, context.config.max_width(), shape)
1238 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1242 // Remove the quote characters.
1243 let str_lit = &string_lit[1..string_lit.len() - 1];
1247 &StringFormat::new(shape.visual_indent(0), context.config),
1248 shape.width.saturating_sub(2),
1252 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1253 if context.inside_macro() {
1254 if span_ends_with_comma(context, span) {
1255 Some(SeparatorTactic::Always)
1257 Some(SeparatorTactic::Never)
1264 pub(crate) fn rewrite_call(
1265 context: &RewriteContext<'_>,
1267 args: &[ptr::P<ast::Expr>],
1270 ) -> Option<String> {
1271 overflow::rewrite_with_parens(
1277 context.config.width_heuristics().fn_call_width,
1278 choose_separator_tactic(context, span),
1282 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1284 ast::ExprKind::Lit(..) => true,
1285 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1286 ast::ExprKind::AddrOf(_, ref expr)
1287 | ast::ExprKind::Box(ref expr)
1288 | ast::ExprKind::Cast(ref expr, _)
1289 | ast::ExprKind::Field(ref expr, _)
1290 | ast::ExprKind::Try(ref expr)
1291 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1292 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1293 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1294 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1300 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1301 lists.iter().all(OverflowableItem::is_simple)
1304 pub(crate) fn can_be_overflowed_expr(
1305 context: &RewriteContext<'_>,
1310 _ if !expr.attrs.is_empty() => false,
1311 ast::ExprKind::Match(..) => {
1312 (context.use_block_indent() && args_len == 1)
1313 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1314 || context.config.overflow_delimited_expr()
1316 ast::ExprKind::If(..)
1317 | ast::ExprKind::ForLoop(..)
1318 | ast::ExprKind::Loop(..)
1319 | ast::ExprKind::While(..) => {
1320 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1323 // Handle always block-like expressions
1324 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1326 // Handle `[]` and `{}`-like expressions
1327 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1328 context.config.overflow_delimited_expr()
1329 || (context.use_block_indent() && args_len == 1)
1331 ast::ExprKind::Mac(ref macro_) => {
1332 match (macro_.node.delim, context.config.overflow_delimited_expr()) {
1333 (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
1334 _ => context.use_block_indent() && args_len == 1,
1338 // Handle parenthetical expressions
1339 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1340 context.use_block_indent() && args_len == 1
1343 // Handle unary-like expressions
1344 ast::ExprKind::AddrOf(_, ref expr)
1345 | ast::ExprKind::Box(ref expr)
1346 | ast::ExprKind::Try(ref expr)
1347 | ast::ExprKind::Unary(_, ref expr)
1348 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1353 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1355 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1356 ast::ExprKind::AddrOf(_, ref expr)
1357 | ast::ExprKind::Box(ref expr)
1358 | ast::ExprKind::Try(ref expr)
1359 | ast::ExprKind::Unary(_, ref expr)
1360 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1365 /// Returns `true` if a function call or a method call represented by the given span ends with a
1366 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1367 /// comma from macro can potentially break the code.
1368 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1369 let mut result: bool = Default::default();
1370 let mut prev_char: char = Default::default();
1371 let closing_delimiters = &[')', '}', ']'];
1373 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1375 _ if kind.is_comment() || c.is_whitespace() => continue,
1376 c if closing_delimiters.contains(&c) => {
1377 result &= !closing_delimiters.contains(&prev_char);
1379 ',' => result = true,
1380 _ => result = false,
1389 context: &RewriteContext<'_>,
1390 mut subexpr: &ast::Expr,
1393 ) -> Option<String> {
1394 debug!("rewrite_paren, shape: {:?}", shape);
1396 // Extract comments within parens.
1399 let mut pre_comment;
1400 let mut post_comment;
1401 let remove_nested_parens = context.config.remove_nested_parens();
1404 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1405 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1406 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1407 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1409 // Remove nested parens if there are no comments.
1410 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1411 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1412 span = subexpr.span;
1413 subexpr = subsubexpr;
1422 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1423 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1424 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1425 if fits_single_line {
1426 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1428 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1432 fn rewrite_paren_in_multi_line(
1433 context: &RewriteContext<'_>,
1434 subexpr: &ast::Expr,
1438 ) -> Option<String> {
1439 let nested_indent = shape.indent.block_indent(context.config);
1440 let nested_shape = Shape::indented(nested_indent, context.config);
1441 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1442 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1443 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1445 let mut result = String::with_capacity(subexpr_str.len() * 2);
1447 if !pre_comment.is_empty() {
1448 result.push_str(&nested_indent.to_string_with_newline(context.config));
1449 result.push_str(&pre_comment);
1451 result.push_str(&nested_indent.to_string_with_newline(context.config));
1452 result.push_str(&subexpr_str);
1453 if !post_comment.is_empty() {
1454 result.push_str(&nested_indent.to_string_with_newline(context.config));
1455 result.push_str(&post_comment);
1457 result.push_str(&shape.indent.to_string_with_newline(context.config));
1466 context: &RewriteContext<'_>,
1468 ) -> Option<String> {
1469 let expr_str = expr.rewrite(context, shape)?;
1471 let offset = last_line_width(&expr_str) + 1;
1472 let rhs_overhead = shape.rhs_overhead(context.config);
1473 let index_shape = if expr_str.contains('\n') {
1474 Shape::legacy(context.config.max_width(), shape.indent)
1475 .offset_left(offset)
1476 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1478 match context.config.indent_style() {
1479 IndentStyle::Block => shape
1480 .offset_left(offset)
1481 .and_then(|shape| shape.sub_width(1)),
1482 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1485 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1487 // Return if index fits in a single line.
1488 match orig_index_rw {
1489 Some(ref index_str) if !index_str.contains('\n') => {
1490 return Some(format!("{}[{}]", expr_str, index_str));
1495 // Try putting index on the next line and see if it fits in a single line.
1496 let indent = shape.indent.block_indent(context.config);
1497 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1498 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1499 let new_index_rw = index.rewrite(context, index_shape);
1500 match (orig_index_rw, new_index_rw) {
1501 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1504 indent.to_string_with_newline(context.config),
1507 (None, Some(ref new_index_str)) => Some(format!(
1510 indent.to_string_with_newline(context.config),
1513 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1518 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1523 fields.iter().all(|field| !field.is_shorthand)
1526 fn rewrite_struct_lit<'a>(
1527 context: &RewriteContext<'_>,
1529 fields: &'a [ast::Field],
1530 base: Option<&'a ast::Expr>,
1531 attrs: &[ast::Attribute],
1534 ) -> Option<String> {
1535 debug!("rewrite_struct_lit: shape {:?}", shape);
1537 enum StructLitField<'a> {
1538 Regular(&'a ast::Field),
1539 Base(&'a ast::Expr),
1543 let path_shape = shape.sub_width(2)?;
1544 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1546 if fields.is_empty() && base.is_none() {
1547 return Some(format!("{} {{}}", path_str));
1550 // Foo { a: Foo } - indent is +3, width is -5.
1551 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1553 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1554 let body_lo = context.snippet_provider.span_after(span, "{");
1555 let fields_str = if struct_lit_can_be_aligned(fields, base)
1556 && context.config.struct_field_align_threshold() > 0
1558 rewrite_with_alignment(
1562 mk_sp(body_lo, span.hi()),
1566 let field_iter = fields
1568 .map(StructLitField::Regular)
1569 .chain(base.into_iter().map(StructLitField::Base));
1571 let span_lo = |item: &StructLitField<'_>| match *item {
1572 StructLitField::Regular(field) => field.span().lo(),
1573 StructLitField::Base(expr) => {
1574 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1575 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1576 let pos = snippet.find_uncommented("..").unwrap();
1577 last_field_hi + BytePos(pos as u32)
1580 let span_hi = |item: &StructLitField<'_>| match *item {
1581 StructLitField::Regular(field) => field.span().hi(),
1582 StructLitField::Base(expr) => expr.span.hi(),
1584 let rewrite = |item: &StructLitField<'_>| match *item {
1585 StructLitField::Regular(field) => {
1586 // The 1 taken from the v_budget is for the comma.
1587 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1589 StructLitField::Base(expr) => {
1591 expr.rewrite(context, v_shape.offset_left(2)?)
1592 .map(|s| format!("..{}", s))
1596 let items = itemize_list(
1597 context.snippet_provider,
1608 let item_vec = items.collect::<Vec<_>>();
1610 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1611 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1613 let ends_with_comma = span_ends_with_comma(context, span);
1614 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1616 let fmt = struct_lit_formatting(
1620 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1623 write_list(&item_vec, &fmt)?
1627 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1628 Some(format!("{} {{{}}}", path_str, fields_str))
1630 // FIXME if context.config.indent_style() == Visual, but we run out
1631 // of space, we should fall back to BlockIndent.
1634 pub(crate) fn wrap_struct_field(
1635 context: &RewriteContext<'_>,
1636 attrs: &[ast::Attribute],
1639 nested_shape: Shape,
1640 one_line_width: usize,
1641 ) -> Option<String> {
1642 let should_vertical = context.config.indent_style() == IndentStyle::Block
1643 && (fields_str.contains('\n')
1644 || !context.config.struct_lit_single_line()
1645 || fields_str.len() > one_line_width);
1647 let inner_attrs = &inner_attributes(attrs);
1648 if inner_attrs.is_empty() {
1649 if should_vertical {
1652 nested_shape.indent.to_string_with_newline(context.config),
1654 shape.indent.to_string_with_newline(context.config)
1657 // One liner or visual indent.
1658 Some(format!(" {} ", fields_str))
1663 nested_shape.indent.to_string_with_newline(context.config),
1664 inner_attrs.rewrite(context, shape)?,
1665 nested_shape.indent.to_string_with_newline(context.config),
1667 shape.indent.to_string_with_newline(context.config)
1672 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1673 colon_spaces(config)
1676 pub(crate) fn rewrite_field(
1677 context: &RewriteContext<'_>,
1680 prefix_max_width: usize,
1681 ) -> Option<String> {
1682 if contains_skip(&field.attrs) {
1683 return Some(context.snippet(field.span()).to_owned());
1685 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1686 if !attrs_str.is_empty() {
1687 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1689 let name = context.snippet(field.ident.span);
1690 if field.is_shorthand {
1691 Some(attrs_str + name)
1693 let mut separator = String::from(struct_lit_field_separator(context.config));
1694 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1695 separator.push(' ');
1697 let overhead = name.len() + separator.len();
1698 let expr_shape = shape.offset_left(overhead)?;
1699 let expr = field.expr.rewrite(context, expr_shape);
1702 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1703 Some(attrs_str + name)
1705 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1707 let expr_offset = shape.indent.block_indent(context.config);
1710 .rewrite(context, Shape::indented(expr_offset, context.config));
1716 expr_offset.to_string(context.config),
1725 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1726 context: &RewriteContext<'_>,
1727 mut items: impl Iterator<Item = &'a T>,
1730 is_singleton_tuple: bool,
1731 ) -> Option<String> {
1732 // In case of length 1, need a trailing comma
1733 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1734 if is_singleton_tuple {
1736 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1740 .rewrite(context, nested_shape)
1741 .map(|s| format!("({},)", s));
1744 let list_lo = context.snippet_provider.span_after(span, "(");
1745 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1746 let items = itemize_list(
1747 context.snippet_provider,
1751 |item| item.span().lo(),
1752 |item| item.span().hi(),
1753 |item| item.rewrite(context, nested_shape),
1755 span.hi() - BytePos(1),
1758 let item_vec: Vec<_> = items.collect();
1759 let tactic = definitive_tactic(
1761 ListTactic::HorizontalVertical,
1765 let fmt = ListFormatting::new(nested_shape, context.config)
1767 .ends_with_newline(false);
1768 let list_str = write_list(&item_vec, &fmt)?;
1770 Some(format!("({})", list_str))
1773 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1774 context: &'a RewriteContext<'_>,
1775 items: impl Iterator<Item = &'a T>,
1778 is_singleton_tuple: bool,
1779 ) -> Option<String> {
1780 debug!("rewrite_tuple {:?}", shape);
1781 if context.use_block_indent() {
1782 // We use the same rule as function calls for rewriting tuples.
1783 let force_tactic = if context.inside_macro() {
1784 if span_ends_with_comma(context, span) {
1785 Some(SeparatorTactic::Always)
1787 Some(SeparatorTactic::Never)
1789 } else if is_singleton_tuple {
1790 Some(SeparatorTactic::Always)
1794 overflow::rewrite_with_parens(
1800 context.config.width_heuristics().fn_call_width,
1804 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1808 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1809 context: &RewriteContext<'_>,
1813 ) -> Option<String> {
1815 .rewrite(context, shape.offset_left(prefix.len())?)
1816 .map(|r| format!("{}{}", prefix, r))
1819 // FIXME: this is probably not correct for multi-line Rewrites. we should
1820 // subtract suffix.len() from the last line budget, not the first!
1821 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1822 context: &RewriteContext<'_>,
1826 ) -> Option<String> {
1828 .rewrite(context, shape.sub_width(suffix.len())?)
1835 fn rewrite_unary_op(
1836 context: &RewriteContext<'_>,
1840 ) -> Option<String> {
1841 // For some reason, an UnOp is not spanned like BinOp!
1842 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1845 fn rewrite_assignment(
1846 context: &RewriteContext<'_>,
1849 op: Option<&ast::BinOp>,
1851 ) -> Option<String> {
1852 let operator_str = match op {
1853 Some(op) => context.snippet(op.span),
1857 // 1 = space between lhs and operator.
1858 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1859 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1861 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1864 /// Controls where to put the rhs.
1865 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1866 pub(crate) enum RhsTactics {
1869 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1870 ForceNextLineWithoutIndent,
1871 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1876 // The left hand side must contain everything up to, and including, the
1877 // assignment operator.
1878 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1879 context: &RewriteContext<'_>,
1883 ) -> Option<String> {
1884 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1887 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1888 context: &RewriteContext<'_>,
1892 rhs_tactics: RhsTactics,
1893 ) -> Option<String> {
1894 let lhs = lhs.into();
1895 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1896 shape.indent.width()
1900 // 1 = space between operator and rhs.
1901 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1903 offset: shape.offset + last_line_width + 1,
1906 let rhs = choose_rhs(
1910 ex.rewrite(context, orig_shape),
1916 fn choose_rhs<R: Rewrite>(
1917 context: &RewriteContext<'_>,
1920 orig_rhs: Option<String>,
1921 rhs_tactics: RhsTactics,
1922 ) -> Option<String> {
1925 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1927 Some(format!(" {}", new_str))
1930 // Expression did not fit on the same line as the identifier.
1931 // Try splitting the line and see if that works better.
1932 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1933 let new_rhs = expr.rewrite(context, new_shape);
1934 let new_indent_str = &shape
1936 .block_indent(context.config)
1937 .to_string_with_newline(context.config);
1939 match (orig_rhs, new_rhs) {
1940 (Some(ref orig_rhs), Some(ref new_rhs))
1941 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1944 Some(format!(" {}", orig_rhs))
1946 (Some(ref orig_rhs), Some(ref new_rhs))
1947 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1949 Some(format!("{}{}", new_indent_str, new_rhs))
1951 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1952 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1953 let shape = shape.infinite_width();
1954 expr.rewrite(context, shape).map(|s| format!(" {}", s))
1956 (None, None) => None,
1957 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1963 fn shape_from_rhs_tactic(
1964 context: &RewriteContext<'_>,
1966 rhs_tactic: RhsTactics,
1967 ) -> Option<Shape> {
1969 RhsTactics::ForceNextLineWithoutIndent => shape
1970 .with_max_width(context.config)
1971 .sub_width(shape.indent.width()),
1972 RhsTactics::Default | RhsTactics::AllowOverflow => {
1973 Shape::indented(shape.indent.block_indent(context.config), context.config)
1974 .sub_width(shape.rhs_overhead(context.config))
1979 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
1980 /// original's line formatting.
1982 /// It is considered better if:
1983 /// 1. the tactic is ForceNextLineWithoutIndent
1984 /// 2. next_line_rhs doesn't have newlines
1985 /// 3. the original line has more newlines than next_line_rhs
1986 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
1988 pub(crate) fn prefer_next_line(
1990 next_line_rhs: &str,
1991 rhs_tactics: RhsTactics,
1993 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1994 || !next_line_rhs.contains('\n')
1995 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
1996 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
1997 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
1998 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2001 fn rewrite_expr_addrof(
2002 context: &RewriteContext<'_>,
2003 mutability: ast::Mutability,
2006 ) -> Option<String> {
2007 let operator_str = match mutability {
2008 ast::Mutability::Immutable => "&",
2009 ast::Mutability::Mutable => "&mut ",
2011 rewrite_unary_prefix(context, operator_str, expr, shape)
2014 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2016 ast::ExprKind::MethodCall(..) => true,
2017 ast::ExprKind::AddrOf(_, ref expr)
2018 | ast::ExprKind::Box(ref expr)
2019 | ast::ExprKind::Cast(ref expr, _)
2020 | ast::ExprKind::Try(ref expr)
2021 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2028 use super::last_line_offsetted;
2031 fn test_last_line_offsetted() {
2032 let lines = "one\n two";
2033 assert_eq!(last_line_offsetted(2, lines), true);
2034 assert_eq!(last_line_offsetted(4, lines), false);
2035 assert_eq!(last_line_offsetted(6, lines), false);
2037 let lines = "one two";
2038 assert_eq!(last_line_offsetted(2, lines), false);
2039 assert_eq!(last_line_offsetted(0, lines), false);
2041 let lines = "\ntwo";
2042 assert_eq!(last_line_offsetted(2, lines), false);
2043 assert_eq!(last_line_offsetted(0, lines), false);
2045 let lines = "one\n two three";
2046 assert_eq!(last_line_offsetted(2, lines), true);
2047 let lines = "one\n two three";
2048 assert_eq!(last_line_offsetted(2, lines), false);