4 use itertools::Itertools;
5 use rustc_ast::token::{Delimiter, LitKind};
6 use rustc_ast::{ast, ptr};
7 use rustc_span::{BytePos, Span};
9 use crate::chains::rewrite_chain;
12 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
13 rewrite_missing_comment, CharClasses, FindUncommented,
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, Version};
18 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
19 struct_lit_tactic, write_list, ListFormatting, Separator,
21 use crate::macros::{rewrite_macro, MacroPosition};
22 use crate::matches::rewrite_match;
23 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
24 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::{Indent, Shape};
27 use crate::source_map::{LineRangeUtils, SpanUtils};
28 use crate::spanned::Spanned;
29 use crate::string::{rewrite_string, StringFormat};
30 use crate::types::{rewrite_path, PathContext};
32 colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
33 last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr,
34 unicode_str_width, wrap_str,
36 use crate::vertical::rewrite_with_alignment;
37 use crate::visitor::FmtVisitor;
39 impl Rewrite for ast::Expr {
40 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
41 format_expr(self, ExprType::SubExpression, context, shape)
45 #[derive(Copy, Clone, PartialEq)]
46 pub(crate) enum ExprType {
51 pub(crate) fn format_expr(
54 context: &RewriteContext<'_>,
57 skip_out_of_file_lines_range!(context, expr.span);
59 if contains_skip(&*expr.attrs) {
60 return Some(context.snippet(expr.span()).to_owned());
62 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
68 let expr_rw = match expr.kind {
69 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
75 choose_separator_tactic(context, expr.span),
78 ast::ExprKind::Lit(ref l) => {
79 if let Some(expr_rw) = rewrite_literal(context, l, shape) {
82 if let LitKind::StrRaw(_) = l.token.kind {
83 Some(context.snippet(l.span).trim().into())
89 ast::ExprKind::Call(ref callee, ref args) => {
90 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
91 let callee_str = callee.rewrite(context, shape)?;
92 rewrite_call(context, &callee_str, args, inner_span, shape)
94 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
95 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
96 // FIXME: format comments between operands and operator
97 rewrite_all_pairs(expr, shape, context).or_else(|| {
101 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
104 context.config.binop_separator(),
108 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
109 ast::ExprKind::Struct(ref struct_expr) => {
110 let ast::StructExpr {
127 ast::ExprKind::Tup(ref items) => {
128 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
130 ast::ExprKind::Let(..) => None,
131 ast::ExprKind::If(..)
132 | ast::ExprKind::ForLoop(..)
133 | ast::ExprKind::Loop(..)
134 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
135 .and_then(|control_flow| control_flow.rewrite(context, shape)),
136 ast::ExprKind::ConstBlock(ref anon_const) => {
137 Some(format!("const {}", anon_const.rewrite(context, shape)?))
139 ast::ExprKind::Block(ref block, opt_label) => {
141 ExprType::Statement => {
142 if is_unsafe_block(block) {
143 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
144 } else if let rw @ Some(_) =
145 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
147 // Rewrite block without trying to put it in a single line.
150 let prefix = block_prefix(context, block, shape)?;
152 rewrite_block_with_visitor(
163 ExprType::SubExpression => {
164 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
168 ast::ExprKind::Match(ref cond, ref arms) => {
169 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
171 ast::ExprKind::Path(ref qself, ref path) => {
172 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
174 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
175 rewrite_assignment(context, lhs, rhs, None, shape)
177 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
178 rewrite_assignment(context, lhs, rhs, Some(op), shape)
180 ast::ExprKind::Continue(ref opt_label) => {
181 let id_str = match *opt_label {
182 Some(label) => format!(" {}", label.ident),
183 None => String::new(),
185 Some(format!("continue{}", id_str))
187 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
188 let id_str = match *opt_label {
189 Some(label) => format!(" {}", label.ident),
190 None => String::new(),
193 if let Some(ref expr) = *opt_expr {
194 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
196 Some(format!("break{}", id_str))
199 ast::ExprKind::Yield(ref opt_expr) => {
200 if let Some(ref expr) = *opt_expr {
201 rewrite_unary_prefix(context, "yield ", &**expr, shape)
203 Some("yield".to_string())
206 ast::ExprKind::Closure(
214 ) => closures::rewrite_closure(
215 binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape,
217 ast::ExprKind::Try(..)
218 | ast::ExprKind::Field(..)
219 | ast::ExprKind::MethodCall(..)
220 | ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
221 ast::ExprKind::MacCall(ref mac) => {
222 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
224 context.snippet(expr.span).to_owned(),
225 context.config.max_width(),
230 ast::ExprKind::Ret(None) => Some("return".to_owned()),
231 ast::ExprKind::Ret(Some(ref expr)) => {
232 rewrite_unary_prefix(context, "return ", &**expr, shape)
234 ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()),
235 ast::ExprKind::Yeet(Some(ref expr)) => {
236 rewrite_unary_prefix(context, "do yeet ", &**expr, shape)
238 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
239 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
240 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
242 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
245 PairParts::infix(" as "),
248 SeparatorPlace::Front,
250 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
253 PairParts::infix(": "),
256 SeparatorPlace::Back,
258 ast::ExprKind::Index(ref expr, ref index) => {
259 rewrite_index(&**expr, &**index, context, shape)
261 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
264 PairParts::new("[", "; ", "]"),
267 SeparatorPlace::Back,
269 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
270 let delim = match limits {
271 ast::RangeLimits::HalfOpen => "..",
272 ast::RangeLimits::Closed => "..=",
275 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
277 ast::ExprKind::Lit(ref lit) => match lit.kind {
278 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
279 context.snippet(lit.span).ends_with('.')
283 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
288 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
289 // Don't format `.. ..` into `....`, which is invalid.
291 // This check is unnecessary for `lhs`, because a range
292 // starting from another range needs parentheses as `(x ..) ..`
293 // (`x .. ..` is a range from `x` to `..`).
294 matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
297 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
298 let space_if = |b: bool| if b { " " } else { "" };
302 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
304 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
308 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
309 (Some(lhs), Some(rhs)) => {
310 let sp_delim = if context.config.spaces_around_ranges() {
311 format!(" {} ", delim)
313 default_sp_delim(Some(lhs), Some(rhs))
318 PairParts::infix(&sp_delim),
321 context.config.binop_separator(),
324 (None, Some(rhs)) => {
325 let sp_delim = if context.config.spaces_around_ranges() {
326 format!("{} ", delim)
328 default_sp_delim(None, Some(rhs))
330 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
332 (Some(lhs), None) => {
333 let sp_delim = if context.config.spaces_around_ranges() {
334 format!(" {}", delim)
336 default_sp_delim(Some(lhs), None)
338 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
340 (None, None) => Some(delim.to_owned()),
343 // We do not format these expressions yet, but they should still
344 // satisfy our width restrictions.
345 // Style Guide RFC for InlineAsm variant pending
346 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
347 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
348 ast::ExprKind::TryBlock(ref block) => {
349 if let rw @ Some(_) =
350 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
355 let budget = shape.width.saturating_sub(9);
364 Shape::legacy(budget, shape.indent)
369 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
370 let mover = if capture_by == ast::CaptureBy::Value {
375 if let rw @ Some(_) = rewrite_single_line_block(
377 format!("{}{}", "async ", mover).as_str(),
386 let budget = shape.width.saturating_sub(6);
396 Shape::legacy(budget, shape.indent)
401 ast::ExprKind::Underscore => Some("_".to_owned()),
402 ast::ExprKind::Err => None,
406 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
407 .and_then(|expr_str| {
408 let attrs = outer_attributes(&expr.attrs);
409 let attrs_str = attrs.rewrite(context, shape)?;
411 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
414 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
418 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
420 exprs: impl Iterator<Item = &'a T>,
422 context: &'a RewriteContext<'_>,
424 force_separator_tactic: Option<SeparatorTactic>,
425 delim_token: Option<Delimiter>,
426 ) -> Option<String> {
427 overflow::rewrite_with_square_brackets(
433 force_separator_tactic,
438 fn rewrite_empty_block(
439 context: &RewriteContext<'_>,
441 attrs: Option<&[ast::Attribute]>,
442 label: Option<ast::Label>,
445 ) -> Option<String> {
446 if block_has_statements(block) {
450 let label_str = rewrite_label(label);
451 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
455 if !block_contains_comment(context, block) && shape.width >= 2 {
456 return Some(format!("{}{}{{}}", prefix, label_str));
459 // If a block contains only a single-line comment, then leave it on one line.
460 let user_str = context.snippet(block.span);
461 let user_str = user_str.trim();
462 if user_str.starts_with('{') && user_str.ends_with('}') {
463 let comment_str = user_str[1..user_str.len() - 1].trim();
464 if block.stmts.is_empty()
465 && !comment_str.contains('\n')
466 && !comment_str.starts_with("//")
467 && comment_str.len() + 4 <= shape.width
469 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
476 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
477 Some(match block.rules {
478 ast::BlockCheckMode::Unsafe(..) => {
479 let snippet = context.snippet(block.span);
480 let open_pos = snippet.find_uncommented("{")?;
481 // Extract comment between unsafe and block start.
482 let trimmed = &snippet[6..open_pos].trim();
484 if !trimmed.is_empty() {
485 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
486 let budget = shape.width.checked_sub(9)?;
492 Shape::legacy(budget, shape.indent + 7),
500 ast::BlockCheckMode::Default => String::new(),
504 fn rewrite_single_line_block(
505 context: &RewriteContext<'_>,
508 attrs: Option<&[ast::Attribute]>,
509 label: Option<ast::Label>,
511 ) -> Option<String> {
512 if is_simple_block(context, block, attrs) {
513 let expr_shape = shape.offset_left(last_line_width(prefix))?;
514 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
515 let label_str = rewrite_label(label);
516 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
517 if result.len() <= shape.width && !result.contains('\n') {
524 pub(crate) fn rewrite_block_with_visitor(
525 context: &RewriteContext<'_>,
528 attrs: Option<&[ast::Attribute]>,
529 label: Option<ast::Label>,
532 ) -> Option<String> {
533 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
537 let mut visitor = FmtVisitor::from_context(context);
538 visitor.block_indent = shape.indent;
539 visitor.is_if_else_block = context.is_if_else_block();
540 match (block.rules, label) {
541 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
542 let snippet = context.snippet(block.span);
543 let open_pos = snippet.find_uncommented("{")?;
544 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
546 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
549 let inner_attrs = attrs.map(inner_attributes);
550 let label_str = rewrite_label(label);
551 visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
552 let visitor_context = visitor.get_context();
556 .append(&mut visitor_context.skipped_range.borrow_mut());
557 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
560 impl Rewrite for ast::Block {
561 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
562 rewrite_block(self, None, None, context, shape)
568 attrs: Option<&[ast::Attribute]>,
569 label: Option<ast::Label>,
570 context: &RewriteContext<'_>,
572 ) -> Option<String> {
573 let prefix = block_prefix(context, block, shape)?;
575 // shape.width is used only for the single line case: either the empty block `{}`,
576 // or an unsafe expression `unsafe { e }`.
577 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
581 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
582 if let Some(ref result_str) = result {
583 if result_str.lines().count() <= 3 {
584 if let rw @ Some(_) =
585 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
595 // Rewrite condition if the given expression has one.
596 pub(crate) fn rewrite_cond(
597 context: &RewriteContext<'_>,
600 ) -> Option<String> {
602 ast::ExprKind::Match(ref cond, _) => {
604 let cond_shape = match context.config.indent_style() {
605 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
606 IndentStyle::Block => shape.offset_left(8)?,
608 cond.rewrite(context, cond_shape)
610 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
612 String::from("\n") + &shape.indent.block_only().to_string(context.config);
614 .rewrite_cond(context, shape, &alt_block_sep)
620 // Abstraction over control flow expressions
622 struct ControlFlow<'a> {
623 cond: Option<&'a ast::Expr>,
624 block: &'a ast::Block,
625 else_block: Option<&'a ast::Expr>,
626 label: Option<ast::Label>,
627 pat: Option<&'a ast::Pat>,
631 allow_single_line: bool,
632 // HACK: `true` if this is an `if` expression in an `else if`.
637 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
639 ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
644 // FIXME: Refactor this.
645 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
647 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
648 let (pat, cond) = extract_pats_and_cond(cond);
649 Some(ControlFlow::new_if(
653 else_block.as_ref().map(|e| &**e),
654 expr_type == ExprType::SubExpression,
659 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
660 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
662 ast::ExprKind::Loop(ref block, label) => {
663 Some(ControlFlow::new_loop(block, label, expr.span))
665 ast::ExprKind::While(ref cond, ref block, label) => {
666 let (pat, cond) = extract_pats_and_cond(cond);
667 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
673 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
674 pat.map_or("", |_| "let")
677 impl<'a> ControlFlow<'a> {
680 pat: Option<&'a ast::Pat>,
681 block: &'a ast::Block,
682 else_block: Option<&'a ast::Expr>,
683 allow_single_line: bool,
686 ) -> ControlFlow<'a> {
687 let matcher = choose_matcher(pat);
703 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
713 allow_single_line: false,
720 pat: Option<&'a ast::Pat>,
722 block: &'a ast::Block,
723 label: Option<ast::Label>,
725 ) -> ControlFlow<'a> {
726 let matcher = choose_matcher(pat);
736 allow_single_line: false,
745 block: &'a ast::Block,
746 label: Option<ast::Label>,
748 ) -> ControlFlow<'a> {
758 allow_single_line: false,
764 fn rewrite_single_line(
767 context: &RewriteContext<'_>,
769 ) -> Option<String> {
770 assert!(self.allow_single_line);
771 let else_block = self.else_block?;
772 let fixed_cost = self.keyword.len() + " { } else { }".len();
774 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
775 if !is_simple_block(context, self.block, None)
776 || !is_simple_block(context, else_node, None)
777 || pat_expr_str.contains('\n')
782 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
783 let expr = &self.block.stmts[0];
784 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
786 let new_width = new_width.checked_sub(if_str.len())?;
787 let else_expr = &else_node.stmts[0];
788 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
790 if if_str.contains('\n') || else_str.contains('\n') {
794 let result = format!(
795 "{} {} {{ {} }} else {{ {} }}",
796 self.keyword, pat_expr_str, if_str, else_str
799 if result.len() <= width {
808 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
810 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
811 let mut leading_whitespaces = 0;
812 for c in pat_str.chars().rev() {
815 _ if c.is_whitespace() => leading_whitespaces += 1,
816 _ => leading_whitespaces = 0,
819 leading_whitespaces > start_column
822 impl<'a> ControlFlow<'a> {
825 context: &RewriteContext<'_>,
829 ) -> Option<String> {
830 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
832 let cond_shape = shape.offset_left(offset)?;
833 if let Some(pat) = self.pat {
834 let matcher = if self.matcher.is_empty() {
835 self.matcher.to_owned()
837 format!("{} ", self.matcher)
839 let pat_shape = cond_shape
840 .offset_left(matcher.len())?
841 .sub_width(self.connector.len())?;
842 let pat_string = pat.rewrite(context, pat_shape)?;
843 let comments_lo = context
845 .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
846 let comments_span = mk_sp(comments_lo, expr.span.lo());
847 return rewrite_assign_rhs_with_comments(
849 &format!("{}{}{}", matcher, pat_string, self.connector),
852 &RhsAssignKind::Expr(&expr.kind, expr.span),
859 let expr_rw = expr.rewrite(context, cond_shape);
860 // The expression may (partially) fit on the current line.
861 // We do not allow splitting between `if` and condition.
862 if self.keyword == "if" || expr_rw.is_some() {
866 // The expression won't fit on the current line, jump to next.
867 let nested_shape = shape
868 .block_indent(context.config.tab_spaces())
869 .with_max_width(context.config);
870 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
871 expr.rewrite(context, nested_shape)
872 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
877 context: &RewriteContext<'_>,
880 ) -> Option<(String, usize)> {
881 // Do not take the rhs overhead from the upper expressions into account
882 // when rewriting pattern.
883 let new_width = context.budget(shape.used_width());
884 let fresh_shape = Shape {
888 let constr_shape = if self.nested_if {
889 // We are part of an if-elseif-else chain. Our constraints are tightened.
890 // 7 = "} else " .len()
891 fresh_shape.offset_left(7)?
896 let label_string = rewrite_label(self.label);
897 // 1 = space after keyword.
898 let offset = self.keyword.len() + label_string.len() + 1;
900 let pat_expr_string = match self.cond {
901 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
902 None => String::new(),
906 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
912 let one_line_budget = context
915 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
916 let force_newline_brace = (pat_expr_string.contains('\n')
917 || pat_expr_string.len() > one_line_budget)
918 && (!last_line_extendable(&pat_expr_string)
919 || last_line_offsetted(shape.used_width(), &pat_expr_string));
921 // Try to format if-else on single line.
922 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
923 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
925 if let Some(cond_str) = trial {
926 if cond_str.len() <= context.config.single_line_if_else_max_width() {
927 return Some((cond_str, 0));
932 let cond_span = if let Some(cond) = self.cond {
935 mk_sp(self.block.span.lo(), self.block.span.lo())
938 // `for event in event`
939 // Do not include label in the span.
942 .map_or(self.span.lo(), |label| label.ident.span.hi());
943 let between_kwd_cond = mk_sp(
946 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
947 if self.pat.is_none() {
949 } else if self.matcher.is_empty() {
950 self.pat.unwrap().span.lo()
954 .span_before(self.span, self.matcher.trim())
958 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
960 let after_cond_comment =
961 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
963 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
965 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
966 || force_newline_brace
973 let used_width = if pat_expr_string.contains('\n') {
974 last_line_width(&pat_expr_string)
976 // 2 = spaces after keyword and condition.
977 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
985 between_kwd_cond_comment.as_ref().map_or(
986 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
994 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1001 impl<'a> Rewrite for ControlFlow<'a> {
1002 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1003 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1005 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1006 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1007 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1008 if used_width == 0 {
1009 return Some(cond_str);
1012 let block_width = shape.width.saturating_sub(used_width);
1013 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1014 // we should avoid the single line case.
1015 let block_width = if self.else_block.is_some() || self.nested_if {
1020 let block_shape = Shape {
1025 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1027 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1028 context.is_if_else_block.replace(old_val);
1032 let mut result = format!("{}{}", cond_str, block_str);
1034 if let Some(else_block) = self.else_block {
1035 let shape = Shape::indented(shape.indent, context.config);
1036 let mut last_in_chain = false;
1037 let rewrite = match else_block.kind {
1038 // If the else expression is another if-else expression, prevent it
1039 // from being formatted on a single line.
1040 // Note how we're passing the original shape, as the
1041 // cost of "else" should not cascade.
1042 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1043 let (pats, cond) = extract_pats_and_cond(cond);
1044 ControlFlow::new_if(
1048 next_else_block.as_ref().map(|e| &**e),
1051 mk_sp(else_block.span.lo(), self.span.hi()),
1053 .rewrite(context, shape)
1056 last_in_chain = true;
1057 // When rewriting a block, the width is only used for single line
1058 // blocks, passing 1 lets us avoid that.
1059 let else_shape = Shape {
1060 width: min(1, shape.width),
1063 format_expr(else_block, ExprType::Statement, context, else_shape)
1067 let between_kwd_else_block = mk_sp(
1068 self.block.span.hi(),
1071 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1073 let between_kwd_else_block_comment =
1074 extract_comment(between_kwd_else_block, context, shape);
1076 let after_else = mk_sp(
1079 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1080 else_block.span.lo(),
1082 let after_else_comment = extract_comment(after_else, context, shape);
1084 let between_sep = match context.config.control_brace_style() {
1085 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1088 ControlBraceStyle::AlwaysSameLine => " ",
1090 let after_sep = match context.config.control_brace_style() {
1091 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1095 result.push_str(&format!(
1097 between_kwd_else_block_comment
1099 .map_or(between_sep, |s| &**s),
1100 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1102 result.push_str(&rewrite?);
1109 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1111 Some(label) => Cow::from(format!("{}: ", label.ident)),
1112 None => Cow::from(""),
1116 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1117 match rewrite_missing_comment(span, shape, context) {
1118 Some(ref comment) if !comment.is_empty() => Some(format!(
1119 "{indent}{}{indent}",
1121 indent = shape.indent.to_string_with_newline(context.config)
1127 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1128 contains_comment(context.snippet(block.span))
1131 // Checks that a block contains no statements, an expression and no comments or
1133 // FIXME: incorrectly returns false when comment is contained completely within
1135 pub(crate) fn is_simple_block(
1136 context: &RewriteContext<'_>,
1138 attrs: Option<&[ast::Attribute]>,
1140 block.stmts.len() == 1
1141 && stmt_is_expr(&block.stmts[0])
1142 && !block_contains_comment(context, block)
1143 && attrs.map_or(true, |a| a.is_empty())
1146 /// Checks whether a block contains at most one statement or expression, and no
1147 /// comments or attributes.
1148 pub(crate) fn is_simple_block_stmt(
1149 context: &RewriteContext<'_>,
1151 attrs: Option<&[ast::Attribute]>,
1153 block.stmts.len() <= 1
1154 && !block_contains_comment(context, block)
1155 && attrs.map_or(true, |a| a.is_empty())
1158 fn block_has_statements(block: &ast::Block) -> bool {
1162 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1165 /// Checks whether a block contains no statements, expressions, comments, or
1166 /// inner attributes.
1167 pub(crate) fn is_empty_block(
1168 context: &RewriteContext<'_>,
1170 attrs: Option<&[ast::Attribute]>,
1172 !block_has_statements(block)
1173 && !block_contains_comment(context, block)
1174 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1177 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1178 matches!(stmt.kind, ast::StmtKind::Expr(..))
1181 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1182 matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1185 pub(crate) fn rewrite_literal(
1186 context: &RewriteContext<'_>,
1189 ) -> Option<String> {
1191 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1192 ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape),
1194 context.snippet(l.span).to_owned(),
1195 context.config.max_width(),
1201 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1202 let string_lit = context.snippet(span);
1204 if !context.config.format_strings() {
1208 .all(|line| line.ends_with('\\'))
1209 && context.config.version() == Version::Two
1211 return Some(string_lit.to_owned());
1213 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1217 // Remove the quote characters.
1218 let str_lit = &string_lit[1..string_lit.len() - 1];
1222 &StringFormat::new(shape.visual_indent(0), context.config),
1223 shape.width.saturating_sub(2),
1227 fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option<String> {
1228 let span = lit.span;
1229 let symbol = lit.token.symbol.as_str();
1231 if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1232 let hex_lit = match context.config.hex_literal_case() {
1233 HexLiteralCase::Preserve => None,
1234 HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1235 HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1237 if let Some(hex_lit) = hex_lit {
1242 lit.token.suffix.map_or(String::new(), |s| s.to_string())
1244 context.config.max_width(),
1251 context.snippet(span).to_owned(),
1252 context.config.max_width(),
1257 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1258 if context.inside_macro() {
1259 if span_ends_with_comma(context, span) {
1260 Some(SeparatorTactic::Always)
1262 Some(SeparatorTactic::Never)
1269 pub(crate) fn rewrite_call(
1270 context: &RewriteContext<'_>,
1272 args: &[ptr::P<ast::Expr>],
1275 ) -> Option<String> {
1276 overflow::rewrite_with_parens(
1282 context.config.fn_call_width(),
1283 choose_separator_tactic(context, span),
1287 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1289 ast::ExprKind::Lit(..) => true,
1290 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1291 ast::ExprKind::AddrOf(_, _, ref expr)
1292 | ast::ExprKind::Box(ref expr)
1293 | ast::ExprKind::Cast(ref expr, _)
1294 | ast::ExprKind::Field(ref expr, _)
1295 | ast::ExprKind::Try(ref expr)
1296 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1297 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1298 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1299 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1305 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1306 lists.iter().all(OverflowableItem::is_simple)
1309 pub(crate) fn can_be_overflowed_expr(
1310 context: &RewriteContext<'_>,
1315 _ if !expr.attrs.is_empty() => false,
1316 ast::ExprKind::Match(..) => {
1317 (context.use_block_indent() && args_len == 1)
1318 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1319 || context.config.overflow_delimited_expr()
1321 ast::ExprKind::If(..)
1322 | ast::ExprKind::ForLoop(..)
1323 | ast::ExprKind::Loop(..)
1324 | ast::ExprKind::While(..) => {
1325 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1328 // Handle always block-like expressions
1329 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1331 // Handle `[]` and `{}`-like expressions
1332 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1333 context.config.overflow_delimited_expr()
1334 || (context.use_block_indent() && args_len == 1)
1336 ast::ExprKind::MacCall(ref mac) => {
1338 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim().unwrap()),
1339 context.config.overflow_delimited_expr(),
1341 (Some(ast::MacDelimiter::Bracket), true)
1342 | (Some(ast::MacDelimiter::Brace), true) => true,
1343 _ => context.use_block_indent() && args_len == 1,
1347 // Handle parenthetical expressions
1348 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1349 context.use_block_indent() && args_len == 1
1352 // Handle unary-like expressions
1353 ast::ExprKind::AddrOf(_, _, ref expr)
1354 | ast::ExprKind::Box(ref expr)
1355 | ast::ExprKind::Try(ref expr)
1356 | ast::ExprKind::Unary(_, ref expr)
1357 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1362 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1364 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1365 ast::ExprKind::AddrOf(_, _, ref expr)
1366 | ast::ExprKind::Box(ref expr)
1367 | ast::ExprKind::Try(ref expr)
1368 | ast::ExprKind::Unary(_, ref expr)
1369 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1374 /// Returns `true` if a function call or a method call represented by the given span ends with a
1375 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1376 /// comma from macro can potentially break the code.
1377 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1378 let mut result: bool = Default::default();
1379 let mut prev_char: char = Default::default();
1380 let closing_delimiters = &[')', '}', ']'];
1382 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1384 _ if kind.is_comment() || c.is_whitespace() => continue,
1385 c if closing_delimiters.contains(&c) => {
1386 result &= !closing_delimiters.contains(&prev_char);
1388 ',' => result = true,
1389 _ => result = false,
1398 context: &RewriteContext<'_>,
1399 mut subexpr: &ast::Expr,
1402 ) -> Option<String> {
1403 debug!("rewrite_paren, shape: {:?}", shape);
1405 // Extract comments within parens.
1408 let mut pre_comment;
1409 let mut post_comment;
1410 let remove_nested_parens = context.config.remove_nested_parens();
1413 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1414 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1415 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1416 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1418 // Remove nested parens if there are no comments.
1419 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1420 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1421 span = subexpr.span;
1422 subexpr = subsubexpr;
1431 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1432 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1433 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1434 if fits_single_line {
1435 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1437 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1441 fn rewrite_paren_in_multi_line(
1442 context: &RewriteContext<'_>,
1443 subexpr: &ast::Expr,
1447 ) -> Option<String> {
1448 let nested_indent = shape.indent.block_indent(context.config);
1449 let nested_shape = Shape::indented(nested_indent, context.config);
1450 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1451 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1452 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1454 let mut result = String::with_capacity(subexpr_str.len() * 2);
1456 if !pre_comment.is_empty() {
1457 result.push_str(&nested_indent.to_string_with_newline(context.config));
1458 result.push_str(&pre_comment);
1460 result.push_str(&nested_indent.to_string_with_newline(context.config));
1461 result.push_str(&subexpr_str);
1462 if !post_comment.is_empty() {
1463 result.push_str(&nested_indent.to_string_with_newline(context.config));
1464 result.push_str(&post_comment);
1466 result.push_str(&shape.indent.to_string_with_newline(context.config));
1475 context: &RewriteContext<'_>,
1477 ) -> Option<String> {
1478 let expr_str = expr.rewrite(context, shape)?;
1480 let offset = last_line_width(&expr_str) + 1;
1481 let rhs_overhead = shape.rhs_overhead(context.config);
1482 let index_shape = if expr_str.contains('\n') {
1483 Shape::legacy(context.config.max_width(), shape.indent)
1484 .offset_left(offset)
1485 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1487 match context.config.indent_style() {
1488 IndentStyle::Block => shape
1489 .offset_left(offset)
1490 .and_then(|shape| shape.sub_width(1)),
1491 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1494 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1496 // Return if index fits in a single line.
1497 match orig_index_rw {
1498 Some(ref index_str) if !index_str.contains('\n') => {
1499 return Some(format!("{}[{}]", expr_str, index_str));
1504 // Try putting index on the next line and see if it fits in a single line.
1505 let indent = shape.indent.block_indent(context.config);
1506 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1507 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1508 let new_index_rw = index.rewrite(context, index_shape);
1509 match (orig_index_rw, new_index_rw) {
1510 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1513 indent.to_string_with_newline(context.config),
1516 (None, Some(ref new_index_str)) => Some(format!(
1519 indent.to_string_with_newline(context.config),
1522 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1527 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1528 !has_base && fields.iter().all(|field| !field.is_shorthand)
1531 fn rewrite_struct_lit<'a>(
1532 context: &RewriteContext<'_>,
1534 qself: Option<&ast::QSelf>,
1535 fields: &'a [ast::ExprField],
1536 struct_rest: &ast::StructRest,
1537 attrs: &[ast::Attribute],
1540 ) -> Option<String> {
1541 debug!("rewrite_struct_lit: shape {:?}", shape);
1543 enum StructLitField<'a> {
1544 Regular(&'a ast::ExprField),
1545 Base(&'a ast::Expr),
1550 let path_shape = shape.sub_width(2)?;
1551 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1553 let has_base_or_rest = match struct_rest {
1554 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1555 ast::StructRest::Rest(_) if fields.is_empty() => {
1556 return Some(format!("{} {{ .. }}", path_str));
1558 ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1562 // Foo { a: Foo } - indent is +3, width is -5.
1563 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1565 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1566 let body_lo = context.snippet_provider.span_after(span, "{");
1567 let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1568 && context.config.struct_field_align_threshold() > 0
1570 rewrite_with_alignment(
1574 mk_sp(body_lo, span.hi()),
1578 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1580 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1581 ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1582 ast::StructRest::None => None,
1587 let span_lo = |item: &StructLitField<'_>| match *item {
1588 StructLitField::Regular(field) => field.span().lo(),
1589 StructLitField::Base(expr) => {
1590 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1591 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1592 let pos = snippet.find_uncommented("..").unwrap();
1593 last_field_hi + BytePos(pos as u32)
1595 StructLitField::Rest(span) => span.lo(),
1597 let span_hi = |item: &StructLitField<'_>| match *item {
1598 StructLitField::Regular(field) => field.span().hi(),
1599 StructLitField::Base(expr) => expr.span.hi(),
1600 StructLitField::Rest(span) => span.hi(),
1602 let rewrite = |item: &StructLitField<'_>| match *item {
1603 StructLitField::Regular(field) => {
1604 // The 1 taken from the v_budget is for the comma.
1605 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1607 StructLitField::Base(expr) => {
1609 expr.rewrite(context, v_shape.offset_left(2)?)
1610 .map(|s| format!("..{}", s))
1612 StructLitField::Rest(_) => Some("..".to_owned()),
1615 let items = itemize_list(
1616 context.snippet_provider,
1627 let item_vec = items.collect::<Vec<_>>();
1629 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1630 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1632 let ends_with_comma = span_ends_with_comma(context, span);
1633 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1635 let fmt = struct_lit_formatting(
1639 force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1642 write_list(&item_vec, &fmt)?
1646 wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1647 Some(format!("{} {{{}}}", path_str, fields_str))
1649 // FIXME if context.config.indent_style() == Visual, but we run out
1650 // of space, we should fall back to BlockIndent.
1653 pub(crate) fn wrap_struct_field(
1654 context: &RewriteContext<'_>,
1655 attrs: &[ast::Attribute],
1658 nested_shape: Shape,
1659 one_line_width: usize,
1660 ) -> Option<String> {
1661 let should_vertical = context.config.indent_style() == IndentStyle::Block
1662 && (fields_str.contains('\n')
1663 || !context.config.struct_lit_single_line()
1664 || fields_str.len() > one_line_width);
1666 let inner_attrs = &inner_attributes(attrs);
1667 if inner_attrs.is_empty() {
1668 if should_vertical {
1671 nested_shape.indent.to_string_with_newline(context.config),
1673 shape.indent.to_string_with_newline(context.config)
1676 // One liner or visual indent.
1677 Some(format!(" {} ", fields_str))
1682 nested_shape.indent.to_string_with_newline(context.config),
1683 inner_attrs.rewrite(context, shape)?,
1684 nested_shape.indent.to_string_with_newline(context.config),
1686 shape.indent.to_string_with_newline(context.config)
1691 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1692 colon_spaces(config)
1695 pub(crate) fn rewrite_field(
1696 context: &RewriteContext<'_>,
1697 field: &ast::ExprField,
1699 prefix_max_width: usize,
1700 ) -> Option<String> {
1701 if contains_skip(&field.attrs) {
1702 return Some(context.snippet(field.span()).to_owned());
1704 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1705 if !attrs_str.is_empty() {
1706 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1708 let name = context.snippet(field.ident.span);
1709 if field.is_shorthand {
1710 Some(attrs_str + name)
1712 let mut separator = String::from(struct_lit_field_separator(context.config));
1713 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1714 separator.push(' ');
1716 let overhead = name.len() + separator.len();
1717 let expr_shape = shape.offset_left(overhead)?;
1718 let expr = field.expr.rewrite(context, expr_shape);
1721 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1722 Some(attrs_str + name)
1724 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1726 let expr_offset = shape.indent.block_indent(context.config);
1729 .rewrite(context, Shape::indented(expr_offset, context.config));
1735 expr_offset.to_string(context.config),
1744 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1745 context: &RewriteContext<'_>,
1746 mut items: impl Iterator<Item = &'a T>,
1749 is_singleton_tuple: bool,
1750 ) -> Option<String> {
1751 // In case of length 1, need a trailing comma
1752 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1753 if is_singleton_tuple {
1755 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1759 .rewrite(context, nested_shape)
1760 .map(|s| format!("({},)", s));
1763 let list_lo = context.snippet_provider.span_after(span, "(");
1764 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1765 let items = itemize_list(
1766 context.snippet_provider,
1770 |item| item.span().lo(),
1771 |item| item.span().hi(),
1772 |item| item.rewrite(context, nested_shape),
1774 span.hi() - BytePos(1),
1777 let item_vec: Vec<_> = items.collect();
1778 let tactic = definitive_tactic(
1780 ListTactic::HorizontalVertical,
1784 let fmt = ListFormatting::new(nested_shape, context.config)
1786 .ends_with_newline(false);
1787 let list_str = write_list(&item_vec, &fmt)?;
1789 Some(format!("({})", list_str))
1792 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1793 context: &'a RewriteContext<'_>,
1794 items: impl Iterator<Item = &'a T>,
1797 is_singleton_tuple: bool,
1798 ) -> Option<String> {
1799 debug!("rewrite_tuple {:?}", shape);
1800 if context.use_block_indent() {
1801 // We use the same rule as function calls for rewriting tuples.
1802 let force_tactic = if context.inside_macro() {
1803 if span_ends_with_comma(context, span) {
1804 Some(SeparatorTactic::Always)
1806 Some(SeparatorTactic::Never)
1808 } else if is_singleton_tuple {
1809 Some(SeparatorTactic::Always)
1813 overflow::rewrite_with_parens(
1819 context.config.fn_call_width(),
1823 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1827 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1828 context: &RewriteContext<'_>,
1832 ) -> Option<String> {
1834 .rewrite(context, shape.offset_left(prefix.len())?)
1835 .map(|r| format!("{}{}", prefix, r))
1838 // FIXME: this is probably not correct for multi-line Rewrites. we should
1839 // subtract suffix.len() from the last line budget, not the first!
1840 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1841 context: &RewriteContext<'_>,
1845 ) -> Option<String> {
1847 .rewrite(context, shape.sub_width(suffix.len())?)
1854 fn rewrite_unary_op(
1855 context: &RewriteContext<'_>,
1859 ) -> Option<String> {
1860 // For some reason, an UnOp is not spanned like BinOp!
1861 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1864 pub(crate) enum RhsAssignKind<'ast> {
1865 Expr(&'ast ast::ExprKind, Span),
1870 impl<'ast> RhsAssignKind<'ast> {
1871 // TODO(calebcartwright)
1872 // Preemptive addition for handling RHS with chains, not yet utilized.
1873 // It may make more sense to construct the chain first and then check
1874 // whether there are actually chain elements.
1876 fn is_chain(&self) -> bool {
1878 RhsAssignKind::Expr(kind, _) => {
1881 ast::ExprKind::Try(..)
1882 | ast::ExprKind::Field(..)
1883 | ast::ExprKind::MethodCall(..)
1884 | ast::ExprKind::Await(_)
1892 fn rewrite_assignment(
1893 context: &RewriteContext<'_>,
1896 op: Option<&ast::BinOp>,
1898 ) -> Option<String> {
1899 let operator_str = match op {
1900 Some(op) => context.snippet(op.span),
1904 // 1 = space between lhs and operator.
1905 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1906 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1912 &RhsAssignKind::Expr(&rhs.kind, rhs.span),
1917 /// Controls where to put the rhs.
1918 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1919 pub(crate) enum RhsTactics {
1922 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1923 ForceNextLineWithoutIndent,
1924 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1929 // The left hand side must contain everything up to, and including, the
1930 // assignment operator.
1931 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1932 context: &RewriteContext<'_>,
1935 rhs_kind: &RhsAssignKind<'_>,
1937 ) -> Option<String> {
1938 rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
1941 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1942 context: &RewriteContext<'_>,
1946 rhs_kind: &RhsAssignKind<'_>,
1947 rhs_tactics: RhsTactics,
1948 ) -> Option<String> {
1949 let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1950 shape.indent.width()
1954 // 1 = space between operator and rhs.
1955 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1957 offset: shape.offset + last_line_width + 1,
1960 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
1961 lhs.trim_end().len() > offset + 1
1970 ex.rewrite(context, orig_shape),
1977 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1978 context: &RewriteContext<'_>,
1982 rhs_kind: &RhsAssignKind<'_>,
1983 rhs_tactics: RhsTactics,
1984 ) -> Option<String> {
1985 let lhs = lhs.into();
1986 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
1990 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
1991 context: &RewriteContext<'_>,
1995 rhs_kind: &RhsAssignKind<'_>,
1996 rhs_tactics: RhsTactics,
1999 ) -> Option<String> {
2000 let lhs = lhs.into();
2001 let contains_comment = contains_comment(context.snippet(between_span));
2002 let shape = if contains_comment {
2003 shape.block_left(context.config.tab_spaces())?
2007 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2009 if contains_comment {
2010 let rhs = rhs.trim_start();
2011 combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2017 fn choose_rhs<R: Rewrite>(
2018 context: &RewriteContext<'_>,
2021 orig_rhs: Option<String>,
2022 _rhs_kind: &RhsAssignKind<'_>,
2023 rhs_tactics: RhsTactics,
2024 has_rhs_comment: bool,
2025 ) -> Option<String> {
2027 Some(ref new_str) if new_str.is_empty() => Some(String::new()),
2029 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
2031 Some(format!(" {}", new_str))
2034 // Expression did not fit on the same line as the identifier.
2035 // Try splitting the line and see if that works better.
2036 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
2037 let new_rhs = expr.rewrite(context, new_shape);
2038 let new_indent_str = &shape
2040 .block_indent(context.config)
2041 .to_string_with_newline(context.config);
2042 let before_space_str = if has_rhs_comment { "" } else { " " };
2044 match (orig_rhs, new_rhs) {
2045 (Some(ref orig_rhs), Some(ref new_rhs))
2046 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2049 Some(format!("{}{}", before_space_str, orig_rhs))
2051 (Some(ref orig_rhs), Some(ref new_rhs))
2052 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2054 Some(format!("{}{}", new_indent_str, new_rhs))
2056 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2057 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2058 let shape = shape.infinite_width();
2059 expr.rewrite(context, shape)
2060 .map(|s| format!("{}{}", before_space_str, s))
2062 (None, None) => None,
2063 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2069 fn shape_from_rhs_tactic(
2070 context: &RewriteContext<'_>,
2072 rhs_tactic: RhsTactics,
2073 ) -> Option<Shape> {
2075 RhsTactics::ForceNextLineWithoutIndent => shape
2076 .with_max_width(context.config)
2077 .sub_width(shape.indent.width()),
2078 RhsTactics::Default | RhsTactics::AllowOverflow => {
2079 Shape::indented(shape.indent.block_indent(context.config), context.config)
2080 .sub_width(shape.rhs_overhead(context.config))
2085 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2086 /// original's line formatting.
2088 /// It is considered better if:
2089 /// 1. the tactic is ForceNextLineWithoutIndent
2090 /// 2. next_line_rhs doesn't have newlines
2091 /// 3. the original line has more newlines than next_line_rhs
2092 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2094 pub(crate) fn prefer_next_line(
2096 next_line_rhs: &str,
2097 rhs_tactics: RhsTactics,
2099 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2100 || !next_line_rhs.contains('\n')
2101 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2102 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2103 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2104 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2107 fn rewrite_expr_addrof(
2108 context: &RewriteContext<'_>,
2109 borrow_kind: ast::BorrowKind,
2110 mutability: ast::Mutability,
2113 ) -> Option<String> {
2114 let operator_str = match (mutability, borrow_kind) {
2115 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2116 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2117 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2118 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2120 rewrite_unary_prefix(context, operator_str, expr, shape)
2123 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2125 ast::ExprKind::MethodCall(..) => true,
2126 ast::ExprKind::AddrOf(_, _, ref expr)
2127 | ast::ExprKind::Box(ref expr)
2128 | ast::ExprKind::Cast(ref expr, _)
2129 | ast::ExprKind::Try(ref expr)
2130 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2137 use super::last_line_offsetted;
2140 fn test_last_line_offsetted() {
2141 let lines = "one\n two";
2142 assert_eq!(last_line_offsetted(2, lines), true);
2143 assert_eq!(last_line_offsetted(4, lines), false);
2144 assert_eq!(last_line_offsetted(6, lines), false);
2146 let lines = "one two";
2147 assert_eq!(last_line_offsetted(2, lines), false);
2148 assert_eq!(last_line_offsetted(0, lines), false);
2150 let lines = "\ntwo";
2151 assert_eq!(last_line_offsetted(2, lines), false);
2152 assert_eq!(last_line_offsetted(0, lines), false);
2154 let lines = "one\n two three";
2155 assert_eq!(last_line_offsetted(2, lines), true);
2156 let lines = "one\n two three";
2157 assert_eq!(last_line_offsetted(2, lines), false);