4 use itertools::Itertools;
5 use syntax::parse::token::{DelimToken, LitKind};
6 use syntax::source_map::{BytePos, SourceMap, Span};
7 use syntax::{ast, ptr};
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 base) => rewrite_struct_lit(
113 base.as_ref().map(|e| &**e),
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::Block(ref block, opt_label) => {
129 ExprType::Statement => {
130 if is_unsafe_block(block) {
131 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
132 } else if let rw @ Some(_) =
133 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
135 // Rewrite block without trying to put it in a single line.
138 let prefix = block_prefix(context, block, shape)?;
140 rewrite_block_with_visitor(
151 ExprType::SubExpression => {
152 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
156 ast::ExprKind::Match(ref cond, ref arms) => {
157 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
159 ast::ExprKind::Path(ref qself, ref path) => {
160 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
162 ast::ExprKind::Assign(ref lhs, ref rhs) => {
163 rewrite_assignment(context, lhs, rhs, None, shape)
165 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
166 rewrite_assignment(context, lhs, rhs, Some(op), shape)
168 ast::ExprKind::Continue(ref opt_label) => {
169 let id_str = match *opt_label {
170 Some(label) => format!(" {}", label.ident),
171 None => String::new(),
173 Some(format!("continue{}", id_str))
175 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
176 let id_str = match *opt_label {
177 Some(label) => format!(" {}", label.ident),
178 None => String::new(),
181 if let Some(ref expr) = *opt_expr {
182 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
184 Some(format!("break{}", id_str))
187 ast::ExprKind::Yield(ref opt_expr) => {
188 if let Some(ref expr) = *opt_expr {
189 rewrite_unary_prefix(context, "yield ", &**expr, shape)
191 Some("yield".to_string())
194 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
195 closures::rewrite_closure(
196 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
199 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
200 rewrite_chain(expr, context, shape)
202 ast::ExprKind::Mac(ref mac) => {
203 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
205 context.snippet(expr.span).to_owned(),
206 context.config.max_width(),
211 ast::ExprKind::Ret(None) => Some("return".to_owned()),
212 ast::ExprKind::Ret(Some(ref expr)) => {
213 rewrite_unary_prefix(context, "return ", &**expr, shape)
215 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
216 ast::ExprKind::AddrOf(mutability, ref expr) => {
217 rewrite_expr_addrof(context, mutability, expr, shape)
219 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
222 PairParts::infix(" as "),
225 SeparatorPlace::Front,
227 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
230 PairParts::infix(": "),
233 SeparatorPlace::Back,
235 ast::ExprKind::Index(ref expr, ref index) => {
236 rewrite_index(&**expr, &**index, context, shape)
238 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
241 PairParts::new("[", "; ", "]"),
244 SeparatorPlace::Back,
246 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
247 let delim = match limits {
248 ast::RangeLimits::HalfOpen => "..",
249 ast::RangeLimits::Closed => "..=",
252 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
254 ast::ExprKind::Lit(ref lit) => match lit.kind {
255 ast::LitKind::FloatUnsuffixed(..) => {
256 context.snippet(lit.span).ends_with('.')
260 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
265 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
267 // Don't format `.. ..` into `....`, which is invalid.
269 // This check is unnecessary for `lhs`, because a range
270 // starting from another range needs parentheses as `(x ..) ..`
271 // (`x .. ..` is a range from `x` to `..`).
272 ast::ExprKind::Range(None, _, _) => true,
277 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
278 let space_if = |b: bool| if b { " " } else { "" };
282 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
284 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
288 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
289 (Some(lhs), Some(rhs)) => {
290 let sp_delim = if context.config.spaces_around_ranges() {
291 format!(" {} ", delim)
293 default_sp_delim(Some(lhs), Some(rhs))
298 PairParts::infix(&sp_delim),
301 context.config.binop_separator(),
304 (None, Some(rhs)) => {
305 let sp_delim = if context.config.spaces_around_ranges() {
306 format!("{} ", delim)
308 default_sp_delim(None, Some(rhs))
310 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
312 (Some(lhs), None) => {
313 let sp_delim = if context.config.spaces_around_ranges() {
314 format!(" {}", delim)
316 default_sp_delim(Some(lhs), None)
318 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
320 (None, None) => Some(delim.to_owned()),
323 // We do not format these expressions yet, but they should still
324 // satisfy our width restrictions.
325 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
326 ast::ExprKind::TryBlock(ref block) => {
327 if let rw @ Some(_) =
328 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
333 let budget = shape.width.saturating_sub(9);
342 Shape::legacy(budget, shape.indent)
347 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
348 let mover = if capture_by == ast::CaptureBy::Value {
353 if let rw @ Some(_) = rewrite_single_line_block(
355 format!("{}{}", "async ", mover).as_str(),
364 let budget = shape.width.saturating_sub(6);
374 Shape::legacy(budget, shape.indent)
379 ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
380 ast::ExprKind::Err => None,
384 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
385 .and_then(|expr_str| {
386 let attrs = outer_attributes(&expr.attrs);
387 let attrs_str = attrs.rewrite(context, shape)?;
389 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
392 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
396 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
398 exprs: impl Iterator<Item = &'a T>,
400 context: &'a RewriteContext<'_>,
402 force_separator_tactic: Option<SeparatorTactic>,
403 delim_token: Option<DelimToken>,
404 ) -> Option<String> {
405 overflow::rewrite_with_square_brackets(
411 force_separator_tactic,
416 fn rewrite_empty_block(
417 context: &RewriteContext<'_>,
419 attrs: Option<&[ast::Attribute]>,
420 label: Option<ast::Label>,
423 ) -> Option<String> {
424 if !block.stmts.is_empty() {
428 let label_str = rewrite_label(label);
429 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
433 if !block_contains_comment(block, context.source_map) && shape.width >= 2 {
434 return Some(format!("{}{}{{}}", prefix, label_str));
437 // If a block contains only a single-line comment, then leave it on one line.
438 let user_str = context.snippet(block.span);
439 let user_str = user_str.trim();
440 if user_str.starts_with('{') && user_str.ends_with('}') {
441 let comment_str = user_str[1..user_str.len() - 1].trim();
442 if block.stmts.is_empty()
443 && !comment_str.contains('\n')
444 && !comment_str.starts_with("//")
445 && comment_str.len() + 4 <= shape.width
447 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
454 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
455 Some(match block.rules {
456 ast::BlockCheckMode::Unsafe(..) => {
457 let snippet = context.snippet(block.span);
458 let open_pos = snippet.find_uncommented("{")?;
459 // Extract comment between unsafe and block start.
460 let trimmed = &snippet[6..open_pos].trim();
462 if !trimmed.is_empty() {
463 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
464 let budget = shape.width.checked_sub(9)?;
470 Shape::legacy(budget, shape.indent + 7),
478 ast::BlockCheckMode::Default => String::new(),
482 fn rewrite_single_line_block(
483 context: &RewriteContext<'_>,
486 attrs: Option<&[ast::Attribute]>,
487 label: Option<ast::Label>,
489 ) -> Option<String> {
490 if is_simple_block(block, attrs, context.source_map) {
491 let expr_shape = shape.offset_left(last_line_width(prefix))?;
492 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
493 let label_str = rewrite_label(label);
494 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
495 if result.len() <= shape.width && !result.contains('\n') {
502 pub(crate) fn rewrite_block_with_visitor(
503 context: &RewriteContext<'_>,
506 attrs: Option<&[ast::Attribute]>,
507 label: Option<ast::Label>,
510 ) -> Option<String> {
511 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
515 let mut visitor = FmtVisitor::from_context(context);
516 visitor.block_indent = shape.indent;
517 visitor.is_if_else_block = context.is_if_else_block();
518 match (block.rules, label) {
519 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
520 let snippet = context.snippet(block.span);
521 let open_pos = snippet.find_uncommented("{")?;
522 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
524 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
527 let inner_attrs = attrs.map(inner_attributes);
528 let label_str = rewrite_label(label);
529 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
530 let visitor_context = visitor.get_context();
534 .append(&mut visitor_context.skipped_range.borrow_mut());
535 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
538 impl Rewrite for ast::Block {
539 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
540 rewrite_block(self, None, None, context, shape)
546 attrs: Option<&[ast::Attribute]>,
547 label: Option<ast::Label>,
548 context: &RewriteContext<'_>,
550 ) -> Option<String> {
551 let prefix = block_prefix(context, block, shape)?;
553 // shape.width is used only for the single line case: either the empty block `{}`,
554 // or an unsafe expression `unsafe { e }`.
555 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
559 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
560 if let Some(ref result_str) = result {
561 if result_str.lines().count() <= 3 {
562 if let rw @ Some(_) =
563 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
573 // Rewrite condition if the given expression has one.
574 pub(crate) fn rewrite_cond(
575 context: &RewriteContext<'_>,
578 ) -> Option<String> {
580 ast::ExprKind::Match(ref cond, _) => {
582 let cond_shape = match context.config.indent_style() {
583 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
584 IndentStyle::Block => shape.offset_left(8)?,
586 cond.rewrite(context, cond_shape)
588 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
590 String::from("\n") + &shape.indent.block_only().to_string(context.config);
592 .rewrite_cond(context, shape, &alt_block_sep)
593 .and_then(|rw| Some(rw.0))
598 // Abstraction over control flow expressions
600 struct ControlFlow<'a> {
601 cond: Option<&'a ast::Expr>,
602 block: &'a ast::Block,
603 else_block: Option<&'a ast::Expr>,
604 label: Option<ast::Label>,
605 pat: Option<&'a ast::Pat>,
609 allow_single_line: bool,
610 // HACK: `true` if this is an `if` expression in an `else if`.
615 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
617 ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
622 // FIXME: Refactor this.
623 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
625 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
626 let (pat, cond) = extract_pats_and_cond(cond);
627 Some(ControlFlow::new_if(
631 else_block.as_ref().map(|e| &**e),
632 expr_type == ExprType::SubExpression,
637 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
638 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
640 ast::ExprKind::Loop(ref block, label) => {
641 Some(ControlFlow::new_loop(block, label, expr.span))
643 ast::ExprKind::While(ref cond, ref block, label) => {
644 let (pat, cond) = extract_pats_and_cond(cond);
645 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
651 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
652 pat.map_or("", |_| "let")
655 impl<'a> ControlFlow<'a> {
658 pat: Option<&'a ast::Pat>,
659 block: &'a ast::Block,
660 else_block: Option<&'a ast::Expr>,
661 allow_single_line: bool,
664 ) -> ControlFlow<'a> {
665 let matcher = choose_matcher(pat);
681 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
691 allow_single_line: false,
698 pat: Option<&'a ast::Pat>,
700 block: &'a ast::Block,
701 label: Option<ast::Label>,
703 ) -> ControlFlow<'a> {
704 let matcher = choose_matcher(pat);
714 allow_single_line: false,
723 block: &'a ast::Block,
724 label: Option<ast::Label>,
726 ) -> ControlFlow<'a> {
736 allow_single_line: false,
742 fn rewrite_single_line(
745 context: &RewriteContext<'_>,
747 ) -> Option<String> {
748 assert!(self.allow_single_line);
749 let else_block = self.else_block?;
750 let fixed_cost = self.keyword.len() + " { } else { }".len();
752 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
753 if !is_simple_block(self.block, None, context.source_map)
754 || !is_simple_block(else_node, None, context.source_map)
755 || pat_expr_str.contains('\n')
760 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
761 let expr = &self.block.stmts[0];
762 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
764 let new_width = new_width.checked_sub(if_str.len())?;
765 let else_expr = &else_node.stmts[0];
766 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
768 if if_str.contains('\n') || else_str.contains('\n') {
772 let result = format!(
773 "{} {} {{ {} }} else {{ {} }}",
774 self.keyword, pat_expr_str, if_str, else_str
777 if result.len() <= width {
786 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
788 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
789 let mut leading_whitespaces = 0;
790 for c in pat_str.chars().rev() {
793 _ if c.is_whitespace() => leading_whitespaces += 1,
794 _ => leading_whitespaces = 0,
797 leading_whitespaces > start_column
800 impl<'a> ControlFlow<'a> {
803 context: &RewriteContext<'_>,
807 ) -> Option<String> {
808 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
810 let cond_shape = shape.offset_left(offset)?;
811 if let Some(pat) = self.pat {
812 let matcher = if self.matcher.is_empty() {
813 self.matcher.to_owned()
815 format!("{} ", self.matcher)
817 let pat_shape = cond_shape
818 .offset_left(matcher.len())?
819 .sub_width(self.connector.len())?;
820 let pat_string = pat.rewrite(context, pat_shape)?;
821 let comments_lo = context
823 .span_after(self.span, self.connector.trim());
824 let missing_comments = if let Some(comment) =
825 rewrite_missing_comment(mk_sp(comments_lo, expr.span.lo()), cond_shape, context)
827 if !self.connector.is_empty() && !comment.is_empty() {
828 if comment_style(&comment, false).is_line_comment() || comment.contains("\n") {
829 let newline = &pat_shape
831 .block_indent(context.config)
832 .to_string_with_newline(context.config);
833 // An extra space is added when the lhs and rhs are joined
834 // so we need to remove one space from the end to ensure
835 // the comment and rhs are aligned.
836 let mut suffix = newline.as_ref().to_string();
837 if !suffix.is_empty() {
838 suffix.truncate(suffix.len() - 1);
840 format!("{}{}{}", newline, comment, suffix)
842 format!(" {}", comment)
851 let result = format!(
853 matcher, pat_string, self.connector, missing_comments
855 return rewrite_assign_rhs(context, result, expr, cond_shape);
858 let expr_rw = expr.rewrite(context, cond_shape);
859 // The expression may (partially) fit on the current line.
860 // We do not allow splitting between `if` and condition.
861 if self.keyword == "if" || expr_rw.is_some() {
865 // The expression won't fit on the current line, jump to next.
866 let nested_shape = shape
867 .block_indent(context.config.tab_spaces())
868 .with_max_width(context.config);
869 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
870 expr.rewrite(context, nested_shape)
871 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
876 context: &RewriteContext<'_>,
879 ) -> Option<(String, usize)> {
880 // Do not take the rhs overhead from the upper expressions into account
881 // when rewriting pattern.
882 let new_width = context.budget(shape.used_width());
883 let fresh_shape = Shape {
887 let constr_shape = if self.nested_if {
888 // We are part of an if-elseif-else chain. Our constraints are tightened.
889 // 7 = "} else " .len()
890 fresh_shape.offset_left(7)?
895 let label_string = rewrite_label(self.label);
896 // 1 = space after keyword.
897 let offset = self.keyword.len() + label_string.len() + 1;
899 let pat_expr_string = match self.cond {
900 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
901 None => String::new(),
905 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
911 let one_line_budget = context
914 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
915 let force_newline_brace = (pat_expr_string.contains('\n')
916 || pat_expr_string.len() > one_line_budget)
917 && (!last_line_extendable(&pat_expr_string)
918 || last_line_offsetted(shape.used_width(), &pat_expr_string));
920 // Try to format if-else on single line.
921 if self.allow_single_line
925 .single_line_if_else_max_width
928 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
930 if let Some(cond_str) = trial {
935 .single_line_if_else_max_width
937 return Some((cond_str, 0));
942 let cond_span = if let Some(cond) = self.cond {
945 mk_sp(self.block.span.lo(), self.block.span.lo())
948 // `for event in event`
949 // Do not include label in the span.
952 .map_or(self.span.lo(), |label| label.ident.span.hi());
953 let between_kwd_cond = mk_sp(
956 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
957 if self.pat.is_none() {
959 } else if self.matcher.is_empty() {
960 self.pat.unwrap().span.lo()
964 .span_before(self.span, self.matcher.trim())
968 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
970 let after_cond_comment =
971 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
973 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
975 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
976 || force_newline_brace
983 let used_width = if pat_expr_string.contains('\n') {
984 last_line_width(&pat_expr_string)
986 // 2 = spaces after keyword and condition.
987 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
995 between_kwd_cond_comment.as_ref().map_or(
996 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1004 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1011 impl<'a> Rewrite for ControlFlow<'a> {
1012 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1013 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1015 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1016 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1017 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1018 if used_width == 0 {
1019 return Some(cond_str);
1022 let block_width = shape.width.saturating_sub(used_width);
1023 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1024 // we should avoid the single line case.
1025 let block_width = if self.else_block.is_some() || self.nested_if {
1030 let block_shape = Shape {
1035 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1037 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1038 context.is_if_else_block.replace(old_val);
1042 let mut result = format!("{}{}", cond_str, block_str);
1044 if let Some(else_block) = self.else_block {
1045 let shape = Shape::indented(shape.indent, context.config);
1046 let mut last_in_chain = false;
1047 let rewrite = match else_block.kind {
1048 // If the else expression is another if-else expression, prevent it
1049 // from being formatted on a single line.
1050 // Note how we're passing the original shape, as the
1051 // cost of "else" should not cascade.
1052 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1053 let (pats, cond) = extract_pats_and_cond(cond);
1054 ControlFlow::new_if(
1058 next_else_block.as_ref().map(|e| &**e),
1061 mk_sp(else_block.span.lo(), self.span.hi()),
1063 .rewrite(context, shape)
1066 last_in_chain = true;
1067 // When rewriting a block, the width is only used for single line
1068 // blocks, passing 1 lets us avoid that.
1069 let else_shape = Shape {
1070 width: min(1, shape.width),
1073 format_expr(else_block, ExprType::Statement, context, else_shape)
1077 let between_kwd_else_block = mk_sp(
1078 self.block.span.hi(),
1081 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1083 let between_kwd_else_block_comment =
1084 extract_comment(between_kwd_else_block, context, shape);
1086 let after_else = mk_sp(
1089 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1090 else_block.span.lo(),
1092 let after_else_comment = extract_comment(after_else, context, shape);
1094 let between_sep = match context.config.control_brace_style() {
1095 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1098 ControlBraceStyle::AlwaysSameLine => " ",
1100 let after_sep = match context.config.control_brace_style() {
1101 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1105 result.push_str(&format!(
1107 between_kwd_else_block_comment
1109 .map_or(between_sep, |s| &**s),
1110 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1112 result.push_str(&rewrite?);
1119 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1121 Some(label) => Cow::from(format!("{}: ", label.ident)),
1122 None => Cow::from(""),
1126 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1127 match rewrite_missing_comment(span, shape, context) {
1128 Some(ref comment) if !comment.is_empty() => Some(format!(
1129 "{indent}{}{indent}",
1131 indent = shape.indent.to_string_with_newline(context.config)
1137 pub(crate) fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1138 let snippet = source_map.span_to_snippet(block.span).unwrap();
1139 contains_comment(&snippet)
1142 // Checks that a block contains no statements, an expression and no comments or
1144 // FIXME: incorrectly returns false when comment is contained completely within
1146 pub(crate) fn is_simple_block(
1148 attrs: Option<&[ast::Attribute]>,
1149 source_map: &SourceMap,
1151 (block.stmts.len() == 1
1152 && stmt_is_expr(&block.stmts[0])
1153 && !block_contains_comment(block, source_map)
1154 && attrs.map_or(true, |a| a.is_empty()))
1157 /// Checks whether a block contains at most one statement or expression, and no
1158 /// comments or attributes.
1159 pub(crate) fn is_simple_block_stmt(
1161 attrs: Option<&[ast::Attribute]>,
1162 source_map: &SourceMap,
1164 block.stmts.len() <= 1
1165 && !block_contains_comment(block, source_map)
1166 && attrs.map_or(true, |a| a.is_empty())
1169 /// Checks whether a block contains no statements, expressions, comments, or
1170 /// inner attributes.
1171 pub(crate) fn is_empty_block(
1173 attrs: Option<&[ast::Attribute]>,
1174 source_map: &SourceMap,
1176 block.stmts.is_empty()
1177 && !block_contains_comment(block, source_map)
1178 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1181 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1183 ast::StmtKind::Expr(..) => true,
1188 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1189 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1196 pub(crate) fn rewrite_literal(
1197 context: &RewriteContext<'_>,
1200 ) -> Option<String> {
1202 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1204 context.snippet(l.span).to_owned(),
1205 context.config.max_width(),
1211 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1212 let string_lit = context.snippet(span);
1214 if !context.config.format_strings() {
1218 .all(|line| line.ends_with('\\'))
1220 let new_indent = shape.visual_indent(1).indent;
1221 let indented_string_lit = String::from(
1227 new_indent.to_string(context.config),
1231 .collect::<Vec<_>>()
1235 return if context.config.version() == Version::Two {
1236 Some(indented_string_lit)
1238 wrap_str(indented_string_lit, context.config.max_width(), shape)
1241 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1245 // Remove the quote characters.
1246 let str_lit = &string_lit[1..string_lit.len() - 1];
1250 &StringFormat::new(shape.visual_indent(0), context.config),
1251 shape.width.saturating_sub(2),
1255 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1256 if context.inside_macro() {
1257 if span_ends_with_comma(context, span) {
1258 Some(SeparatorTactic::Always)
1260 Some(SeparatorTactic::Never)
1267 pub(crate) fn rewrite_call(
1268 context: &RewriteContext<'_>,
1270 args: &[ptr::P<ast::Expr>],
1273 ) -> Option<String> {
1274 overflow::rewrite_with_parens(
1280 context.config.width_heuristics().fn_call_width,
1281 choose_separator_tactic(context, span),
1285 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1287 ast::ExprKind::Lit(..) => true,
1288 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1289 ast::ExprKind::AddrOf(_, ref expr)
1290 | ast::ExprKind::Box(ref expr)
1291 | ast::ExprKind::Cast(ref expr, _)
1292 | ast::ExprKind::Field(ref expr, _)
1293 | ast::ExprKind::Try(ref expr)
1294 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1295 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1296 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1297 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1303 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1304 lists.iter().all(OverflowableItem::is_simple)
1307 pub(crate) fn can_be_overflowed_expr(
1308 context: &RewriteContext<'_>,
1313 _ if !expr.attrs.is_empty() => false,
1314 ast::ExprKind::Match(..) => {
1315 (context.use_block_indent() && args_len == 1)
1316 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1317 || context.config.overflow_delimited_expr()
1319 ast::ExprKind::If(..)
1320 | ast::ExprKind::ForLoop(..)
1321 | ast::ExprKind::Loop(..)
1322 | ast::ExprKind::While(..) => {
1323 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1326 // Handle always block-like expressions
1327 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1329 // Handle `[]` and `{}`-like expressions
1330 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1331 context.config.overflow_delimited_expr()
1332 || (context.use_block_indent() && args_len == 1)
1334 ast::ExprKind::Mac(ref mac) => {
1335 match (mac.delim, context.config.overflow_delimited_expr()) {
1336 (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
1337 _ => context.use_block_indent() && args_len == 1,
1341 // Handle parenthetical expressions
1342 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1343 context.use_block_indent() && args_len == 1
1346 // Handle unary-like expressions
1347 ast::ExprKind::AddrOf(_, ref expr)
1348 | ast::ExprKind::Box(ref expr)
1349 | ast::ExprKind::Try(ref expr)
1350 | ast::ExprKind::Unary(_, ref expr)
1351 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1356 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1358 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1359 ast::ExprKind::AddrOf(_, ref expr)
1360 | ast::ExprKind::Box(ref expr)
1361 | ast::ExprKind::Try(ref expr)
1362 | ast::ExprKind::Unary(_, ref expr)
1363 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1368 /// Returns `true` if a function call or a method call represented by the given span ends with a
1369 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1370 /// comma from macro can potentially break the code.
1371 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1372 let mut result: bool = Default::default();
1373 let mut prev_char: char = Default::default();
1374 let closing_delimiters = &[')', '}', ']'];
1376 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1378 _ if kind.is_comment() || c.is_whitespace() => continue,
1379 c if closing_delimiters.contains(&c) => {
1380 result &= !closing_delimiters.contains(&prev_char);
1382 ',' => result = true,
1383 _ => result = false,
1392 context: &RewriteContext<'_>,
1393 mut subexpr: &ast::Expr,
1396 ) -> Option<String> {
1397 debug!("rewrite_paren, shape: {:?}", shape);
1399 // Extract comments within parens.
1402 let mut pre_comment;
1403 let mut post_comment;
1404 let remove_nested_parens = context.config.remove_nested_parens();
1407 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1408 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1409 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1410 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1412 // Remove nested parens if there are no comments.
1413 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1414 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1415 span = subexpr.span;
1416 subexpr = subsubexpr;
1425 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1426 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1427 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1428 if fits_single_line {
1429 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1431 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1435 fn rewrite_paren_in_multi_line(
1436 context: &RewriteContext<'_>,
1437 subexpr: &ast::Expr,
1441 ) -> Option<String> {
1442 let nested_indent = shape.indent.block_indent(context.config);
1443 let nested_shape = Shape::indented(nested_indent, context.config);
1444 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1445 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1446 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1448 let mut result = String::with_capacity(subexpr_str.len() * 2);
1450 if !pre_comment.is_empty() {
1451 result.push_str(&nested_indent.to_string_with_newline(context.config));
1452 result.push_str(&pre_comment);
1454 result.push_str(&nested_indent.to_string_with_newline(context.config));
1455 result.push_str(&subexpr_str);
1456 if !post_comment.is_empty() {
1457 result.push_str(&nested_indent.to_string_with_newline(context.config));
1458 result.push_str(&post_comment);
1460 result.push_str(&shape.indent.to_string_with_newline(context.config));
1469 context: &RewriteContext<'_>,
1471 ) -> Option<String> {
1472 let expr_str = expr.rewrite(context, shape)?;
1474 let offset = last_line_width(&expr_str) + 1;
1475 let rhs_overhead = shape.rhs_overhead(context.config);
1476 let index_shape = if expr_str.contains('\n') {
1477 Shape::legacy(context.config.max_width(), shape.indent)
1478 .offset_left(offset)
1479 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1481 match context.config.indent_style() {
1482 IndentStyle::Block => shape
1483 .offset_left(offset)
1484 .and_then(|shape| shape.sub_width(1)),
1485 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1488 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1490 // Return if index fits in a single line.
1491 match orig_index_rw {
1492 Some(ref index_str) if !index_str.contains('\n') => {
1493 return Some(format!("{}[{}]", expr_str, index_str));
1498 // Try putting index on the next line and see if it fits in a single line.
1499 let indent = shape.indent.block_indent(context.config);
1500 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1501 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1502 let new_index_rw = index.rewrite(context, index_shape);
1503 match (orig_index_rw, new_index_rw) {
1504 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1507 indent.to_string_with_newline(context.config),
1510 (None, Some(ref new_index_str)) => Some(format!(
1513 indent.to_string_with_newline(context.config),
1516 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1521 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1526 fields.iter().all(|field| !field.is_shorthand)
1529 fn rewrite_struct_lit<'a>(
1530 context: &RewriteContext<'_>,
1532 fields: &'a [ast::Field],
1533 base: Option<&'a ast::Expr>,
1534 attrs: &[ast::Attribute],
1537 ) -> Option<String> {
1538 debug!("rewrite_struct_lit: shape {:?}", shape);
1540 enum StructLitField<'a> {
1541 Regular(&'a ast::Field),
1542 Base(&'a ast::Expr),
1546 let path_shape = shape.sub_width(2)?;
1547 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1549 if fields.is_empty() && base.is_none() {
1550 return Some(format!("{} {{}}", path_str));
1553 // Foo { a: Foo } - indent is +3, width is -5.
1554 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1556 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1557 let body_lo = context.snippet_provider.span_after(span, "{");
1558 let fields_str = if struct_lit_can_be_aligned(fields, base)
1559 && context.config.struct_field_align_threshold() > 0
1561 rewrite_with_alignment(
1565 mk_sp(body_lo, span.hi()),
1569 let field_iter = fields
1571 .map(StructLitField::Regular)
1572 .chain(base.into_iter().map(StructLitField::Base));
1574 let span_lo = |item: &StructLitField<'_>| match *item {
1575 StructLitField::Regular(field) => field.span().lo(),
1576 StructLitField::Base(expr) => {
1577 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1578 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1579 let pos = snippet.find_uncommented("..").unwrap();
1580 last_field_hi + BytePos(pos as u32)
1583 let span_hi = |item: &StructLitField<'_>| match *item {
1584 StructLitField::Regular(field) => field.span().hi(),
1585 StructLitField::Base(expr) => expr.span.hi(),
1587 let rewrite = |item: &StructLitField<'_>| match *item {
1588 StructLitField::Regular(field) => {
1589 // The 1 taken from the v_budget is for the comma.
1590 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1592 StructLitField::Base(expr) => {
1594 expr.rewrite(context, v_shape.offset_left(2)?)
1595 .map(|s| format!("..{}", s))
1599 let items = itemize_list(
1600 context.snippet_provider,
1611 let item_vec = items.collect::<Vec<_>>();
1613 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1614 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1616 let ends_with_comma = span_ends_with_comma(context, span);
1617 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1619 let fmt = struct_lit_formatting(
1623 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1626 write_list(&item_vec, &fmt)?
1630 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1631 Some(format!("{} {{{}}}", path_str, fields_str))
1633 // FIXME if context.config.indent_style() == Visual, but we run out
1634 // of space, we should fall back to BlockIndent.
1637 pub(crate) fn wrap_struct_field(
1638 context: &RewriteContext<'_>,
1639 attrs: &[ast::Attribute],
1642 nested_shape: Shape,
1643 one_line_width: usize,
1644 ) -> Option<String> {
1645 let should_vertical = context.config.indent_style() == IndentStyle::Block
1646 && (fields_str.contains('\n')
1647 || !context.config.struct_lit_single_line()
1648 || fields_str.len() > one_line_width);
1650 let inner_attrs = &inner_attributes(attrs);
1651 if inner_attrs.is_empty() {
1652 if should_vertical {
1655 nested_shape.indent.to_string_with_newline(context.config),
1657 shape.indent.to_string_with_newline(context.config)
1660 // One liner or visual indent.
1661 Some(format!(" {} ", fields_str))
1666 nested_shape.indent.to_string_with_newline(context.config),
1667 inner_attrs.rewrite(context, shape)?,
1668 nested_shape.indent.to_string_with_newline(context.config),
1670 shape.indent.to_string_with_newline(context.config)
1675 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1676 colon_spaces(config)
1679 pub(crate) fn rewrite_field(
1680 context: &RewriteContext<'_>,
1683 prefix_max_width: usize,
1684 ) -> Option<String> {
1685 if contains_skip(&field.attrs) {
1686 return Some(context.snippet(field.span()).to_owned());
1688 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1689 if !attrs_str.is_empty() {
1690 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1692 let name = context.snippet(field.ident.span);
1693 if field.is_shorthand {
1694 Some(attrs_str + name)
1696 let mut separator = String::from(struct_lit_field_separator(context.config));
1697 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1698 separator.push(' ');
1700 let overhead = name.len() + separator.len();
1701 let expr_shape = shape.offset_left(overhead)?;
1702 let expr = field.expr.rewrite(context, expr_shape);
1705 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1706 Some(attrs_str + name)
1708 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1710 let expr_offset = shape.indent.block_indent(context.config);
1713 .rewrite(context, Shape::indented(expr_offset, context.config));
1719 expr_offset.to_string(context.config),
1728 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1729 context: &RewriteContext<'_>,
1730 mut items: impl Iterator<Item = &'a T>,
1733 is_singleton_tuple: bool,
1734 ) -> Option<String> {
1735 // In case of length 1, need a trailing comma
1736 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1737 if is_singleton_tuple {
1739 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1743 .rewrite(context, nested_shape)
1744 .map(|s| format!("({},)", s));
1747 let list_lo = context.snippet_provider.span_after(span, "(");
1748 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1749 let items = itemize_list(
1750 context.snippet_provider,
1754 |item| item.span().lo(),
1755 |item| item.span().hi(),
1756 |item| item.rewrite(context, nested_shape),
1758 span.hi() - BytePos(1),
1761 let item_vec: Vec<_> = items.collect();
1762 let tactic = definitive_tactic(
1764 ListTactic::HorizontalVertical,
1768 let fmt = ListFormatting::new(nested_shape, context.config)
1770 .ends_with_newline(false);
1771 let list_str = write_list(&item_vec, &fmt)?;
1773 Some(format!("({})", list_str))
1776 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1777 context: &'a RewriteContext<'_>,
1778 items: impl Iterator<Item = &'a T>,
1781 is_singleton_tuple: bool,
1782 ) -> Option<String> {
1783 debug!("rewrite_tuple {:?}", shape);
1784 if context.use_block_indent() {
1785 // We use the same rule as function calls for rewriting tuples.
1786 let force_tactic = if context.inside_macro() {
1787 if span_ends_with_comma(context, span) {
1788 Some(SeparatorTactic::Always)
1790 Some(SeparatorTactic::Never)
1792 } else if is_singleton_tuple {
1793 Some(SeparatorTactic::Always)
1797 overflow::rewrite_with_parens(
1803 context.config.width_heuristics().fn_call_width,
1807 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1811 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1812 context: &RewriteContext<'_>,
1816 ) -> Option<String> {
1818 .rewrite(context, shape.offset_left(prefix.len())?)
1819 .map(|r| format!("{}{}", prefix, r))
1822 // FIXME: this is probably not correct for multi-line Rewrites. we should
1823 // subtract suffix.len() from the last line budget, not the first!
1824 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1825 context: &RewriteContext<'_>,
1829 ) -> Option<String> {
1831 .rewrite(context, shape.sub_width(suffix.len())?)
1838 fn rewrite_unary_op(
1839 context: &RewriteContext<'_>,
1843 ) -> Option<String> {
1844 // For some reason, an UnOp is not spanned like BinOp!
1845 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1848 fn rewrite_assignment(
1849 context: &RewriteContext<'_>,
1852 op: Option<&ast::BinOp>,
1854 ) -> Option<String> {
1855 let operator_str = match op {
1856 Some(op) => context.snippet(op.span),
1860 // 1 = space between lhs and operator.
1861 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1862 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1864 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1867 /// Controls where to put the rhs.
1868 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1869 pub(crate) enum RhsTactics {
1872 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1873 ForceNextLineWithoutIndent,
1874 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1879 // The left hand side must contain everything up to, and including, the
1880 // assignment operator.
1881 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1882 context: &RewriteContext<'_>,
1886 ) -> Option<String> {
1887 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1890 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1891 context: &RewriteContext<'_>,
1895 rhs_tactics: RhsTactics,
1896 ) -> Option<String> {
1897 let lhs = lhs.into();
1898 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1899 shape.indent.width()
1903 // 1 = space between operator and rhs.
1904 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1906 offset: shape.offset + last_line_width + 1,
1909 let rhs = choose_rhs(
1913 ex.rewrite(context, orig_shape),
1919 fn choose_rhs<R: Rewrite>(
1920 context: &RewriteContext<'_>,
1923 orig_rhs: Option<String>,
1924 rhs_tactics: RhsTactics,
1925 ) -> Option<String> {
1928 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1930 Some(format!(" {}", new_str))
1933 // Expression did not fit on the same line as the identifier.
1934 // Try splitting the line and see if that works better.
1935 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1936 let new_rhs = expr.rewrite(context, new_shape);
1937 let new_indent_str = &shape
1939 .block_indent(context.config)
1940 .to_string_with_newline(context.config);
1942 match (orig_rhs, new_rhs) {
1943 (Some(ref orig_rhs), Some(ref new_rhs))
1944 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1947 Some(format!(" {}", orig_rhs))
1949 (Some(ref orig_rhs), Some(ref new_rhs))
1950 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1952 Some(format!("{}{}", new_indent_str, new_rhs))
1954 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1955 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1956 let shape = shape.infinite_width();
1957 expr.rewrite(context, shape).map(|s| format!(" {}", s))
1959 (None, None) => None,
1960 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1966 fn shape_from_rhs_tactic(
1967 context: &RewriteContext<'_>,
1969 rhs_tactic: RhsTactics,
1970 ) -> Option<Shape> {
1972 RhsTactics::ForceNextLineWithoutIndent => shape
1973 .with_max_width(context.config)
1974 .sub_width(shape.indent.width()),
1975 RhsTactics::Default | RhsTactics::AllowOverflow => {
1976 Shape::indented(shape.indent.block_indent(context.config), context.config)
1977 .sub_width(shape.rhs_overhead(context.config))
1982 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
1983 /// original's line formatting.
1985 /// It is considered better if:
1986 /// 1. the tactic is ForceNextLineWithoutIndent
1987 /// 2. next_line_rhs doesn't have newlines
1988 /// 3. the original line has more newlines than next_line_rhs
1989 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
1991 pub(crate) fn prefer_next_line(
1993 next_line_rhs: &str,
1994 rhs_tactics: RhsTactics,
1996 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1997 || !next_line_rhs.contains('\n')
1998 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
1999 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2000 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2001 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2004 fn rewrite_expr_addrof(
2005 context: &RewriteContext<'_>,
2006 mutability: ast::Mutability,
2009 ) -> Option<String> {
2010 let operator_str = match mutability {
2011 ast::Mutability::Immutable => "&",
2012 ast::Mutability::Mutable => "&mut ",
2014 rewrite_unary_prefix(context, operator_str, expr, shape)
2017 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2019 ast::ExprKind::MethodCall(..) => true,
2020 ast::ExprKind::AddrOf(_, ref expr)
2021 | ast::ExprKind::Box(ref expr)
2022 | ast::ExprKind::Cast(ref expr, _)
2023 | ast::ExprKind::Try(ref expr)
2024 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2031 use super::last_line_offsetted;
2034 fn test_last_line_offsetted() {
2035 let lines = "one\n two";
2036 assert_eq!(last_line_offsetted(2, lines), true);
2037 assert_eq!(last_line_offsetted(4, lines), false);
2038 assert_eq!(last_line_offsetted(6, lines), false);
2040 let lines = "one two";
2041 assert_eq!(last_line_offsetted(2, lines), false);
2042 assert_eq!(last_line_offsetted(0, lines), false);
2044 let lines = "\ntwo";
2045 assert_eq!(last_line_offsetted(2, lines), false);
2046 assert_eq!(last_line_offsetted(0, lines), false);
2048 let lines = "one\n two three";
2049 assert_eq!(last_line_offsetted(2, lines), true);
2050 let lines = "one\n two three";
2051 assert_eq!(last_line_offsetted(2, lines), false);