4 use itertools::Itertools;
5 use rustc_ast::token::{Delimiter, 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, contains_comment, recover_comment_removed, rewrite_comment,
13 rewrite_missing_comment, CharClasses, FindUncommented,
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, HexLiteralCase, 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_lit.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 struct_expr) => {
110 let ast::StructExpr {
127 ast::ExprKind::Tup(ref items) => {
128 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
130 ast::ExprKind::Let(..) => None,
131 ast::ExprKind::If(..)
132 | ast::ExprKind::ForLoop(..)
133 | ast::ExprKind::Loop(..)
134 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
135 .and_then(|control_flow| control_flow.rewrite(context, shape)),
136 ast::ExprKind::ConstBlock(ref anon_const) => {
137 Some(format!("const {}", anon_const.rewrite(context, shape)?))
139 ast::ExprKind::Block(ref block, opt_label) => {
141 ExprType::Statement => {
142 if is_unsafe_block(block) {
143 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
144 } else if let rw @ Some(_) =
145 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
147 // Rewrite block without trying to put it in a single line.
150 let prefix = block_prefix(context, block, shape)?;
152 rewrite_block_with_visitor(
163 ExprType::SubExpression => {
164 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
168 ast::ExprKind::Match(ref cond, ref arms) => {
169 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
171 ast::ExprKind::Path(ref qself, ref path) => {
172 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
174 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
175 rewrite_assignment(context, lhs, rhs, None, shape)
177 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
178 rewrite_assignment(context, lhs, rhs, Some(op), shape)
180 ast::ExprKind::Continue(ref opt_label) => {
181 let id_str = match *opt_label {
182 Some(label) => format!(" {}", label.ident),
183 None => String::new(),
185 Some(format!("continue{}", id_str))
187 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
188 let id_str = match *opt_label {
189 Some(label) => format!(" {}", label.ident),
190 None => String::new(),
193 if let Some(ref expr) = *opt_expr {
194 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
196 Some(format!("break{}", id_str))
199 ast::ExprKind::Yield(ref opt_expr) => {
200 if let Some(ref expr) = *opt_expr {
201 rewrite_unary_prefix(context, "yield ", &**expr, shape)
203 Some("yield".to_string())
206 ast::ExprKind::Closure(
214 ) => closures::rewrite_closure(
215 binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape,
217 ast::ExprKind::Try(..)
218 | ast::ExprKind::Field(..)
219 | ast::ExprKind::MethodCall(..)
220 | ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
221 ast::ExprKind::MacCall(ref mac) => {
222 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
224 context.snippet(expr.span).to_owned(),
225 context.config.max_width(),
230 ast::ExprKind::Ret(None) => Some("return".to_owned()),
231 ast::ExprKind::Ret(Some(ref expr)) => {
232 rewrite_unary_prefix(context, "return ", &**expr, shape)
234 ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()),
235 ast::ExprKind::Yeet(Some(ref expr)) => {
236 rewrite_unary_prefix(context, "do yeet ", &**expr, shape)
238 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
239 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
240 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
242 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
245 PairParts::infix(" as "),
248 SeparatorPlace::Front,
250 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
253 PairParts::infix(": "),
256 SeparatorPlace::Back,
258 ast::ExprKind::Index(ref expr, ref index) => {
259 rewrite_index(&**expr, &**index, context, shape)
261 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
264 PairParts::new("[", "; ", "]"),
267 SeparatorPlace::Back,
269 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
270 let delim = match limits {
271 ast::RangeLimits::HalfOpen => "..",
272 ast::RangeLimits::Closed => "..=",
275 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
277 ast::ExprKind::Lit(ref lit) => match lit.kind {
278 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
279 context.snippet(lit.span).ends_with('.')
283 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
288 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
289 // Don't format `.. ..` into `....`, which is invalid.
291 // This check is unnecessary for `lhs`, because a range
292 // starting from another range needs parentheses as `(x ..) ..`
293 // (`x .. ..` is a range from `x` to `..`).
294 matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
297 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
298 let space_if = |b: bool| if b { " " } else { "" };
302 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
304 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
308 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
309 (Some(lhs), Some(rhs)) => {
310 let sp_delim = if context.config.spaces_around_ranges() {
311 format!(" {} ", delim)
313 default_sp_delim(Some(lhs), Some(rhs))
318 PairParts::infix(&sp_delim),
321 context.config.binop_separator(),
324 (None, Some(rhs)) => {
325 let sp_delim = if context.config.spaces_around_ranges() {
326 format!("{} ", delim)
328 default_sp_delim(None, Some(rhs))
330 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
332 (Some(lhs), None) => {
333 let sp_delim = if context.config.spaces_around_ranges() {
334 format!(" {}", delim)
336 default_sp_delim(Some(lhs), None)
338 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
340 (None, None) => Some(delim.to_owned()),
343 // We do not format these expressions yet, but they should still
344 // satisfy our width restrictions.
345 // Style Guide RFC for InlineAsm variant pending
346 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
347 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
348 ast::ExprKind::TryBlock(ref block) => {
349 if let rw @ Some(_) =
350 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
355 let budget = shape.width.saturating_sub(9);
364 Shape::legacy(budget, shape.indent)
369 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
370 let mover = if capture_by == ast::CaptureBy::Value {
375 if let rw @ Some(_) = rewrite_single_line_block(
377 format!("{}{}", "async ", mover).as_str(),
386 let budget = shape.width.saturating_sub(6);
396 Shape::legacy(budget, shape.indent)
401 ast::ExprKind::Underscore => Some("_".to_owned()),
402 ast::ExprKind::IncludedBytes(..) => unreachable!(),
403 ast::ExprKind::Err => None,
407 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
408 .and_then(|expr_str| {
409 let attrs = outer_attributes(&expr.attrs);
410 let attrs_str = attrs.rewrite(context, shape)?;
412 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
415 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
419 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
421 exprs: impl Iterator<Item = &'a T>,
423 context: &'a RewriteContext<'_>,
425 force_separator_tactic: Option<SeparatorTactic>,
426 delim_token: Option<Delimiter>,
427 ) -> Option<String> {
428 overflow::rewrite_with_square_brackets(
434 force_separator_tactic,
439 fn rewrite_empty_block(
440 context: &RewriteContext<'_>,
442 attrs: Option<&[ast::Attribute]>,
443 label: Option<ast::Label>,
446 ) -> Option<String> {
447 if block_has_statements(block) {
451 let label_str = rewrite_label(label);
452 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
456 if !block_contains_comment(context, block) && shape.width >= 2 {
457 return Some(format!("{}{}{{}}", prefix, label_str));
460 // If a block contains only a single-line comment, then leave it on one line.
461 let user_str = context.snippet(block.span);
462 let user_str = user_str.trim();
463 if user_str.starts_with('{') && user_str.ends_with('}') {
464 let comment_str = user_str[1..user_str.len() - 1].trim();
465 if block.stmts.is_empty()
466 && !comment_str.contains('\n')
467 && !comment_str.starts_with("//")
468 && comment_str.len() + 4 <= shape.width
470 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
477 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
478 Some(match block.rules {
479 ast::BlockCheckMode::Unsafe(..) => {
480 let snippet = context.snippet(block.span);
481 let open_pos = snippet.find_uncommented("{")?;
482 // Extract comment between unsafe and block start.
483 let trimmed = &snippet[6..open_pos].trim();
485 if !trimmed.is_empty() {
486 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
487 let budget = shape.width.checked_sub(9)?;
493 Shape::legacy(budget, shape.indent + 7),
501 ast::BlockCheckMode::Default => String::new(),
505 fn rewrite_single_line_block(
506 context: &RewriteContext<'_>,
509 attrs: Option<&[ast::Attribute]>,
510 label: Option<ast::Label>,
512 ) -> Option<String> {
513 if is_simple_block(context, block, attrs) {
514 let expr_shape = shape.offset_left(last_line_width(prefix))?;
515 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
516 let label_str = rewrite_label(label);
517 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
518 if result.len() <= shape.width && !result.contains('\n') {
525 pub(crate) fn rewrite_block_with_visitor(
526 context: &RewriteContext<'_>,
529 attrs: Option<&[ast::Attribute]>,
530 label: Option<ast::Label>,
533 ) -> Option<String> {
534 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
538 let mut visitor = FmtVisitor::from_context(context);
539 visitor.block_indent = shape.indent;
540 visitor.is_if_else_block = context.is_if_else_block();
541 match (block.rules, label) {
542 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
543 let snippet = context.snippet(block.span);
544 let open_pos = snippet.find_uncommented("{")?;
545 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
547 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
550 let inner_attrs = attrs.map(inner_attributes);
551 let label_str = rewrite_label(label);
552 visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
553 let visitor_context = visitor.get_context();
557 .append(&mut visitor_context.skipped_range.borrow_mut());
558 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
561 impl Rewrite for ast::Block {
562 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
563 rewrite_block(self, None, None, context, shape)
569 attrs: Option<&[ast::Attribute]>,
570 label: Option<ast::Label>,
571 context: &RewriteContext<'_>,
573 ) -> Option<String> {
574 let prefix = block_prefix(context, block, shape)?;
576 // shape.width is used only for the single line case: either the empty block `{}`,
577 // or an unsafe expression `unsafe { e }`.
578 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
582 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
583 if let Some(ref result_str) = result {
584 if result_str.lines().count() <= 3 {
585 if let rw @ Some(_) =
586 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
596 // Rewrite condition if the given expression has one.
597 pub(crate) fn rewrite_cond(
598 context: &RewriteContext<'_>,
601 ) -> Option<String> {
603 ast::ExprKind::Match(ref cond, _) => {
605 let cond_shape = match context.config.indent_style() {
606 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
607 IndentStyle::Block => shape.offset_left(8)?,
609 cond.rewrite(context, cond_shape)
611 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
613 String::from("\n") + &shape.indent.block_only().to_string(context.config);
615 .rewrite_cond(context, shape, &alt_block_sep)
621 // Abstraction over control flow expressions
623 struct ControlFlow<'a> {
624 cond: Option<&'a ast::Expr>,
625 block: &'a ast::Block,
626 else_block: Option<&'a ast::Expr>,
627 label: Option<ast::Label>,
628 pat: Option<&'a ast::Pat>,
632 allow_single_line: bool,
633 // HACK: `true` if this is an `if` expression in an `else if`.
638 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
640 ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
645 // FIXME: Refactor this.
646 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
648 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
649 let (pat, cond) = extract_pats_and_cond(cond);
650 Some(ControlFlow::new_if(
654 else_block.as_ref().map(|e| &**e),
655 expr_type == ExprType::SubExpression,
660 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
661 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
663 ast::ExprKind::Loop(ref block, label) => {
664 Some(ControlFlow::new_loop(block, label, expr.span))
666 ast::ExprKind::While(ref cond, ref block, label) => {
667 let (pat, cond) = extract_pats_and_cond(cond);
668 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
674 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
675 pat.map_or("", |_| "let")
678 impl<'a> ControlFlow<'a> {
681 pat: Option<&'a ast::Pat>,
682 block: &'a ast::Block,
683 else_block: Option<&'a ast::Expr>,
684 allow_single_line: bool,
687 ) -> ControlFlow<'a> {
688 let matcher = choose_matcher(pat);
704 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
714 allow_single_line: false,
721 pat: Option<&'a ast::Pat>,
723 block: &'a ast::Block,
724 label: Option<ast::Label>,
726 ) -> ControlFlow<'a> {
727 let matcher = choose_matcher(pat);
737 allow_single_line: false,
746 block: &'a ast::Block,
747 label: Option<ast::Label>,
749 ) -> ControlFlow<'a> {
759 allow_single_line: false,
765 fn rewrite_single_line(
768 context: &RewriteContext<'_>,
770 ) -> Option<String> {
771 assert!(self.allow_single_line);
772 let else_block = self.else_block?;
773 let fixed_cost = self.keyword.len() + " { } else { }".len();
775 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
776 if !is_simple_block(context, self.block, None)
777 || !is_simple_block(context, else_node, None)
778 || pat_expr_str.contains('\n')
783 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
784 let expr = &self.block.stmts[0];
785 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
787 let new_width = new_width.checked_sub(if_str.len())?;
788 let else_expr = &else_node.stmts[0];
789 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
791 if if_str.contains('\n') || else_str.contains('\n') {
795 let result = format!(
796 "{} {} {{ {} }} else {{ {} }}",
797 self.keyword, pat_expr_str, if_str, else_str
800 if result.len() <= width {
809 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
811 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
812 let mut leading_whitespaces = 0;
813 for c in pat_str.chars().rev() {
816 _ if c.is_whitespace() => leading_whitespaces += 1,
817 _ => leading_whitespaces = 0,
820 leading_whitespaces > start_column
823 impl<'a> ControlFlow<'a> {
826 context: &RewriteContext<'_>,
830 ) -> Option<String> {
831 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
833 let cond_shape = shape.offset_left(offset)?;
834 if let Some(pat) = self.pat {
835 let matcher = if self.matcher.is_empty() {
836 self.matcher.to_owned()
838 format!("{} ", self.matcher)
840 let pat_shape = cond_shape
841 .offset_left(matcher.len())?
842 .sub_width(self.connector.len())?;
843 let pat_string = pat.rewrite(context, pat_shape)?;
844 let comments_lo = context
846 .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
847 let comments_span = mk_sp(comments_lo, expr.span.lo());
848 return rewrite_assign_rhs_with_comments(
850 &format!("{}{}{}", matcher, pat_string, self.connector),
853 &RhsAssignKind::Expr(&expr.kind, expr.span),
860 let expr_rw = expr.rewrite(context, cond_shape);
861 // The expression may (partially) fit on the current line.
862 // We do not allow splitting between `if` and condition.
863 if self.keyword == "if" || expr_rw.is_some() {
867 // The expression won't fit on the current line, jump to next.
868 let nested_shape = shape
869 .block_indent(context.config.tab_spaces())
870 .with_max_width(context.config);
871 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
872 expr.rewrite(context, nested_shape)
873 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
878 context: &RewriteContext<'_>,
881 ) -> Option<(String, usize)> {
882 // Do not take the rhs overhead from the upper expressions into account
883 // when rewriting pattern.
884 let new_width = context.budget(shape.used_width());
885 let fresh_shape = Shape {
889 let constr_shape = if self.nested_if {
890 // We are part of an if-elseif-else chain. Our constraints are tightened.
891 // 7 = "} else " .len()
892 fresh_shape.offset_left(7)?
897 let label_string = rewrite_label(self.label);
898 // 1 = space after keyword.
899 let offset = self.keyword.len() + label_string.len() + 1;
901 let pat_expr_string = match self.cond {
902 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
903 None => String::new(),
907 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
913 let one_line_budget = context
916 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
917 let force_newline_brace = (pat_expr_string.contains('\n')
918 || pat_expr_string.len() > one_line_budget)
919 && (!last_line_extendable(&pat_expr_string)
920 || last_line_offsetted(shape.used_width(), &pat_expr_string));
922 // Try to format if-else on single line.
923 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
924 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
926 if let Some(cond_str) = trial {
927 if cond_str.len() <= context.config.single_line_if_else_max_width() {
928 return Some((cond_str, 0));
933 let cond_span = if let Some(cond) = self.cond {
936 mk_sp(self.block.span.lo(), self.block.span.lo())
939 // `for event in event`
940 // Do not include label in the span.
943 .map_or(self.span.lo(), |label| label.ident.span.hi());
944 let between_kwd_cond = mk_sp(
947 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
948 if self.pat.is_none() {
950 } else if self.matcher.is_empty() {
951 self.pat.unwrap().span.lo()
955 .span_before(self.span, self.matcher.trim())
959 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
961 let after_cond_comment =
962 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
964 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
966 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
967 || force_newline_brace
974 let used_width = if pat_expr_string.contains('\n') {
975 last_line_width(&pat_expr_string)
977 // 2 = spaces after keyword and condition.
978 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
986 between_kwd_cond_comment.as_ref().map_or(
987 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
995 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1002 impl<'a> Rewrite for ControlFlow<'a> {
1003 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1004 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1006 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1007 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1008 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1009 if used_width == 0 {
1010 return Some(cond_str);
1013 let block_width = shape.width.saturating_sub(used_width);
1014 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1015 // we should avoid the single line case.
1016 let block_width = if self.else_block.is_some() || self.nested_if {
1021 let block_shape = Shape {
1026 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1028 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1029 context.is_if_else_block.replace(old_val);
1033 let mut result = format!("{}{}", cond_str, block_str);
1035 if let Some(else_block) = self.else_block {
1036 let shape = Shape::indented(shape.indent, context.config);
1037 let mut last_in_chain = false;
1038 let rewrite = match else_block.kind {
1039 // If the else expression is another if-else expression, prevent it
1040 // from being formatted on a single line.
1041 // Note how we're passing the original shape, as the
1042 // cost of "else" should not cascade.
1043 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1044 let (pats, cond) = extract_pats_and_cond(cond);
1045 ControlFlow::new_if(
1049 next_else_block.as_ref().map(|e| &**e),
1052 mk_sp(else_block.span.lo(), self.span.hi()),
1054 .rewrite(context, shape)
1057 last_in_chain = true;
1058 // When rewriting a block, the width is only used for single line
1059 // blocks, passing 1 lets us avoid that.
1060 let else_shape = Shape {
1061 width: min(1, shape.width),
1064 format_expr(else_block, ExprType::Statement, context, else_shape)
1068 let between_kwd_else_block = mk_sp(
1069 self.block.span.hi(),
1072 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1074 let between_kwd_else_block_comment =
1075 extract_comment(between_kwd_else_block, context, shape);
1077 let after_else = mk_sp(
1080 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1081 else_block.span.lo(),
1083 let after_else_comment = extract_comment(after_else, context, shape);
1085 let between_sep = match context.config.control_brace_style() {
1086 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1089 ControlBraceStyle::AlwaysSameLine => " ",
1091 let after_sep = match context.config.control_brace_style() {
1092 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1096 result.push_str(&format!(
1098 between_kwd_else_block_comment
1100 .map_or(between_sep, |s| &**s),
1101 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1103 result.push_str(&rewrite?);
1110 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1112 Some(label) => Cow::from(format!("{}: ", label.ident)),
1113 None => Cow::from(""),
1117 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1118 match rewrite_missing_comment(span, shape, context) {
1119 Some(ref comment) if !comment.is_empty() => Some(format!(
1120 "{indent}{}{indent}",
1122 indent = shape.indent.to_string_with_newline(context.config)
1128 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1129 contains_comment(context.snippet(block.span))
1132 // Checks that a block contains no statements, an expression and no comments or
1134 // FIXME: incorrectly returns false when comment is contained completely within
1136 pub(crate) fn is_simple_block(
1137 context: &RewriteContext<'_>,
1139 attrs: Option<&[ast::Attribute]>,
1141 block.stmts.len() == 1
1142 && stmt_is_expr(&block.stmts[0])
1143 && !block_contains_comment(context, block)
1144 && attrs.map_or(true, |a| a.is_empty())
1147 /// Checks whether a block contains at most one statement or expression, and no
1148 /// comments or attributes.
1149 pub(crate) fn is_simple_block_stmt(
1150 context: &RewriteContext<'_>,
1152 attrs: Option<&[ast::Attribute]>,
1154 block.stmts.len() <= 1
1155 && !block_contains_comment(context, block)
1156 && attrs.map_or(true, |a| a.is_empty())
1159 fn block_has_statements(block: &ast::Block) -> bool {
1163 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1166 /// Checks whether a block contains no statements, expressions, comments, or
1167 /// inner attributes.
1168 pub(crate) fn is_empty_block(
1169 context: &RewriteContext<'_>,
1171 attrs: Option<&[ast::Attribute]>,
1173 !block_has_statements(block)
1174 && !block_contains_comment(context, block)
1175 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1178 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1179 matches!(stmt.kind, ast::StmtKind::Expr(..))
1182 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1183 matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1186 pub(crate) fn rewrite_literal(
1187 context: &RewriteContext<'_>,
1190 ) -> Option<String> {
1192 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1193 ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape),
1195 context.snippet(l.span).to_owned(),
1196 context.config.max_width(),
1202 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1203 let string_lit = context.snippet(span);
1205 if !context.config.format_strings() {
1209 .all(|line| line.ends_with('\\'))
1210 && context.config.version() == Version::Two
1212 return Some(string_lit.to_owned());
1214 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1218 // Remove the quote characters.
1219 let str_lit = &string_lit[1..string_lit.len() - 1];
1223 &StringFormat::new(shape.visual_indent(0), context.config),
1224 shape.width.saturating_sub(2),
1228 fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option<String> {
1229 let span = lit.span;
1230 let symbol = lit.token_lit.symbol.as_str();
1232 if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1233 let hex_lit = match context.config.hex_literal_case() {
1234 HexLiteralCase::Preserve => None,
1235 HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1236 HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1238 if let Some(hex_lit) = hex_lit {
1245 .map_or(String::new(), |s| s.to_string())
1247 context.config.max_width(),
1254 context.snippet(span).to_owned(),
1255 context.config.max_width(),
1260 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1261 if context.inside_macro() {
1262 if span_ends_with_comma(context, span) {
1263 Some(SeparatorTactic::Always)
1265 Some(SeparatorTactic::Never)
1272 pub(crate) fn rewrite_call(
1273 context: &RewriteContext<'_>,
1275 args: &[ptr::P<ast::Expr>],
1278 ) -> Option<String> {
1279 overflow::rewrite_with_parens(
1285 context.config.fn_call_width(),
1286 choose_separator_tactic(context, span),
1290 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1292 ast::ExprKind::Lit(..) => true,
1293 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1294 ast::ExprKind::AddrOf(_, _, ref expr)
1295 | ast::ExprKind::Box(ref expr)
1296 | ast::ExprKind::Cast(ref expr, _)
1297 | ast::ExprKind::Field(ref expr, _)
1298 | ast::ExprKind::Try(ref expr)
1299 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1300 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1301 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1302 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1308 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1309 lists.iter().all(OverflowableItem::is_simple)
1312 pub(crate) fn can_be_overflowed_expr(
1313 context: &RewriteContext<'_>,
1318 _ if !expr.attrs.is_empty() => false,
1319 ast::ExprKind::Match(..) => {
1320 (context.use_block_indent() && args_len == 1)
1321 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1322 || context.config.overflow_delimited_expr()
1324 ast::ExprKind::If(..)
1325 | ast::ExprKind::ForLoop(..)
1326 | ast::ExprKind::Loop(..)
1327 | ast::ExprKind::While(..) => {
1328 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1331 // Handle always block-like expressions
1332 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1334 // Handle `[]` and `{}`-like expressions
1335 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1336 context.config.overflow_delimited_expr()
1337 || (context.use_block_indent() && args_len == 1)
1339 ast::ExprKind::MacCall(ref mac) => {
1341 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim().unwrap()),
1342 context.config.overflow_delimited_expr(),
1344 (Some(ast::MacDelimiter::Bracket), true)
1345 | (Some(ast::MacDelimiter::Brace), true) => true,
1346 _ => context.use_block_indent() && args_len == 1,
1350 // Handle parenthetical expressions
1351 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1352 context.use_block_indent() && args_len == 1
1355 // Handle unary-like expressions
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, _) => can_be_overflowed_expr(context, expr, args_len),
1365 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1367 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1368 ast::ExprKind::AddrOf(_, _, ref expr)
1369 | ast::ExprKind::Box(ref expr)
1370 | ast::ExprKind::Try(ref expr)
1371 | ast::ExprKind::Unary(_, ref expr)
1372 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1377 /// Returns `true` if a function call or a method call represented by the given span ends with a
1378 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1379 /// comma from macro can potentially break the code.
1380 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1381 let mut result: bool = Default::default();
1382 let mut prev_char: char = Default::default();
1383 let closing_delimiters = &[')', '}', ']'];
1385 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1387 _ if kind.is_comment() || c.is_whitespace() => continue,
1388 c if closing_delimiters.contains(&c) => {
1389 result &= !closing_delimiters.contains(&prev_char);
1391 ',' => result = true,
1392 _ => result = false,
1401 context: &RewriteContext<'_>,
1402 mut subexpr: &ast::Expr,
1405 ) -> Option<String> {
1406 debug!("rewrite_paren, shape: {:?}", shape);
1408 // Extract comments within parens.
1411 let mut pre_comment;
1412 let mut post_comment;
1413 let remove_nested_parens = context.config.remove_nested_parens();
1416 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1417 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1418 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1419 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1421 // Remove nested parens if there are no comments.
1422 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1423 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1424 span = subexpr.span;
1425 subexpr = subsubexpr;
1434 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1435 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1436 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1437 if fits_single_line {
1438 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1440 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1444 fn rewrite_paren_in_multi_line(
1445 context: &RewriteContext<'_>,
1446 subexpr: &ast::Expr,
1450 ) -> Option<String> {
1451 let nested_indent = shape.indent.block_indent(context.config);
1452 let nested_shape = Shape::indented(nested_indent, context.config);
1453 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1454 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1455 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1457 let mut result = String::with_capacity(subexpr_str.len() * 2);
1459 if !pre_comment.is_empty() {
1460 result.push_str(&nested_indent.to_string_with_newline(context.config));
1461 result.push_str(&pre_comment);
1463 result.push_str(&nested_indent.to_string_with_newline(context.config));
1464 result.push_str(&subexpr_str);
1465 if !post_comment.is_empty() {
1466 result.push_str(&nested_indent.to_string_with_newline(context.config));
1467 result.push_str(&post_comment);
1469 result.push_str(&shape.indent.to_string_with_newline(context.config));
1478 context: &RewriteContext<'_>,
1480 ) -> Option<String> {
1481 let expr_str = expr.rewrite(context, shape)?;
1483 let offset = last_line_width(&expr_str) + 1;
1484 let rhs_overhead = shape.rhs_overhead(context.config);
1485 let index_shape = if expr_str.contains('\n') {
1486 Shape::legacy(context.config.max_width(), shape.indent)
1487 .offset_left(offset)
1488 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1490 match context.config.indent_style() {
1491 IndentStyle::Block => shape
1492 .offset_left(offset)
1493 .and_then(|shape| shape.sub_width(1)),
1494 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1497 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1499 // Return if index fits in a single line.
1500 match orig_index_rw {
1501 Some(ref index_str) if !index_str.contains('\n') => {
1502 return Some(format!("{}[{}]", expr_str, index_str));
1507 // Try putting index on the next line and see if it fits in a single line.
1508 let indent = shape.indent.block_indent(context.config);
1509 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1510 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1511 let new_index_rw = index.rewrite(context, index_shape);
1512 match (orig_index_rw, new_index_rw) {
1513 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1516 indent.to_string_with_newline(context.config),
1519 (None, Some(ref new_index_str)) => Some(format!(
1522 indent.to_string_with_newline(context.config),
1525 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1530 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1531 !has_base && fields.iter().all(|field| !field.is_shorthand)
1534 fn rewrite_struct_lit<'a>(
1535 context: &RewriteContext<'_>,
1537 qself: Option<&ast::QSelf>,
1538 fields: &'a [ast::ExprField],
1539 struct_rest: &ast::StructRest,
1540 attrs: &[ast::Attribute],
1543 ) -> Option<String> {
1544 debug!("rewrite_struct_lit: shape {:?}", shape);
1546 enum StructLitField<'a> {
1547 Regular(&'a ast::ExprField),
1548 Base(&'a ast::Expr),
1553 let path_shape = shape.sub_width(2)?;
1554 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1556 let has_base_or_rest = match struct_rest {
1557 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1558 ast::StructRest::Rest(_) if fields.is_empty() => {
1559 return Some(format!("{} {{ .. }}", path_str));
1561 ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1565 // Foo { a: Foo } - indent is +3, width is -5.
1566 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1568 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1569 let body_lo = context.snippet_provider.span_after(span, "{");
1570 let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1571 && context.config.struct_field_align_threshold() > 0
1573 rewrite_with_alignment(
1577 mk_sp(body_lo, span.hi()),
1581 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1583 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1584 ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1585 ast::StructRest::None => None,
1590 let span_lo = |item: &StructLitField<'_>| match *item {
1591 StructLitField::Regular(field) => field.span().lo(),
1592 StructLitField::Base(expr) => {
1593 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1594 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1595 let pos = snippet.find_uncommented("..").unwrap();
1596 last_field_hi + BytePos(pos as u32)
1598 StructLitField::Rest(span) => span.lo(),
1600 let span_hi = |item: &StructLitField<'_>| match *item {
1601 StructLitField::Regular(field) => field.span().hi(),
1602 StructLitField::Base(expr) => expr.span.hi(),
1603 StructLitField::Rest(span) => span.hi(),
1605 let rewrite = |item: &StructLitField<'_>| match *item {
1606 StructLitField::Regular(field) => {
1607 // The 1 taken from the v_budget is for the comma.
1608 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1610 StructLitField::Base(expr) => {
1612 expr.rewrite(context, v_shape.offset_left(2)?)
1613 .map(|s| format!("..{}", s))
1615 StructLitField::Rest(_) => Some("..".to_owned()),
1618 let items = itemize_list(
1619 context.snippet_provider,
1630 let item_vec = items.collect::<Vec<_>>();
1632 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1633 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1635 let ends_with_comma = span_ends_with_comma(context, span);
1636 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1638 let fmt = struct_lit_formatting(
1642 force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1645 write_list(&item_vec, &fmt)?
1649 wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1650 Some(format!("{} {{{}}}", path_str, fields_str))
1652 // FIXME if context.config.indent_style() == Visual, but we run out
1653 // of space, we should fall back to BlockIndent.
1656 pub(crate) fn wrap_struct_field(
1657 context: &RewriteContext<'_>,
1658 attrs: &[ast::Attribute],
1661 nested_shape: Shape,
1662 one_line_width: usize,
1663 ) -> Option<String> {
1664 let should_vertical = context.config.indent_style() == IndentStyle::Block
1665 && (fields_str.contains('\n')
1666 || !context.config.struct_lit_single_line()
1667 || fields_str.len() > one_line_width);
1669 let inner_attrs = &inner_attributes(attrs);
1670 if inner_attrs.is_empty() {
1671 if should_vertical {
1674 nested_shape.indent.to_string_with_newline(context.config),
1676 shape.indent.to_string_with_newline(context.config)
1679 // One liner or visual indent.
1680 Some(format!(" {} ", fields_str))
1685 nested_shape.indent.to_string_with_newline(context.config),
1686 inner_attrs.rewrite(context, shape)?,
1687 nested_shape.indent.to_string_with_newline(context.config),
1689 shape.indent.to_string_with_newline(context.config)
1694 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1695 colon_spaces(config)
1698 pub(crate) fn rewrite_field(
1699 context: &RewriteContext<'_>,
1700 field: &ast::ExprField,
1702 prefix_max_width: usize,
1703 ) -> Option<String> {
1704 if contains_skip(&field.attrs) {
1705 return Some(context.snippet(field.span()).to_owned());
1707 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1708 if !attrs_str.is_empty() {
1709 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1711 let name = context.snippet(field.ident.span);
1712 if field.is_shorthand {
1713 Some(attrs_str + name)
1715 let mut separator = String::from(struct_lit_field_separator(context.config));
1716 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1717 separator.push(' ');
1719 let overhead = name.len() + separator.len();
1720 let expr_shape = shape.offset_left(overhead)?;
1721 let expr = field.expr.rewrite(context, expr_shape);
1724 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1725 Some(attrs_str + name)
1727 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1729 let expr_offset = shape.indent.block_indent(context.config);
1732 .rewrite(context, Shape::indented(expr_offset, context.config));
1738 expr_offset.to_string(context.config),
1747 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1748 context: &RewriteContext<'_>,
1749 mut items: impl Iterator<Item = &'a T>,
1752 is_singleton_tuple: bool,
1753 ) -> Option<String> {
1754 // In case of length 1, need a trailing comma
1755 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1756 if is_singleton_tuple {
1758 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1762 .rewrite(context, nested_shape)
1763 .map(|s| format!("({},)", s));
1766 let list_lo = context.snippet_provider.span_after(span, "(");
1767 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1768 let items = itemize_list(
1769 context.snippet_provider,
1773 |item| item.span().lo(),
1774 |item| item.span().hi(),
1775 |item| item.rewrite(context, nested_shape),
1777 span.hi() - BytePos(1),
1780 let item_vec: Vec<_> = items.collect();
1781 let tactic = definitive_tactic(
1783 ListTactic::HorizontalVertical,
1787 let fmt = ListFormatting::new(nested_shape, context.config)
1789 .ends_with_newline(false);
1790 let list_str = write_list(&item_vec, &fmt)?;
1792 Some(format!("({})", list_str))
1795 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1796 context: &'a RewriteContext<'_>,
1797 items: impl Iterator<Item = &'a T>,
1800 is_singleton_tuple: bool,
1801 ) -> Option<String> {
1802 debug!("rewrite_tuple {:?}", shape);
1803 if context.use_block_indent() {
1804 // We use the same rule as function calls for rewriting tuples.
1805 let force_tactic = if context.inside_macro() {
1806 if span_ends_with_comma(context, span) {
1807 Some(SeparatorTactic::Always)
1809 Some(SeparatorTactic::Never)
1811 } else if is_singleton_tuple {
1812 Some(SeparatorTactic::Always)
1816 overflow::rewrite_with_parens(
1822 context.config.fn_call_width(),
1826 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1830 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1831 context: &RewriteContext<'_>,
1835 ) -> Option<String> {
1837 .rewrite(context, shape.offset_left(prefix.len())?)
1838 .map(|r| format!("{}{}", prefix, r))
1841 // FIXME: this is probably not correct for multi-line Rewrites. we should
1842 // subtract suffix.len() from the last line budget, not the first!
1843 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1844 context: &RewriteContext<'_>,
1848 ) -> Option<String> {
1850 .rewrite(context, shape.sub_width(suffix.len())?)
1857 fn rewrite_unary_op(
1858 context: &RewriteContext<'_>,
1862 ) -> Option<String> {
1863 // For some reason, an UnOp is not spanned like BinOp!
1864 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1867 pub(crate) enum RhsAssignKind<'ast> {
1868 Expr(&'ast ast::ExprKind, Span),
1873 impl<'ast> RhsAssignKind<'ast> {
1874 // TODO(calebcartwright)
1875 // Preemptive addition for handling RHS with chains, not yet utilized.
1876 // It may make more sense to construct the chain first and then check
1877 // whether there are actually chain elements.
1879 fn is_chain(&self) -> bool {
1881 RhsAssignKind::Expr(kind, _) => {
1884 ast::ExprKind::Try(..)
1885 | ast::ExprKind::Field(..)
1886 | ast::ExprKind::MethodCall(..)
1887 | ast::ExprKind::Await(_)
1895 fn rewrite_assignment(
1896 context: &RewriteContext<'_>,
1899 op: Option<&ast::BinOp>,
1901 ) -> Option<String> {
1902 let operator_str = match op {
1903 Some(op) => context.snippet(op.span),
1907 // 1 = space between lhs and operator.
1908 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1909 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1915 &RhsAssignKind::Expr(&rhs.kind, rhs.span),
1920 /// Controls where to put the rhs.
1921 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1922 pub(crate) enum RhsTactics {
1925 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1926 ForceNextLineWithoutIndent,
1927 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1932 // The left hand side must contain everything up to, and including, the
1933 // assignment operator.
1934 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1935 context: &RewriteContext<'_>,
1938 rhs_kind: &RhsAssignKind<'_>,
1940 ) -> Option<String> {
1941 rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
1944 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1945 context: &RewriteContext<'_>,
1949 rhs_kind: &RhsAssignKind<'_>,
1950 rhs_tactics: RhsTactics,
1951 ) -> Option<String> {
1952 let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1953 shape.indent.width()
1957 // 1 = space between operator and rhs.
1958 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1960 offset: shape.offset + last_line_width + 1,
1963 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1964 lhs.trim_end().len() > offset + 1
1973 ex.rewrite(context, orig_shape),
1980 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1981 context: &RewriteContext<'_>,
1985 rhs_kind: &RhsAssignKind<'_>,
1986 rhs_tactics: RhsTactics,
1987 ) -> Option<String> {
1988 let lhs = lhs.into();
1989 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
1993 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
1994 context: &RewriteContext<'_>,
1998 rhs_kind: &RhsAssignKind<'_>,
1999 rhs_tactics: RhsTactics,
2002 ) -> Option<String> {
2003 let lhs = lhs.into();
2004 let contains_comment = contains_comment(context.snippet(between_span));
2005 let shape = if contains_comment {
2006 shape.block_left(context.config.tab_spaces())?
2010 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2012 if contains_comment {
2013 let rhs = rhs.trim_start();
2014 combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2020 fn choose_rhs<R: Rewrite>(
2021 context: &RewriteContext<'_>,
2024 orig_rhs: Option<String>,
2025 _rhs_kind: &RhsAssignKind<'_>,
2026 rhs_tactics: RhsTactics,
2027 has_rhs_comment: bool,
2028 ) -> Option<String> {
2030 Some(ref new_str) if new_str.is_empty() => Some(String::new()),
2032 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
2034 Some(format!(" {}", new_str))
2037 // Expression did not fit on the same line as the identifier.
2038 // Try splitting the line and see if that works better.
2039 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
2040 let new_rhs = expr.rewrite(context, new_shape);
2041 let new_indent_str = &shape
2043 .block_indent(context.config)
2044 .to_string_with_newline(context.config);
2045 let before_space_str = if has_rhs_comment { "" } else { " " };
2047 match (orig_rhs, new_rhs) {
2048 (Some(ref orig_rhs), Some(ref new_rhs))
2049 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2052 Some(format!("{}{}", before_space_str, orig_rhs))
2054 (Some(ref orig_rhs), Some(ref new_rhs))
2055 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2057 Some(format!("{}{}", new_indent_str, new_rhs))
2059 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2060 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2061 let shape = shape.infinite_width();
2062 expr.rewrite(context, shape)
2063 .map(|s| format!("{}{}", before_space_str, s))
2065 (None, None) => None,
2066 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2072 fn shape_from_rhs_tactic(
2073 context: &RewriteContext<'_>,
2075 rhs_tactic: RhsTactics,
2076 ) -> Option<Shape> {
2078 RhsTactics::ForceNextLineWithoutIndent => shape
2079 .with_max_width(context.config)
2080 .sub_width(shape.indent.width()),
2081 RhsTactics::Default | RhsTactics::AllowOverflow => {
2082 Shape::indented(shape.indent.block_indent(context.config), context.config)
2083 .sub_width(shape.rhs_overhead(context.config))
2088 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2089 /// original's line formatting.
2091 /// It is considered better if:
2092 /// 1. the tactic is ForceNextLineWithoutIndent
2093 /// 2. next_line_rhs doesn't have newlines
2094 /// 3. the original line has more newlines than next_line_rhs
2095 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2097 pub(crate) fn prefer_next_line(
2099 next_line_rhs: &str,
2100 rhs_tactics: RhsTactics,
2102 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2103 || !next_line_rhs.contains('\n')
2104 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2105 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2106 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2107 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2110 fn rewrite_expr_addrof(
2111 context: &RewriteContext<'_>,
2112 borrow_kind: ast::BorrowKind,
2113 mutability: ast::Mutability,
2116 ) -> Option<String> {
2117 let operator_str = match (mutability, borrow_kind) {
2118 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2119 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2120 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2121 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2123 rewrite_unary_prefix(context, operator_str, expr, shape)
2126 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2128 ast::ExprKind::MethodCall(..) => true,
2129 ast::ExprKind::AddrOf(_, _, ref expr)
2130 | ast::ExprKind::Box(ref expr)
2131 | ast::ExprKind::Cast(ref expr, _)
2132 | ast::ExprKind::Try(ref expr)
2133 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2140 use super::last_line_offsetted;
2143 fn test_last_line_offsetted() {
2144 let lines = "one\n two";
2145 assert_eq!(last_line_offsetted(2, lines), true);
2146 assert_eq!(last_line_offsetted(4, lines), false);
2147 assert_eq!(last_line_offsetted(6, lines), false);
2149 let lines = "one two";
2150 assert_eq!(last_line_offsetted(2, lines), false);
2151 assert_eq!(last_line_offsetted(0, lines), false);
2153 let lines = "\ntwo";
2154 assert_eq!(last_line_offsetted(2, lines), false);
2155 assert_eq!(last_line_offsetted(0, lines), false);
2157 let lines = "one\n two three";
2158 assert_eq!(last_line_offsetted(2, lines), true);
2159 let lines = "one\n two three";
2160 assert_eq!(last_line_offsetted(2, lines), false);