4 use itertools::Itertools;
5 use rustc_ast::token::{DelimToken, LitKind};
6 use rustc_ast::{ast, ptr};
7 use rustc_span::{BytePos, Span};
9 use crate::chains::rewrite_chain;
12 combine_strs_with_missing_comments, 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.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 {
111 fields, path, rest, ..
113 rewrite_struct_lit(context, path, fields, rest, &expr.attrs, expr.span, shape)
115 ast::ExprKind::Tup(ref items) => {
116 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
118 ast::ExprKind::Let(..) => None,
119 ast::ExprKind::If(..)
120 | ast::ExprKind::ForLoop(..)
121 | ast::ExprKind::Loop(..)
122 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
123 .and_then(|control_flow| control_flow.rewrite(context, shape)),
124 ast::ExprKind::ConstBlock(ref anon_const) => {
125 Some(format!("const {}", anon_const.rewrite(context, shape)?))
127 ast::ExprKind::Block(ref block, opt_label) => {
129 ExprType::Statement => {
130 if is_unsafe_block(block) {
131 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
132 } else if let rw @ Some(_) =
133 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
135 // Rewrite block without trying to put it in a single line.
138 let prefix = block_prefix(context, block, shape)?;
140 rewrite_block_with_visitor(
151 ExprType::SubExpression => {
152 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
156 ast::ExprKind::Match(ref cond, ref arms) => {
157 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
159 ast::ExprKind::Path(ref qself, ref path) => {
160 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
162 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
163 rewrite_assignment(context, lhs, rhs, None, shape)
165 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
166 rewrite_assignment(context, lhs, rhs, Some(op), shape)
168 ast::ExprKind::Continue(ref opt_label) => {
169 let id_str = match *opt_label {
170 Some(label) => format!(" {}", label.ident),
171 None => String::new(),
173 Some(format!("continue{}", id_str))
175 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
176 let id_str = match *opt_label {
177 Some(label) => format!(" {}", label.ident),
178 None => String::new(),
181 if let Some(ref expr) = *opt_expr {
182 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
184 Some(format!("break{}", id_str))
187 ast::ExprKind::Yield(ref opt_expr) => {
188 if let Some(ref expr) = *opt_expr {
189 rewrite_unary_prefix(context, "yield ", &**expr, shape)
191 Some("yield".to_string())
194 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
195 closures::rewrite_closure(
196 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
199 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
200 rewrite_chain(expr, context, shape)
202 ast::ExprKind::MacCall(ref mac) => {
203 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
205 context.snippet(expr.span).to_owned(),
206 context.config.max_width(),
211 ast::ExprKind::Ret(None) => Some("return".to_owned()),
212 ast::ExprKind::Ret(Some(ref expr)) => {
213 rewrite_unary_prefix(context, "return ", &**expr, shape)
215 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
216 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
217 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
219 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
222 PairParts::infix(" as "),
225 SeparatorPlace::Front,
227 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
230 PairParts::infix(": "),
233 SeparatorPlace::Back,
235 ast::ExprKind::Index(ref expr, ref index) => {
236 rewrite_index(&**expr, &**index, context, shape)
238 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
241 PairParts::new("[", "; ", "]"),
244 SeparatorPlace::Back,
246 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
247 let delim = match limits {
248 ast::RangeLimits::HalfOpen => "..",
249 ast::RangeLimits::Closed => "..=",
252 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
254 ast::ExprKind::Lit(ref lit) => match lit.kind {
255 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
256 context.snippet(lit.span).ends_with('.')
260 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
265 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
266 // Don't format `.. ..` into `....`, which is invalid.
268 // This check is unnecessary for `lhs`, because a range
269 // starting from another range needs parentheses as `(x ..) ..`
270 // (`x .. ..` is a range from `x` to `..`).
271 matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
274 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
275 let space_if = |b: bool| if b { " " } else { "" };
279 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
281 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
285 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
286 (Some(lhs), Some(rhs)) => {
287 let sp_delim = if context.config.spaces_around_ranges() {
288 format!(" {} ", delim)
290 default_sp_delim(Some(lhs), Some(rhs))
295 PairParts::infix(&sp_delim),
298 context.config.binop_separator(),
301 (None, Some(rhs)) => {
302 let sp_delim = if context.config.spaces_around_ranges() {
303 format!("{} ", delim)
305 default_sp_delim(None, Some(rhs))
307 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
309 (Some(lhs), None) => {
310 let sp_delim = if context.config.spaces_around_ranges() {
311 format!(" {}", delim)
313 default_sp_delim(Some(lhs), None)
315 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
317 (None, None) => Some(delim.to_owned()),
320 // We do not format these expressions yet, but they should still
321 // satisfy our width restrictions.
322 // Style Guide RFC for InlineAsm variant pending
323 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
324 ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
325 Some(context.snippet(expr.span).to_owned())
327 ast::ExprKind::TryBlock(ref block) => {
328 if let rw @ Some(_) =
329 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
334 let budget = shape.width.saturating_sub(9);
343 Shape::legacy(budget, shape.indent)
348 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
349 let mover = if capture_by == ast::CaptureBy::Value {
354 if let rw @ Some(_) = rewrite_single_line_block(
356 format!("{}{}", "async ", mover).as_str(),
365 let budget = shape.width.saturating_sub(6);
375 Shape::legacy(budget, shape.indent)
380 ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
381 ast::ExprKind::Underscore => Some("_".to_owned()),
382 ast::ExprKind::Err => None,
386 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
387 .and_then(|expr_str| {
388 let attrs = outer_attributes(&expr.attrs);
389 let attrs_str = attrs.rewrite(context, shape)?;
391 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
394 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
398 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
400 exprs: impl Iterator<Item = &'a T>,
402 context: &'a RewriteContext<'_>,
404 force_separator_tactic: Option<SeparatorTactic>,
405 delim_token: Option<DelimToken>,
406 ) -> Option<String> {
407 overflow::rewrite_with_square_brackets(
413 force_separator_tactic,
418 fn rewrite_empty_block(
419 context: &RewriteContext<'_>,
421 attrs: Option<&[ast::Attribute]>,
422 label: Option<ast::Label>,
425 ) -> Option<String> {
426 if block_has_statements(block) {
430 let label_str = rewrite_label(label);
431 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
435 if !block_contains_comment(context, block) && shape.width >= 2 {
436 return Some(format!("{}{}{{}}", prefix, label_str));
439 // If a block contains only a single-line comment, then leave it on one line.
440 let user_str = context.snippet(block.span);
441 let user_str = user_str.trim();
442 if user_str.starts_with('{') && user_str.ends_with('}') {
443 let comment_str = user_str[1..user_str.len() - 1].trim();
444 if block.stmts.is_empty()
445 && !comment_str.contains('\n')
446 && !comment_str.starts_with("//")
447 && comment_str.len() + 4 <= shape.width
449 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
456 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
457 Some(match block.rules {
458 ast::BlockCheckMode::Unsafe(..) => {
459 let snippet = context.snippet(block.span);
460 let open_pos = snippet.find_uncommented("{")?;
461 // Extract comment between unsafe and block start.
462 let trimmed = &snippet[6..open_pos].trim();
464 if !trimmed.is_empty() {
465 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
466 let budget = shape.width.checked_sub(9)?;
472 Shape::legacy(budget, shape.indent + 7),
480 ast::BlockCheckMode::Default => String::new(),
484 fn rewrite_single_line_block(
485 context: &RewriteContext<'_>,
488 attrs: Option<&[ast::Attribute]>,
489 label: Option<ast::Label>,
491 ) -> Option<String> {
492 if is_simple_block(context, block, attrs) {
493 let expr_shape = shape.offset_left(last_line_width(prefix))?;
494 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
495 let label_str = rewrite_label(label);
496 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
497 if result.len() <= shape.width && !result.contains('\n') {
504 pub(crate) fn rewrite_block_with_visitor(
505 context: &RewriteContext<'_>,
508 attrs: Option<&[ast::Attribute]>,
509 label: Option<ast::Label>,
512 ) -> Option<String> {
513 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
517 let mut visitor = FmtVisitor::from_context(context);
518 visitor.block_indent = shape.indent;
519 visitor.is_if_else_block = context.is_if_else_block();
520 match (block.rules, label) {
521 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
522 let snippet = context.snippet(block.span);
523 let open_pos = snippet.find_uncommented("{")?;
524 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
526 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
529 let inner_attrs = attrs.map(inner_attributes);
530 let label_str = rewrite_label(label);
531 visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
532 let visitor_context = visitor.get_context();
536 .append(&mut visitor_context.skipped_range.borrow_mut());
537 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
540 impl Rewrite for ast::Block {
541 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
542 rewrite_block(self, None, None, context, shape)
548 attrs: Option<&[ast::Attribute]>,
549 label: Option<ast::Label>,
550 context: &RewriteContext<'_>,
552 ) -> Option<String> {
553 let prefix = block_prefix(context, block, shape)?;
555 // shape.width is used only for the single line case: either the empty block `{}`,
556 // or an unsafe expression `unsafe { e }`.
557 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
561 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
562 if let Some(ref result_str) = result {
563 if result_str.lines().count() <= 3 {
564 if let rw @ Some(_) =
565 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
575 // Rewrite condition if the given expression has one.
576 pub(crate) fn rewrite_cond(
577 context: &RewriteContext<'_>,
580 ) -> Option<String> {
582 ast::ExprKind::Match(ref cond, _) => {
584 let cond_shape = match context.config.indent_style() {
585 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
586 IndentStyle::Block => shape.offset_left(8)?,
588 cond.rewrite(context, cond_shape)
590 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
592 String::from("\n") + &shape.indent.block_only().to_string(context.config);
594 .rewrite_cond(context, shape, &alt_block_sep)
600 // Abstraction over control flow expressions
602 struct ControlFlow<'a> {
603 cond: Option<&'a ast::Expr>,
604 block: &'a ast::Block,
605 else_block: Option<&'a ast::Expr>,
606 label: Option<ast::Label>,
607 pat: Option<&'a ast::Pat>,
611 allow_single_line: bool,
612 // HACK: `true` if this is an `if` expression in an `else if`.
617 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
619 ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
624 // FIXME: Refactor this.
625 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
627 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
628 let (pat, cond) = extract_pats_and_cond(cond);
629 Some(ControlFlow::new_if(
633 else_block.as_ref().map(|e| &**e),
634 expr_type == ExprType::SubExpression,
639 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
640 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
642 ast::ExprKind::Loop(ref block, label) => {
643 Some(ControlFlow::new_loop(block, label, expr.span))
645 ast::ExprKind::While(ref cond, ref block, label) => {
646 let (pat, cond) = extract_pats_and_cond(cond);
647 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
653 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
654 pat.map_or("", |_| "let")
657 impl<'a> ControlFlow<'a> {
660 pat: Option<&'a ast::Pat>,
661 block: &'a ast::Block,
662 else_block: Option<&'a ast::Expr>,
663 allow_single_line: bool,
666 ) -> ControlFlow<'a> {
667 let matcher = choose_matcher(pat);
683 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
693 allow_single_line: false,
700 pat: Option<&'a ast::Pat>,
702 block: &'a ast::Block,
703 label: Option<ast::Label>,
705 ) -> ControlFlow<'a> {
706 let matcher = choose_matcher(pat);
716 allow_single_line: false,
725 block: &'a ast::Block,
726 label: Option<ast::Label>,
728 ) -> ControlFlow<'a> {
738 allow_single_line: false,
744 fn rewrite_single_line(
747 context: &RewriteContext<'_>,
749 ) -> Option<String> {
750 assert!(self.allow_single_line);
751 let else_block = self.else_block?;
752 let fixed_cost = self.keyword.len() + " { } else { }".len();
754 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
755 if !is_simple_block(context, self.block, None)
756 || !is_simple_block(context, else_node, None)
757 || pat_expr_str.contains('\n')
762 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
763 let expr = &self.block.stmts[0];
764 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
766 let new_width = new_width.checked_sub(if_str.len())?;
767 let else_expr = &else_node.stmts[0];
768 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
770 if if_str.contains('\n') || else_str.contains('\n') {
774 let result = format!(
775 "{} {} {{ {} }} else {{ {} }}",
776 self.keyword, pat_expr_str, if_str, else_str
779 if result.len() <= width {
788 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
790 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
791 let mut leading_whitespaces = 0;
792 for c in pat_str.chars().rev() {
795 _ if c.is_whitespace() => leading_whitespaces += 1,
796 _ => leading_whitespaces = 0,
799 leading_whitespaces > start_column
802 impl<'a> ControlFlow<'a> {
805 context: &RewriteContext<'_>,
809 ) -> Option<String> {
810 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
812 let cond_shape = shape.offset_left(offset)?;
813 if let Some(pat) = self.pat {
814 let matcher = if self.matcher.is_empty() {
815 self.matcher.to_owned()
817 format!("{} ", self.matcher)
819 let pat_shape = cond_shape
820 .offset_left(matcher.len())?
821 .sub_width(self.connector.len())?;
822 let pat_string = pat.rewrite(context, pat_shape)?;
823 let comments_lo = context
825 .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
826 let comments_span = mk_sp(comments_lo, expr.span.lo());
827 return rewrite_assign_rhs_with_comments(
829 &format!("{}{}{}", matcher, pat_string, self.connector),
838 let expr_rw = expr.rewrite(context, cond_shape);
839 // The expression may (partially) fit on the current line.
840 // We do not allow splitting between `if` and condition.
841 if self.keyword == "if" || expr_rw.is_some() {
845 // The expression won't fit on the current line, jump to next.
846 let nested_shape = shape
847 .block_indent(context.config.tab_spaces())
848 .with_max_width(context.config);
849 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
850 expr.rewrite(context, nested_shape)
851 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
856 context: &RewriteContext<'_>,
859 ) -> Option<(String, usize)> {
860 // Do not take the rhs overhead from the upper expressions into account
861 // when rewriting pattern.
862 let new_width = context.budget(shape.used_width());
863 let fresh_shape = Shape {
867 let constr_shape = if self.nested_if {
868 // We are part of an if-elseif-else chain. Our constraints are tightened.
869 // 7 = "} else " .len()
870 fresh_shape.offset_left(7)?
875 let label_string = rewrite_label(self.label);
876 // 1 = space after keyword.
877 let offset = self.keyword.len() + label_string.len() + 1;
879 let pat_expr_string = match self.cond {
880 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
881 None => String::new(),
885 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
891 let one_line_budget = context
894 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
895 let force_newline_brace = (pat_expr_string.contains('\n')
896 || pat_expr_string.len() > one_line_budget)
897 && (!last_line_extendable(&pat_expr_string)
898 || last_line_offsetted(shape.used_width(), &pat_expr_string));
900 // Try to format if-else on single line.
901 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
902 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
904 if let Some(cond_str) = trial {
905 if cond_str.len() <= context.config.single_line_if_else_max_width() {
906 return Some((cond_str, 0));
911 let cond_span = if let Some(cond) = self.cond {
914 mk_sp(self.block.span.lo(), self.block.span.lo())
917 // `for event in event`
918 // Do not include label in the span.
921 .map_or(self.span.lo(), |label| label.ident.span.hi());
922 let between_kwd_cond = mk_sp(
925 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
926 if self.pat.is_none() {
928 } else if self.matcher.is_empty() {
929 self.pat.unwrap().span.lo()
933 .span_before(self.span, self.matcher.trim())
937 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
939 let after_cond_comment =
940 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
942 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
944 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
945 || force_newline_brace
952 let used_width = if pat_expr_string.contains('\n') {
953 last_line_width(&pat_expr_string)
955 // 2 = spaces after keyword and condition.
956 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
964 between_kwd_cond_comment.as_ref().map_or(
965 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
973 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
980 impl<'a> Rewrite for ControlFlow<'a> {
981 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
982 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
984 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
985 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
986 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
988 return Some(cond_str);
991 let block_width = shape.width.saturating_sub(used_width);
992 // This is used only for the empty block case: `{}`. So, we use 1 if we know
993 // we should avoid the single line case.
994 let block_width = if self.else_block.is_some() || self.nested_if {
999 let block_shape = Shape {
1004 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1006 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1007 context.is_if_else_block.replace(old_val);
1011 let mut result = format!("{}{}", cond_str, block_str);
1013 if let Some(else_block) = self.else_block {
1014 let shape = Shape::indented(shape.indent, context.config);
1015 let mut last_in_chain = false;
1016 let rewrite = match else_block.kind {
1017 // If the else expression is another if-else expression, prevent it
1018 // from being formatted on a single line.
1019 // Note how we're passing the original shape, as the
1020 // cost of "else" should not cascade.
1021 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1022 let (pats, cond) = extract_pats_and_cond(cond);
1023 ControlFlow::new_if(
1027 next_else_block.as_ref().map(|e| &**e),
1030 mk_sp(else_block.span.lo(), self.span.hi()),
1032 .rewrite(context, shape)
1035 last_in_chain = true;
1036 // When rewriting a block, the width is only used for single line
1037 // blocks, passing 1 lets us avoid that.
1038 let else_shape = Shape {
1039 width: min(1, shape.width),
1042 format_expr(else_block, ExprType::Statement, context, else_shape)
1046 let between_kwd_else_block = mk_sp(
1047 self.block.span.hi(),
1050 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1052 let between_kwd_else_block_comment =
1053 extract_comment(between_kwd_else_block, context, shape);
1055 let after_else = mk_sp(
1058 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1059 else_block.span.lo(),
1061 let after_else_comment = extract_comment(after_else, context, shape);
1063 let between_sep = match context.config.control_brace_style() {
1064 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1067 ControlBraceStyle::AlwaysSameLine => " ",
1069 let after_sep = match context.config.control_brace_style() {
1070 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1074 result.push_str(&format!(
1076 between_kwd_else_block_comment
1078 .map_or(between_sep, |s| &**s),
1079 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1081 result.push_str(&rewrite?);
1088 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1090 Some(label) => Cow::from(format!("{}: ", label.ident)),
1091 None => Cow::from(""),
1095 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1096 match rewrite_missing_comment(span, shape, context) {
1097 Some(ref comment) if !comment.is_empty() => Some(format!(
1098 "{indent}{}{indent}",
1100 indent = shape.indent.to_string_with_newline(context.config)
1106 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1107 contains_comment(context.snippet(block.span))
1110 // Checks that a block contains no statements, an expression and no comments or
1112 // FIXME: incorrectly returns false when comment is contained completely within
1114 pub(crate) fn is_simple_block(
1115 context: &RewriteContext<'_>,
1117 attrs: Option<&[ast::Attribute]>,
1119 block.stmts.len() == 1
1120 && stmt_is_expr(&block.stmts[0])
1121 && !block_contains_comment(context, block)
1122 && attrs.map_or(true, |a| a.is_empty())
1125 /// Checks whether a block contains at most one statement or expression, and no
1126 /// comments or attributes.
1127 pub(crate) fn is_simple_block_stmt(
1128 context: &RewriteContext<'_>,
1130 attrs: Option<&[ast::Attribute]>,
1132 block.stmts.len() <= 1
1133 && !block_contains_comment(context, block)
1134 && attrs.map_or(true, |a| a.is_empty())
1137 fn block_has_statements(block: &ast::Block) -> bool {
1141 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1144 /// Checks whether a block contains no statements, expressions, comments, or
1145 /// inner attributes.
1146 pub(crate) fn is_empty_block(
1147 context: &RewriteContext<'_>,
1149 attrs: Option<&[ast::Attribute]>,
1151 !block_has_statements(block)
1152 && !block_contains_comment(context, block)
1153 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1156 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1157 matches!(stmt.kind, ast::StmtKind::Expr(..))
1160 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1161 matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1164 pub(crate) fn rewrite_literal(
1165 context: &RewriteContext<'_>,
1168 ) -> Option<String> {
1170 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1171 ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape),
1173 context.snippet(l.span).to_owned(),
1174 context.config.max_width(),
1180 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1181 let string_lit = context.snippet(span);
1183 if !context.config.format_strings() {
1187 .all(|line| line.ends_with('\\'))
1188 && context.config.version() == Version::Two
1190 return Some(string_lit.to_owned());
1192 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1196 // Remove the quote characters.
1197 let str_lit = &string_lit[1..string_lit.len() - 1];
1201 &StringFormat::new(shape.visual_indent(0), context.config),
1202 shape.width.saturating_sub(2),
1206 fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option<String> {
1207 let span = lit.span;
1208 let symbol = lit.token.symbol.as_str();
1210 if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1211 let hex_lit = match context.config.hex_literal_case() {
1212 HexLiteralCase::Preserve => None,
1213 HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1214 HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1216 if let Some(hex_lit) = hex_lit {
1221 lit.token.suffix.map_or(String::new(), |s| s.to_string())
1223 context.config.max_width(),
1230 context.snippet(span).to_owned(),
1231 context.config.max_width(),
1236 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1237 if context.inside_macro() {
1238 if span_ends_with_comma(context, span) {
1239 Some(SeparatorTactic::Always)
1241 Some(SeparatorTactic::Never)
1248 pub(crate) fn rewrite_call(
1249 context: &RewriteContext<'_>,
1251 args: &[ptr::P<ast::Expr>],
1254 ) -> Option<String> {
1255 overflow::rewrite_with_parens(
1261 context.config.fn_call_width(),
1262 choose_separator_tactic(context, span),
1266 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1268 ast::ExprKind::Lit(..) => true,
1269 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1270 ast::ExprKind::AddrOf(_, _, ref expr)
1271 | ast::ExprKind::Box(ref expr)
1272 | ast::ExprKind::Cast(ref expr, _)
1273 | ast::ExprKind::Field(ref expr, _)
1274 | ast::ExprKind::Try(ref expr)
1275 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1276 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1277 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1278 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1284 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1285 lists.iter().all(OverflowableItem::is_simple)
1288 pub(crate) fn can_be_overflowed_expr(
1289 context: &RewriteContext<'_>,
1294 _ if !expr.attrs.is_empty() => false,
1295 ast::ExprKind::Match(..) => {
1296 (context.use_block_indent() && args_len == 1)
1297 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1298 || context.config.overflow_delimited_expr()
1300 ast::ExprKind::If(..)
1301 | ast::ExprKind::ForLoop(..)
1302 | ast::ExprKind::Loop(..)
1303 | ast::ExprKind::While(..) => {
1304 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1307 // Handle always block-like expressions
1308 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1310 // Handle `[]` and `{}`-like expressions
1311 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1312 context.config.overflow_delimited_expr()
1313 || (context.use_block_indent() && args_len == 1)
1315 ast::ExprKind::MacCall(ref mac) => {
1317 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
1318 context.config.overflow_delimited_expr(),
1320 (Some(ast::MacDelimiter::Bracket), true)
1321 | (Some(ast::MacDelimiter::Brace), true) => true,
1322 _ => context.use_block_indent() && args_len == 1,
1326 // Handle parenthetical expressions
1327 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1328 context.use_block_indent() && args_len == 1
1331 // Handle unary-like expressions
1332 ast::ExprKind::AddrOf(_, _, ref expr)
1333 | ast::ExprKind::Box(ref expr)
1334 | ast::ExprKind::Try(ref expr)
1335 | ast::ExprKind::Unary(_, ref expr)
1336 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1341 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1343 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1344 ast::ExprKind::AddrOf(_, _, ref expr)
1345 | ast::ExprKind::Box(ref expr)
1346 | ast::ExprKind::Try(ref expr)
1347 | ast::ExprKind::Unary(_, ref expr)
1348 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1353 /// Returns `true` if a function call or a method call represented by the given span ends with a
1354 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1355 /// comma from macro can potentially break the code.
1356 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1357 let mut result: bool = Default::default();
1358 let mut prev_char: char = Default::default();
1359 let closing_delimiters = &[')', '}', ']'];
1361 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1363 _ if kind.is_comment() || c.is_whitespace() => continue,
1364 c if closing_delimiters.contains(&c) => {
1365 result &= !closing_delimiters.contains(&prev_char);
1367 ',' => result = true,
1368 _ => result = false,
1377 context: &RewriteContext<'_>,
1378 mut subexpr: &ast::Expr,
1381 ) -> Option<String> {
1382 debug!("rewrite_paren, shape: {:?}", shape);
1384 // Extract comments within parens.
1387 let mut pre_comment;
1388 let mut post_comment;
1389 let remove_nested_parens = context.config.remove_nested_parens();
1392 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1393 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1394 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1395 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1397 // Remove nested parens if there are no comments.
1398 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1399 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1400 span = subexpr.span;
1401 subexpr = subsubexpr;
1410 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1411 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1412 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1413 if fits_single_line {
1414 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1416 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1420 fn rewrite_paren_in_multi_line(
1421 context: &RewriteContext<'_>,
1422 subexpr: &ast::Expr,
1426 ) -> Option<String> {
1427 let nested_indent = shape.indent.block_indent(context.config);
1428 let nested_shape = Shape::indented(nested_indent, context.config);
1429 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1430 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1431 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1433 let mut result = String::with_capacity(subexpr_str.len() * 2);
1435 if !pre_comment.is_empty() {
1436 result.push_str(&nested_indent.to_string_with_newline(context.config));
1437 result.push_str(&pre_comment);
1439 result.push_str(&nested_indent.to_string_with_newline(context.config));
1440 result.push_str(&subexpr_str);
1441 if !post_comment.is_empty() {
1442 result.push_str(&nested_indent.to_string_with_newline(context.config));
1443 result.push_str(&post_comment);
1445 result.push_str(&shape.indent.to_string_with_newline(context.config));
1454 context: &RewriteContext<'_>,
1456 ) -> Option<String> {
1457 let expr_str = expr.rewrite(context, shape)?;
1459 let offset = last_line_width(&expr_str) + 1;
1460 let rhs_overhead = shape.rhs_overhead(context.config);
1461 let index_shape = if expr_str.contains('\n') {
1462 Shape::legacy(context.config.max_width(), shape.indent)
1463 .offset_left(offset)
1464 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1466 match context.config.indent_style() {
1467 IndentStyle::Block => shape
1468 .offset_left(offset)
1469 .and_then(|shape| shape.sub_width(1)),
1470 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1473 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1475 // Return if index fits in a single line.
1476 match orig_index_rw {
1477 Some(ref index_str) if !index_str.contains('\n') => {
1478 return Some(format!("{}[{}]", expr_str, index_str));
1483 // Try putting index on the next line and see if it fits in a single line.
1484 let indent = shape.indent.block_indent(context.config);
1485 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1486 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1487 let new_index_rw = index.rewrite(context, index_shape);
1488 match (orig_index_rw, new_index_rw) {
1489 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1492 indent.to_string_with_newline(context.config),
1495 (None, Some(ref new_index_str)) => Some(format!(
1498 indent.to_string_with_newline(context.config),
1501 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1506 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1507 !has_base && fields.iter().all(|field| !field.is_shorthand)
1510 fn rewrite_struct_lit<'a>(
1511 context: &RewriteContext<'_>,
1513 fields: &'a [ast::ExprField],
1514 struct_rest: &ast::StructRest,
1515 attrs: &[ast::Attribute],
1518 ) -> Option<String> {
1519 debug!("rewrite_struct_lit: shape {:?}", shape);
1521 enum StructLitField<'a> {
1522 Regular(&'a ast::ExprField),
1523 Base(&'a ast::Expr),
1528 let path_shape = shape.sub_width(2)?;
1529 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1531 let has_base_or_rest = match struct_rest {
1532 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1533 ast::StructRest::Rest(_) if fields.is_empty() => {
1534 return Some(format!("{} {{ .. }}", path_str));
1536 ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1540 // Foo { a: Foo } - indent is +3, width is -5.
1541 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1543 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1544 let body_lo = context.snippet_provider.span_after(span, "{");
1545 let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1546 && context.config.struct_field_align_threshold() > 0
1548 rewrite_with_alignment(
1552 mk_sp(body_lo, span.hi()),
1556 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1558 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1559 ast::StructRest::Rest(span) => Some(StructLitField::Rest(span)),
1560 ast::StructRest::None => None,
1565 let span_lo = |item: &StructLitField<'_>| match *item {
1566 StructLitField::Regular(field) => field.span().lo(),
1567 StructLitField::Base(expr) => {
1568 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1569 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1570 let pos = snippet.find_uncommented("..").unwrap();
1571 last_field_hi + BytePos(pos as u32)
1573 StructLitField::Rest(span) => span.lo(),
1575 let span_hi = |item: &StructLitField<'_>| match *item {
1576 StructLitField::Regular(field) => field.span().hi(),
1577 StructLitField::Base(expr) => expr.span.hi(),
1578 StructLitField::Rest(span) => span.hi(),
1580 let rewrite = |item: &StructLitField<'_>| match *item {
1581 StructLitField::Regular(field) => {
1582 // The 1 taken from the v_budget is for the comma.
1583 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1585 StructLitField::Base(expr) => {
1587 expr.rewrite(context, v_shape.offset_left(2)?)
1588 .map(|s| format!("..{}", s))
1590 StructLitField::Rest(_) => Some("..".to_owned()),
1593 let items = itemize_list(
1594 context.snippet_provider,
1605 let item_vec = items.collect::<Vec<_>>();
1607 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1608 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1610 let ends_with_comma = span_ends_with_comma(context, span);
1611 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1613 let fmt = struct_lit_formatting(
1617 force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1620 write_list(&item_vec, &fmt)?
1624 wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1625 Some(format!("{} {{{}}}", path_str, fields_str))
1627 // FIXME if context.config.indent_style() == Visual, but we run out
1628 // of space, we should fall back to BlockIndent.
1631 pub(crate) fn wrap_struct_field(
1632 context: &RewriteContext<'_>,
1633 attrs: &[ast::Attribute],
1636 nested_shape: Shape,
1637 one_line_width: usize,
1638 ) -> Option<String> {
1639 let should_vertical = context.config.indent_style() == IndentStyle::Block
1640 && (fields_str.contains('\n')
1641 || !context.config.struct_lit_single_line()
1642 || fields_str.len() > one_line_width);
1644 let inner_attrs = &inner_attributes(attrs);
1645 if inner_attrs.is_empty() {
1646 if should_vertical {
1649 nested_shape.indent.to_string_with_newline(context.config),
1651 shape.indent.to_string_with_newline(context.config)
1654 // One liner or visual indent.
1655 Some(format!(" {} ", fields_str))
1660 nested_shape.indent.to_string_with_newline(context.config),
1661 inner_attrs.rewrite(context, shape)?,
1662 nested_shape.indent.to_string_with_newline(context.config),
1664 shape.indent.to_string_with_newline(context.config)
1669 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1670 colon_spaces(config)
1673 pub(crate) fn rewrite_field(
1674 context: &RewriteContext<'_>,
1675 field: &ast::ExprField,
1677 prefix_max_width: usize,
1678 ) -> Option<String> {
1679 if contains_skip(&field.attrs) {
1680 return Some(context.snippet(field.span()).to_owned());
1682 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1683 if !attrs_str.is_empty() {
1684 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1686 let name = context.snippet(field.ident.span);
1687 if field.is_shorthand {
1688 Some(attrs_str + name)
1690 let mut separator = String::from(struct_lit_field_separator(context.config));
1691 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1692 separator.push(' ');
1694 let overhead = name.len() + separator.len();
1695 let expr_shape = shape.offset_left(overhead)?;
1696 let expr = field.expr.rewrite(context, expr_shape);
1699 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1700 Some(attrs_str + name)
1702 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1704 let expr_offset = shape.indent.block_indent(context.config);
1707 .rewrite(context, Shape::indented(expr_offset, context.config));
1713 expr_offset.to_string(context.config),
1722 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1723 context: &RewriteContext<'_>,
1724 mut items: impl Iterator<Item = &'a T>,
1727 is_singleton_tuple: bool,
1728 ) -> Option<String> {
1729 // In case of length 1, need a trailing comma
1730 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1731 if is_singleton_tuple {
1733 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1737 .rewrite(context, nested_shape)
1738 .map(|s| format!("({},)", s));
1741 let list_lo = context.snippet_provider.span_after(span, "(");
1742 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1743 let items = itemize_list(
1744 context.snippet_provider,
1748 |item| item.span().lo(),
1749 |item| item.span().hi(),
1750 |item| item.rewrite(context, nested_shape),
1752 span.hi() - BytePos(1),
1755 let item_vec: Vec<_> = items.collect();
1756 let tactic = definitive_tactic(
1758 ListTactic::HorizontalVertical,
1762 let fmt = ListFormatting::new(nested_shape, context.config)
1764 .ends_with_newline(false);
1765 let list_str = write_list(&item_vec, &fmt)?;
1767 Some(format!("({})", list_str))
1770 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1771 context: &'a RewriteContext<'_>,
1772 items: impl Iterator<Item = &'a T>,
1775 is_singleton_tuple: bool,
1776 ) -> Option<String> {
1777 debug!("rewrite_tuple {:?}", shape);
1778 if context.use_block_indent() {
1779 // We use the same rule as function calls for rewriting tuples.
1780 let force_tactic = if context.inside_macro() {
1781 if span_ends_with_comma(context, span) {
1782 Some(SeparatorTactic::Always)
1784 Some(SeparatorTactic::Never)
1786 } else if is_singleton_tuple {
1787 Some(SeparatorTactic::Always)
1791 overflow::rewrite_with_parens(
1797 context.config.fn_call_width(),
1801 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1805 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1806 context: &RewriteContext<'_>,
1810 ) -> Option<String> {
1812 .rewrite(context, shape.offset_left(prefix.len())?)
1813 .map(|r| format!("{}{}", prefix, r))
1816 // FIXME: this is probably not correct for multi-line Rewrites. we should
1817 // subtract suffix.len() from the last line budget, not the first!
1818 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1819 context: &RewriteContext<'_>,
1823 ) -> Option<String> {
1825 .rewrite(context, shape.sub_width(suffix.len())?)
1832 fn rewrite_unary_op(
1833 context: &RewriteContext<'_>,
1837 ) -> Option<String> {
1838 // For some reason, an UnOp is not spanned like BinOp!
1839 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1842 fn rewrite_assignment(
1843 context: &RewriteContext<'_>,
1846 op: Option<&ast::BinOp>,
1848 ) -> Option<String> {
1849 let operator_str = match op {
1850 Some(op) => context.snippet(op.span),
1854 // 1 = space between lhs and operator.
1855 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1856 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1858 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1861 /// Controls where to put the rhs.
1862 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1863 pub(crate) enum RhsTactics {
1866 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1867 ForceNextLineWithoutIndent,
1868 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1873 // The left hand side must contain everything up to, and including, the
1874 // assignment operator.
1875 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1876 context: &RewriteContext<'_>,
1880 ) -> Option<String> {
1881 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1884 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1885 context: &RewriteContext<'_>,
1889 rhs_tactics: RhsTactics,
1890 ) -> Option<String> {
1891 let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1892 shape.indent.width()
1896 // 1 = space between operator and rhs.
1897 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1899 offset: shape.offset + last_line_width + 1,
1902 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1903 lhs.trim_end().len() > offset + 1
1912 ex.rewrite(context, orig_shape),
1918 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1919 context: &RewriteContext<'_>,
1923 rhs_tactics: RhsTactics,
1924 ) -> Option<String> {
1925 let lhs = lhs.into();
1926 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
1930 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
1931 context: &RewriteContext<'_>,
1935 rhs_tactics: RhsTactics,
1938 ) -> Option<String> {
1939 let lhs = lhs.into();
1940 let contains_comment = contains_comment(context.snippet(between_span));
1941 let shape = if contains_comment {
1942 shape.block_left(context.config.tab_spaces())?
1946 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
1948 if contains_comment {
1949 let rhs = rhs.trim_start();
1950 combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
1956 fn choose_rhs<R: Rewrite>(
1957 context: &RewriteContext<'_>,
1960 orig_rhs: Option<String>,
1961 rhs_tactics: RhsTactics,
1962 has_rhs_comment: bool,
1963 ) -> Option<String> {
1965 Some(ref new_str) if new_str.is_empty() => {
1966 return Some(String::new());
1969 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1971 Some(format!(" {}", new_str))
1974 // Expression did not fit on the same line as the identifier.
1975 // Try splitting the line and see if that works better.
1976 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1977 let new_rhs = expr.rewrite(context, new_shape);
1978 let new_indent_str = &shape
1980 .block_indent(context.config)
1981 .to_string_with_newline(context.config);
1982 let before_space_str = if has_rhs_comment { "" } else { " " };
1984 match (orig_rhs, new_rhs) {
1985 (Some(ref orig_rhs), Some(ref new_rhs))
1986 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1989 Some(format!("{}{}", before_space_str, orig_rhs))
1991 (Some(ref orig_rhs), Some(ref new_rhs))
1992 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1994 Some(format!("{}{}", new_indent_str, new_rhs))
1996 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1997 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1998 let shape = shape.infinite_width();
1999 expr.rewrite(context, shape)
2000 .map(|s| format!("{}{}", before_space_str, s))
2002 (None, None) => None,
2003 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2009 fn shape_from_rhs_tactic(
2010 context: &RewriteContext<'_>,
2012 rhs_tactic: RhsTactics,
2013 ) -> Option<Shape> {
2015 RhsTactics::ForceNextLineWithoutIndent => shape
2016 .with_max_width(context.config)
2017 .sub_width(shape.indent.width()),
2018 RhsTactics::Default | RhsTactics::AllowOverflow => {
2019 Shape::indented(shape.indent.block_indent(context.config), context.config)
2020 .sub_width(shape.rhs_overhead(context.config))
2025 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2026 /// original's line formatting.
2028 /// It is considered better if:
2029 /// 1. the tactic is ForceNextLineWithoutIndent
2030 /// 2. next_line_rhs doesn't have newlines
2031 /// 3. the original line has more newlines than next_line_rhs
2032 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2034 pub(crate) fn prefer_next_line(
2036 next_line_rhs: &str,
2037 rhs_tactics: RhsTactics,
2039 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2040 || !next_line_rhs.contains('\n')
2041 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2042 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2043 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2044 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2047 fn rewrite_expr_addrof(
2048 context: &RewriteContext<'_>,
2049 borrow_kind: ast::BorrowKind,
2050 mutability: ast::Mutability,
2053 ) -> Option<String> {
2054 let operator_str = match (mutability, borrow_kind) {
2055 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2056 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2057 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2058 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2060 rewrite_unary_prefix(context, operator_str, expr, shape)
2063 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2065 ast::ExprKind::MethodCall(..) => true,
2066 ast::ExprKind::AddrOf(_, _, ref expr)
2067 | ast::ExprKind::Box(ref expr)
2068 | ast::ExprKind::Cast(ref expr, _)
2069 | ast::ExprKind::Try(ref expr)
2070 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2077 use super::last_line_offsetted;
2080 fn test_last_line_offsetted() {
2081 let lines = "one\n two";
2082 assert_eq!(last_line_offsetted(2, lines), true);
2083 assert_eq!(last_line_offsetted(4, lines), false);
2084 assert_eq!(last_line_offsetted(6, lines), false);
2086 let lines = "one two";
2087 assert_eq!(last_line_offsetted(2, lines), false);
2088 assert_eq!(last_line_offsetted(0, lines), false);
2090 let lines = "\ntwo";
2091 assert_eq!(last_line_offsetted(2, lines), false);
2092 assert_eq!(last_line_offsetted(0, lines), false);
2094 let lines = "one\n two three";
2095 assert_eq!(last_line_offsetted(2, lines), true);
2096 let lines = "one\n two three";
2097 assert_eq!(last_line_offsetted(2, lines), false);