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, comment_style, contains_comment, recover_comment_removed,
13 rewrite_comment, 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 path, ref fields, ref struct_rest) => rewrite_struct_lit(
118 ast::ExprKind::Tup(ref items) => {
119 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
121 ast::ExprKind::Let(..) => None,
122 ast::ExprKind::If(..)
123 | ast::ExprKind::ForLoop(..)
124 | ast::ExprKind::Loop(..)
125 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
126 .and_then(|control_flow| control_flow.rewrite(context, shape)),
127 ast::ExprKind::ConstBlock(ref anon_const) => {
128 Some(format!("const {}", anon_const.rewrite(context, shape)?))
130 ast::ExprKind::Block(ref block, opt_label) => {
132 ExprType::Statement => {
133 if is_unsafe_block(block) {
134 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
135 } else if let rw @ Some(_) =
136 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
138 // Rewrite block without trying to put it in a single line.
141 let prefix = block_prefix(context, block, shape)?;
143 rewrite_block_with_visitor(
154 ExprType::SubExpression => {
155 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
159 ast::ExprKind::Match(ref cond, ref arms) => {
160 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
162 ast::ExprKind::Path(ref qself, ref path) => {
163 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
165 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
166 rewrite_assignment(context, lhs, rhs, None, shape)
168 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
169 rewrite_assignment(context, lhs, rhs, Some(op), shape)
171 ast::ExprKind::Continue(ref opt_label) => {
172 let id_str = match *opt_label {
173 Some(label) => format!(" {}", label.ident),
174 None => String::new(),
176 Some(format!("continue{}", id_str))
178 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
179 let id_str = match *opt_label {
180 Some(label) => format!(" {}", label.ident),
181 None => String::new(),
184 if let Some(ref expr) = *opt_expr {
185 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
187 Some(format!("break{}", id_str))
190 ast::ExprKind::Yield(ref opt_expr) => {
191 if let Some(ref expr) = *opt_expr {
192 rewrite_unary_prefix(context, "yield ", &**expr, shape)
194 Some("yield".to_string())
197 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
198 closures::rewrite_closure(
199 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
202 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
203 rewrite_chain(expr, context, shape)
205 ast::ExprKind::MacCall(ref mac) => {
206 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
208 context.snippet(expr.span).to_owned(),
209 context.config.max_width(),
214 ast::ExprKind::Ret(None) => Some("return".to_owned()),
215 ast::ExprKind::Ret(Some(ref expr)) => {
216 rewrite_unary_prefix(context, "return ", &**expr, shape)
218 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
219 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
220 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
222 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
225 PairParts::infix(" as "),
228 SeparatorPlace::Front,
230 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
233 PairParts::infix(": "),
236 SeparatorPlace::Back,
238 ast::ExprKind::Index(ref expr, ref index) => {
239 rewrite_index(&**expr, &**index, context, shape)
241 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
244 PairParts::new("[", "; ", "]"),
247 SeparatorPlace::Back,
249 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
250 let delim = match limits {
251 ast::RangeLimits::HalfOpen => "..",
252 ast::RangeLimits::Closed => "..=",
255 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
257 ast::ExprKind::Lit(ref lit) => match lit.kind {
258 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
259 context.snippet(lit.span).ends_with('.')
263 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
268 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
270 // Don't format `.. ..` into `....`, which is invalid.
272 // This check is unnecessary for `lhs`, because a range
273 // starting from another range needs parentheses as `(x ..) ..`
274 // (`x .. ..` is a range from `x` to `..`).
275 ast::ExprKind::Range(None, _, _) => true,
280 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
281 let space_if = |b: bool| if b { " " } else { "" };
285 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
287 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
291 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
292 (Some(lhs), Some(rhs)) => {
293 let sp_delim = if context.config.spaces_around_ranges() {
294 format!(" {} ", delim)
296 default_sp_delim(Some(lhs), Some(rhs))
301 PairParts::infix(&sp_delim),
304 context.config.binop_separator(),
307 (None, Some(rhs)) => {
308 let sp_delim = if context.config.spaces_around_ranges() {
309 format!("{} ", delim)
311 default_sp_delim(None, Some(rhs))
313 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
315 (Some(lhs), None) => {
316 let sp_delim = if context.config.spaces_around_ranges() {
317 format!(" {}", delim)
319 default_sp_delim(Some(lhs), None)
321 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
323 (None, None) => Some(delim.to_owned()),
326 // We do not format these expressions yet, but they should still
327 // satisfy our width restrictions.
328 // Style Guide RFC for InlineAsm variant pending
329 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
330 ast::ExprKind::LlvmInlineAsm(..) | ast::ExprKind::InlineAsm(..) => {
331 Some(context.snippet(expr.span).to_owned())
333 ast::ExprKind::TryBlock(ref block) => {
334 if let rw @ Some(_) =
335 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
340 let budget = shape.width.saturating_sub(9);
349 Shape::legacy(budget, shape.indent)
354 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
355 let mover = if capture_by == ast::CaptureBy::Value {
360 if let rw @ Some(_) = rewrite_single_line_block(
362 format!("{}{}", "async ", mover).as_str(),
371 let budget = shape.width.saturating_sub(6);
381 Shape::legacy(budget, shape.indent)
386 ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
387 ast::ExprKind::Underscore => Some("_".to_owned()),
388 ast::ExprKind::Err => None,
392 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
393 .and_then(|expr_str| {
394 let attrs = outer_attributes(&expr.attrs);
395 let attrs_str = attrs.rewrite(context, shape)?;
397 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
400 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
404 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
406 exprs: impl Iterator<Item = &'a T>,
408 context: &'a RewriteContext<'_>,
410 force_separator_tactic: Option<SeparatorTactic>,
411 delim_token: Option<DelimToken>,
412 ) -> Option<String> {
413 overflow::rewrite_with_square_brackets(
419 force_separator_tactic,
424 fn rewrite_empty_block(
425 context: &RewriteContext<'_>,
427 attrs: Option<&[ast::Attribute]>,
428 label: Option<ast::Label>,
431 ) -> Option<String> {
432 if !block.stmts.is_empty() {
436 let label_str = rewrite_label(label);
437 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
441 if !block_contains_comment(context, block) && shape.width >= 2 {
442 return Some(format!("{}{}{{}}", prefix, label_str));
445 // If a block contains only a single-line comment, then leave it on one line.
446 let user_str = context.snippet(block.span);
447 let user_str = user_str.trim();
448 if user_str.starts_with('{') && user_str.ends_with('}') {
449 let comment_str = user_str[1..user_str.len() - 1].trim();
450 if block.stmts.is_empty()
451 && !comment_str.contains('\n')
452 && !comment_str.starts_with("//")
453 && comment_str.len() + 4 <= shape.width
455 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
462 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
463 Some(match block.rules {
464 ast::BlockCheckMode::Unsafe(..) => {
465 let snippet = context.snippet(block.span);
466 let open_pos = snippet.find_uncommented("{")?;
467 // Extract comment between unsafe and block start.
468 let trimmed = &snippet[6..open_pos].trim();
470 if !trimmed.is_empty() {
471 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
472 let budget = shape.width.checked_sub(9)?;
478 Shape::legacy(budget, shape.indent + 7),
486 ast::BlockCheckMode::Default => String::new(),
490 fn rewrite_single_line_block(
491 context: &RewriteContext<'_>,
494 attrs: Option<&[ast::Attribute]>,
495 label: Option<ast::Label>,
497 ) -> Option<String> {
498 if is_simple_block(context, block, attrs) {
499 let expr_shape = shape.offset_left(last_line_width(prefix))?;
500 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
501 let label_str = rewrite_label(label);
502 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
503 if result.len() <= shape.width && !result.contains('\n') {
510 pub(crate) fn rewrite_block_with_visitor(
511 context: &RewriteContext<'_>,
514 attrs: Option<&[ast::Attribute]>,
515 label: Option<ast::Label>,
518 ) -> Option<String> {
519 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
523 let mut visitor = FmtVisitor::from_context(context);
524 visitor.block_indent = shape.indent;
525 visitor.is_if_else_block = context.is_if_else_block();
526 match (block.rules, label) {
527 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
528 let snippet = context.snippet(block.span);
529 let open_pos = snippet.find_uncommented("{")?;
530 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
532 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
535 let inner_attrs = attrs.map(inner_attributes);
536 let label_str = rewrite_label(label);
537 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
538 let visitor_context = visitor.get_context();
542 .append(&mut visitor_context.skipped_range.borrow_mut());
543 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
546 impl Rewrite for ast::Block {
547 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
548 rewrite_block(self, None, None, context, shape)
554 attrs: Option<&[ast::Attribute]>,
555 label: Option<ast::Label>,
556 context: &RewriteContext<'_>,
558 ) -> Option<String> {
559 let prefix = block_prefix(context, block, shape)?;
561 // shape.width is used only for the single line case: either the empty block `{}`,
562 // or an unsafe expression `unsafe { e }`.
563 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
567 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
568 if let Some(ref result_str) = result {
569 if result_str.lines().count() <= 3 {
570 if let rw @ Some(_) =
571 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
581 // Rewrite condition if the given expression has one.
582 pub(crate) fn rewrite_cond(
583 context: &RewriteContext<'_>,
586 ) -> Option<String> {
588 ast::ExprKind::Match(ref cond, _) => {
590 let cond_shape = match context.config.indent_style() {
591 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
592 IndentStyle::Block => shape.offset_left(8)?,
594 cond.rewrite(context, cond_shape)
596 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
598 String::from("\n") + &shape.indent.block_only().to_string(context.config);
600 .rewrite_cond(context, shape, &alt_block_sep)
601 .and_then(|rw| Some(rw.0))
606 // Abstraction over control flow expressions
608 struct ControlFlow<'a> {
609 cond: Option<&'a ast::Expr>,
610 block: &'a ast::Block,
611 else_block: Option<&'a ast::Expr>,
612 label: Option<ast::Label>,
613 pat: Option<&'a ast::Pat>,
617 allow_single_line: bool,
618 // HACK: `true` if this is an `if` expression in an `else if`.
623 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
625 ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
630 // FIXME: Refactor this.
631 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
633 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
634 let (pat, cond) = extract_pats_and_cond(cond);
635 Some(ControlFlow::new_if(
639 else_block.as_ref().map(|e| &**e),
640 expr_type == ExprType::SubExpression,
645 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
646 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
648 ast::ExprKind::Loop(ref block, label) => {
649 Some(ControlFlow::new_loop(block, label, expr.span))
651 ast::ExprKind::While(ref cond, ref block, label) => {
652 let (pat, cond) = extract_pats_and_cond(cond);
653 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
659 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
660 pat.map_or("", |_| "let")
663 impl<'a> ControlFlow<'a> {
666 pat: Option<&'a ast::Pat>,
667 block: &'a ast::Block,
668 else_block: Option<&'a ast::Expr>,
669 allow_single_line: bool,
672 ) -> ControlFlow<'a> {
673 let matcher = choose_matcher(pat);
689 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
699 allow_single_line: false,
706 pat: Option<&'a ast::Pat>,
708 block: &'a ast::Block,
709 label: Option<ast::Label>,
711 ) -> ControlFlow<'a> {
712 let matcher = choose_matcher(pat);
722 allow_single_line: false,
731 block: &'a ast::Block,
732 label: Option<ast::Label>,
734 ) -> ControlFlow<'a> {
744 allow_single_line: false,
750 fn rewrite_single_line(
753 context: &RewriteContext<'_>,
755 ) -> Option<String> {
756 assert!(self.allow_single_line);
757 let else_block = self.else_block?;
758 let fixed_cost = self.keyword.len() + " { } else { }".len();
760 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
761 if !is_simple_block(context, self.block, None)
762 || !is_simple_block(context, else_node, None)
763 || pat_expr_str.contains('\n')
768 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
769 let expr = &self.block.stmts[0];
770 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
772 let new_width = new_width.checked_sub(if_str.len())?;
773 let else_expr = &else_node.stmts[0];
774 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
776 if if_str.contains('\n') || else_str.contains('\n') {
780 let result = format!(
781 "{} {} {{ {} }} else {{ {} }}",
782 self.keyword, pat_expr_str, if_str, else_str
785 if result.len() <= width {
794 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
796 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
797 let mut leading_whitespaces = 0;
798 for c in pat_str.chars().rev() {
801 _ if c.is_whitespace() => leading_whitespaces += 1,
802 _ => leading_whitespaces = 0,
805 leading_whitespaces > start_column
808 impl<'a> ControlFlow<'a> {
811 context: &RewriteContext<'_>,
815 ) -> Option<String> {
816 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
818 let cond_shape = shape.offset_left(offset)?;
819 if let Some(pat) = self.pat {
820 let matcher = if self.matcher.is_empty() {
821 self.matcher.to_owned()
823 format!("{} ", self.matcher)
825 let pat_shape = cond_shape
826 .offset_left(matcher.len())?
827 .sub_width(self.connector.len())?;
828 let pat_string = pat.rewrite(context, pat_shape)?;
829 let comments_lo = context
831 .span_after(self.span, self.connector.trim());
832 let missing_comments = if let Some(comment) =
833 rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
835 if !self.connector.is_empty() && !comment.is_empty() {
836 if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
837 let newline = &pat_shape
839 .block_indent(context.config)
840 .to_string_with_newline(context.config);
841 // An extra space is added when the lhs and rhs are joined
842 // so we need to remove one space from the end to ensure
843 // the comment and rhs are aligned.
844 let mut suffix = newline.as_ref().to_string();
845 if !suffix.is_empty() {
846 suffix.truncate(suffix.len() - 1);
848 format!("{}{}{}", newline, comment, suffix)
850 format!(" {}", comment)
859 let result = format!(
861 matcher, pat_string, self.connector, missing_comments
863 return rewrite_assign_rhs(context, result, expr, cond_shape);
866 let expr_rw = expr.rewrite(context, cond_shape);
867 // The expression may (partially) fit on the current line.
868 // We do not allow splitting between `if` and condition.
869 if self.keyword == "if" || expr_rw.is_some() {
873 // The expression won't fit on the current line, jump to next.
874 let nested_shape = shape
875 .block_indent(context.config.tab_spaces())
876 .with_max_width(context.config);
877 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
878 expr.rewrite(context, nested_shape)
879 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
884 context: &RewriteContext<'_>,
887 ) -> Option<(String, usize)> {
888 // Do not take the rhs overhead from the upper expressions into account
889 // when rewriting pattern.
890 let new_width = context.budget(shape.used_width());
891 let fresh_shape = Shape {
895 let constr_shape = if self.nested_if {
896 // We are part of an if-elseif-else chain. Our constraints are tightened.
897 // 7 = "} else " .len()
898 fresh_shape.offset_left(7)?
903 let label_string = rewrite_label(self.label);
904 // 1 = space after keyword.
905 let offset = self.keyword.len() + label_string.len() + 1;
907 let pat_expr_string = match self.cond {
908 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
909 None => String::new(),
913 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
919 let one_line_budget = context
922 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
923 let force_newline_brace = (pat_expr_string.contains('\n')
924 || pat_expr_string.len() > one_line_budget)
925 && (!last_line_extendable(&pat_expr_string)
926 || last_line_offsetted(shape.used_width(), &pat_expr_string));
928 // Try to format if-else on single line.
929 if self.allow_single_line
933 .single_line_if_else_max_width
936 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
938 if let Some(cond_str) = trial {
943 .single_line_if_else_max_width
945 return Some((cond_str, 0));
950 let cond_span = if let Some(cond) = self.cond {
953 mk_sp(self.block.span.lo(), self.block.span.lo())
956 // `for event in event`
957 // Do not include label in the span.
960 .map_or(self.span.lo(), |label| label.ident.span.hi());
961 let between_kwd_cond = mk_sp(
964 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
965 if self.pat.is_none() {
967 } else if self.matcher.is_empty() {
968 self.pat.unwrap().span.lo()
972 .span_before(self.span, self.matcher.trim())
976 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
978 let after_cond_comment =
979 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
981 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
983 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
984 || force_newline_brace
991 let used_width = if pat_expr_string.contains('\n') {
992 last_line_width(&pat_expr_string)
994 // 2 = spaces after keyword and condition.
995 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1003 between_kwd_cond_comment.as_ref().map_or(
1004 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1012 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1019 impl<'a> Rewrite for ControlFlow<'a> {
1020 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1021 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1023 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1024 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1025 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1026 if used_width == 0 {
1027 return Some(cond_str);
1030 let block_width = shape.width.saturating_sub(used_width);
1031 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1032 // we should avoid the single line case.
1033 let block_width = if self.else_block.is_some() || self.nested_if {
1038 let block_shape = Shape {
1043 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1045 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1046 context.is_if_else_block.replace(old_val);
1050 let mut result = format!("{}{}", cond_str, block_str);
1052 if let Some(else_block) = self.else_block {
1053 let shape = Shape::indented(shape.indent, context.config);
1054 let mut last_in_chain = false;
1055 let rewrite = match else_block.kind {
1056 // If the else expression is another if-else expression, prevent it
1057 // from being formatted on a single line.
1058 // Note how we're passing the original shape, as the
1059 // cost of "else" should not cascade.
1060 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1061 let (pats, cond) = extract_pats_and_cond(cond);
1062 ControlFlow::new_if(
1066 next_else_block.as_ref().map(|e| &**e),
1069 mk_sp(else_block.span.lo(), self.span.hi()),
1071 .rewrite(context, shape)
1074 last_in_chain = true;
1075 // When rewriting a block, the width is only used for single line
1076 // blocks, passing 1 lets us avoid that.
1077 let else_shape = Shape {
1078 width: min(1, shape.width),
1081 format_expr(else_block, ExprType::Statement, context, else_shape)
1085 let between_kwd_else_block = mk_sp(
1086 self.block.span.hi(),
1089 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1091 let between_kwd_else_block_comment =
1092 extract_comment(between_kwd_else_block, context, shape);
1094 let after_else = mk_sp(
1097 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1098 else_block.span.lo(),
1100 let after_else_comment = extract_comment(after_else, context, shape);
1102 let between_sep = match context.config.control_brace_style() {
1103 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1106 ControlBraceStyle::AlwaysSameLine => " ",
1108 let after_sep = match context.config.control_brace_style() {
1109 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1113 result.push_str(&format!(
1115 between_kwd_else_block_comment
1117 .map_or(between_sep, |s| &**s),
1118 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1120 result.push_str(&rewrite?);
1127 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1129 Some(label) => Cow::from(format!("{}: ", label.ident)),
1130 None => Cow::from(""),
1134 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1135 match rewrite_missing_comment(span, shape, context) {
1136 Some(ref comment) if !comment.is_empty() => Some(format!(
1137 "{indent}{}{indent}",
1139 indent = shape.indent.to_string_with_newline(context.config)
1145 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1146 contains_comment(context.snippet(block.span))
1149 // Checks that a block contains no statements, an expression and no comments or
1151 // FIXME: incorrectly returns false when comment is contained completely within
1153 pub(crate) fn is_simple_block(
1154 context: &RewriteContext<'_>,
1156 attrs: Option<&[ast::Attribute]>,
1158 block.stmts.len() == 1
1159 && stmt_is_expr(&block.stmts[0])
1160 && !block_contains_comment(context, block)
1161 && attrs.map_or(true, |a| a.is_empty())
1164 /// Checks whether a block contains at most one statement or expression, and no
1165 /// comments or attributes.
1166 pub(crate) fn is_simple_block_stmt(
1167 context: &RewriteContext<'_>,
1169 attrs: Option<&[ast::Attribute]>,
1171 block.stmts.len() <= 1
1172 && !block_contains_comment(context, block)
1173 && attrs.map_or(true, |a| a.is_empty())
1176 /// Checks whether a block contains no statements, expressions, comments, or
1177 /// inner attributes.
1178 pub(crate) fn is_empty_block(
1179 context: &RewriteContext<'_>,
1181 attrs: Option<&[ast::Attribute]>,
1183 block.stmts.is_empty()
1184 && !block_contains_comment(context, block)
1185 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1188 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1190 ast::StmtKind::Expr(..) => true,
1195 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1196 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1203 pub(crate) fn rewrite_literal(
1204 context: &RewriteContext<'_>,
1207 ) -> Option<String> {
1209 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1211 context.snippet(l.span).to_owned(),
1212 context.config.max_width(),
1218 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1219 let string_lit = context.snippet(span);
1221 if !context.config.format_strings() {
1225 .all(|line| line.ends_with('\\'))
1226 && context.config.version() == Version::Two
1228 return Some(string_lit.to_owned());
1230 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1234 // Remove the quote characters.
1235 let str_lit = &string_lit[1..string_lit.len() - 1];
1239 &StringFormat::new(shape.visual_indent(0), context.config),
1240 shape.width.saturating_sub(2),
1244 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1245 if context.inside_macro() {
1246 if span_ends_with_comma(context, span) {
1247 Some(SeparatorTactic::Always)
1249 Some(SeparatorTactic::Never)
1256 pub(crate) fn rewrite_call(
1257 context: &RewriteContext<'_>,
1259 args: &[ptr::P<ast::Expr>],
1262 ) -> Option<String> {
1263 overflow::rewrite_with_parens(
1269 context.config.width_heuristics().fn_call_width,
1270 choose_separator_tactic(context, span),
1274 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1276 ast::ExprKind::Lit(..) => true,
1277 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1278 ast::ExprKind::AddrOf(_, _, ref expr)
1279 | ast::ExprKind::Box(ref expr)
1280 | ast::ExprKind::Cast(ref expr, _)
1281 | ast::ExprKind::Field(ref expr, _)
1282 | ast::ExprKind::Try(ref expr)
1283 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1284 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1285 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1286 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1292 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1293 lists.iter().all(OverflowableItem::is_simple)
1296 pub(crate) fn can_be_overflowed_expr(
1297 context: &RewriteContext<'_>,
1302 _ if !expr.attrs.is_empty() => false,
1303 ast::ExprKind::Match(..) => {
1304 (context.use_block_indent() && args_len == 1)
1305 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1306 || context.config.overflow_delimited_expr()
1308 ast::ExprKind::If(..)
1309 | ast::ExprKind::ForLoop(..)
1310 | ast::ExprKind::Loop(..)
1311 | ast::ExprKind::While(..) => {
1312 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1315 // Handle always block-like expressions
1316 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1318 // Handle `[]` and `{}`-like expressions
1319 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1320 context.config.overflow_delimited_expr()
1321 || (context.use_block_indent() && args_len == 1)
1323 ast::ExprKind::MacCall(ref mac) => {
1325 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
1326 context.config.overflow_delimited_expr(),
1328 (Some(ast::MacDelimiter::Bracket), true)
1329 | (Some(ast::MacDelimiter::Brace), true) => true,
1330 _ => context.use_block_indent() && args_len == 1,
1334 // Handle parenthetical expressions
1335 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1336 context.use_block_indent() && args_len == 1
1339 // Handle unary-like expressions
1340 ast::ExprKind::AddrOf(_, _, ref expr)
1341 | ast::ExprKind::Box(ref expr)
1342 | ast::ExprKind::Try(ref expr)
1343 | ast::ExprKind::Unary(_, ref expr)
1344 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1349 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1351 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1352 ast::ExprKind::AddrOf(_, _, ref expr)
1353 | ast::ExprKind::Box(ref expr)
1354 | ast::ExprKind::Try(ref expr)
1355 | ast::ExprKind::Unary(_, ref expr)
1356 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1361 /// Returns `true` if a function call or a method call represented by the given span ends with a
1362 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1363 /// comma from macro can potentially break the code.
1364 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1365 let mut result: bool = Default::default();
1366 let mut prev_char: char = Default::default();
1367 let closing_delimiters = &[')', '}', ']'];
1369 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1371 _ if kind.is_comment() || c.is_whitespace() => continue,
1372 c if closing_delimiters.contains(&c) => {
1373 result &= !closing_delimiters.contains(&prev_char);
1375 ',' => result = true,
1376 _ => result = false,
1385 context: &RewriteContext<'_>,
1386 mut subexpr: &ast::Expr,
1389 ) -> Option<String> {
1390 debug!("rewrite_paren, shape: {:?}", shape);
1392 // Extract comments within parens.
1395 let mut pre_comment;
1396 let mut post_comment;
1397 let remove_nested_parens = context.config.remove_nested_parens();
1400 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1401 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1402 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1403 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1405 // Remove nested parens if there are no comments.
1406 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1407 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1408 span = subexpr.span;
1409 subexpr = subsubexpr;
1418 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1419 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1420 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1421 if fits_single_line {
1422 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1424 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1428 fn rewrite_paren_in_multi_line(
1429 context: &RewriteContext<'_>,
1430 subexpr: &ast::Expr,
1434 ) -> Option<String> {
1435 let nested_indent = shape.indent.block_indent(context.config);
1436 let nested_shape = Shape::indented(nested_indent, context.config);
1437 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1438 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1439 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1441 let mut result = String::with_capacity(subexpr_str.len() * 2);
1443 if !pre_comment.is_empty() {
1444 result.push_str(&nested_indent.to_string_with_newline(context.config));
1445 result.push_str(&pre_comment);
1447 result.push_str(&nested_indent.to_string_with_newline(context.config));
1448 result.push_str(&subexpr_str);
1449 if !post_comment.is_empty() {
1450 result.push_str(&nested_indent.to_string_with_newline(context.config));
1451 result.push_str(&post_comment);
1453 result.push_str(&shape.indent.to_string_with_newline(context.config));
1462 context: &RewriteContext<'_>,
1464 ) -> Option<String> {
1465 let expr_str = expr.rewrite(context, shape)?;
1467 let offset = last_line_width(&expr_str) + 1;
1468 let rhs_overhead = shape.rhs_overhead(context.config);
1469 let index_shape = if expr_str.contains('\n') {
1470 Shape::legacy(context.config.max_width(), shape.indent)
1471 .offset_left(offset)
1472 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1474 match context.config.indent_style() {
1475 IndentStyle::Block => shape
1476 .offset_left(offset)
1477 .and_then(|shape| shape.sub_width(1)),
1478 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1481 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1483 // Return if index fits in a single line.
1484 match orig_index_rw {
1485 Some(ref index_str) if !index_str.contains('\n') => {
1486 return Some(format!("{}[{}]", expr_str, index_str));
1491 // Try putting index on the next line and see if it fits in a single line.
1492 let indent = shape.indent.block_indent(context.config);
1493 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1494 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1495 let new_index_rw = index.rewrite(context, index_shape);
1496 match (orig_index_rw, new_index_rw) {
1497 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1500 indent.to_string_with_newline(context.config),
1503 (None, Some(ref new_index_str)) => Some(format!(
1506 indent.to_string_with_newline(context.config),
1509 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1514 fn struct_lit_can_be_aligned(fields: &[ast::Field], has_base: bool) -> bool {
1515 !has_base && fields.iter().all(|field| !field.is_shorthand)
1518 fn rewrite_struct_lit<'a>(
1519 context: &RewriteContext<'_>,
1521 fields: &'a [ast::Field],
1522 struct_rest: &ast::StructRest,
1523 attrs: &[ast::Attribute],
1526 ) -> Option<String> {
1527 debug!("rewrite_struct_lit: shape {:?}", shape);
1529 enum StructLitField<'a> {
1530 Regular(&'a ast::Field),
1531 Base(&'a ast::Expr),
1536 let path_shape = shape.sub_width(2)?;
1537 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1539 let has_base = match struct_rest {
1540 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1541 ast::StructRest::Rest(_) if fields.is_empty() => {
1542 return Some(format!("{} {{ .. }}", path_str));
1544 ast::StructRest::Base(_) => true,
1548 // Foo { a: Foo } - indent is +3, width is -5.
1549 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1551 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1552 let body_lo = context.snippet_provider.span_after(span, "{");
1553 let fields_str = if struct_lit_can_be_aligned(fields, has_base)
1554 && context.config.struct_field_align_threshold() > 0
1556 rewrite_with_alignment(
1560 mk_sp(body_lo, span.hi()),
1564 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1566 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1567 ast::StructRest::Rest(span) => Some(StructLitField::Rest(span)),
1568 ast::StructRest::None => None,
1573 let span_lo = |item: &StructLitField<'_>| match *item {
1574 StructLitField::Regular(field) => field.span().lo(),
1575 StructLitField::Base(expr) => {
1576 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1577 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1578 let pos = snippet.find_uncommented("..").unwrap();
1579 last_field_hi + BytePos(pos as u32)
1581 StructLitField::Rest(span) => span.lo(),
1583 let span_hi = |item: &StructLitField<'_>| match *item {
1584 StructLitField::Regular(field) => field.span().hi(),
1585 StructLitField::Base(expr) => expr.span.hi(),
1586 StructLitField::Rest(span) => span.hi(),
1588 let rewrite = |item: &StructLitField<'_>| match *item {
1589 StructLitField::Regular(field) => {
1590 // The 1 taken from the v_budget is for the comma.
1591 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1593 StructLitField::Base(expr) => {
1595 expr.rewrite(context, v_shape.offset_left(2)?)
1596 .map(|s| format!("..{}", s))
1598 StructLitField::Rest(_) => Some("..".to_owned()),
1601 let items = itemize_list(
1602 context.snippet_provider,
1613 let item_vec = items.collect::<Vec<_>>();
1615 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1616 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1618 let ends_with_comma = span_ends_with_comma(context, span);
1619 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1621 let fmt = struct_lit_formatting(
1625 force_no_trailing_comma || has_base || !context.use_block_indent(),
1628 write_list(&item_vec, &fmt)?
1632 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1633 Some(format!("{} {{{}}}", path_str, fields_str))
1635 // FIXME if context.config.indent_style() == Visual, but we run out
1636 // of space, we should fall back to BlockIndent.
1639 pub(crate) fn wrap_struct_field(
1640 context: &RewriteContext<'_>,
1641 attrs: &[ast::Attribute],
1644 nested_shape: Shape,
1645 one_line_width: usize,
1646 ) -> Option<String> {
1647 let should_vertical = context.config.indent_style() == IndentStyle::Block
1648 && (fields_str.contains('\n')
1649 || !context.config.struct_lit_single_line()
1650 || fields_str.len() > one_line_width);
1652 let inner_attrs = &inner_attributes(attrs);
1653 if inner_attrs.is_empty() {
1654 if should_vertical {
1657 nested_shape.indent.to_string_with_newline(context.config),
1659 shape.indent.to_string_with_newline(context.config)
1662 // One liner or visual indent.
1663 Some(format!(" {} ", fields_str))
1668 nested_shape.indent.to_string_with_newline(context.config),
1669 inner_attrs.rewrite(context, shape)?,
1670 nested_shape.indent.to_string_with_newline(context.config),
1672 shape.indent.to_string_with_newline(context.config)
1677 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1678 colon_spaces(config)
1681 pub(crate) fn rewrite_field(
1682 context: &RewriteContext<'_>,
1685 prefix_max_width: usize,
1686 ) -> Option<String> {
1687 if contains_skip(&field.attrs) {
1688 return Some(context.snippet(field.span()).to_owned());
1690 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1691 if !attrs_str.is_empty() {
1692 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1694 let name = context.snippet(field.ident.span);
1695 if field.is_shorthand {
1696 Some(attrs_str + name)
1698 let mut separator = String::from(struct_lit_field_separator(context.config));
1699 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1700 separator.push(' ');
1702 let overhead = name.len() + separator.len();
1703 let expr_shape = shape.offset_left(overhead)?;
1704 let expr = field.expr.rewrite(context, expr_shape);
1707 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1708 Some(attrs_str + name)
1710 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1712 let expr_offset = shape.indent.block_indent(context.config);
1715 .rewrite(context, Shape::indented(expr_offset, context.config));
1721 expr_offset.to_string(context.config),
1730 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1731 context: &RewriteContext<'_>,
1732 mut items: impl Iterator<Item = &'a T>,
1735 is_singleton_tuple: bool,
1736 ) -> Option<String> {
1737 // In case of length 1, need a trailing comma
1738 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1739 if is_singleton_tuple {
1741 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1745 .rewrite(context, nested_shape)
1746 .map(|s| format!("({},)", s));
1749 let list_lo = context.snippet_provider.span_after(span, "(");
1750 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1751 let items = itemize_list(
1752 context.snippet_provider,
1756 |item| item.span().lo(),
1757 |item| item.span().hi(),
1758 |item| item.rewrite(context, nested_shape),
1760 span.hi() - BytePos(1),
1763 let item_vec: Vec<_> = items.collect();
1764 let tactic = definitive_tactic(
1766 ListTactic::HorizontalVertical,
1770 let fmt = ListFormatting::new(nested_shape, context.config)
1772 .ends_with_newline(false);
1773 let list_str = write_list(&item_vec, &fmt)?;
1775 Some(format!("({})", list_str))
1778 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1779 context: &'a RewriteContext<'_>,
1780 items: impl Iterator<Item = &'a T>,
1783 is_singleton_tuple: bool,
1784 ) -> Option<String> {
1785 debug!("rewrite_tuple {:?}", shape);
1786 if context.use_block_indent() {
1787 // We use the same rule as function calls for rewriting tuples.
1788 let force_tactic = if context.inside_macro() {
1789 if span_ends_with_comma(context, span) {
1790 Some(SeparatorTactic::Always)
1792 Some(SeparatorTactic::Never)
1794 } else if is_singleton_tuple {
1795 Some(SeparatorTactic::Always)
1799 overflow::rewrite_with_parens(
1805 context.config.width_heuristics().fn_call_width,
1809 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1813 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1814 context: &RewriteContext<'_>,
1818 ) -> Option<String> {
1820 .rewrite(context, shape.offset_left(prefix.len())?)
1821 .map(|r| format!("{}{}", prefix, r))
1824 // FIXME: this is probably not correct for multi-line Rewrites. we should
1825 // subtract suffix.len() from the last line budget, not the first!
1826 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1827 context: &RewriteContext<'_>,
1831 ) -> Option<String> {
1833 .rewrite(context, shape.sub_width(suffix.len())?)
1840 fn rewrite_unary_op(
1841 context: &RewriteContext<'_>,
1845 ) -> Option<String> {
1846 // For some reason, an UnOp is not spanned like BinOp!
1847 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1850 fn rewrite_assignment(
1851 context: &RewriteContext<'_>,
1854 op: Option<&ast::BinOp>,
1856 ) -> Option<String> {
1857 let operator_str = match op {
1858 Some(op) => context.snippet(op.span),
1862 // 1 = space between lhs and operator.
1863 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1864 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1866 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1869 /// Controls where to put the rhs.
1870 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1871 pub(crate) enum RhsTactics {
1874 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1875 ForceNextLineWithoutIndent,
1876 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1881 // The left hand side must contain everything up to, and including, the
1882 // assignment operator.
1883 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1884 context: &RewriteContext<'_>,
1888 ) -> Option<String> {
1889 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1892 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1893 context: &RewriteContext<'_>,
1897 rhs_tactics: RhsTactics,
1898 ) -> Option<String> {
1899 let lhs = lhs.into();
1900 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1901 shape.indent.width()
1905 // 1 = space between operator and rhs.
1906 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1908 offset: shape.offset + last_line_width + 1,
1911 let rhs = choose_rhs(
1915 ex.rewrite(context, orig_shape),
1921 fn choose_rhs<R: Rewrite>(
1922 context: &RewriteContext<'_>,
1925 orig_rhs: Option<String>,
1926 rhs_tactics: RhsTactics,
1927 ) -> Option<String> {
1930 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1932 Some(format!(" {}", new_str))
1935 // Expression did not fit on the same line as the identifier.
1936 // Try splitting the line and see if that works better.
1937 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1938 let new_rhs = expr.rewrite(context, new_shape);
1939 let new_indent_str = &shape
1941 .block_indent(context.config)
1942 .to_string_with_newline(context.config);
1944 match (orig_rhs, new_rhs) {
1945 (Some(ref orig_rhs), Some(ref new_rhs))
1946 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1949 Some(format!(" {}", orig_rhs))
1951 (Some(ref orig_rhs), Some(ref new_rhs))
1952 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1954 Some(format!("{}{}", new_indent_str, new_rhs))
1956 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1957 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1958 let shape = shape.infinite_width();
1959 expr.rewrite(context, shape).map(|s| format!(" {}", s))
1961 (None, None) => None,
1962 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1968 fn shape_from_rhs_tactic(
1969 context: &RewriteContext<'_>,
1971 rhs_tactic: RhsTactics,
1972 ) -> Option<Shape> {
1974 RhsTactics::ForceNextLineWithoutIndent => shape
1975 .with_max_width(context.config)
1976 .sub_width(shape.indent.width()),
1977 RhsTactics::Default | RhsTactics::AllowOverflow => {
1978 Shape::indented(shape.indent.block_indent(context.config), context.config)
1979 .sub_width(shape.rhs_overhead(context.config))
1984 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
1985 /// original's line formatting.
1987 /// It is considered better if:
1988 /// 1. the tactic is ForceNextLineWithoutIndent
1989 /// 2. next_line_rhs doesn't have newlines
1990 /// 3. the original line has more newlines than next_line_rhs
1991 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
1993 pub(crate) fn prefer_next_line(
1995 next_line_rhs: &str,
1996 rhs_tactics: RhsTactics,
1998 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1999 || !next_line_rhs.contains('\n')
2000 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2001 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2002 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2003 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2006 fn rewrite_expr_addrof(
2007 context: &RewriteContext<'_>,
2008 borrow_kind: ast::BorrowKind,
2009 mutability: ast::Mutability,
2012 ) -> Option<String> {
2013 let operator_str = match (mutability, borrow_kind) {
2014 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2015 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2016 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2017 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2019 rewrite_unary_prefix(context, operator_str, expr, shape)
2022 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2024 ast::ExprKind::MethodCall(..) => true,
2025 ast::ExprKind::AddrOf(_, _, ref expr)
2026 | ast::ExprKind::Box(ref expr)
2027 | ast::ExprKind::Cast(ref expr, _)
2028 | ast::ExprKind::Try(ref expr)
2029 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2036 use super::last_line_offsetted;
2039 fn test_last_line_offsetted() {
2040 let lines = "one\n two";
2041 assert_eq!(last_line_offsetted(2, lines), true);
2042 assert_eq!(last_line_offsetted(4, lines), false);
2043 assert_eq!(last_line_offsetted(6, lines), false);
2045 let lines = "one two";
2046 assert_eq!(last_line_offsetted(2, lines), false);
2047 assert_eq!(last_line_offsetted(0, lines), false);
2049 let lines = "\ntwo";
2050 assert_eq!(last_line_offsetted(2, lines), false);
2051 assert_eq!(last_line_offsetted(0, lines), false);
2053 let lines = "one\n two three";
2054 assert_eq!(last_line_offsetted(2, lines), true);
2055 let lines = "one\n two three";
2056 assert_eq!(last_line_offsetted(2, lines), false);