4 use itertools::Itertools;
5 use rustc_ast::token::{DelimToken, LitKind};
6 use rustc_ast::{ast, ptr};
7 use rustc_span::{BytePos, Span};
9 use crate::chains::rewrite_chain;
12 combine_strs_with_missing_comments, comment_style, contains_comment, recover_comment_removed,
13 rewrite_comment, rewrite_missing_comment, CharClasses, FindUncommented,
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
18 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
19 struct_lit_tactic, write_list, ListFormatting, Separator,
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};
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,
36 use crate::vertical::rewrite_with_alignment;
37 use crate::visitor::FmtVisitor;
39 impl Rewrite for ast::Expr {
40 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
41 format_expr(self, ExprType::SubExpression, context, shape)
45 #[derive(Copy, Clone, PartialEq)]
46 pub(crate) enum ExprType {
51 pub(crate) fn format_expr(
54 context: &RewriteContext<'_>,
57 skip_out_of_file_lines_range!(context, expr.span);
59 if contains_skip(&*expr.attrs) {
60 return Some(context.snippet(expr.span()).to_owned());
62 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
68 let expr_rw = match expr.kind {
69 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
75 choose_separator_tactic(context, expr.span),
78 ast::ExprKind::Lit(ref l) => {
79 if let Some(expr_rw) = rewrite_literal(context, l, shape) {
82 if let LitKind::StrRaw(_) = l.token.kind {
83 Some(context.snippet(l.span).trim().into())
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)
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(|| {
101 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
104 context.config.binop_separator(),
108 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
109 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
113 base.as_ref().map(|e| &**e),
118 ast::ExprKind::Tup(ref items) => {
119 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
121 ast::ExprKind::Let(..) => None,
122 ast::ExprKind::If(..)
123 | ast::ExprKind::ForLoop(..)
124 | ast::ExprKind::Loop(..)
125 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
126 .and_then(|control_flow| control_flow.rewrite(context, shape)),
127 ast::ExprKind::ConstBlock(ref anon_const) => {
128 Some(format!("const {}", anon_const.rewrite(context, shape)?))
130 ast::ExprKind::Block(ref block, opt_label) => {
132 ExprType::Statement => {
133 if is_unsafe_block(block) {
134 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
135 } else if let rw @ Some(_) =
136 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
138 // Rewrite block without trying to put it in a single line.
141 let prefix = block_prefix(context, block, shape)?;
143 rewrite_block_with_visitor(
154 ExprType::SubExpression => {
155 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
159 ast::ExprKind::Match(ref cond, ref arms) => {
160 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
162 ast::ExprKind::Path(ref qself, ref path) => {
163 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
165 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
166 rewrite_assignment(context, lhs, rhs, None, shape)
168 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
169 rewrite_assignment(context, lhs, rhs, Some(op), shape)
171 ast::ExprKind::Continue(ref opt_label) => {
172 let id_str = match *opt_label {
173 Some(label) => format!(" {}", label.ident),
174 None => String::new(),
176 Some(format!("continue{}", id_str))
178 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
179 let id_str = match *opt_label {
180 Some(label) => format!(" {}", label.ident),
181 None => String::new(),
184 if let Some(ref expr) = *opt_expr {
185 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
187 Some(format!("break{}", id_str))
190 ast::ExprKind::Yield(ref opt_expr) => {
191 if let Some(ref expr) = *opt_expr {
192 rewrite_unary_prefix(context, "yield ", &**expr, shape)
194 Some("yield".to_string())
197 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
198 closures::rewrite_closure(
199 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
202 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
203 rewrite_chain(expr, context, shape)
205 ast::ExprKind::MacCall(ref mac) => {
206 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
208 context.snippet(expr.span).to_owned(),
209 context.config.max_width(),
214 ast::ExprKind::Ret(None) => Some("return".to_owned()),
215 ast::ExprKind::Ret(Some(ref expr)) => {
216 rewrite_unary_prefix(context, "return ", &**expr, shape)
218 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
219 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
220 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
222 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
225 PairParts::infix(" as "),
228 SeparatorPlace::Front,
230 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
233 PairParts::infix(": "),
236 SeparatorPlace::Back,
238 ast::ExprKind::Index(ref expr, ref index) => {
239 rewrite_index(&**expr, &**index, context, shape)
241 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
244 PairParts::new("[", "; ", "]"),
247 SeparatorPlace::Back,
249 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
250 let delim = match limits {
251 ast::RangeLimits::HalfOpen => "..",
252 ast::RangeLimits::Closed => "..=",
255 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
257 ast::ExprKind::Lit(ref lit) => match lit.kind {
258 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
259 context.snippet(lit.span).ends_with('.')
263 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
268 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
270 // Don't format `.. ..` into `....`, which is invalid.
272 // This check is unnecessary for `lhs`, because a range
273 // starting from another range needs parentheses as `(x ..) ..`
274 // (`x .. ..` is a range from `x` to `..`).
275 ast::ExprKind::Range(None, _, _) => true,
280 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
281 let space_if = |b: bool| if b { " " } else { "" };
285 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
287 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
291 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
292 (Some(lhs), Some(rhs)) => {
293 let sp_delim = if context.config.spaces_around_ranges() {
294 format!(" {} ", delim)
296 default_sp_delim(Some(lhs), Some(rhs))
301 PairParts::infix(&sp_delim),
304 context.config.binop_separator(),
307 (None, Some(rhs)) => {
308 let sp_delim = if context.config.spaces_around_ranges() {
309 format!("{} ", delim)
311 default_sp_delim(None, Some(rhs))
313 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
315 (Some(lhs), None) => {
316 let sp_delim = if context.config.spaces_around_ranges() {
317 format!(" {}", delim)
319 default_sp_delim(Some(lhs), None)
321 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
323 (None, None) => Some(delim.to_owned()),
326 // We do not format these expressions yet, but they should still
327 // satisfy our width restrictions.
328 // Style Guide RFC for InlineAsm variant pending
329 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
330 ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
331 Some(context.snippet(expr.span).to_owned())
333 ast::ExprKind::TryBlock(ref block) => {
334 if let rw @ Some(_) =
335 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
340 let budget = shape.width.saturating_sub(9);
349 Shape::legacy(budget, shape.indent)
354 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
355 let mover = if capture_by == ast::CaptureBy::Value {
360 if let rw @ Some(_) = rewrite_single_line_block(
362 format!("{}{}", "async ", mover).as_str(),
371 let budget = shape.width.saturating_sub(6);
381 Shape::legacy(budget, shape.indent)
386 ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
387 ast::ExprKind::Err => None,
391 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
392 .and_then(|expr_str| {
393 let attrs = outer_attributes(&expr.attrs);
394 let attrs_str = attrs.rewrite(context, shape)?;
396 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
399 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
403 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
405 exprs: impl Iterator<Item = &'a T>,
407 context: &'a RewriteContext<'_>,
409 force_separator_tactic: Option<SeparatorTactic>,
410 delim_token: Option<DelimToken>,
411 ) -> Option<String> {
412 overflow::rewrite_with_square_brackets(
418 force_separator_tactic,
423 fn rewrite_empty_block(
424 context: &RewriteContext<'_>,
426 attrs: Option<&[ast::Attribute]>,
427 label: Option<ast::Label>,
430 ) -> Option<String> {
431 if !block.stmts.is_empty() {
435 let label_str = rewrite_label(label);
436 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
440 if !block_contains_comment(context, block) && shape.width >= 2 {
441 return Some(format!("{}{}{{}}", prefix, label_str));
444 // If a block contains only a single-line comment, then leave it on one line.
445 let user_str = context.snippet(block.span);
446 let user_str = user_str.trim();
447 if user_str.starts_with('{') && user_str.ends_with('}') {
448 let comment_str = user_str[1..user_str.len() - 1].trim();
449 if block.stmts.is_empty()
450 && !comment_str.contains('\n')
451 && !comment_str.starts_with("//")
452 && comment_str.len() + 4 <= shape.width
454 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
461 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
462 Some(match block.rules {
463 ast::BlockCheckMode::Unsafe(..) => {
464 let snippet = context.snippet(block.span);
465 let open_pos = snippet.find_uncommented("{")?;
466 // Extract comment between unsafe and block start.
467 let trimmed = &snippet[6..open_pos].trim();
469 if !trimmed.is_empty() {
470 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
471 let budget = shape.width.checked_sub(9)?;
477 Shape::legacy(budget, shape.indent + 7),
485 ast::BlockCheckMode::Default => String::new(),
489 fn rewrite_single_line_block(
490 context: &RewriteContext<'_>,
493 attrs: Option<&[ast::Attribute]>,
494 label: Option<ast::Label>,
496 ) -> Option<String> {
497 if is_simple_block(context, block, attrs) {
498 let expr_shape = shape.offset_left(last_line_width(prefix))?;
499 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
500 let label_str = rewrite_label(label);
501 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
502 if result.len() <= shape.width && !result.contains('\n') {
509 pub(crate) fn rewrite_block_with_visitor(
510 context: &RewriteContext<'_>,
513 attrs: Option<&[ast::Attribute]>,
514 label: Option<ast::Label>,
517 ) -> Option<String> {
518 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
522 let mut visitor = FmtVisitor::from_context(context);
523 visitor.block_indent = shape.indent;
524 visitor.is_if_else_block = context.is_if_else_block();
525 match (block.rules, label) {
526 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
527 let snippet = context.snippet(block.span);
528 let open_pos = snippet.find_uncommented("{")?;
529 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
531 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
534 let inner_attrs = attrs.map(inner_attributes);
535 let label_str = rewrite_label(label);
536 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
537 let visitor_context = visitor.get_context();
541 .append(&mut visitor_context.skipped_range.borrow_mut());
542 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
545 impl Rewrite for ast::Block {
546 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
547 rewrite_block(self, None, None, context, shape)
553 attrs: Option<&[ast::Attribute]>,
554 label: Option<ast::Label>,
555 context: &RewriteContext<'_>,
557 ) -> Option<String> {
558 let prefix = block_prefix(context, block, shape)?;
560 // shape.width is used only for the single line case: either the empty block `{}`,
561 // or an unsafe expression `unsafe { e }`.
562 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
566 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
567 if let Some(ref result_str) = result {
568 if result_str.lines().count() <= 3 {
569 if let rw @ Some(_) =
570 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
580 // Rewrite condition if the given expression has one.
581 pub(crate) fn rewrite_cond(
582 context: &RewriteContext<'_>,
585 ) -> Option<String> {
587 ast::ExprKind::Match(ref cond, _) => {
589 let cond_shape = match context.config.indent_style() {
590 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
591 IndentStyle::Block => shape.offset_left(8)?,
593 cond.rewrite(context, cond_shape)
595 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
597 String::from("\n") + &shape.indent.block_only().to_string(context.config);
599 .rewrite_cond(context, shape, &alt_block_sep)
600 .and_then(|rw| Some(rw.0))
605 // Abstraction over control flow expressions
607 struct ControlFlow<'a> {
608 cond: Option<&'a ast::Expr>,
609 block: &'a ast::Block,
610 else_block: Option<&'a ast::Expr>,
611 label: Option<ast::Label>,
612 pat: Option<&'a ast::Pat>,
616 allow_single_line: bool,
617 // HACK: `true` if this is an `if` expression in an `else if`.
622 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
624 ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
629 // FIXME: Refactor this.
630 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
632 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
633 let (pat, cond) = extract_pats_and_cond(cond);
634 Some(ControlFlow::new_if(
638 else_block.as_ref().map(|e| &**e),
639 expr_type == ExprType::SubExpression,
644 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
645 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
647 ast::ExprKind::Loop(ref block, label) => {
648 Some(ControlFlow::new_loop(block, label, expr.span))
650 ast::ExprKind::While(ref cond, ref block, label) => {
651 let (pat, cond) = extract_pats_and_cond(cond);
652 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
658 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
659 pat.map_or("", |_| "let")
662 impl<'a> ControlFlow<'a> {
665 pat: Option<&'a ast::Pat>,
666 block: &'a ast::Block,
667 else_block: Option<&'a ast::Expr>,
668 allow_single_line: bool,
671 ) -> ControlFlow<'a> {
672 let matcher = choose_matcher(pat);
688 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
698 allow_single_line: false,
705 pat: Option<&'a ast::Pat>,
707 block: &'a ast::Block,
708 label: Option<ast::Label>,
710 ) -> ControlFlow<'a> {
711 let matcher = choose_matcher(pat);
721 allow_single_line: false,
730 block: &'a ast::Block,
731 label: Option<ast::Label>,
733 ) -> ControlFlow<'a> {
743 allow_single_line: false,
749 fn rewrite_single_line(
752 context: &RewriteContext<'_>,
754 ) -> Option<String> {
755 assert!(self.allow_single_line);
756 let else_block = self.else_block?;
757 let fixed_cost = self.keyword.len() + " { } else { }".len();
759 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
760 if !is_simple_block(context, self.block, None)
761 || !is_simple_block(context, else_node, None)
762 || pat_expr_str.contains('\n')
767 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
768 let expr = &self.block.stmts[0];
769 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
771 let new_width = new_width.checked_sub(if_str.len())?;
772 let else_expr = &else_node.stmts[0];
773 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
775 if if_str.contains('\n') || else_str.contains('\n') {
779 let result = format!(
780 "{} {} {{ {} }} else {{ {} }}",
781 self.keyword, pat_expr_str, if_str, else_str
784 if result.len() <= width {
793 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
795 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
796 let mut leading_whitespaces = 0;
797 for c in pat_str.chars().rev() {
800 _ if c.is_whitespace() => leading_whitespaces += 1,
801 _ => leading_whitespaces = 0,
804 leading_whitespaces > start_column
807 impl<'a> ControlFlow<'a> {
810 context: &RewriteContext<'_>,
814 ) -> Option<String> {
815 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
817 let cond_shape = shape.offset_left(offset)?;
818 if let Some(pat) = self.pat {
819 let matcher = if self.matcher.is_empty() {
820 self.matcher.to_owned()
822 format!("{} ", self.matcher)
824 let pat_shape = cond_shape
825 .offset_left(matcher.len())?
826 .sub_width(self.connector.len())?;
827 let pat_string = pat.rewrite(context, pat_shape)?;
828 let comments_lo = context
830 .span_after(self.span, self.connector.trim());
831 let missing_comments = if let Some(comment) =
832 rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
834 if !self.connector.is_empty() && !comment.is_empty() {
835 if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
836 let newline = &pat_shape
838 .block_indent(context.config)
839 .to_string_with_newline(context.config);
840 // An extra space is added when the lhs and rhs are joined
841 // so we need to remove one space from the end to ensure
842 // the comment and rhs are aligned.
843 let mut suffix = newline.as_ref().to_string();
844 if !suffix.is_empty() {
845 suffix.truncate(suffix.len() - 1);
847 format!("{}{}{}", newline, comment, suffix)
849 format!(" {}", comment)
858 let result = format!(
860 matcher, pat_string, self.connector, missing_comments
862 return rewrite_assign_rhs(context, result, expr, cond_shape);
865 let expr_rw = expr.rewrite(context, cond_shape);
866 // The expression may (partially) fit on the current line.
867 // We do not allow splitting between `if` and condition.
868 if self.keyword == "if" || expr_rw.is_some() {
872 // The expression won't fit on the current line, jump to next.
873 let nested_shape = shape
874 .block_indent(context.config.tab_spaces())
875 .with_max_width(context.config);
876 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
877 expr.rewrite(context, nested_shape)
878 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
883 context: &RewriteContext<'_>,
886 ) -> Option<(String, usize)> {
887 // Do not take the rhs overhead from the upper expressions into account
888 // when rewriting pattern.
889 let new_width = context.budget(shape.used_width());
890 let fresh_shape = Shape {
894 let constr_shape = if self.nested_if {
895 // We are part of an if-elseif-else chain. Our constraints are tightened.
896 // 7 = "} else " .len()
897 fresh_shape.offset_left(7)?
902 let label_string = rewrite_label(self.label);
903 // 1 = space after keyword.
904 let offset = self.keyword.len() + label_string.len() + 1;
906 let pat_expr_string = match self.cond {
907 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
908 None => String::new(),
912 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
918 let one_line_budget = context
921 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
922 let force_newline_brace = (pat_expr_string.contains('\n')
923 || pat_expr_string.len() > one_line_budget)
924 && (!last_line_extendable(&pat_expr_string)
925 || last_line_offsetted(shape.used_width(), &pat_expr_string));
927 // Try to format if-else on single line.
928 if self.allow_single_line
932 .single_line_if_else_max_width
935 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
937 if let Some(cond_str) = trial {
942 .single_line_if_else_max_width
944 return Some((cond_str, 0));
949 let cond_span = if let Some(cond) = self.cond {
952 mk_sp(self.block.span.lo(), self.block.span.lo())
955 // `for event in event`
956 // Do not include label in the span.
959 .map_or(self.span.lo(), |label| label.ident.span.hi());
960 let between_kwd_cond = mk_sp(
963 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
964 if self.pat.is_none() {
966 } else if self.matcher.is_empty() {
967 self.pat.unwrap().span.lo()
971 .span_before(self.span, self.matcher.trim())
975 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
977 let after_cond_comment =
978 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
980 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
982 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
983 || force_newline_brace
990 let used_width = if pat_expr_string.contains('\n') {
991 last_line_width(&pat_expr_string)
993 // 2 = spaces after keyword and condition.
994 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1002 between_kwd_cond_comment.as_ref().map_or(
1003 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1011 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1018 impl<'a> Rewrite for ControlFlow<'a> {
1019 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1020 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1022 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1023 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1024 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1025 if used_width == 0 {
1026 return Some(cond_str);
1029 let block_width = shape.width.saturating_sub(used_width);
1030 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1031 // we should avoid the single line case.
1032 let block_width = if self.else_block.is_some() || self.nested_if {
1037 let block_shape = Shape {
1042 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1044 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1045 context.is_if_else_block.replace(old_val);
1049 let mut result = format!("{}{}", cond_str, block_str);
1051 if let Some(else_block) = self.else_block {
1052 let shape = Shape::indented(shape.indent, context.config);
1053 let mut last_in_chain = false;
1054 let rewrite = match else_block.kind {
1055 // If the else expression is another if-else expression, prevent it
1056 // from being formatted on a single line.
1057 // Note how we're passing the original shape, as the
1058 // cost of "else" should not cascade.
1059 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1060 let (pats, cond) = extract_pats_and_cond(cond);
1061 ControlFlow::new_if(
1065 next_else_block.as_ref().map(|e| &**e),
1068 mk_sp(else_block.span.lo(), self.span.hi()),
1070 .rewrite(context, shape)
1073 last_in_chain = true;
1074 // When rewriting a block, the width is only used for single line
1075 // blocks, passing 1 lets us avoid that.
1076 let else_shape = Shape {
1077 width: min(1, shape.width),
1080 format_expr(else_block, ExprType::Statement, context, else_shape)
1084 let between_kwd_else_block = mk_sp(
1085 self.block.span.hi(),
1088 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1090 let between_kwd_else_block_comment =
1091 extract_comment(between_kwd_else_block, context, shape);
1093 let after_else = mk_sp(
1096 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1097 else_block.span.lo(),
1099 let after_else_comment = extract_comment(after_else, context, shape);
1101 let between_sep = match context.config.control_brace_style() {
1102 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1105 ControlBraceStyle::AlwaysSameLine => " ",
1107 let after_sep = match context.config.control_brace_style() {
1108 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1112 result.push_str(&format!(
1114 between_kwd_else_block_comment
1116 .map_or(between_sep, |s| &**s),
1117 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1119 result.push_str(&rewrite?);
1126 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1128 Some(label) => Cow::from(format!("{}: ", label.ident)),
1129 None => Cow::from(""),
1133 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1134 match rewrite_missing_comment(span, shape, context) {
1135 Some(ref comment) if !comment.is_empty() => Some(format!(
1136 "{indent}{}{indent}",
1138 indent = shape.indent.to_string_with_newline(context.config)
1144 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1145 contains_comment(context.snippet(block.span))
1148 // Checks that a block contains no statements, an expression and no comments or
1150 // FIXME: incorrectly returns false when comment is contained completely within
1152 pub(crate) fn is_simple_block(
1153 context: &RewriteContext<'_>,
1155 attrs: Option<&[ast::Attribute]>,
1157 block.stmts.len() == 1
1158 && stmt_is_expr(&block.stmts[0])
1159 && !block_contains_comment(context, block)
1160 && attrs.map_or(true, |a| a.is_empty())
1163 /// Checks whether a block contains at most one statement or expression, and no
1164 /// comments or attributes.
1165 pub(crate) fn is_simple_block_stmt(
1166 context: &RewriteContext<'_>,
1168 attrs: Option<&[ast::Attribute]>,
1170 block.stmts.len() <= 1
1171 && !block_contains_comment(context, block)
1172 && attrs.map_or(true, |a| a.is_empty())
1175 /// Checks whether a block contains no statements, expressions, comments, or
1176 /// inner attributes.
1177 pub(crate) fn is_empty_block(
1178 context: &RewriteContext<'_>,
1180 attrs: Option<&[ast::Attribute]>,
1182 block.stmts.is_empty()
1183 && !block_contains_comment(context, block)
1184 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1187 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1189 ast::StmtKind::Expr(..) => true,
1194 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1195 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1202 pub(crate) fn rewrite_literal(
1203 context: &RewriteContext<'_>,
1206 ) -> Option<String> {
1208 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1210 context.snippet(l.span).to_owned(),
1211 context.config.max_width(),
1217 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1218 let string_lit = context.snippet(span);
1220 if !context.config.format_strings() {
1224 .all(|line| line.ends_with('\\'))
1225 && context.config.version() == Version::Two
1227 return Some(string_lit.to_owned());
1229 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1233 // Remove the quote characters.
1234 let str_lit = &string_lit[1..string_lit.len() - 1];
1238 &StringFormat::new(shape.visual_indent(0), context.config),
1239 shape.width.saturating_sub(2),
1243 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1244 if context.inside_macro() {
1245 if span_ends_with_comma(context, span) {
1246 Some(SeparatorTactic::Always)
1248 Some(SeparatorTactic::Never)
1255 pub(crate) fn rewrite_call(
1256 context: &RewriteContext<'_>,
1258 args: &[ptr::P<ast::Expr>],
1261 ) -> Option<String> {
1262 overflow::rewrite_with_parens(
1268 context.config.width_heuristics().fn_call_width,
1269 choose_separator_tactic(context, span),
1273 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1275 ast::ExprKind::Lit(..) => true,
1276 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1277 ast::ExprKind::AddrOf(_, _, ref expr)
1278 | ast::ExprKind::Box(ref expr)
1279 | ast::ExprKind::Cast(ref expr, _)
1280 | ast::ExprKind::Field(ref expr, _)
1281 | ast::ExprKind::Try(ref expr)
1282 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1283 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1284 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1285 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1291 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1292 lists.iter().all(OverflowableItem::is_simple)
1295 pub(crate) fn can_be_overflowed_expr(
1296 context: &RewriteContext<'_>,
1301 _ if !expr.attrs.is_empty() => false,
1302 ast::ExprKind::Match(..) => {
1303 (context.use_block_indent() && args_len == 1)
1304 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1305 || context.config.overflow_delimited_expr()
1307 ast::ExprKind::If(..)
1308 | ast::ExprKind::ForLoop(..)
1309 | ast::ExprKind::Loop(..)
1310 | ast::ExprKind::While(..) => {
1311 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1314 // Handle always block-like expressions
1315 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1317 // Handle `[]` and `{}`-like expressions
1318 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1319 context.config.overflow_delimited_expr()
1320 || (context.use_block_indent() && args_len == 1)
1322 ast::ExprKind::MacCall(ref mac) => {
1324 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
1325 context.config.overflow_delimited_expr(),
1327 (Some(ast::MacDelimiter::Bracket), true)
1328 | (Some(ast::MacDelimiter::Brace), true) => true,
1329 _ => context.use_block_indent() && args_len == 1,
1333 // Handle parenthetical expressions
1334 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1335 context.use_block_indent() && args_len == 1
1338 // Handle unary-like expressions
1339 ast::ExprKind::AddrOf(_, _, ref expr)
1340 | ast::ExprKind::Box(ref expr)
1341 | ast::ExprKind::Try(ref expr)
1342 | ast::ExprKind::Unary(_, ref expr)
1343 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1348 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1350 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1351 ast::ExprKind::AddrOf(_, _, ref expr)
1352 | ast::ExprKind::Box(ref expr)
1353 | ast::ExprKind::Try(ref expr)
1354 | ast::ExprKind::Unary(_, ref expr)
1355 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1360 /// Returns `true` if a function call or a method call represented by the given span ends with a
1361 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1362 /// comma from macro can potentially break the code.
1363 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1364 let mut result: bool = Default::default();
1365 let mut prev_char: char = Default::default();
1366 let closing_delimiters = &[')', '}', ']'];
1368 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1370 _ if kind.is_comment() || c.is_whitespace() => continue,
1371 c if closing_delimiters.contains(&c) => {
1372 result &= !closing_delimiters.contains(&prev_char);
1374 ',' => result = true,
1375 _ => result = false,
1384 context: &RewriteContext<'_>,
1385 mut subexpr: &ast::Expr,
1388 ) -> Option<String> {
1389 debug!("rewrite_paren, shape: {:?}", shape);
1391 // Extract comments within parens.
1394 let mut pre_comment;
1395 let mut post_comment;
1396 let remove_nested_parens = context.config.remove_nested_parens();
1399 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1400 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1401 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1402 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1404 // Remove nested parens if there are no comments.
1405 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1406 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1407 span = subexpr.span;
1408 subexpr = subsubexpr;
1417 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1418 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1419 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1420 if fits_single_line {
1421 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1423 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1427 fn rewrite_paren_in_multi_line(
1428 context: &RewriteContext<'_>,
1429 subexpr: &ast::Expr,
1433 ) -> Option<String> {
1434 let nested_indent = shape.indent.block_indent(context.config);
1435 let nested_shape = Shape::indented(nested_indent, context.config);
1436 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1437 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1438 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1440 let mut result = String::with_capacity(subexpr_str.len() * 2);
1442 if !pre_comment.is_empty() {
1443 result.push_str(&nested_indent.to_string_with_newline(context.config));
1444 result.push_str(&pre_comment);
1446 result.push_str(&nested_indent.to_string_with_newline(context.config));
1447 result.push_str(&subexpr_str);
1448 if !post_comment.is_empty() {
1449 result.push_str(&nested_indent.to_string_with_newline(context.config));
1450 result.push_str(&post_comment);
1452 result.push_str(&shape.indent.to_string_with_newline(context.config));
1461 context: &RewriteContext<'_>,
1463 ) -> Option<String> {
1464 let expr_str = expr.rewrite(context, shape)?;
1466 let offset = last_line_width(&expr_str) + 1;
1467 let rhs_overhead = shape.rhs_overhead(context.config);
1468 let index_shape = if expr_str.contains('\n') {
1469 Shape::legacy(context.config.max_width(), shape.indent)
1470 .offset_left(offset)
1471 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1473 match context.config.indent_style() {
1474 IndentStyle::Block => shape
1475 .offset_left(offset)
1476 .and_then(|shape| shape.sub_width(1)),
1477 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1480 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1482 // Return if index fits in a single line.
1483 match orig_index_rw {
1484 Some(ref index_str) if !index_str.contains('\n') => {
1485 return Some(format!("{}[{}]", expr_str, index_str));
1490 // Try putting index on the next line and see if it fits in a single line.
1491 let indent = shape.indent.block_indent(context.config);
1492 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1493 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1494 let new_index_rw = index.rewrite(context, index_shape);
1495 match (orig_index_rw, new_index_rw) {
1496 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1499 indent.to_string_with_newline(context.config),
1502 (None, Some(ref new_index_str)) => Some(format!(
1505 indent.to_string_with_newline(context.config),
1508 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1513 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1518 fields.iter().all(|field| !field.is_shorthand)
1521 fn rewrite_struct_lit<'a>(
1522 context: &RewriteContext<'_>,
1524 fields: &'a [ast::Field],
1525 base: Option<&'a ast::Expr>,
1526 attrs: &[ast::Attribute],
1529 ) -> Option<String> {
1530 debug!("rewrite_struct_lit: shape {:?}", shape);
1532 enum StructLitField<'a> {
1533 Regular(&'a ast::Field),
1534 Base(&'a ast::Expr),
1538 let path_shape = shape.sub_width(2)?;
1539 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1541 if fields.is_empty() && base.is_none() {
1542 return Some(format!("{} {{}}", path_str));
1545 // Foo { a: Foo } - indent is +3, width is -5.
1546 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1548 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1549 let body_lo = context.snippet_provider.span_after(span, "{");
1550 let fields_str = if struct_lit_can_be_aligned(fields, base)
1551 && context.config.struct_field_align_threshold() > 0
1553 rewrite_with_alignment(
1557 mk_sp(body_lo, span.hi()),
1561 let field_iter = fields
1563 .map(StructLitField::Regular)
1564 .chain(base.into_iter().map(StructLitField::Base));
1566 let span_lo = |item: &StructLitField<'_>| match *item {
1567 StructLitField::Regular(field) => field.span().lo(),
1568 StructLitField::Base(expr) => {
1569 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1570 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1571 let pos = snippet.find_uncommented("..").unwrap();
1572 last_field_hi + BytePos(pos as u32)
1575 let span_hi = |item: &StructLitField<'_>| match *item {
1576 StructLitField::Regular(field) => field.span().hi(),
1577 StructLitField::Base(expr) => expr.span.hi(),
1579 let rewrite = |item: &StructLitField<'_>| match *item {
1580 StructLitField::Regular(field) => {
1581 // The 1 taken from the v_budget is for the comma.
1582 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1584 StructLitField::Base(expr) => {
1586 expr.rewrite(context, v_shape.offset_left(2)?)
1587 .map(|s| format!("..{}", s))
1591 let items = itemize_list(
1592 context.snippet_provider,
1603 let item_vec = items.collect::<Vec<_>>();
1605 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1606 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1608 let ends_with_comma = span_ends_with_comma(context, span);
1609 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1611 let fmt = struct_lit_formatting(
1615 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1618 write_list(&item_vec, &fmt)?
1622 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1623 Some(format!("{} {{{}}}", path_str, fields_str))
1625 // FIXME if context.config.indent_style() == Visual, but we run out
1626 // of space, we should fall back to BlockIndent.
1629 pub(crate) fn wrap_struct_field(
1630 context: &RewriteContext<'_>,
1631 attrs: &[ast::Attribute],
1634 nested_shape: Shape,
1635 one_line_width: usize,
1636 ) -> Option<String> {
1637 let should_vertical = context.config.indent_style() == IndentStyle::Block
1638 && (fields_str.contains('\n')
1639 || !context.config.struct_lit_single_line()
1640 || fields_str.len() > one_line_width);
1642 let inner_attrs = &inner_attributes(attrs);
1643 if inner_attrs.is_empty() {
1644 if should_vertical {
1647 nested_shape.indent.to_string_with_newline(context.config),
1649 shape.indent.to_string_with_newline(context.config)
1652 // One liner or visual indent.
1653 Some(format!(" {} ", fields_str))
1658 nested_shape.indent.to_string_with_newline(context.config),
1659 inner_attrs.rewrite(context, shape)?,
1660 nested_shape.indent.to_string_with_newline(context.config),
1662 shape.indent.to_string_with_newline(context.config)
1667 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1668 colon_spaces(config)
1671 pub(crate) fn rewrite_field(
1672 context: &RewriteContext<'_>,
1675 prefix_max_width: usize,
1676 ) -> Option<String> {
1677 if contains_skip(&field.attrs) {
1678 return Some(context.snippet(field.span()).to_owned());
1680 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1681 if !attrs_str.is_empty() {
1682 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1684 let name = context.snippet(field.ident.span);
1685 if field.is_shorthand {
1686 Some(attrs_str + name)
1688 let mut separator = String::from(struct_lit_field_separator(context.config));
1689 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1690 separator.push(' ');
1692 let overhead = name.len() + separator.len();
1693 let expr_shape = shape.offset_left(overhead)?;
1694 let expr = field.expr.rewrite(context, expr_shape);
1697 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1698 Some(attrs_str + name)
1700 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1702 let expr_offset = shape.indent.block_indent(context.config);
1705 .rewrite(context, Shape::indented(expr_offset, context.config));
1711 expr_offset.to_string(context.config),
1720 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1721 context: &RewriteContext<'_>,
1722 mut items: impl Iterator<Item = &'a T>,
1725 is_singleton_tuple: bool,
1726 ) -> Option<String> {
1727 // In case of length 1, need a trailing comma
1728 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1729 if is_singleton_tuple {
1731 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1735 .rewrite(context, nested_shape)
1736 .map(|s| format!("({},)", s));
1739 let list_lo = context.snippet_provider.span_after(span, "(");
1740 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1741 let items = itemize_list(
1742 context.snippet_provider,
1746 |item| item.span().lo(),
1747 |item| item.span().hi(),
1748 |item| item.rewrite(context, nested_shape),
1750 span.hi() - BytePos(1),
1753 let item_vec: Vec<_> = items.collect();
1754 let tactic = definitive_tactic(
1756 ListTactic::HorizontalVertical,
1760 let fmt = ListFormatting::new(nested_shape, context.config)
1762 .ends_with_newline(false);
1763 let list_str = write_list(&item_vec, &fmt)?;
1765 Some(format!("({})", list_str))
1768 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1769 context: &'a RewriteContext<'_>,
1770 items: impl Iterator<Item = &'a T>,
1773 is_singleton_tuple: bool,
1774 ) -> Option<String> {
1775 debug!("rewrite_tuple {:?}", shape);
1776 if context.use_block_indent() {
1777 // We use the same rule as function calls for rewriting tuples.
1778 let force_tactic = if context.inside_macro() {
1779 if span_ends_with_comma(context, span) {
1780 Some(SeparatorTactic::Always)
1782 Some(SeparatorTactic::Never)
1784 } else if is_singleton_tuple {
1785 Some(SeparatorTactic::Always)
1789 overflow::rewrite_with_parens(
1795 context.config.width_heuristics().fn_call_width,
1799 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1803 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1804 context: &RewriteContext<'_>,
1808 ) -> Option<String> {
1810 .rewrite(context, shape.offset_left(prefix.len())?)
1811 .map(|r| format!("{}{}", prefix, r))
1814 // FIXME: this is probably not correct for multi-line Rewrites. we should
1815 // subtract suffix.len() from the last line budget, not the first!
1816 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1817 context: &RewriteContext<'_>,
1821 ) -> Option<String> {
1823 .rewrite(context, shape.sub_width(suffix.len())?)
1830 fn rewrite_unary_op(
1831 context: &RewriteContext<'_>,
1835 ) -> Option<String> {
1836 // For some reason, an UnOp is not spanned like BinOp!
1837 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1840 fn rewrite_assignment(
1841 context: &RewriteContext<'_>,
1844 op: Option<&ast::BinOp>,
1846 ) -> Option<String> {
1847 let operator_str = match op {
1848 Some(op) => context.snippet(op.span),
1852 // 1 = space between lhs and operator.
1853 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1854 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1856 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1859 /// Controls where to put the rhs.
1860 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1861 pub(crate) enum RhsTactics {
1864 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1865 ForceNextLineWithoutIndent,
1866 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1871 // The left hand side must contain everything up to, and including, the
1872 // assignment operator.
1873 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1874 context: &RewriteContext<'_>,
1878 ) -> Option<String> {
1879 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1882 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1883 context: &RewriteContext<'_>,
1887 rhs_tactics: RhsTactics,
1888 ) -> Option<String> {
1889 let lhs = lhs.into();
1890 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1891 shape.indent.width()
1895 // 1 = space between operator and rhs.
1896 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1898 offset: shape.offset + last_line_width + 1,
1901 let rhs = choose_rhs(
1905 ex.rewrite(context, orig_shape),
1911 fn choose_rhs<R: Rewrite>(
1912 context: &RewriteContext<'_>,
1915 orig_rhs: Option<String>,
1916 rhs_tactics: RhsTactics,
1917 ) -> Option<String> {
1920 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1922 Some(format!(" {}", new_str))
1925 // Expression did not fit on the same line as the identifier.
1926 // Try splitting the line and see if that works better.
1927 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1928 let new_rhs = expr.rewrite(context, new_shape);
1929 let new_indent_str = &shape
1931 .block_indent(context.config)
1932 .to_string_with_newline(context.config);
1934 match (orig_rhs, new_rhs) {
1935 (Some(ref orig_rhs), Some(ref new_rhs))
1936 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1939 Some(format!(" {}", orig_rhs))
1941 (Some(ref orig_rhs), Some(ref new_rhs))
1942 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1944 Some(format!("{}{}", new_indent_str, new_rhs))
1946 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1947 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1948 let shape = shape.infinite_width();
1949 expr.rewrite(context, shape).map(|s| format!(" {}", s))
1951 (None, None) => None,
1952 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1958 fn shape_from_rhs_tactic(
1959 context: &RewriteContext<'_>,
1961 rhs_tactic: RhsTactics,
1962 ) -> Option<Shape> {
1964 RhsTactics::ForceNextLineWithoutIndent => shape
1965 .with_max_width(context.config)
1966 .sub_width(shape.indent.width()),
1967 RhsTactics::Default | RhsTactics::AllowOverflow => {
1968 Shape::indented(shape.indent.block_indent(context.config), context.config)
1969 .sub_width(shape.rhs_overhead(context.config))
1974 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
1975 /// original's line formatting.
1977 /// It is considered better if:
1978 /// 1. the tactic is ForceNextLineWithoutIndent
1979 /// 2. next_line_rhs doesn't have newlines
1980 /// 3. the original line has more newlines than next_line_rhs
1981 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
1983 pub(crate) fn prefer_next_line(
1985 next_line_rhs: &str,
1986 rhs_tactics: RhsTactics,
1988 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1989 || !next_line_rhs.contains('\n')
1990 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
1991 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
1992 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
1993 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
1996 fn rewrite_expr_addrof(
1997 context: &RewriteContext<'_>,
1998 borrow_kind: ast::BorrowKind,
1999 mutability: ast::Mutability,
2002 ) -> Option<String> {
2003 let operator_str = match (mutability, borrow_kind) {
2004 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2005 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2006 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2007 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2009 rewrite_unary_prefix(context, operator_str, expr, shape)
2012 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2014 ast::ExprKind::MethodCall(..) => true,
2015 ast::ExprKind::AddrOf(_, _, ref expr)
2016 | ast::ExprKind::Box(ref expr)
2017 | ast::ExprKind::Cast(ref expr, _)
2018 | ast::ExprKind::Try(ref expr)
2019 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2026 use super::last_line_offsetted;
2029 fn test_last_line_offsetted() {
2030 let lines = "one\n two";
2031 assert_eq!(last_line_offsetted(2, lines), true);
2032 assert_eq!(last_line_offsetted(4, lines), false);
2033 assert_eq!(last_line_offsetted(6, lines), false);
2035 let lines = "one two";
2036 assert_eq!(last_line_offsetted(2, lines), false);
2037 assert_eq!(last_line_offsetted(0, lines), false);
2039 let lines = "\ntwo";
2040 assert_eq!(last_line_offsetted(2, lines), false);
2041 assert_eq!(last_line_offsetted(0, lines), false);
2043 let lines = "one\n two three";
2044 assert_eq!(last_line_offsetted(2, lines), true);
2045 let lines = "one\n two three";
2046 assert_eq!(last_line_offsetted(2, lines), false);