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, 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 { fields, path, rest } = &**struct_expr;
111 rewrite_struct_lit(context, path, fields, rest, &expr.attrs, expr.span, shape)
113 ast::ExprKind::Tup(ref items) => {
114 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
116 ast::ExprKind::Let(..) => None,
117 ast::ExprKind::If(..)
118 | ast::ExprKind::ForLoop(..)
119 | ast::ExprKind::Loop(..)
120 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
121 .and_then(|control_flow| control_flow.rewrite(context, shape)),
122 ast::ExprKind::ConstBlock(ref anon_const) => {
123 Some(format!("const {}", anon_const.rewrite(context, shape)?))
125 ast::ExprKind::Block(ref block, opt_label) => {
127 ExprType::Statement => {
128 if is_unsafe_block(block) {
129 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
130 } else if let rw @ Some(_) =
131 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
133 // Rewrite block without trying to put it in a single line.
136 let prefix = block_prefix(context, block, shape)?;
138 rewrite_block_with_visitor(
149 ExprType::SubExpression => {
150 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
154 ast::ExprKind::Match(ref cond, ref arms) => {
155 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
157 ast::ExprKind::Path(ref qself, ref path) => {
158 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
160 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
161 rewrite_assignment(context, lhs, rhs, None, shape)
163 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
164 rewrite_assignment(context, lhs, rhs, Some(op), shape)
166 ast::ExprKind::Continue(ref opt_label) => {
167 let id_str = match *opt_label {
168 Some(label) => format!(" {}", label.ident),
169 None => String::new(),
171 Some(format!("continue{}", id_str))
173 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
174 let id_str = match *opt_label {
175 Some(label) => format!(" {}", label.ident),
176 None => String::new(),
179 if let Some(ref expr) = *opt_expr {
180 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
182 Some(format!("break{}", id_str))
185 ast::ExprKind::Yield(ref opt_expr) => {
186 if let Some(ref expr) = *opt_expr {
187 rewrite_unary_prefix(context, "yield ", &**expr, shape)
189 Some("yield".to_string())
192 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
193 closures::rewrite_closure(
194 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
197 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
198 rewrite_chain(expr, context, shape)
200 ast::ExprKind::MacCall(ref mac) => {
201 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
203 context.snippet(expr.span).to_owned(),
204 context.config.max_width(),
209 ast::ExprKind::Ret(None) => Some("return".to_owned()),
210 ast::ExprKind::Ret(Some(ref expr)) => {
211 rewrite_unary_prefix(context, "return ", &**expr, shape)
213 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
214 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
215 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
217 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
220 PairParts::infix(" as "),
223 SeparatorPlace::Front,
225 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
228 PairParts::infix(": "),
231 SeparatorPlace::Back,
233 ast::ExprKind::Index(ref expr, ref index) => {
234 rewrite_index(&**expr, &**index, context, shape)
236 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
239 PairParts::new("[", "; ", "]"),
242 SeparatorPlace::Back,
244 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
245 let delim = match limits {
246 ast::RangeLimits::HalfOpen => "..",
247 ast::RangeLimits::Closed => "..=",
250 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
252 ast::ExprKind::Lit(ref lit) => match lit.kind {
253 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
254 context.snippet(lit.span).ends_with('.')
258 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
263 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
265 // Don't format `.. ..` into `....`, which is invalid.
267 // This check is unnecessary for `lhs`, because a range
268 // starting from another range needs parentheses as `(x ..) ..`
269 // (`x .. ..` is a range from `x` to `..`).
270 ast::ExprKind::Range(None, _, _) => true,
275 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
276 let space_if = |b: bool| if b { " " } else { "" };
280 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
282 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
286 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
287 (Some(lhs), Some(rhs)) => {
288 let sp_delim = if context.config.spaces_around_ranges() {
289 format!(" {} ", delim)
291 default_sp_delim(Some(lhs), Some(rhs))
296 PairParts::infix(&sp_delim),
299 context.config.binop_separator(),
302 (None, Some(rhs)) => {
303 let sp_delim = if context.config.spaces_around_ranges() {
304 format!("{} ", delim)
306 default_sp_delim(None, Some(rhs))
308 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
310 (Some(lhs), None) => {
311 let sp_delim = if context.config.spaces_around_ranges() {
312 format!(" {}", delim)
314 default_sp_delim(Some(lhs), None)
316 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
318 (None, None) => Some(delim.to_owned()),
321 // We do not format these expressions yet, but they should still
322 // satisfy our width restrictions.
323 // Style Guide RFC for InlineAsm variant pending
324 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
325 ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
326 Some(context.snippet(expr.span).to_owned())
328 ast::ExprKind::TryBlock(ref block) => {
329 if let rw @ Some(_) =
330 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
335 let budget = shape.width.saturating_sub(9);
344 Shape::legacy(budget, shape.indent)
349 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
350 let mover = if capture_by == ast::CaptureBy::Value {
355 if let rw @ Some(_) = rewrite_single_line_block(
357 format!("{}{}", "async ", mover).as_str(),
366 let budget = shape.width.saturating_sub(6);
376 Shape::legacy(budget, shape.indent)
381 ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
382 ast::ExprKind::Underscore => Some("_".to_owned()),
383 ast::ExprKind::Err => None,
387 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
388 .and_then(|expr_str| {
389 let attrs = outer_attributes(&expr.attrs);
390 let attrs_str = attrs.rewrite(context, shape)?;
392 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
395 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
399 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
401 exprs: impl Iterator<Item = &'a T>,
403 context: &'a RewriteContext<'_>,
405 force_separator_tactic: Option<SeparatorTactic>,
406 delim_token: Option<DelimToken>,
407 ) -> Option<String> {
408 overflow::rewrite_with_square_brackets(
414 force_separator_tactic,
419 fn rewrite_empty_block(
420 context: &RewriteContext<'_>,
422 attrs: Option<&[ast::Attribute]>,
423 label: Option<ast::Label>,
426 ) -> Option<String> {
427 if block_has_statements(&block) {
431 let label_str = rewrite_label(label);
432 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
436 if !block_contains_comment(context, block) && shape.width >= 2 {
437 return Some(format!("{}{}{{}}", prefix, label_str));
440 // If a block contains only a single-line comment, then leave it on one line.
441 let user_str = context.snippet(block.span);
442 let user_str = user_str.trim();
443 if user_str.starts_with('{') && user_str.ends_with('}') {
444 let comment_str = user_str[1..user_str.len() - 1].trim();
445 if block.stmts.is_empty()
446 && !comment_str.contains('\n')
447 && !comment_str.starts_with("//")
448 && comment_str.len() + 4 <= shape.width
450 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
457 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
458 Some(match block.rules {
459 ast::BlockCheckMode::Unsafe(..) => {
460 let snippet = context.snippet(block.span);
461 let open_pos = snippet.find_uncommented("{")?;
462 // Extract comment between unsafe and block start.
463 let trimmed = &snippet[6..open_pos].trim();
465 if !trimmed.is_empty() {
466 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
467 let budget = shape.width.checked_sub(9)?;
473 Shape::legacy(budget, shape.indent + 7),
481 ast::BlockCheckMode::Default => String::new(),
485 fn rewrite_single_line_block(
486 context: &RewriteContext<'_>,
489 attrs: Option<&[ast::Attribute]>,
490 label: Option<ast::Label>,
492 ) -> Option<String> {
493 if is_simple_block(context, block, attrs) {
494 let expr_shape = shape.offset_left(last_line_width(prefix))?;
495 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
496 let label_str = rewrite_label(label);
497 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
498 if result.len() <= shape.width && !result.contains('\n') {
505 pub(crate) fn rewrite_block_with_visitor(
506 context: &RewriteContext<'_>,
509 attrs: Option<&[ast::Attribute]>,
510 label: Option<ast::Label>,
513 ) -> Option<String> {
514 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
518 let mut visitor = FmtVisitor::from_context(context);
519 visitor.block_indent = shape.indent;
520 visitor.is_if_else_block = context.is_if_else_block();
521 match (block.rules, label) {
522 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
523 let snippet = context.snippet(block.span);
524 let open_pos = snippet.find_uncommented("{")?;
525 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
527 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
530 let inner_attrs = attrs.map(inner_attributes);
531 let label_str = rewrite_label(label);
532 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
533 let visitor_context = visitor.get_context();
537 .append(&mut visitor_context.skipped_range.borrow_mut());
538 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
541 impl Rewrite for ast::Block {
542 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
543 rewrite_block(self, None, None, context, shape)
549 attrs: Option<&[ast::Attribute]>,
550 label: Option<ast::Label>,
551 context: &RewriteContext<'_>,
553 ) -> Option<String> {
554 let prefix = block_prefix(context, block, shape)?;
556 // shape.width is used only for the single line case: either the empty block `{}`,
557 // or an unsafe expression `unsafe { e }`.
558 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
562 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
563 if let Some(ref result_str) = result {
564 if result_str.lines().count() <= 3 {
565 if let rw @ Some(_) =
566 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
576 // Rewrite condition if the given expression has one.
577 pub(crate) fn rewrite_cond(
578 context: &RewriteContext<'_>,
581 ) -> Option<String> {
583 ast::ExprKind::Match(ref cond, _) => {
585 let cond_shape = match context.config.indent_style() {
586 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
587 IndentStyle::Block => shape.offset_left(8)?,
589 cond.rewrite(context, cond_shape)
591 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
593 String::from("\n") + &shape.indent.block_only().to_string(context.config);
595 .rewrite_cond(context, shape, &alt_block_sep)
596 .and_then(|rw| Some(rw.0))
601 // Abstraction over control flow expressions
603 struct ControlFlow<'a> {
604 cond: Option<&'a ast::Expr>,
605 block: &'a ast::Block,
606 else_block: Option<&'a ast::Expr>,
607 label: Option<ast::Label>,
608 pat: Option<&'a ast::Pat>,
612 allow_single_line: bool,
613 // HACK: `true` if this is an `if` expression in an `else if`.
618 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
620 ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
625 // FIXME: Refactor this.
626 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
628 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
629 let (pat, cond) = extract_pats_and_cond(cond);
630 Some(ControlFlow::new_if(
634 else_block.as_ref().map(|e| &**e),
635 expr_type == ExprType::SubExpression,
640 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
641 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
643 ast::ExprKind::Loop(ref block, label) => {
644 Some(ControlFlow::new_loop(block, label, expr.span))
646 ast::ExprKind::While(ref cond, ref block, label) => {
647 let (pat, cond) = extract_pats_and_cond(cond);
648 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
654 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
655 pat.map_or("", |_| "let")
658 impl<'a> ControlFlow<'a> {
661 pat: Option<&'a ast::Pat>,
662 block: &'a ast::Block,
663 else_block: Option<&'a ast::Expr>,
664 allow_single_line: bool,
667 ) -> ControlFlow<'a> {
668 let matcher = choose_matcher(pat);
684 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
694 allow_single_line: false,
701 pat: Option<&'a ast::Pat>,
703 block: &'a ast::Block,
704 label: Option<ast::Label>,
706 ) -> ControlFlow<'a> {
707 let matcher = choose_matcher(pat);
717 allow_single_line: false,
726 block: &'a ast::Block,
727 label: Option<ast::Label>,
729 ) -> ControlFlow<'a> {
739 allow_single_line: false,
745 fn rewrite_single_line(
748 context: &RewriteContext<'_>,
750 ) -> Option<String> {
751 assert!(self.allow_single_line);
752 let else_block = self.else_block?;
753 let fixed_cost = self.keyword.len() + " { } else { }".len();
755 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
756 if !is_simple_block(context, self.block, None)
757 || !is_simple_block(context, else_node, None)
758 || pat_expr_str.contains('\n')
763 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
764 let expr = &self.block.stmts[0];
765 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
767 let new_width = new_width.checked_sub(if_str.len())?;
768 let else_expr = &else_node.stmts[0];
769 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
771 if if_str.contains('\n') || else_str.contains('\n') {
775 let result = format!(
776 "{} {} {{ {} }} else {{ {} }}",
777 self.keyword, pat_expr_str, if_str, else_str
780 if result.len() <= width {
789 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
791 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
792 let mut leading_whitespaces = 0;
793 for c in pat_str.chars().rev() {
796 _ if c.is_whitespace() => leading_whitespaces += 1,
797 _ => leading_whitespaces = 0,
800 leading_whitespaces > start_column
803 impl<'a> ControlFlow<'a> {
806 context: &RewriteContext<'_>,
810 ) -> Option<String> {
811 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
813 let cond_shape = shape.offset_left(offset)?;
814 if let Some(pat) = self.pat {
815 let matcher = if self.matcher.is_empty() {
816 self.matcher.to_owned()
818 format!("{} ", self.matcher)
820 let pat_shape = cond_shape
821 .offset_left(matcher.len())?
822 .sub_width(self.connector.len())?;
823 let pat_string = pat.rewrite(context, pat_shape)?;
824 let comments_lo = context
826 .span_after(self.span, self.connector.trim());
827 let comments_span = mk_sp(comments_lo, expr.span.lo());
828 return rewrite_assign_rhs_with_comments(
830 &format!("{}{}{}", matcher, pat_string, self.connector),
839 let expr_rw = expr.rewrite(context, cond_shape);
840 // The expression may (partially) fit on the current line.
841 // We do not allow splitting between `if` and condition.
842 if self.keyword == "if" || expr_rw.is_some() {
846 // The expression won't fit on the current line, jump to next.
847 let nested_shape = shape
848 .block_indent(context.config.tab_spaces())
849 .with_max_width(context.config);
850 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
851 expr.rewrite(context, nested_shape)
852 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
857 context: &RewriteContext<'_>,
860 ) -> Option<(String, usize)> {
861 // Do not take the rhs overhead from the upper expressions into account
862 // when rewriting pattern.
863 let new_width = context.budget(shape.used_width());
864 let fresh_shape = Shape {
868 let constr_shape = if self.nested_if {
869 // We are part of an if-elseif-else chain. Our constraints are tightened.
870 // 7 = "} else " .len()
871 fresh_shape.offset_left(7)?
876 let label_string = rewrite_label(self.label);
877 // 1 = space after keyword.
878 let offset = self.keyword.len() + label_string.len() + 1;
880 let pat_expr_string = match self.cond {
881 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
882 None => String::new(),
886 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
892 let one_line_budget = context
895 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
896 let force_newline_brace = (pat_expr_string.contains('\n')
897 || pat_expr_string.len() > one_line_budget)
898 && (!last_line_extendable(&pat_expr_string)
899 || last_line_offsetted(shape.used_width(), &pat_expr_string));
901 // Try to format if-else on single line.
902 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
903 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
905 if let Some(cond_str) = trial {
906 if cond_str.len() <= context.config.single_line_if_else_max_width() {
907 return Some((cond_str, 0));
912 let cond_span = if let Some(cond) = self.cond {
915 mk_sp(self.block.span.lo(), self.block.span.lo())
918 // `for event in event`
919 // Do not include label in the span.
922 .map_or(self.span.lo(), |label| label.ident.span.hi());
923 let between_kwd_cond = mk_sp(
926 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
927 if self.pat.is_none() {
929 } else if self.matcher.is_empty() {
930 self.pat.unwrap().span.lo()
934 .span_before(self.span, self.matcher.trim())
938 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
940 let after_cond_comment =
941 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
943 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
945 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
946 || force_newline_brace
953 let used_width = if pat_expr_string.contains('\n') {
954 last_line_width(&pat_expr_string)
956 // 2 = spaces after keyword and condition.
957 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
965 between_kwd_cond_comment.as_ref().map_or(
966 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
974 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
981 impl<'a> Rewrite for ControlFlow<'a> {
982 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
983 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
985 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
986 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
987 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
989 return Some(cond_str);
992 let block_width = shape.width.saturating_sub(used_width);
993 // This is used only for the empty block case: `{}`. So, we use 1 if we know
994 // we should avoid the single line case.
995 let block_width = if self.else_block.is_some() || self.nested_if {
1000 let block_shape = Shape {
1005 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1007 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1008 context.is_if_else_block.replace(old_val);
1012 let mut result = format!("{}{}", cond_str, block_str);
1014 if let Some(else_block) = self.else_block {
1015 let shape = Shape::indented(shape.indent, context.config);
1016 let mut last_in_chain = false;
1017 let rewrite = match else_block.kind {
1018 // If the else expression is another if-else expression, prevent it
1019 // from being formatted on a single line.
1020 // Note how we're passing the original shape, as the
1021 // cost of "else" should not cascade.
1022 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1023 let (pats, cond) = extract_pats_and_cond(cond);
1024 ControlFlow::new_if(
1028 next_else_block.as_ref().map(|e| &**e),
1031 mk_sp(else_block.span.lo(), self.span.hi()),
1033 .rewrite(context, shape)
1036 last_in_chain = true;
1037 // When rewriting a block, the width is only used for single line
1038 // blocks, passing 1 lets us avoid that.
1039 let else_shape = Shape {
1040 width: min(1, shape.width),
1043 format_expr(else_block, ExprType::Statement, context, else_shape)
1047 let between_kwd_else_block = mk_sp(
1048 self.block.span.hi(),
1051 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1053 let between_kwd_else_block_comment =
1054 extract_comment(between_kwd_else_block, context, shape);
1056 let after_else = mk_sp(
1059 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1060 else_block.span.lo(),
1062 let after_else_comment = extract_comment(after_else, context, shape);
1064 let between_sep = match context.config.control_brace_style() {
1065 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1068 ControlBraceStyle::AlwaysSameLine => " ",
1070 let after_sep = match context.config.control_brace_style() {
1071 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1075 result.push_str(&format!(
1077 between_kwd_else_block_comment
1079 .map_or(between_sep, |s| &**s),
1080 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1082 result.push_str(&rewrite?);
1089 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1091 Some(label) => Cow::from(format!("{}: ", label.ident)),
1092 None => Cow::from(""),
1096 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1097 match rewrite_missing_comment(span, shape, context) {
1098 Some(ref comment) if !comment.is_empty() => Some(format!(
1099 "{indent}{}{indent}",
1101 indent = shape.indent.to_string_with_newline(context.config)
1107 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1108 contains_comment(context.snippet(block.span))
1111 // Checks that a block contains no statements, an expression and no comments or
1113 // FIXME: incorrectly returns false when comment is contained completely within
1115 pub(crate) fn is_simple_block(
1116 context: &RewriteContext<'_>,
1118 attrs: Option<&[ast::Attribute]>,
1120 block.stmts.len() == 1
1121 && stmt_is_expr(&block.stmts[0])
1122 && !block_contains_comment(context, block)
1123 && attrs.map_or(true, |a| a.is_empty())
1126 /// Checks whether a block contains at most one statement or expression, and no
1127 /// comments or attributes.
1128 pub(crate) fn is_simple_block_stmt(
1129 context: &RewriteContext<'_>,
1131 attrs: Option<&[ast::Attribute]>,
1133 block.stmts.len() <= 1
1134 && !block_contains_comment(context, block)
1135 && attrs.map_or(true, |a| a.is_empty())
1138 fn block_has_statements(block: &ast::Block) -> bool {
1142 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1145 /// Checks whether a block contains no statements, expressions, comments, or
1146 /// inner attributes.
1147 pub(crate) fn is_empty_block(
1148 context: &RewriteContext<'_>,
1150 attrs: Option<&[ast::Attribute]>,
1152 !block_has_statements(&block)
1153 && !block_contains_comment(context, block)
1154 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1157 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1159 ast::StmtKind::Expr(..) => true,
1164 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1165 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1172 pub(crate) fn rewrite_literal(
1173 context: &RewriteContext<'_>,
1176 ) -> Option<String> {
1178 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1180 context.snippet(l.span).to_owned(),
1181 context.config.max_width(),
1187 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1188 let string_lit = context.snippet(span);
1190 if !context.config.format_strings() {
1194 .all(|line| line.ends_with('\\'))
1195 && context.config.version() == Version::Two
1197 return Some(string_lit.to_owned());
1199 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1203 // Remove the quote characters.
1204 let str_lit = &string_lit[1..string_lit.len() - 1];
1208 &StringFormat::new(shape.visual_indent(0), context.config),
1209 shape.width.saturating_sub(2),
1213 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1214 if context.inside_macro() {
1215 if span_ends_with_comma(context, span) {
1216 Some(SeparatorTactic::Always)
1218 Some(SeparatorTactic::Never)
1225 pub(crate) fn rewrite_call(
1226 context: &RewriteContext<'_>,
1228 args: &[ptr::P<ast::Expr>],
1231 ) -> Option<String> {
1232 overflow::rewrite_with_parens(
1238 context.config.fn_call_width(),
1239 choose_separator_tactic(context, span),
1243 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1245 ast::ExprKind::Lit(..) => true,
1246 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1247 ast::ExprKind::AddrOf(_, _, ref expr)
1248 | ast::ExprKind::Box(ref expr)
1249 | ast::ExprKind::Cast(ref expr, _)
1250 | ast::ExprKind::Field(ref expr, _)
1251 | ast::ExprKind::Try(ref expr)
1252 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1253 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1254 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1255 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1261 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1262 lists.iter().all(OverflowableItem::is_simple)
1265 pub(crate) fn can_be_overflowed_expr(
1266 context: &RewriteContext<'_>,
1271 _ if !expr.attrs.is_empty() => false,
1272 ast::ExprKind::Match(..) => {
1273 (context.use_block_indent() && args_len == 1)
1274 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1275 || context.config.overflow_delimited_expr()
1277 ast::ExprKind::If(..)
1278 | ast::ExprKind::ForLoop(..)
1279 | ast::ExprKind::Loop(..)
1280 | ast::ExprKind::While(..) => {
1281 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1284 // Handle always block-like expressions
1285 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1287 // Handle `[]` and `{}`-like expressions
1288 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1289 context.config.overflow_delimited_expr()
1290 || (context.use_block_indent() && args_len == 1)
1292 ast::ExprKind::MacCall(ref mac) => {
1294 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
1295 context.config.overflow_delimited_expr(),
1297 (Some(ast::MacDelimiter::Bracket), true)
1298 | (Some(ast::MacDelimiter::Brace), true) => true,
1299 _ => context.use_block_indent() && args_len == 1,
1303 // Handle parenthetical expressions
1304 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1305 context.use_block_indent() && args_len == 1
1308 // Handle unary-like expressions
1309 ast::ExprKind::AddrOf(_, _, ref expr)
1310 | ast::ExprKind::Box(ref expr)
1311 | ast::ExprKind::Try(ref expr)
1312 | ast::ExprKind::Unary(_, ref expr)
1313 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1318 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1320 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1321 ast::ExprKind::AddrOf(_, _, ref expr)
1322 | ast::ExprKind::Box(ref expr)
1323 | ast::ExprKind::Try(ref expr)
1324 | ast::ExprKind::Unary(_, ref expr)
1325 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1330 /// Returns `true` if a function call or a method call represented by the given span ends with a
1331 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1332 /// comma from macro can potentially break the code.
1333 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1334 let mut result: bool = Default::default();
1335 let mut prev_char: char = Default::default();
1336 let closing_delimiters = &[')', '}', ']'];
1338 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1340 _ if kind.is_comment() || c.is_whitespace() => continue,
1341 c if closing_delimiters.contains(&c) => {
1342 result &= !closing_delimiters.contains(&prev_char);
1344 ',' => result = true,
1345 _ => result = false,
1354 context: &RewriteContext<'_>,
1355 mut subexpr: &ast::Expr,
1358 ) -> Option<String> {
1359 debug!("rewrite_paren, shape: {:?}", shape);
1361 // Extract comments within parens.
1364 let mut pre_comment;
1365 let mut post_comment;
1366 let remove_nested_parens = context.config.remove_nested_parens();
1369 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1370 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1371 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1372 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1374 // Remove nested parens if there are no comments.
1375 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1376 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1377 span = subexpr.span;
1378 subexpr = subsubexpr;
1387 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1388 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1389 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1390 if fits_single_line {
1391 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1393 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1397 fn rewrite_paren_in_multi_line(
1398 context: &RewriteContext<'_>,
1399 subexpr: &ast::Expr,
1403 ) -> Option<String> {
1404 let nested_indent = shape.indent.block_indent(context.config);
1405 let nested_shape = Shape::indented(nested_indent, context.config);
1406 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1407 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1408 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1410 let mut result = String::with_capacity(subexpr_str.len() * 2);
1412 if !pre_comment.is_empty() {
1413 result.push_str(&nested_indent.to_string_with_newline(context.config));
1414 result.push_str(&pre_comment);
1416 result.push_str(&nested_indent.to_string_with_newline(context.config));
1417 result.push_str(&subexpr_str);
1418 if !post_comment.is_empty() {
1419 result.push_str(&nested_indent.to_string_with_newline(context.config));
1420 result.push_str(&post_comment);
1422 result.push_str(&shape.indent.to_string_with_newline(context.config));
1431 context: &RewriteContext<'_>,
1433 ) -> Option<String> {
1434 let expr_str = expr.rewrite(context, shape)?;
1436 let offset = last_line_width(&expr_str) + 1;
1437 let rhs_overhead = shape.rhs_overhead(context.config);
1438 let index_shape = if expr_str.contains('\n') {
1439 Shape::legacy(context.config.max_width(), shape.indent)
1440 .offset_left(offset)
1441 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1443 match context.config.indent_style() {
1444 IndentStyle::Block => shape
1445 .offset_left(offset)
1446 .and_then(|shape| shape.sub_width(1)),
1447 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1450 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1452 // Return if index fits in a single line.
1453 match orig_index_rw {
1454 Some(ref index_str) if !index_str.contains('\n') => {
1455 return Some(format!("{}[{}]", expr_str, index_str));
1460 // Try putting index on the next line and see if it fits in a single line.
1461 let indent = shape.indent.block_indent(context.config);
1462 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1463 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1464 let new_index_rw = index.rewrite(context, index_shape);
1465 match (orig_index_rw, new_index_rw) {
1466 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1469 indent.to_string_with_newline(context.config),
1472 (None, Some(ref new_index_str)) => Some(format!(
1475 indent.to_string_with_newline(context.config),
1478 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1483 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1484 !has_base && fields.iter().all(|field| !field.is_shorthand)
1487 fn rewrite_struct_lit<'a>(
1488 context: &RewriteContext<'_>,
1490 fields: &'a [ast::ExprField],
1491 struct_rest: &ast::StructRest,
1492 attrs: &[ast::Attribute],
1495 ) -> Option<String> {
1496 debug!("rewrite_struct_lit: shape {:?}", shape);
1498 enum StructLitField<'a> {
1499 Regular(&'a ast::ExprField),
1500 Base(&'a ast::Expr),
1505 let path_shape = shape.sub_width(2)?;
1506 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1508 let has_base = match struct_rest {
1509 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1510 ast::StructRest::Rest(_) if fields.is_empty() => {
1511 return Some(format!("{} {{ .. }}", path_str));
1513 ast::StructRest::Base(_) => true,
1517 // Foo { a: Foo } - indent is +3, width is -5.
1518 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1520 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1521 let body_lo = context.snippet_provider.span_after(span, "{");
1522 let fields_str = if struct_lit_can_be_aligned(fields, has_base)
1523 && context.config.struct_field_align_threshold() > 0
1525 rewrite_with_alignment(
1529 mk_sp(body_lo, span.hi()),
1533 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1535 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1536 ast::StructRest::Rest(span) => Some(StructLitField::Rest(span)),
1537 ast::StructRest::None => None,
1542 let span_lo = |item: &StructLitField<'_>| match *item {
1543 StructLitField::Regular(field) => field.span().lo(),
1544 StructLitField::Base(expr) => {
1545 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1546 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1547 let pos = snippet.find_uncommented("..").unwrap();
1548 last_field_hi + BytePos(pos as u32)
1550 StructLitField::Rest(span) => span.lo(),
1552 let span_hi = |item: &StructLitField<'_>| match *item {
1553 StructLitField::Regular(field) => field.span().hi(),
1554 StructLitField::Base(expr) => expr.span.hi(),
1555 StructLitField::Rest(span) => span.hi(),
1557 let rewrite = |item: &StructLitField<'_>| match *item {
1558 StructLitField::Regular(field) => {
1559 // The 1 taken from the v_budget is for the comma.
1560 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1562 StructLitField::Base(expr) => {
1564 expr.rewrite(context, v_shape.offset_left(2)?)
1565 .map(|s| format!("..{}", s))
1567 StructLitField::Rest(_) => Some("..".to_owned()),
1570 let items = itemize_list(
1571 context.snippet_provider,
1582 let item_vec = items.collect::<Vec<_>>();
1584 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1585 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1587 let ends_with_comma = span_ends_with_comma(context, span);
1588 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1590 let fmt = struct_lit_formatting(
1594 force_no_trailing_comma
1596 || !context.use_block_indent()
1597 || matches!(struct_rest, ast::StructRest::Rest(_)),
1600 write_list(&item_vec, &fmt)?
1604 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1605 Some(format!("{} {{{}}}", path_str, fields_str))
1607 // FIXME if context.config.indent_style() == Visual, but we run out
1608 // of space, we should fall back to BlockIndent.
1611 pub(crate) fn wrap_struct_field(
1612 context: &RewriteContext<'_>,
1613 attrs: &[ast::Attribute],
1616 nested_shape: Shape,
1617 one_line_width: usize,
1618 ) -> Option<String> {
1619 let should_vertical = context.config.indent_style() == IndentStyle::Block
1620 && (fields_str.contains('\n')
1621 || !context.config.struct_lit_single_line()
1622 || fields_str.len() > one_line_width);
1624 let inner_attrs = &inner_attributes(attrs);
1625 if inner_attrs.is_empty() {
1626 if should_vertical {
1629 nested_shape.indent.to_string_with_newline(context.config),
1631 shape.indent.to_string_with_newline(context.config)
1634 // One liner or visual indent.
1635 Some(format!(" {} ", fields_str))
1640 nested_shape.indent.to_string_with_newline(context.config),
1641 inner_attrs.rewrite(context, shape)?,
1642 nested_shape.indent.to_string_with_newline(context.config),
1644 shape.indent.to_string_with_newline(context.config)
1649 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1650 colon_spaces(config)
1653 pub(crate) fn rewrite_field(
1654 context: &RewriteContext<'_>,
1655 field: &ast::ExprField,
1657 prefix_max_width: usize,
1658 ) -> Option<String> {
1659 if contains_skip(&field.attrs) {
1660 return Some(context.snippet(field.span()).to_owned());
1662 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1663 if !attrs_str.is_empty() {
1664 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1666 let name = context.snippet(field.ident.span);
1667 if field.is_shorthand {
1668 Some(attrs_str + name)
1670 let mut separator = String::from(struct_lit_field_separator(context.config));
1671 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1672 separator.push(' ');
1674 let overhead = name.len() + separator.len();
1675 let expr_shape = shape.offset_left(overhead)?;
1676 let expr = field.expr.rewrite(context, expr_shape);
1679 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1680 Some(attrs_str + name)
1682 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1684 let expr_offset = shape.indent.block_indent(context.config);
1687 .rewrite(context, Shape::indented(expr_offset, context.config));
1693 expr_offset.to_string(context.config),
1702 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1703 context: &RewriteContext<'_>,
1704 mut items: impl Iterator<Item = &'a T>,
1707 is_singleton_tuple: bool,
1708 ) -> Option<String> {
1709 // In case of length 1, need a trailing comma
1710 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1711 if is_singleton_tuple {
1713 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1717 .rewrite(context, nested_shape)
1718 .map(|s| format!("({},)", s));
1721 let list_lo = context.snippet_provider.span_after(span, "(");
1722 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1723 let items = itemize_list(
1724 context.snippet_provider,
1728 |item| item.span().lo(),
1729 |item| item.span().hi(),
1730 |item| item.rewrite(context, nested_shape),
1732 span.hi() - BytePos(1),
1735 let item_vec: Vec<_> = items.collect();
1736 let tactic = definitive_tactic(
1738 ListTactic::HorizontalVertical,
1742 let fmt = ListFormatting::new(nested_shape, context.config)
1744 .ends_with_newline(false);
1745 let list_str = write_list(&item_vec, &fmt)?;
1747 Some(format!("({})", list_str))
1750 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1751 context: &'a RewriteContext<'_>,
1752 items: impl Iterator<Item = &'a T>,
1755 is_singleton_tuple: bool,
1756 ) -> Option<String> {
1757 debug!("rewrite_tuple {:?}", shape);
1758 if context.use_block_indent() {
1759 // We use the same rule as function calls for rewriting tuples.
1760 let force_tactic = if context.inside_macro() {
1761 if span_ends_with_comma(context, span) {
1762 Some(SeparatorTactic::Always)
1764 Some(SeparatorTactic::Never)
1766 } else if is_singleton_tuple {
1767 Some(SeparatorTactic::Always)
1771 overflow::rewrite_with_parens(
1777 context.config.fn_call_width(),
1781 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1785 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1786 context: &RewriteContext<'_>,
1790 ) -> Option<String> {
1792 .rewrite(context, shape.offset_left(prefix.len())?)
1793 .map(|r| format!("{}{}", prefix, r))
1796 // FIXME: this is probably not correct for multi-line Rewrites. we should
1797 // subtract suffix.len() from the last line budget, not the first!
1798 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1799 context: &RewriteContext<'_>,
1803 ) -> Option<String> {
1805 .rewrite(context, shape.sub_width(suffix.len())?)
1812 fn rewrite_unary_op(
1813 context: &RewriteContext<'_>,
1817 ) -> Option<String> {
1818 // For some reason, an UnOp is not spanned like BinOp!
1819 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1822 fn rewrite_assignment(
1823 context: &RewriteContext<'_>,
1826 op: Option<&ast::BinOp>,
1828 ) -> Option<String> {
1829 let operator_str = match op {
1830 Some(op) => context.snippet(op.span),
1834 // 1 = space between lhs and operator.
1835 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1836 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1838 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1841 /// Controls where to put the rhs.
1842 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1843 pub(crate) enum RhsTactics {
1846 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1847 ForceNextLineWithoutIndent,
1848 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1853 // The left hand side must contain everything up to, and including, the
1854 // assignment operator.
1855 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1856 context: &RewriteContext<'_>,
1860 ) -> Option<String> {
1861 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1864 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1865 context: &RewriteContext<'_>,
1869 rhs_tactics: RhsTactics,
1870 ) -> Option<String> {
1871 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1872 shape.indent.width()
1876 // 1 = space between operator and rhs.
1877 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1879 offset: shape.offset + last_line_width + 1,
1882 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1883 lhs.trim_end().len() > offset + 1
1892 ex.rewrite(context, orig_shape),
1898 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1899 context: &RewriteContext<'_>,
1903 rhs_tactics: RhsTactics,
1904 ) -> Option<String> {
1905 let lhs = lhs.into();
1906 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
1910 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
1911 context: &RewriteContext<'_>,
1915 rhs_tactics: RhsTactics,
1918 ) -> Option<String> {
1919 let lhs = lhs.into();
1920 let contains_comment = contains_comment(context.snippet(between_span));
1921 let shape = if contains_comment {
1922 shape.block_left(context.config.tab_spaces())?
1926 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_tactics)?;
1928 if contains_comment {
1929 let rhs = rhs.trim_start();
1930 combine_strs_with_missing_comments(context, &lhs, &rhs, between_span, shape, allow_extend)
1936 fn choose_rhs<R: Rewrite>(
1937 context: &RewriteContext<'_>,
1940 orig_rhs: Option<String>,
1941 rhs_tactics: RhsTactics,
1942 has_rhs_comment: bool,
1943 ) -> Option<String> {
1946 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1948 Some(format!(" {}", new_str))
1951 // Expression did not fit on the same line as the identifier.
1952 // Try splitting the line and see if that works better.
1953 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1954 let new_rhs = expr.rewrite(context, new_shape);
1955 let new_indent_str = &shape
1957 .block_indent(context.config)
1958 .to_string_with_newline(context.config);
1959 let before_space_str = if has_rhs_comment { "" } else { " " };
1961 match (orig_rhs, new_rhs) {
1962 (Some(ref orig_rhs), Some(ref new_rhs))
1963 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1966 Some(format!("{}{}", before_space_str, orig_rhs))
1968 (Some(ref orig_rhs), Some(ref new_rhs))
1969 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1971 Some(format!("{}{}", new_indent_str, new_rhs))
1973 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1974 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1975 let shape = shape.infinite_width();
1976 expr.rewrite(context, shape)
1977 .map(|s| format!("{}{}", before_space_str, s))
1979 (None, None) => None,
1980 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
1986 fn shape_from_rhs_tactic(
1987 context: &RewriteContext<'_>,
1989 rhs_tactic: RhsTactics,
1990 ) -> Option<Shape> {
1992 RhsTactics::ForceNextLineWithoutIndent => shape
1993 .with_max_width(context.config)
1994 .sub_width(shape.indent.width()),
1995 RhsTactics::Default | RhsTactics::AllowOverflow => {
1996 Shape::indented(shape.indent.block_indent(context.config), context.config)
1997 .sub_width(shape.rhs_overhead(context.config))
2002 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2003 /// original's line formatting.
2005 /// It is considered better if:
2006 /// 1. the tactic is ForceNextLineWithoutIndent
2007 /// 2. next_line_rhs doesn't have newlines
2008 /// 3. the original line has more newlines than next_line_rhs
2009 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2011 pub(crate) fn prefer_next_line(
2013 next_line_rhs: &str,
2014 rhs_tactics: RhsTactics,
2016 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2017 || !next_line_rhs.contains('\n')
2018 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2019 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2020 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2021 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2024 fn rewrite_expr_addrof(
2025 context: &RewriteContext<'_>,
2026 borrow_kind: ast::BorrowKind,
2027 mutability: ast::Mutability,
2030 ) -> Option<String> {
2031 let operator_str = match (mutability, borrow_kind) {
2032 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2033 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2034 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2035 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2037 rewrite_unary_prefix(context, operator_str, expr, shape)
2040 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2042 ast::ExprKind::MethodCall(..) => true,
2043 ast::ExprKind::AddrOf(_, _, ref expr)
2044 | ast::ExprKind::Box(ref expr)
2045 | ast::ExprKind::Cast(ref expr, _)
2046 | ast::ExprKind::Try(ref expr)
2047 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2054 use super::last_line_offsetted;
2057 fn test_last_line_offsetted() {
2058 let lines = "one\n two";
2059 assert_eq!(last_line_offsetted(2, lines), true);
2060 assert_eq!(last_line_offsetted(4, lines), false);
2061 assert_eq!(last_line_offsetted(6, lines), false);
2063 let lines = "one two";
2064 assert_eq!(last_line_offsetted(2, lines), false);
2065 assert_eq!(last_line_offsetted(0, lines), false);
2067 let lines = "\ntwo";
2068 assert_eq!(last_line_offsetted(2, lines), false);
2069 assert_eq!(last_line_offsetted(0, lines), false);
2071 let lines = "one\n two three";
2072 assert_eq!(last_line_offsetted(2, lines), true);
2073 let lines = "one\n two three";
2074 assert_eq!(last_line_offsetted(2, lines), false);