4 use itertools::Itertools;
5 use rustc_ast::token::{Delimiter, LitKind};
6 use rustc_ast::{ast, ptr, token};
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, filtered_str_fits, first_line_ends_with,
33 inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
34 semicolon_for_expr, 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(token_lit) => {
79 if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
82 if let LitKind::StrRaw(_) = token_lit.kind {
83 Some(context.snippet(expr.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, 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(ref cl) => closures::rewrite_closure(
218 ast::ExprKind::Try(..)
219 | ast::ExprKind::Field(..)
220 | ast::ExprKind::MethodCall(..)
221 | ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
222 ast::ExprKind::MacCall(ref mac) => {
223 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
225 context.snippet(expr.span).to_owned(),
226 context.config.max_width(),
231 ast::ExprKind::Ret(None) => Some("return".to_owned()),
232 ast::ExprKind::Ret(Some(ref expr)) => {
233 rewrite_unary_prefix(context, "return ", &**expr, shape)
235 ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()),
236 ast::ExprKind::Yeet(Some(ref expr)) => {
237 rewrite_unary_prefix(context, "do yeet ", &**expr, shape)
239 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
240 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
241 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
243 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
246 PairParts::infix(" as "),
249 SeparatorPlace::Front,
251 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
254 PairParts::infix(": "),
257 SeparatorPlace::Back,
259 ast::ExprKind::Index(ref expr, ref index) => {
260 rewrite_index(&**expr, &**index, context, shape)
262 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
265 PairParts::new("[", "; ", "]"),
268 SeparatorPlace::Back,
270 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
271 let delim = match limits {
272 ast::RangeLimits::HalfOpen => "..",
273 ast::RangeLimits::Closed => "..=",
276 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
278 ast::ExprKind::Lit(token_lit) => match token_lit.kind {
279 token::LitKind::Float if token_lit.suffix.is_none() => {
280 context.snippet(lhs.span).ends_with('.')
284 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
289 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
290 // Don't format `.. ..` into `....`, which is invalid.
292 // This check is unnecessary for `lhs`, because a range
293 // starting from another range needs parentheses as `(x ..) ..`
294 // (`x .. ..` is a range from `x` to `..`).
295 matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
298 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
299 let space_if = |b: bool| if b { " " } else { "" };
303 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
305 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
309 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
310 (Some(lhs), Some(rhs)) => {
311 let sp_delim = if context.config.spaces_around_ranges() {
312 format!(" {} ", delim)
314 default_sp_delim(Some(lhs), Some(rhs))
319 PairParts::infix(&sp_delim),
322 context.config.binop_separator(),
325 (None, Some(rhs)) => {
326 let sp_delim = if context.config.spaces_around_ranges() {
327 format!("{} ", delim)
329 default_sp_delim(None, Some(rhs))
331 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
333 (Some(lhs), None) => {
334 let sp_delim = if context.config.spaces_around_ranges() {
335 format!(" {}", delim)
337 default_sp_delim(Some(lhs), None)
339 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
341 (None, None) => Some(delim.to_owned()),
344 // We do not format these expressions yet, but they should still
345 // satisfy our width restrictions.
346 // Style Guide RFC for InlineAsm variant pending
347 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
348 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
349 ast::ExprKind::TryBlock(ref block) => {
350 if let rw @ Some(_) =
351 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
356 let budget = shape.width.saturating_sub(9);
365 Shape::legacy(budget, shape.indent)
370 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
371 let mover = if capture_by == ast::CaptureBy::Value {
376 if let rw @ Some(_) = rewrite_single_line_block(
378 format!("{}{}", "async ", mover).as_str(),
387 let budget = shape.width.saturating_sub(6);
397 Shape::legacy(budget, shape.indent)
402 ast::ExprKind::Underscore => Some("_".to_owned()),
403 ast::ExprKind::FormatArgs(..) | ast::ExprKind::IncludedBytes(..) => {
404 // These do not occur in the AST because macros aren't expanded.
407 ast::ExprKind::Err => None,
411 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
412 .and_then(|expr_str| {
413 let attrs = outer_attributes(&expr.attrs);
414 let attrs_str = attrs.rewrite(context, shape)?;
416 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
419 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
423 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
425 exprs: impl Iterator<Item = &'a T>,
427 context: &'a RewriteContext<'_>,
429 force_separator_tactic: Option<SeparatorTactic>,
430 delim_token: Option<Delimiter>,
431 ) -> Option<String> {
432 overflow::rewrite_with_square_brackets(
438 force_separator_tactic,
443 fn rewrite_empty_block(
444 context: &RewriteContext<'_>,
446 attrs: Option<&[ast::Attribute]>,
447 label: Option<ast::Label>,
450 ) -> Option<String> {
451 if block_has_statements(block) {
455 let label_str = rewrite_label(label);
456 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
460 if !block_contains_comment(context, block) && shape.width >= 2 {
461 return Some(format!("{}{}{{}}", prefix, label_str));
464 // If a block contains only a single-line comment, then leave it on one line.
465 let user_str = context.snippet(block.span);
466 let user_str = user_str.trim();
467 if user_str.starts_with('{') && user_str.ends_with('}') {
468 let comment_str = user_str[1..user_str.len() - 1].trim();
469 if block.stmts.is_empty()
470 && !comment_str.contains('\n')
471 && !comment_str.starts_with("//")
472 && comment_str.len() + 4 <= shape.width
474 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
481 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
482 Some(match block.rules {
483 ast::BlockCheckMode::Unsafe(..) => {
484 let snippet = context.snippet(block.span);
485 let open_pos = snippet.find_uncommented("{")?;
486 // Extract comment between unsafe and block start.
487 let trimmed = &snippet[6..open_pos].trim();
489 if !trimmed.is_empty() {
490 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
491 let budget = shape.width.checked_sub(9)?;
497 Shape::legacy(budget, shape.indent + 7),
505 ast::BlockCheckMode::Default => String::new(),
509 fn rewrite_single_line_block(
510 context: &RewriteContext<'_>,
513 attrs: Option<&[ast::Attribute]>,
514 label: Option<ast::Label>,
516 ) -> Option<String> {
517 if is_simple_block(context, block, attrs) {
518 let expr_shape = shape.offset_left(last_line_width(prefix))?;
519 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
520 let label_str = rewrite_label(label);
521 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
522 if result.len() <= shape.width && !result.contains('\n') {
529 pub(crate) fn rewrite_block_with_visitor(
530 context: &RewriteContext<'_>,
533 attrs: Option<&[ast::Attribute]>,
534 label: Option<ast::Label>,
537 ) -> Option<String> {
538 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
542 let mut visitor = FmtVisitor::from_context(context);
543 visitor.block_indent = shape.indent;
544 visitor.is_if_else_block = context.is_if_else_block();
545 match (block.rules, label) {
546 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
547 let snippet = context.snippet(block.span);
548 let open_pos = snippet.find_uncommented("{")?;
549 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
551 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
554 let inner_attrs = attrs.map(inner_attributes);
555 let label_str = rewrite_label(label);
556 visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
557 let visitor_context = visitor.get_context();
561 .append(&mut visitor_context.skipped_range.borrow_mut());
562 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
565 impl Rewrite for ast::Block {
566 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
567 rewrite_block(self, None, None, context, shape)
573 attrs: Option<&[ast::Attribute]>,
574 label: Option<ast::Label>,
575 context: &RewriteContext<'_>,
577 ) -> Option<String> {
578 let prefix = block_prefix(context, block, shape)?;
580 // shape.width is used only for the single line case: either the empty block `{}`,
581 // or an unsafe expression `unsafe { e }`.
582 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
586 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
587 if let Some(ref result_str) = result {
588 if result_str.lines().count() <= 3 {
589 if let rw @ Some(_) =
590 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
600 // Rewrite condition if the given expression has one.
601 pub(crate) fn rewrite_cond(
602 context: &RewriteContext<'_>,
605 ) -> Option<String> {
607 ast::ExprKind::Match(ref cond, _) => {
609 let cond_shape = match context.config.indent_style() {
610 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
611 IndentStyle::Block => shape.offset_left(8)?,
613 cond.rewrite(context, cond_shape)
615 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
617 String::from("\n") + &shape.indent.block_only().to_string(context.config);
619 .rewrite_cond(context, shape, &alt_block_sep)
625 // Abstraction over control flow expressions
627 struct ControlFlow<'a> {
628 cond: Option<&'a ast::Expr>,
629 block: &'a ast::Block,
630 else_block: Option<&'a ast::Expr>,
631 label: Option<ast::Label>,
632 pat: Option<&'a ast::Pat>,
636 allow_single_line: bool,
637 // HACK: `true` if this is an `if` expression in an `else if`.
642 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
644 ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
649 // FIXME: Refactor this.
650 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
652 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
653 let (pat, cond) = extract_pats_and_cond(cond);
654 Some(ControlFlow::new_if(
658 else_block.as_ref().map(|e| &**e),
659 expr_type == ExprType::SubExpression,
664 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
665 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
667 ast::ExprKind::Loop(ref block, label, _) => {
668 Some(ControlFlow::new_loop(block, label, expr.span))
670 ast::ExprKind::While(ref cond, ref block, label) => {
671 let (pat, cond) = extract_pats_and_cond(cond);
672 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
678 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
679 pat.map_or("", |_| "let")
682 impl<'a> ControlFlow<'a> {
685 pat: Option<&'a ast::Pat>,
686 block: &'a ast::Block,
687 else_block: Option<&'a ast::Expr>,
688 allow_single_line: bool,
691 ) -> ControlFlow<'a> {
692 let matcher = choose_matcher(pat);
708 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
718 allow_single_line: false,
725 pat: Option<&'a ast::Pat>,
727 block: &'a ast::Block,
728 label: Option<ast::Label>,
730 ) -> ControlFlow<'a> {
731 let matcher = choose_matcher(pat);
741 allow_single_line: false,
750 block: &'a ast::Block,
751 label: Option<ast::Label>,
753 ) -> ControlFlow<'a> {
763 allow_single_line: false,
769 fn rewrite_single_line(
772 context: &RewriteContext<'_>,
774 ) -> Option<String> {
775 assert!(self.allow_single_line);
776 let else_block = self.else_block?;
777 let fixed_cost = self.keyword.len() + " { } else { }".len();
779 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
780 if !is_simple_block(context, self.block, None)
781 || !is_simple_block(context, else_node, None)
782 || pat_expr_str.contains('\n')
787 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
788 let expr = &self.block.stmts[0];
789 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
791 let new_width = new_width.checked_sub(if_str.len())?;
792 let else_expr = &else_node.stmts[0];
793 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
795 if if_str.contains('\n') || else_str.contains('\n') {
799 let result = format!(
800 "{} {} {{ {} }} else {{ {} }}",
801 self.keyword, pat_expr_str, if_str, else_str
804 if result.len() <= width {
813 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
815 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
816 let mut leading_whitespaces = 0;
817 for c in pat_str.chars().rev() {
820 _ if c.is_whitespace() => leading_whitespaces += 1,
821 _ => leading_whitespaces = 0,
824 leading_whitespaces > start_column
827 impl<'a> ControlFlow<'a> {
830 context: &RewriteContext<'_>,
834 ) -> Option<String> {
835 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
837 let cond_shape = shape.offset_left(offset)?;
838 if let Some(pat) = self.pat {
839 let matcher = if self.matcher.is_empty() {
840 self.matcher.to_owned()
842 format!("{} ", self.matcher)
844 let pat_shape = cond_shape
845 .offset_left(matcher.len())?
846 .sub_width(self.connector.len())?;
847 let pat_string = pat.rewrite(context, pat_shape)?;
848 let comments_lo = context
850 .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
851 let comments_span = mk_sp(comments_lo, expr.span.lo());
852 return rewrite_assign_rhs_with_comments(
854 &format!("{}{}{}", matcher, pat_string, self.connector),
857 &RhsAssignKind::Expr(&expr.kind, expr.span),
864 let expr_rw = expr.rewrite(context, cond_shape);
865 // The expression may (partially) fit on the current line.
866 // We do not allow splitting between `if` and condition.
867 if self.keyword == "if" || expr_rw.is_some() {
871 // The expression won't fit on the current line, jump to next.
872 let nested_shape = shape
873 .block_indent(context.config.tab_spaces())
874 .with_max_width(context.config);
875 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
876 expr.rewrite(context, nested_shape)
877 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
882 context: &RewriteContext<'_>,
885 ) -> Option<(String, usize)> {
886 // Do not take the rhs overhead from the upper expressions into account
887 // when rewriting pattern.
888 let new_width = context.budget(shape.used_width());
889 let fresh_shape = Shape {
893 let constr_shape = if self.nested_if {
894 // We are part of an if-elseif-else chain. Our constraints are tightened.
895 // 7 = "} else " .len()
896 fresh_shape.offset_left(7)?
901 let label_string = rewrite_label(self.label);
902 // 1 = space after keyword.
903 let offset = self.keyword.len() + label_string.len() + 1;
905 let pat_expr_string = match self.cond {
906 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
907 None => String::new(),
911 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
917 let one_line_budget = context
920 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
921 let force_newline_brace = (pat_expr_string.contains('\n')
922 || pat_expr_string.len() > one_line_budget)
923 && (!last_line_extendable(&pat_expr_string)
924 || last_line_offsetted(shape.used_width(), &pat_expr_string));
926 // Try to format if-else on single line.
927 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
928 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
930 if let Some(cond_str) = trial {
931 if cond_str.len() <= context.config.single_line_if_else_max_width() {
932 return Some((cond_str, 0));
937 let cond_span = if let Some(cond) = self.cond {
940 mk_sp(self.block.span.lo(), self.block.span.lo())
943 // `for event in event`
944 // Do not include label in the span.
947 .map_or(self.span.lo(), |label| label.ident.span.hi());
948 let between_kwd_cond = mk_sp(
951 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
952 if self.pat.is_none() {
954 } else if self.matcher.is_empty() {
955 self.pat.unwrap().span.lo()
959 .span_before(self.span, self.matcher.trim())
963 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
965 let after_cond_comment =
966 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
968 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
970 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
971 || force_newline_brace
978 let used_width = if pat_expr_string.contains('\n') {
979 last_line_width(&pat_expr_string)
981 // 2 = spaces after keyword and condition.
982 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
990 between_kwd_cond_comment.as_ref().map_or(
991 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
999 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1006 impl<'a> Rewrite for ControlFlow<'a> {
1007 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1008 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1010 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1011 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1012 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1013 if used_width == 0 {
1014 return Some(cond_str);
1017 let block_width = shape.width.saturating_sub(used_width);
1018 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1019 // we should avoid the single line case.
1020 let block_width = if self.else_block.is_some() || self.nested_if {
1025 let block_shape = Shape {
1030 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1032 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1033 context.is_if_else_block.replace(old_val);
1037 let mut result = format!("{}{}", cond_str, block_str);
1039 if let Some(else_block) = self.else_block {
1040 let shape = Shape::indented(shape.indent, context.config);
1041 let mut last_in_chain = false;
1042 let rewrite = match else_block.kind {
1043 // If the else expression is another if-else expression, prevent it
1044 // from being formatted on a single line.
1045 // Note how we're passing the original shape, as the
1046 // cost of "else" should not cascade.
1047 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1048 let (pats, cond) = extract_pats_and_cond(cond);
1049 ControlFlow::new_if(
1053 next_else_block.as_ref().map(|e| &**e),
1056 mk_sp(else_block.span.lo(), self.span.hi()),
1058 .rewrite(context, shape)
1061 last_in_chain = true;
1062 // When rewriting a block, the width is only used for single line
1063 // blocks, passing 1 lets us avoid that.
1064 let else_shape = Shape {
1065 width: min(1, shape.width),
1068 format_expr(else_block, ExprType::Statement, context, else_shape)
1072 let between_kwd_else_block = mk_sp(
1073 self.block.span.hi(),
1076 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1078 let between_kwd_else_block_comment =
1079 extract_comment(between_kwd_else_block, context, shape);
1081 let after_else = mk_sp(
1084 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1085 else_block.span.lo(),
1087 let after_else_comment = extract_comment(after_else, context, shape);
1089 let between_sep = match context.config.control_brace_style() {
1090 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1093 ControlBraceStyle::AlwaysSameLine => " ",
1095 let after_sep = match context.config.control_brace_style() {
1096 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1100 result.push_str(&format!(
1102 between_kwd_else_block_comment
1104 .map_or(between_sep, |s| &**s),
1105 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1107 result.push_str(&rewrite?);
1114 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1116 Some(label) => Cow::from(format!("{}: ", label.ident)),
1117 None => Cow::from(""),
1121 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1122 match rewrite_missing_comment(span, shape, context) {
1123 Some(ref comment) if !comment.is_empty() => Some(format!(
1124 "{indent}{}{indent}",
1126 indent = shape.indent.to_string_with_newline(context.config)
1132 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1133 contains_comment(context.snippet(block.span))
1136 // Checks that a block contains no statements, an expression and no comments or
1138 // FIXME: incorrectly returns false when comment is contained completely within
1140 pub(crate) fn is_simple_block(
1141 context: &RewriteContext<'_>,
1143 attrs: Option<&[ast::Attribute]>,
1145 block.stmts.len() == 1
1146 && stmt_is_expr(&block.stmts[0])
1147 && !block_contains_comment(context, block)
1148 && attrs.map_or(true, |a| a.is_empty())
1151 /// Checks whether a block contains at most one statement or expression, and no
1152 /// comments or attributes.
1153 pub(crate) fn is_simple_block_stmt(
1154 context: &RewriteContext<'_>,
1156 attrs: Option<&[ast::Attribute]>,
1158 block.stmts.len() <= 1
1159 && !block_contains_comment(context, block)
1160 && attrs.map_or(true, |a| a.is_empty())
1163 fn block_has_statements(block: &ast::Block) -> bool {
1167 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1170 /// Checks whether a block contains no statements, expressions, comments, or
1171 /// inner attributes.
1172 pub(crate) fn is_empty_block(
1173 context: &RewriteContext<'_>,
1175 attrs: Option<&[ast::Attribute]>,
1177 !block_has_statements(block)
1178 && !block_contains_comment(context, block)
1179 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1182 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1183 matches!(stmt.kind, ast::StmtKind::Expr(..))
1186 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1187 matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1190 pub(crate) fn rewrite_literal(
1191 context: &RewriteContext<'_>,
1192 token_lit: token::Lit,
1195 ) -> Option<String> {
1196 match token_lit.kind {
1197 token::LitKind::Str => rewrite_string_lit(context, span, shape),
1198 token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape),
1200 context.snippet(span).to_owned(),
1201 context.config.max_width(),
1207 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1208 let string_lit = context.snippet(span);
1210 if !context.config.format_strings() {
1214 .all(|line| line.ends_with('\\'))
1215 && context.config.version() == Version::Two
1217 return Some(string_lit.to_owned());
1219 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1223 // Remove the quote characters.
1224 let str_lit = &string_lit[1..string_lit.len() - 1];
1228 &StringFormat::new(shape.visual_indent(0), context.config),
1229 shape.width.saturating_sub(2),
1234 context: &RewriteContext<'_>,
1235 token_lit: token::Lit,
1238 ) -> Option<String> {
1239 let symbol = token_lit.symbol.as_str();
1241 if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1242 let hex_lit = match context.config.hex_literal_case() {
1243 HexLiteralCase::Preserve => None,
1244 HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1245 HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1247 if let Some(hex_lit) = hex_lit {
1252 token_lit.suffix.map_or(String::new(), |s| s.to_string())
1254 context.config.max_width(),
1261 context.snippet(span).to_owned(),
1262 context.config.max_width(),
1267 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1268 if context.inside_macro() {
1269 if span_ends_with_comma(context, span) {
1270 Some(SeparatorTactic::Always)
1272 Some(SeparatorTactic::Never)
1279 pub(crate) fn rewrite_call(
1280 context: &RewriteContext<'_>,
1282 args: &[ptr::P<ast::Expr>],
1285 ) -> Option<String> {
1286 overflow::rewrite_with_parens(
1292 context.config.fn_call_width(),
1293 choose_separator_tactic(context, span),
1297 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1299 ast::ExprKind::Lit(..) => true,
1300 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1301 ast::ExprKind::AddrOf(_, _, ref expr)
1302 | ast::ExprKind::Box(ref expr)
1303 | ast::ExprKind::Cast(ref expr, _)
1304 | ast::ExprKind::Field(ref expr, _)
1305 | ast::ExprKind::Try(ref expr)
1306 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1307 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1308 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1309 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1315 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1316 lists.iter().all(OverflowableItem::is_simple)
1319 pub(crate) fn can_be_overflowed_expr(
1320 context: &RewriteContext<'_>,
1325 _ if !expr.attrs.is_empty() => false,
1326 ast::ExprKind::Match(..) => {
1327 (context.use_block_indent() && args_len == 1)
1328 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1329 || context.config.overflow_delimited_expr()
1331 ast::ExprKind::If(..)
1332 | ast::ExprKind::ForLoop(..)
1333 | ast::ExprKind::Loop(..)
1334 | ast::ExprKind::While(..) => {
1335 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1338 // Handle always block-like expressions
1339 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1341 // Handle `[]` and `{}`-like expressions
1342 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1343 context.config.overflow_delimited_expr()
1344 || (context.use_block_indent() && args_len == 1)
1346 ast::ExprKind::MacCall(ref mac) => {
1348 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim.to_token()),
1349 context.config.overflow_delimited_expr(),
1351 (Some(ast::MacDelimiter::Bracket), true)
1352 | (Some(ast::MacDelimiter::Brace), true) => true,
1353 _ => context.use_block_indent() && args_len == 1,
1357 // Handle parenthetical expressions
1358 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1359 context.use_block_indent() && args_len == 1
1362 // Handle unary-like expressions
1363 ast::ExprKind::AddrOf(_, _, ref expr)
1364 | ast::ExprKind::Box(ref expr)
1365 | ast::ExprKind::Try(ref expr)
1366 | ast::ExprKind::Unary(_, ref expr)
1367 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1372 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1374 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1375 ast::ExprKind::AddrOf(_, _, ref expr)
1376 | ast::ExprKind::Box(ref expr)
1377 | ast::ExprKind::Try(ref expr)
1378 | ast::ExprKind::Unary(_, ref expr)
1379 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1384 /// Returns `true` if a function call or a method call represented by the given span ends with a
1385 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1386 /// comma from macro can potentially break the code.
1387 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1388 let mut result: bool = Default::default();
1389 let mut prev_char: char = Default::default();
1390 let closing_delimiters = &[')', '}', ']'];
1392 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1394 _ if kind.is_comment() || c.is_whitespace() => continue,
1395 c if closing_delimiters.contains(&c) => {
1396 result &= !closing_delimiters.contains(&prev_char);
1398 ',' => result = true,
1399 _ => result = false,
1408 context: &RewriteContext<'_>,
1409 mut subexpr: &ast::Expr,
1412 ) -> Option<String> {
1413 debug!("rewrite_paren, shape: {:?}", shape);
1415 // Extract comments within parens.
1418 let mut pre_comment;
1419 let mut post_comment;
1420 let remove_nested_parens = context.config.remove_nested_parens();
1423 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1424 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1425 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1426 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1428 // Remove nested parens if there are no comments.
1429 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1430 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1431 span = subexpr.span;
1432 subexpr = subsubexpr;
1441 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1442 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1443 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1444 if fits_single_line {
1445 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1447 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1451 fn rewrite_paren_in_multi_line(
1452 context: &RewriteContext<'_>,
1453 subexpr: &ast::Expr,
1457 ) -> Option<String> {
1458 let nested_indent = shape.indent.block_indent(context.config);
1459 let nested_shape = Shape::indented(nested_indent, context.config);
1460 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1461 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1462 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1464 let mut result = String::with_capacity(subexpr_str.len() * 2);
1466 if !pre_comment.is_empty() {
1467 result.push_str(&nested_indent.to_string_with_newline(context.config));
1468 result.push_str(&pre_comment);
1470 result.push_str(&nested_indent.to_string_with_newline(context.config));
1471 result.push_str(&subexpr_str);
1472 if !post_comment.is_empty() {
1473 result.push_str(&nested_indent.to_string_with_newline(context.config));
1474 result.push_str(&post_comment);
1476 result.push_str(&shape.indent.to_string_with_newline(context.config));
1485 context: &RewriteContext<'_>,
1487 ) -> Option<String> {
1488 let expr_str = expr.rewrite(context, shape)?;
1490 let offset = last_line_width(&expr_str) + 1;
1491 let rhs_overhead = shape.rhs_overhead(context.config);
1492 let index_shape = if expr_str.contains('\n') {
1493 Shape::legacy(context.config.max_width(), shape.indent)
1494 .offset_left(offset)
1495 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1497 match context.config.indent_style() {
1498 IndentStyle::Block => shape
1499 .offset_left(offset)
1500 .and_then(|shape| shape.sub_width(1)),
1501 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1504 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1506 // Return if index fits in a single line.
1507 match orig_index_rw {
1508 Some(ref index_str) if !index_str.contains('\n') => {
1509 return Some(format!("{}[{}]", expr_str, index_str));
1514 // Try putting index on the next line and see if it fits in a single line.
1515 let indent = shape.indent.block_indent(context.config);
1516 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1517 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1518 let new_index_rw = index.rewrite(context, index_shape);
1519 match (orig_index_rw, new_index_rw) {
1520 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1523 indent.to_string_with_newline(context.config),
1526 (None, Some(ref new_index_str)) => Some(format!(
1529 indent.to_string_with_newline(context.config),
1532 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1537 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1538 !has_base && fields.iter().all(|field| !field.is_shorthand)
1541 fn rewrite_struct_lit<'a>(
1542 context: &RewriteContext<'_>,
1544 qself: &Option<ptr::P<ast::QSelf>>,
1545 fields: &'a [ast::ExprField],
1546 struct_rest: &ast::StructRest,
1547 attrs: &[ast::Attribute],
1550 ) -> Option<String> {
1551 debug!("rewrite_struct_lit: shape {:?}", shape);
1553 enum StructLitField<'a> {
1554 Regular(&'a ast::ExprField),
1555 Base(&'a ast::Expr),
1560 let path_shape = shape.sub_width(2)?;
1561 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1563 let has_base_or_rest = match struct_rest {
1564 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1565 ast::StructRest::Rest(_) if fields.is_empty() => {
1566 return Some(format!("{} {{ .. }}", path_str));
1568 ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1572 // Foo { a: Foo } - indent is +3, width is -5.
1573 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1575 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1576 let body_lo = context.snippet_provider.span_after(span, "{");
1577 let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1578 && context.config.struct_field_align_threshold() > 0
1580 rewrite_with_alignment(
1584 mk_sp(body_lo, span.hi()),
1588 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1590 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1591 ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1592 ast::StructRest::None => None,
1597 let span_lo = |item: &StructLitField<'_>| match *item {
1598 StructLitField::Regular(field) => field.span().lo(),
1599 StructLitField::Base(expr) => {
1600 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1601 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1602 let pos = snippet.find_uncommented("..").unwrap();
1603 last_field_hi + BytePos(pos as u32)
1605 StructLitField::Rest(span) => span.lo(),
1607 let span_hi = |item: &StructLitField<'_>| match *item {
1608 StructLitField::Regular(field) => field.span().hi(),
1609 StructLitField::Base(expr) => expr.span.hi(),
1610 StructLitField::Rest(span) => span.hi(),
1612 let rewrite = |item: &StructLitField<'_>| match *item {
1613 StructLitField::Regular(field) => {
1614 // The 1 taken from the v_budget is for the comma.
1615 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1617 StructLitField::Base(expr) => {
1619 expr.rewrite(context, v_shape.offset_left(2)?)
1620 .map(|s| format!("..{}", s))
1622 StructLitField::Rest(_) => Some("..".to_owned()),
1625 let items = itemize_list(
1626 context.snippet_provider,
1637 let item_vec = items.collect::<Vec<_>>();
1639 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1640 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1642 let ends_with_comma = span_ends_with_comma(context, span);
1643 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1645 let fmt = struct_lit_formatting(
1649 force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1652 write_list(&item_vec, &fmt)?
1656 wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1657 Some(format!("{} {{{}}}", path_str, fields_str))
1659 // FIXME if context.config.indent_style() == Visual, but we run out
1660 // of space, we should fall back to BlockIndent.
1663 pub(crate) fn wrap_struct_field(
1664 context: &RewriteContext<'_>,
1665 attrs: &[ast::Attribute],
1668 nested_shape: Shape,
1669 one_line_width: usize,
1670 ) -> Option<String> {
1671 let should_vertical = context.config.indent_style() == IndentStyle::Block
1672 && (fields_str.contains('\n')
1673 || !context.config.struct_lit_single_line()
1674 || fields_str.len() > one_line_width);
1676 let inner_attrs = &inner_attributes(attrs);
1677 if inner_attrs.is_empty() {
1678 if should_vertical {
1681 nested_shape.indent.to_string_with_newline(context.config),
1683 shape.indent.to_string_with_newline(context.config)
1686 // One liner or visual indent.
1687 Some(format!(" {} ", fields_str))
1692 nested_shape.indent.to_string_with_newline(context.config),
1693 inner_attrs.rewrite(context, shape)?,
1694 nested_shape.indent.to_string_with_newline(context.config),
1696 shape.indent.to_string_with_newline(context.config)
1701 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1702 colon_spaces(config)
1705 pub(crate) fn rewrite_field(
1706 context: &RewriteContext<'_>,
1707 field: &ast::ExprField,
1709 prefix_max_width: usize,
1710 ) -> Option<String> {
1711 if contains_skip(&field.attrs) {
1712 return Some(context.snippet(field.span()).to_owned());
1714 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1715 if !attrs_str.is_empty() {
1716 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1718 let name = context.snippet(field.ident.span);
1719 if field.is_shorthand {
1720 Some(attrs_str + name)
1722 let mut separator = String::from(struct_lit_field_separator(context.config));
1723 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1724 separator.push(' ');
1726 let overhead = name.len() + separator.len();
1727 let expr_shape = shape.offset_left(overhead)?;
1728 let expr = field.expr.rewrite(context, expr_shape);
1731 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1732 Some(attrs_str + name)
1734 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1736 let expr_offset = shape.indent.block_indent(context.config);
1739 .rewrite(context, Shape::indented(expr_offset, context.config));
1745 expr_offset.to_string(context.config),
1754 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1755 context: &RewriteContext<'_>,
1756 mut items: impl Iterator<Item = &'a T>,
1759 is_singleton_tuple: bool,
1760 ) -> Option<String> {
1761 // In case of length 1, need a trailing comma
1762 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1763 if is_singleton_tuple {
1765 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1769 .rewrite(context, nested_shape)
1770 .map(|s| format!("({},)", s));
1773 let list_lo = context.snippet_provider.span_after(span, "(");
1774 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1775 let items = itemize_list(
1776 context.snippet_provider,
1780 |item| item.span().lo(),
1781 |item| item.span().hi(),
1782 |item| item.rewrite(context, nested_shape),
1784 span.hi() - BytePos(1),
1787 let item_vec: Vec<_> = items.collect();
1788 let tactic = definitive_tactic(
1790 ListTactic::HorizontalVertical,
1794 let fmt = ListFormatting::new(nested_shape, context.config)
1796 .ends_with_newline(false);
1797 let list_str = write_list(&item_vec, &fmt)?;
1799 Some(format!("({})", list_str))
1802 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1803 context: &'a RewriteContext<'_>,
1804 items: impl Iterator<Item = &'a T>,
1807 is_singleton_tuple: bool,
1808 ) -> Option<String> {
1809 debug!("rewrite_tuple {:?}", shape);
1810 if context.use_block_indent() {
1811 // We use the same rule as function calls for rewriting tuples.
1812 let force_tactic = if context.inside_macro() {
1813 if span_ends_with_comma(context, span) {
1814 Some(SeparatorTactic::Always)
1816 Some(SeparatorTactic::Never)
1818 } else if is_singleton_tuple {
1819 Some(SeparatorTactic::Always)
1823 overflow::rewrite_with_parens(
1829 context.config.fn_call_width(),
1833 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1837 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1838 context: &RewriteContext<'_>,
1842 ) -> Option<String> {
1844 .rewrite(context, shape.offset_left(prefix.len())?)
1845 .map(|r| format!("{}{}", prefix, r))
1848 // FIXME: this is probably not correct for multi-line Rewrites. we should
1849 // subtract suffix.len() from the last line budget, not the first!
1850 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1851 context: &RewriteContext<'_>,
1855 ) -> Option<String> {
1857 .rewrite(context, shape.sub_width(suffix.len())?)
1864 fn rewrite_unary_op(
1865 context: &RewriteContext<'_>,
1869 ) -> Option<String> {
1870 // For some reason, an UnOp is not spanned like BinOp!
1871 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1874 pub(crate) enum RhsAssignKind<'ast> {
1875 Expr(&'ast ast::ExprKind, Span),
1880 impl<'ast> RhsAssignKind<'ast> {
1881 // TODO(calebcartwright)
1882 // Preemptive addition for handling RHS with chains, not yet utilized.
1883 // It may make more sense to construct the chain first and then check
1884 // whether there are actually chain elements.
1886 fn is_chain(&self) -> bool {
1888 RhsAssignKind::Expr(kind, _) => {
1891 ast::ExprKind::Try(..)
1892 | ast::ExprKind::Field(..)
1893 | ast::ExprKind::MethodCall(..)
1894 | ast::ExprKind::Await(_)
1902 fn rewrite_assignment(
1903 context: &RewriteContext<'_>,
1906 op: Option<&ast::BinOp>,
1908 ) -> Option<String> {
1909 let operator_str = match op {
1910 Some(op) => context.snippet(op.span),
1914 // 1 = space between lhs and operator.
1915 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1916 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1922 &RhsAssignKind::Expr(&rhs.kind, rhs.span),
1927 /// Controls where to put the rhs.
1928 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1929 pub(crate) enum RhsTactics {
1932 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1933 ForceNextLineWithoutIndent,
1934 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1939 // The left hand side must contain everything up to, and including, the
1940 // assignment operator.
1941 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1942 context: &RewriteContext<'_>,
1945 rhs_kind: &RhsAssignKind<'_>,
1947 ) -> Option<String> {
1948 rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
1951 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1952 context: &RewriteContext<'_>,
1956 rhs_kind: &RhsAssignKind<'_>,
1957 rhs_tactics: RhsTactics,
1958 ) -> Option<String> {
1959 let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1960 shape.indent.width()
1964 // 1 = space between operator and rhs.
1965 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1967 offset: shape.offset + last_line_width + 1,
1970 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1971 lhs.trim_end().len() > offset + 1
1980 ex.rewrite(context, orig_shape),
1987 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1988 context: &RewriteContext<'_>,
1992 rhs_kind: &RhsAssignKind<'_>,
1993 rhs_tactics: RhsTactics,
1994 ) -> Option<String> {
1995 let lhs = lhs.into();
1996 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2000 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
2001 context: &RewriteContext<'_>,
2005 rhs_kind: &RhsAssignKind<'_>,
2006 rhs_tactics: RhsTactics,
2009 ) -> Option<String> {
2010 let lhs = lhs.into();
2011 let contains_comment = contains_comment(context.snippet(between_span));
2012 let shape = if contains_comment {
2013 shape.block_left(context.config.tab_spaces())?
2017 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2019 if contains_comment {
2020 let rhs = rhs.trim_start();
2021 combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2027 fn choose_rhs<R: Rewrite>(
2028 context: &RewriteContext<'_>,
2031 orig_rhs: Option<String>,
2032 _rhs_kind: &RhsAssignKind<'_>,
2033 rhs_tactics: RhsTactics,
2034 has_rhs_comment: bool,
2035 ) -> Option<String> {
2037 Some(ref new_str) if new_str.is_empty() => Some(String::new()),
2039 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
2041 Some(format!(" {}", new_str))
2044 // Expression did not fit on the same line as the identifier.
2045 // Try splitting the line and see if that works better.
2046 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
2047 let new_rhs = expr.rewrite(context, new_shape);
2048 let new_indent_str = &shape
2050 .block_indent(context.config)
2051 .to_string_with_newline(context.config);
2052 let before_space_str = if has_rhs_comment { "" } else { " " };
2054 match (orig_rhs, new_rhs) {
2055 (Some(ref orig_rhs), Some(ref new_rhs))
2056 if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) =>
2058 Some(format!("{}{}", before_space_str, orig_rhs))
2060 (Some(ref orig_rhs), Some(ref new_rhs))
2061 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2063 Some(format!("{}{}", new_indent_str, new_rhs))
2065 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2066 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2067 let shape = shape.infinite_width();
2068 expr.rewrite(context, shape)
2069 .map(|s| format!("{}{}", before_space_str, s))
2071 (None, None) => None,
2072 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2078 fn shape_from_rhs_tactic(
2079 context: &RewriteContext<'_>,
2081 rhs_tactic: RhsTactics,
2082 ) -> Option<Shape> {
2084 RhsTactics::ForceNextLineWithoutIndent => shape
2085 .with_max_width(context.config)
2086 .sub_width(shape.indent.width()),
2087 RhsTactics::Default | RhsTactics::AllowOverflow => {
2088 Shape::indented(shape.indent.block_indent(context.config), context.config)
2089 .sub_width(shape.rhs_overhead(context.config))
2094 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2095 /// original's line formatting.
2097 /// It is considered better if:
2098 /// 1. the tactic is ForceNextLineWithoutIndent
2099 /// 2. next_line_rhs doesn't have newlines
2100 /// 3. the original line has more newlines than next_line_rhs
2101 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2103 pub(crate) fn prefer_next_line(
2105 next_line_rhs: &str,
2106 rhs_tactics: RhsTactics,
2108 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2109 || !next_line_rhs.contains('\n')
2110 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2111 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2112 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2113 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2116 fn rewrite_expr_addrof(
2117 context: &RewriteContext<'_>,
2118 borrow_kind: ast::BorrowKind,
2119 mutability: ast::Mutability,
2122 ) -> Option<String> {
2123 let operator_str = match (mutability, borrow_kind) {
2124 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2125 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2126 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2127 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2129 rewrite_unary_prefix(context, operator_str, expr, shape)
2132 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2134 ast::ExprKind::MethodCall(..) => true,
2135 ast::ExprKind::AddrOf(_, _, ref expr)
2136 | ast::ExprKind::Box(ref expr)
2137 | ast::ExprKind::Cast(ref expr, _)
2138 | ast::ExprKind::Try(ref expr)
2139 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2146 use super::last_line_offsetted;
2149 fn test_last_line_offsetted() {
2150 let lines = "one\n two";
2151 assert_eq!(last_line_offsetted(2, lines), true);
2152 assert_eq!(last_line_offsetted(4, lines), false);
2153 assert_eq!(last_line_offsetted(6, lines), false);
2155 let lines = "one two";
2156 assert_eq!(last_line_offsetted(2, lines), false);
2157 assert_eq!(last_line_offsetted(0, lines), false);
2159 let lines = "\ntwo";
2160 assert_eq!(last_line_offsetted(2, lines), false);
2161 assert_eq!(last_line_offsetted(0, lines), false);
2163 let lines = "one\n two three";
2164 assert_eq!(last_line_offsetted(2, lines), true);
2165 let lines = "one\n two three";
2166 assert_eq!(last_line_offsetted(2, lines), false);