5 use itertools::Itertools;
6 use syntax::parse::token::DelimToken;
7 use syntax::source_map::{BytePos, SourceMap, Span};
8 use syntax::{ast, ptr};
10 use crate::chains::rewrite_chain;
13 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
14 rewrite_missing_comment, CharClasses, FindUncommented,
16 use crate::config::lists::*;
17 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
19 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
20 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
22 use crate::macros::{rewrite_macro, MacroPosition};
23 use crate::matches::rewrite_match;
24 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
25 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
26 use crate::patterns::is_short_pattern;
27 use crate::rewrite::{Rewrite, RewriteContext};
28 use crate::shape::{Indent, Shape};
29 use crate::source_map::{LineRangeUtils, SpanUtils};
30 use crate::spanned::Spanned;
31 use crate::string::{rewrite_string, StringFormat};
32 use crate::types::{rewrite_path, PathContext};
34 colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
35 last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
36 semicolon_for_expr, unicode_str_width, wrap_str,
38 use crate::vertical::rewrite_with_alignment;
39 use crate::visitor::FmtVisitor;
41 impl Rewrite for ast::Expr {
42 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
43 format_expr(self, ExprType::SubExpression, context, shape)
47 #[derive(Copy, Clone, PartialEq)]
48 pub(crate) enum ExprType {
53 pub(crate) fn format_expr(
56 context: &RewriteContext<'_>,
59 skip_out_of_file_lines_range!(context, expr.span);
61 if contains_skip(&*expr.attrs) {
62 return Some(context.snippet(expr.span()).to_owned());
64 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
70 let expr_rw = match expr.node {
71 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
77 choose_separator_tactic(context, expr.span),
80 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
81 ast::ExprKind::Call(ref callee, ref args) => {
82 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
83 let callee_str = callee.rewrite(context, shape)?;
84 rewrite_call(context, &callee_str, args, inner_span, shape)
86 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
87 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
88 // FIXME: format comments between operands and operator
89 rewrite_all_pairs(expr, shape, context).or_else(|| {
93 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
96 context.config.binop_separator(),
100 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
101 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
105 base.as_ref().map(|e| &**e),
110 ast::ExprKind::Tup(ref items) => {
111 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
113 ast::ExprKind::If(..)
114 | ast::ExprKind::IfLet(..)
115 | ast::ExprKind::ForLoop(..)
116 | ast::ExprKind::Loop(..)
117 | ast::ExprKind::While(..)
118 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
119 .and_then(|control_flow| control_flow.rewrite(context, shape)),
120 ast::ExprKind::Block(ref block, opt_label) => {
122 ExprType::Statement => {
123 if is_unsafe_block(block) {
124 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
125 } else if let rw @ Some(_) =
126 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
128 // Rewrite block without trying to put it in a single line.
131 let prefix = block_prefix(context, block, shape)?;
133 rewrite_block_with_visitor(
144 ExprType::SubExpression => {
145 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
149 ast::ExprKind::Match(ref cond, ref arms) => {
150 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
152 ast::ExprKind::Path(ref qself, ref path) => {
153 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
155 ast::ExprKind::Assign(ref lhs, ref rhs) => {
156 rewrite_assignment(context, lhs, rhs, None, shape)
158 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
159 rewrite_assignment(context, lhs, rhs, Some(op), shape)
161 ast::ExprKind::Continue(ref opt_label) => {
162 let id_str = match *opt_label {
163 Some(label) => format!(" {}", label.ident),
164 None => String::new(),
166 Some(format!("continue{}", id_str))
168 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
169 let id_str = match *opt_label {
170 Some(label) => format!(" {}", label.ident),
171 None => String::new(),
174 if let Some(ref expr) = *opt_expr {
175 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
177 Some(format!("break{}", id_str))
180 ast::ExprKind::Yield(ref opt_expr) => {
181 if let Some(ref expr) = *opt_expr {
182 rewrite_unary_prefix(context, "yield ", &**expr, shape)
184 Some("yield".to_string())
187 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
188 closures::rewrite_closure(
189 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
192 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
193 rewrite_chain(expr, context, shape)
195 ast::ExprKind::Mac(ref mac) => {
196 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
198 context.snippet(expr.span).to_owned(),
199 context.config.max_width(),
204 ast::ExprKind::Ret(None) => Some("return".to_owned()),
205 ast::ExprKind::Ret(Some(ref expr)) => {
206 rewrite_unary_prefix(context, "return ", &**expr, shape)
208 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
209 ast::ExprKind::AddrOf(mutability, ref expr) => {
210 rewrite_expr_addrof(context, mutability, expr, shape)
212 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
215 PairParts::infix(" as "),
218 SeparatorPlace::Front,
220 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
223 PairParts::infix(": "),
226 SeparatorPlace::Back,
228 ast::ExprKind::Index(ref expr, ref index) => {
229 rewrite_index(&**expr, &**index, context, shape)
231 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
234 PairParts::new("[", "; ", "]"),
237 SeparatorPlace::Back,
239 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
240 let delim = match limits {
241 ast::RangeLimits::HalfOpen => "..",
242 ast::RangeLimits::Closed => "..=",
245 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
247 ast::ExprKind::Lit(ref lit) => match lit.node {
248 ast::LitKind::FloatUnsuffixed(..) => {
249 context.snippet(lit.span).ends_with('.')
257 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
259 // Don't format `.. ..` into `....`, which is invalid.
261 // This check is unnecessary for `lhs`, because a range
262 // starting from another range needs parentheses as `(x ..) ..`
263 // (`x .. ..` is a range from `x` to `..`).
264 ast::ExprKind::Range(None, _, _) => true,
269 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
270 let space_if = |b: bool| if b { " " } else { "" };
274 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
276 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
280 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
281 (Some(lhs), Some(rhs)) => {
282 let sp_delim = if context.config.spaces_around_ranges() {
283 format!(" {} ", delim)
285 default_sp_delim(Some(lhs), Some(rhs))
290 PairParts::infix(&sp_delim),
293 context.config.binop_separator(),
296 (None, Some(rhs)) => {
297 let sp_delim = if context.config.spaces_around_ranges() {
298 format!("{} ", delim)
300 default_sp_delim(None, Some(rhs))
302 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
304 (Some(lhs), None) => {
305 let sp_delim = if context.config.spaces_around_ranges() {
306 format!(" {}", delim)
308 default_sp_delim(Some(lhs), None)
310 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
312 (None, None) => Some(delim.to_owned()),
315 // We do not format these expressions yet, but they should still
316 // satisfy our width restrictions.
317 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
318 ast::ExprKind::TryBlock(ref block) => {
319 if let rw @ Some(_) =
320 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
325 let budget = shape.width.saturating_sub(9);
334 Shape::legacy(budget, shape.indent)
339 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
340 let mover = if capture_by == ast::CaptureBy::Value {
345 if let rw @ Some(_) = rewrite_single_line_block(
347 format!("{}{}", "async ", mover).as_str(),
356 let budget = shape.width.saturating_sub(6);
366 Shape::legacy(budget, shape.indent)
371 ast::ExprKind::Await(ast::AwaitOrigin::FieldLike, _) => rewrite_chain(expr, context, shape),
372 ast::ExprKind::Await(ast::AwaitOrigin::MacroLike, ref nested) => {
373 overflow::rewrite_with_parens(
379 context.config.max_width(),
383 ast::ExprKind::Err => None,
387 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
388 .and_then(|expr_str| {
389 let attrs = outer_attributes(&expr.attrs);
390 let attrs_str = attrs.rewrite(context, shape)?;
392 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
395 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
399 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
401 exprs: impl Iterator<Item = &'a T>,
403 context: &'a RewriteContext<'_>,
405 force_separator_tactic: Option<SeparatorTactic>,
406 delim_token: Option<DelimToken>,
407 ) -> Option<String> {
408 overflow::rewrite_with_square_brackets(
414 force_separator_tactic,
419 fn rewrite_empty_block(
420 context: &RewriteContext<'_>,
422 attrs: Option<&[ast::Attribute]>,
423 label: Option<ast::Label>,
426 ) -> Option<String> {
427 if !block.stmts.is_empty() {
431 let label_str = rewrite_label(label);
432 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
436 if !block_contains_comment(block, context.source_map) && shape.width >= 2 {
437 return Some(format!("{}{}{{}}", prefix, label_str));
440 // If a block contains only a single-line comment, then leave it on one line.
441 let user_str = context.snippet(block.span);
442 let user_str = user_str.trim();
443 if user_str.starts_with('{') && user_str.ends_with('}') {
444 let comment_str = user_str[1..user_str.len() - 1].trim();
445 if block.stmts.is_empty()
446 && !comment_str.contains('\n')
447 && !comment_str.starts_with("//")
448 && comment_str.len() + 4 <= shape.width
450 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
457 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
458 Some(match block.rules {
459 ast::BlockCheckMode::Unsafe(..) => {
460 let snippet = context.snippet(block.span);
461 let open_pos = snippet.find_uncommented("{")?;
462 // Extract comment between unsafe and block start.
463 let trimmed = &snippet[6..open_pos].trim();
465 if !trimmed.is_empty() {
466 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
467 let budget = shape.width.checked_sub(9)?;
473 Shape::legacy(budget, shape.indent + 7),
481 ast::BlockCheckMode::Default => String::new(),
485 fn rewrite_single_line_block(
486 context: &RewriteContext<'_>,
489 attrs: Option<&[ast::Attribute]>,
490 label: Option<ast::Label>,
492 ) -> Option<String> {
493 if is_simple_block(block, attrs, context.source_map) {
494 let expr_shape = shape.offset_left(last_line_width(prefix))?;
495 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
496 let label_str = rewrite_label(label);
497 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
498 if result.len() <= shape.width && !result.contains('\n') {
505 pub(crate) fn rewrite_block_with_visitor(
506 context: &RewriteContext<'_>,
509 attrs: Option<&[ast::Attribute]>,
510 label: Option<ast::Label>,
513 ) -> Option<String> {
514 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
518 let mut visitor = FmtVisitor::from_context(context);
519 visitor.block_indent = shape.indent;
520 visitor.is_if_else_block = context.is_if_else_block();
521 match (block.rules, label) {
522 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
523 let snippet = context.snippet(block.span);
524 let open_pos = snippet.find_uncommented("{")?;
525 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
527 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
530 let inner_attrs = attrs.map(inner_attributes);
531 let label_str = rewrite_label(label);
532 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
533 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
536 impl Rewrite for ast::Block {
537 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
538 rewrite_block(self, None, None, context, shape)
544 attrs: Option<&[ast::Attribute]>,
545 label: Option<ast::Label>,
546 context: &RewriteContext<'_>,
548 ) -> Option<String> {
549 let prefix = block_prefix(context, block, shape)?;
551 // shape.width is used only for the single line case: either the empty block `{}`,
552 // or an unsafe expression `unsafe { e }`.
553 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
557 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
558 if let Some(ref result_str) = result {
559 if result_str.lines().count() <= 3 {
560 if let rw @ Some(_) =
561 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
571 // Rewrite condition if the given expression has one.
572 pub(crate) fn rewrite_cond(
573 context: &RewriteContext<'_>,
576 ) -> Option<String> {
578 ast::ExprKind::Match(ref cond, _) => {
580 let cond_shape = match context.config.indent_style() {
581 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
582 IndentStyle::Block => shape.offset_left(8)?,
584 cond.rewrite(context, cond_shape)
586 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
588 String::from("\n") + &shape.indent.block_only().to_string(context.config);
590 .rewrite_cond(context, shape, &alt_block_sep)
591 .and_then(|rw| Some(rw.0))
596 // Abstraction over control flow expressions
598 struct ControlFlow<'a> {
599 cond: Option<&'a ast::Expr>,
600 block: &'a ast::Block,
601 else_block: Option<&'a ast::Expr>,
602 label: Option<ast::Label>,
603 pats: Vec<&'a ast::Pat>,
607 allow_single_line: bool,
608 // HACK: `true` if this is an `if` expression in an `else if`.
613 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
615 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
619 else_block.as_ref().map(|e| &**e),
620 expr_type == ExprType::SubExpression,
624 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
625 Some(ControlFlow::new_if(
627 ptr_vec_to_ref_vec(pat),
629 else_block.as_ref().map(|e| &**e),
630 expr_type == ExprType::SubExpression,
635 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
636 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
638 ast::ExprKind::Loop(ref block, label) => {
639 Some(ControlFlow::new_loop(block, label, expr.span))
641 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
648 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
649 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
655 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
656 if pats.is_empty() { "" } else { "let" }
659 impl<'a> ControlFlow<'a> {
662 pats: Vec<&'a ast::Pat>,
663 block: &'a ast::Block,
664 else_block: Option<&'a ast::Expr>,
665 allow_single_line: bool,
668 ) -> ControlFlow<'a> {
669 let matcher = choose_matcher(&pats);
685 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
695 allow_single_line: false,
702 pats: Vec<&'a ast::Pat>,
704 block: &'a ast::Block,
705 label: Option<ast::Label>,
707 ) -> ControlFlow<'a> {
708 let matcher = choose_matcher(&pats);
718 allow_single_line: false,
727 block: &'a ast::Block,
728 label: Option<ast::Label>,
730 ) -> ControlFlow<'a> {
740 allow_single_line: false,
746 fn rewrite_single_line(
749 context: &RewriteContext<'_>,
751 ) -> Option<String> {
752 assert!(self.allow_single_line);
753 let else_block = self.else_block?;
754 let fixed_cost = self.keyword.len() + " { } else { }".len();
756 if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
757 if !is_simple_block(self.block, None, context.source_map)
758 || !is_simple_block(else_node, None, context.source_map)
759 || pat_expr_str.contains('\n')
764 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
765 let expr = &self.block.stmts[0];
766 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
768 let new_width = new_width.checked_sub(if_str.len())?;
769 let else_expr = &else_node.stmts[0];
770 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
772 if if_str.contains('\n') || else_str.contains('\n') {
776 let result = format!(
777 "{} {} {{ {} }} else {{ {} }}",
778 self.keyword, pat_expr_str, if_str, else_str
781 if result.len() <= width {
790 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
792 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
793 let mut leading_whitespaces = 0;
794 for c in pat_str.chars().rev() {
797 _ if c.is_whitespace() => leading_whitespaces += 1,
798 _ => leading_whitespaces = 0,
801 leading_whitespaces > start_column
804 impl<'a> ControlFlow<'a> {
807 context: &RewriteContext<'_>,
811 ) -> Option<String> {
812 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
814 let cond_shape = shape.offset_left(offset)?;
815 if !self.pats.is_empty() {
816 let matcher = if self.matcher.is_empty() {
817 self.matcher.to_owned()
819 format!("{} ", self.matcher)
821 let pat_shape = cond_shape
822 .offset_left(matcher.len())?
823 .sub_width(self.connector.len())?;
824 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
825 let result = format!("{}{}{}", matcher, pat_string, self.connector);
826 return rewrite_assign_rhs(context, result, expr, cond_shape);
829 let expr_rw = expr.rewrite(context, cond_shape);
830 // The expression may (partially) fit on the current line.
831 // We do not allow splitting between `if` and condition.
832 if self.keyword == "if" || expr_rw.is_some() {
836 // The expression won't fit on the current line, jump to next.
837 let nested_shape = shape
838 .block_indent(context.config.tab_spaces())
839 .with_max_width(context.config);
840 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
841 expr.rewrite(context, nested_shape)
842 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
847 context: &RewriteContext<'_>,
850 ) -> Option<(String, usize)> {
851 // Do not take the rhs overhead from the upper expressions into account
852 // when rewriting pattern.
853 let new_width = context.budget(shape.used_width());
854 let fresh_shape = Shape {
858 let constr_shape = if self.nested_if {
859 // We are part of an if-elseif-else chain. Our constraints are tightened.
860 // 7 = "} else " .len()
861 fresh_shape.offset_left(7)?
866 let label_string = rewrite_label(self.label);
867 // 1 = space after keyword.
868 let offset = self.keyword.len() + label_string.len() + 1;
870 let pat_expr_string = match self.cond {
871 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
872 None => String::new(),
876 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
882 let one_line_budget = context
885 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
886 let force_newline_brace = (pat_expr_string.contains('\n')
887 || pat_expr_string.len() > one_line_budget)
888 && (!last_line_extendable(&pat_expr_string)
889 || last_line_offsetted(shape.used_width(), &pat_expr_string));
891 // Try to format if-else on single line.
892 if self.allow_single_line
896 .single_line_if_else_max_width
899 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
901 if let Some(cond_str) = trial {
906 .single_line_if_else_max_width
908 return Some((cond_str, 0));
913 let cond_span = if let Some(cond) = self.cond {
916 mk_sp(self.block.span.lo(), self.block.span.lo())
919 // `for event in event`
920 // Do not include label in the span.
923 .map_or(self.span.lo(), |label| label.ident.span.hi());
924 let between_kwd_cond = mk_sp(
927 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
928 if self.pats.is_empty() {
930 } else if self.matcher.is_empty() {
931 self.pats[0].span.lo()
935 .span_before(self.span, self.matcher.trim())
939 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
941 let after_cond_comment =
942 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
944 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
946 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
947 || force_newline_brace
954 let used_width = if pat_expr_string.contains('\n') {
955 last_line_width(&pat_expr_string)
957 // 2 = spaces after keyword and condition.
958 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
966 between_kwd_cond_comment.as_ref().map_or(
967 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
975 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
982 impl<'a> Rewrite for ControlFlow<'a> {
983 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
984 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
986 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
987 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
988 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
990 return Some(cond_str);
993 let block_width = shape.width.saturating_sub(used_width);
994 // This is used only for the empty block case: `{}`. So, we use 1 if we know
995 // we should avoid the single line case.
996 let block_width = if self.else_block.is_some() || self.nested_if {
1001 let block_shape = Shape {
1006 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1008 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1009 context.is_if_else_block.replace(old_val);
1013 let mut result = format!("{}{}", cond_str, block_str);
1015 if let Some(else_block) = self.else_block {
1016 let shape = Shape::indented(shape.indent, context.config);
1017 let mut last_in_chain = false;
1018 let rewrite = match else_block.node {
1019 // If the else expression is another if-else expression, prevent it
1020 // from being formatted on a single line.
1021 // Note how we're passing the original shape, as the
1022 // cost of "else" should not cascade.
1023 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1024 ControlFlow::new_if(
1026 ptr_vec_to_ref_vec(pat),
1028 next_else_block.as_ref().map(|e| &**e),
1031 mk_sp(else_block.span.lo(), self.span.hi()),
1033 .rewrite(context, shape)
1035 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1036 ControlFlow::new_if(
1040 next_else_block.as_ref().map(|e| &**e),
1043 mk_sp(else_block.span.lo(), self.span.hi()),
1045 .rewrite(context, shape)
1048 last_in_chain = true;
1049 // When rewriting a block, the width is only used for single line
1050 // blocks, passing 1 lets us avoid that.
1051 let else_shape = Shape {
1052 width: min(1, shape.width),
1055 format_expr(else_block, ExprType::Statement, context, else_shape)
1059 let between_kwd_else_block = mk_sp(
1060 self.block.span.hi(),
1063 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1065 let between_kwd_else_block_comment =
1066 extract_comment(between_kwd_else_block, context, shape);
1068 let after_else = mk_sp(
1071 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1072 else_block.span.lo(),
1074 let after_else_comment = extract_comment(after_else, context, shape);
1076 let between_sep = match context.config.control_brace_style() {
1077 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1080 ControlBraceStyle::AlwaysSameLine => " ",
1082 let after_sep = match context.config.control_brace_style() {
1083 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1087 result.push_str(&format!(
1089 between_kwd_else_block_comment
1091 .map_or(between_sep, |s| &**s),
1092 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1094 result.push_str(&rewrite?);
1101 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1103 Some(label) => Cow::from(format!("{}: ", label.ident)),
1104 None => Cow::from(""),
1108 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1109 match rewrite_missing_comment(span, shape, context) {
1110 Some(ref comment) if !comment.is_empty() => Some(format!(
1111 "{indent}{}{indent}",
1113 indent = shape.indent.to_string_with_newline(context.config)
1119 pub(crate) fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1120 let snippet = source_map.span_to_snippet(block.span).unwrap();
1121 contains_comment(&snippet)
1124 // Checks that a block contains no statements, an expression and no comments or
1126 // FIXME: incorrectly returns false when comment is contained completely within
1128 pub(crate) fn is_simple_block(
1130 attrs: Option<&[ast::Attribute]>,
1131 source_map: &SourceMap,
1133 (block.stmts.len() == 1
1134 && stmt_is_expr(&block.stmts[0])
1135 && !block_contains_comment(block, source_map)
1136 && attrs.map_or(true, |a| a.is_empty()))
1139 /// Checks whether a block contains at most one statement or expression, and no
1140 /// comments or attributes.
1141 pub(crate) fn is_simple_block_stmt(
1143 attrs: Option<&[ast::Attribute]>,
1144 source_map: &SourceMap,
1146 block.stmts.len() <= 1
1147 && !block_contains_comment(block, source_map)
1148 && attrs.map_or(true, |a| a.is_empty())
1151 /// Checks whether a block contains no statements, expressions, comments, or
1152 /// inner attributes.
1153 pub(crate) fn is_empty_block(
1155 attrs: Option<&[ast::Attribute]>,
1156 source_map: &SourceMap,
1158 block.stmts.is_empty()
1159 && !block_contains_comment(block, source_map)
1160 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1163 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1165 ast::StmtKind::Expr(..) => true,
1170 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1171 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1178 pub(crate) fn rewrite_multiple_patterns(
1179 context: &RewriteContext<'_>,
1182 ) -> Option<String> {
1185 .map(|p| p.rewrite(context, shape))
1186 .collect::<Option<Vec<_>>>()?;
1188 let use_mixed_layout = pats
1190 .zip(pat_strs.iter())
1191 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1192 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1193 let tactic = if use_mixed_layout {
1194 DefinitiveListTactic::Mixed
1198 ListTactic::HorizontalVertical,
1199 Separator::VerticalBar,
1203 let fmt = ListFormatting::new(shape, context.config)
1206 .separator_place(context.config.binop_separator())
1207 .ends_with_newline(false);
1208 write_list(&items, &fmt)
1211 pub(crate) fn rewrite_literal(
1212 context: &RewriteContext<'_>,
1215 ) -> Option<String> {
1217 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1219 context.snippet(l.span).to_owned(),
1220 context.config.max_width(),
1226 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1227 let string_lit = context.snippet(span);
1229 if !context.config.format_strings() {
1233 .all(|line| line.ends_with('\\'))
1235 let new_indent = shape.visual_indent(1).indent;
1236 let indented_string_lit = String::from(
1242 new_indent.to_string(context.config),
1246 .collect::<Vec<_>>()
1250 return if context.config.version() == Version::Two {
1251 Some(indented_string_lit)
1253 wrap_str(indented_string_lit, context.config.max_width(), shape)
1256 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1260 // Remove the quote characters.
1261 let str_lit = &string_lit[1..string_lit.len() - 1];
1265 &StringFormat::new(shape.visual_indent(0), context.config),
1266 shape.width.saturating_sub(2),
1270 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1271 if context.inside_macro() {
1272 if span_ends_with_comma(context, span) {
1273 Some(SeparatorTactic::Always)
1275 Some(SeparatorTactic::Never)
1282 pub(crate) fn rewrite_call(
1283 context: &RewriteContext<'_>,
1285 args: &[ptr::P<ast::Expr>],
1288 ) -> Option<String> {
1289 overflow::rewrite_with_parens(
1295 context.config.width_heuristics().fn_call_width,
1296 choose_separator_tactic(context, span),
1300 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1302 ast::ExprKind::Lit(..) => true,
1303 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1304 ast::ExprKind::AddrOf(_, ref expr)
1305 | ast::ExprKind::Box(ref expr)
1306 | ast::ExprKind::Cast(ref expr, _)
1307 | ast::ExprKind::Field(ref expr, _)
1308 | ast::ExprKind::Try(ref expr)
1309 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1310 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1311 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1312 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1318 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1319 lists.iter().all(OverflowableItem::is_simple)
1322 pub(crate) fn can_be_overflowed_expr(
1323 context: &RewriteContext<'_>,
1328 _ if !expr.attrs.is_empty() => false,
1329 ast::ExprKind::Match(..) => {
1330 (context.use_block_indent() && args_len == 1)
1331 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1332 || context.config.overflow_delimited_expr()
1334 ast::ExprKind::If(..)
1335 | ast::ExprKind::IfLet(..)
1336 | ast::ExprKind::ForLoop(..)
1337 | ast::ExprKind::Loop(..)
1338 | ast::ExprKind::While(..)
1339 | ast::ExprKind::WhileLet(..) => {
1340 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1343 // Handle always block-like expressions
1344 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1346 // Handle `[]` and `{}`-like expressions
1347 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1348 context.config.overflow_delimited_expr()
1349 || (context.use_block_indent() && args_len == 1)
1351 ast::ExprKind::Mac(ref macro_) => {
1352 match (macro_.node.delim, context.config.overflow_delimited_expr()) {
1353 (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
1354 _ => context.use_block_indent() && args_len == 1,
1358 // Handle parenthetical expressions
1359 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1360 context.use_block_indent() && args_len == 1
1363 // Handle unary-like expressions
1364 ast::ExprKind::AddrOf(_, ref expr)
1365 | ast::ExprKind::Box(ref expr)
1366 | ast::ExprKind::Try(ref expr)
1367 | ast::ExprKind::Unary(_, ref expr)
1368 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1373 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1375 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1376 ast::ExprKind::AddrOf(_, ref expr)
1377 | ast::ExprKind::Box(ref expr)
1378 | ast::ExprKind::Try(ref expr)
1379 | ast::ExprKind::Unary(_, ref expr)
1380 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1385 /// Returns `true` if a function call or a method call represented by the given span ends with a
1386 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1387 /// comma from macro can potentially break the code.
1388 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1389 let mut result: bool = Default::default();
1390 let mut prev_char: char = Default::default();
1391 let closing_delimiters = &[')', '}', ']'];
1393 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1395 _ if kind.is_comment() || c.is_whitespace() => continue,
1396 c if closing_delimiters.contains(&c) => {
1397 result &= !closing_delimiters.contains(&prev_char);
1399 ',' => result = true,
1400 _ => result = false,
1409 context: &RewriteContext<'_>,
1410 mut subexpr: &ast::Expr,
1413 ) -> Option<String> {
1414 debug!("rewrite_paren, shape: {:?}", shape);
1416 // Extract comments within parens.
1419 let mut pre_comment;
1420 let mut post_comment;
1421 let remove_nested_parens = context.config.remove_nested_parens();
1424 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1425 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1426 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1427 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1429 // Remove nested parens if there are no comments.
1430 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1431 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1432 span = subexpr.span;
1433 subexpr = subsubexpr;
1442 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1443 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1444 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1445 if fits_single_line {
1446 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1448 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1452 fn rewrite_paren_in_multi_line(
1453 context: &RewriteContext<'_>,
1454 subexpr: &ast::Expr,
1458 ) -> Option<String> {
1459 let nested_indent = shape.indent.block_indent(context.config);
1460 let nested_shape = Shape::indented(nested_indent, context.config);
1461 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1462 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1463 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1465 let mut result = String::with_capacity(subexpr_str.len() * 2);
1467 if !pre_comment.is_empty() {
1468 result.push_str(&nested_indent.to_string_with_newline(context.config));
1469 result.push_str(&pre_comment);
1471 result.push_str(&nested_indent.to_string_with_newline(context.config));
1472 result.push_str(&subexpr_str);
1473 if !post_comment.is_empty() {
1474 result.push_str(&nested_indent.to_string_with_newline(context.config));
1475 result.push_str(&post_comment);
1477 result.push_str(&shape.indent.to_string_with_newline(context.config));
1486 context: &RewriteContext<'_>,
1488 ) -> Option<String> {
1489 let expr_str = expr.rewrite(context, shape)?;
1491 let offset = last_line_width(&expr_str) + 1;
1492 let rhs_overhead = shape.rhs_overhead(context.config);
1493 let index_shape = if expr_str.contains('\n') {
1494 Shape::legacy(context.config.max_width(), shape.indent)
1495 .offset_left(offset)
1496 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1498 match context.config.indent_style() {
1499 IndentStyle::Block => shape
1500 .offset_left(offset)
1501 .and_then(|shape| shape.sub_width(1)),
1502 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1505 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1507 // Return if index fits in a single line.
1508 match orig_index_rw {
1509 Some(ref index_str) if !index_str.contains('\n') => {
1510 return Some(format!("{}[{}]", expr_str, index_str));
1515 // Try putting index on the next line and see if it fits in a single line.
1516 let indent = shape.indent.block_indent(context.config);
1517 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1518 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1519 let new_index_rw = index.rewrite(context, index_shape);
1520 match (orig_index_rw, new_index_rw) {
1521 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1524 indent.to_string_with_newline(context.config),
1527 (None, Some(ref new_index_str)) => Some(format!(
1530 indent.to_string_with_newline(context.config),
1533 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1538 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1543 fields.iter().all(|field| !field.is_shorthand)
1546 fn rewrite_struct_lit<'a>(
1547 context: &RewriteContext<'_>,
1549 fields: &'a [ast::Field],
1550 base: Option<&'a ast::Expr>,
1551 attrs: &[ast::Attribute],
1554 ) -> Option<String> {
1555 debug!("rewrite_struct_lit: shape {:?}", shape);
1557 enum StructLitField<'a> {
1558 Regular(&'a ast::Field),
1559 Base(&'a ast::Expr),
1563 let path_shape = shape.sub_width(2)?;
1564 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1566 if fields.is_empty() && base.is_none() {
1567 return Some(format!("{} {{}}", path_str));
1570 // Foo { a: Foo } - indent is +3, width is -5.
1571 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1573 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1574 let body_lo = context.snippet_provider.span_after(span, "{");
1575 let fields_str = if struct_lit_can_be_aligned(fields, base)
1576 && context.config.struct_field_align_threshold() > 0
1578 rewrite_with_alignment(
1582 mk_sp(body_lo, span.hi()),
1586 let field_iter = fields
1588 .map(StructLitField::Regular)
1589 .chain(base.into_iter().map(StructLitField::Base));
1591 let span_lo = |item: &StructLitField<'_>| match *item {
1592 StructLitField::Regular(field) => field.span().lo(),
1593 StructLitField::Base(expr) => {
1594 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1595 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1596 let pos = snippet.find_uncommented("..").unwrap();
1597 last_field_hi + BytePos(pos as u32)
1600 let span_hi = |item: &StructLitField<'_>| match *item {
1601 StructLitField::Regular(field) => field.span().hi(),
1602 StructLitField::Base(expr) => expr.span.hi(),
1604 let rewrite = |item: &StructLitField<'_>| match *item {
1605 StructLitField::Regular(field) => {
1606 // The 1 taken from the v_budget is for the comma.
1607 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1609 StructLitField::Base(expr) => {
1611 expr.rewrite(context, v_shape.offset_left(2)?)
1612 .map(|s| format!("..{}", s))
1616 let items = itemize_list(
1617 context.snippet_provider,
1628 let item_vec = items.collect::<Vec<_>>();
1630 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1631 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1633 let ends_with_comma = span_ends_with_comma(context, span);
1634 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1636 let fmt = struct_lit_formatting(
1640 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1643 write_list(&item_vec, &fmt)?
1647 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1648 Some(format!("{} {{{}}}", path_str, fields_str))
1650 // FIXME if context.config.indent_style() == Visual, but we run out
1651 // of space, we should fall back to BlockIndent.
1654 pub(crate) fn wrap_struct_field(
1655 context: &RewriteContext<'_>,
1656 attrs: &[ast::Attribute],
1659 nested_shape: Shape,
1660 one_line_width: usize,
1661 ) -> Option<String> {
1662 let should_vertical = context.config.indent_style() == IndentStyle::Block
1663 && (fields_str.contains('\n')
1664 || !context.config.struct_lit_single_line()
1665 || fields_str.len() > one_line_width);
1667 let inner_attrs = &inner_attributes(attrs);
1668 if inner_attrs.is_empty() {
1669 if should_vertical {
1672 nested_shape.indent.to_string_with_newline(context.config),
1674 shape.indent.to_string_with_newline(context.config)
1677 // One liner or visual indent.
1678 Some(format!(" {} ", fields_str))
1683 nested_shape.indent.to_string_with_newline(context.config),
1684 inner_attrs.rewrite(context, shape)?,
1685 nested_shape.indent.to_string_with_newline(context.config),
1687 shape.indent.to_string_with_newline(context.config)
1692 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1693 colon_spaces(config)
1696 pub(crate) fn rewrite_field(
1697 context: &RewriteContext<'_>,
1700 prefix_max_width: usize,
1701 ) -> Option<String> {
1702 if contains_skip(&field.attrs) {
1703 return Some(context.snippet(field.span()).to_owned());
1705 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1706 if !attrs_str.is_empty() {
1707 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1709 let name = context.snippet(field.ident.span);
1710 if field.is_shorthand {
1711 Some(attrs_str + name)
1713 let mut separator = String::from(struct_lit_field_separator(context.config));
1714 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1715 separator.push(' ');
1717 let overhead = name.len() + separator.len();
1718 let expr_shape = shape.offset_left(overhead)?;
1719 let expr = field.expr.rewrite(context, expr_shape);
1722 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1723 Some(attrs_str + name)
1725 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1727 let expr_offset = shape.indent.block_indent(context.config);
1730 .rewrite(context, Shape::indented(expr_offset, context.config));
1736 expr_offset.to_string(context.config),
1745 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1746 context: &RewriteContext<'_>,
1747 mut items: impl Iterator<Item = &'a T>,
1750 is_singleton_tuple: bool,
1751 ) -> Option<String> {
1752 // In case of length 1, need a trailing comma
1753 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1754 if is_singleton_tuple {
1756 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1760 .rewrite(context, nested_shape)
1761 .map(|s| format!("({},)", s));
1764 let list_lo = context.snippet_provider.span_after(span, "(");
1765 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1766 let items = itemize_list(
1767 context.snippet_provider,
1771 |item| item.span().lo(),
1772 |item| item.span().hi(),
1773 |item| item.rewrite(context, nested_shape),
1775 span.hi() - BytePos(1),
1778 let item_vec: Vec<_> = items.collect();
1779 let tactic = definitive_tactic(
1781 ListTactic::HorizontalVertical,
1785 let fmt = ListFormatting::new(nested_shape, context.config)
1787 .ends_with_newline(false);
1788 let list_str = write_list(&item_vec, &fmt)?;
1790 Some(format!("({})", list_str))
1793 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1794 context: &'a RewriteContext<'_>,
1795 items: impl Iterator<Item = &'a T>,
1798 is_singleton_tuple: bool,
1799 ) -> Option<String> {
1800 debug!("rewrite_tuple {:?}", shape);
1801 if context.use_block_indent() {
1802 // We use the same rule as function calls for rewriting tuples.
1803 let force_tactic = if context.inside_macro() {
1804 if span_ends_with_comma(context, span) {
1805 Some(SeparatorTactic::Always)
1807 Some(SeparatorTactic::Never)
1809 } else if is_singleton_tuple {
1810 Some(SeparatorTactic::Always)
1814 overflow::rewrite_with_parens(
1820 context.config.width_heuristics().fn_call_width,
1824 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1828 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1829 context: &RewriteContext<'_>,
1833 ) -> Option<String> {
1835 .rewrite(context, shape.offset_left(prefix.len())?)
1836 .map(|r| format!("{}{}", prefix, r))
1839 // FIXME: this is probably not correct for multi-line Rewrites. we should
1840 // subtract suffix.len() from the last line budget, not the first!
1841 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1842 context: &RewriteContext<'_>,
1846 ) -> Option<String> {
1848 .rewrite(context, shape.sub_width(suffix.len())?)
1855 fn rewrite_unary_op(
1856 context: &RewriteContext<'_>,
1860 ) -> Option<String> {
1861 // For some reason, an UnOp is not spanned like BinOp!
1862 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1865 fn rewrite_assignment(
1866 context: &RewriteContext<'_>,
1869 op: Option<&ast::BinOp>,
1871 ) -> Option<String> {
1872 let operator_str = match op {
1873 Some(op) => context.snippet(op.span),
1877 // 1 = space between lhs and operator.
1878 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1879 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1881 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1884 /// Controls where to put the rhs.
1885 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1886 pub(crate) enum RhsTactics {
1889 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1890 ForceNextLineWithoutIndent,
1891 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1896 // The left hand side must contain everything up to, and including, the
1897 // assignment operator.
1898 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1899 context: &RewriteContext<'_>,
1903 ) -> Option<String> {
1904 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1907 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1908 context: &RewriteContext<'_>,
1912 rhs_tactics: RhsTactics,
1913 ) -> Option<String> {
1914 let lhs = lhs.into();
1915 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1916 shape.indent.width()
1920 // 1 = space between operator and rhs.
1921 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1923 offset: shape.offset + last_line_width + 1,
1926 let rhs = choose_rhs(
1930 ex.rewrite(context, orig_shape),
1936 fn choose_rhs<R: Rewrite>(
1937 context: &RewriteContext<'_>,
1940 orig_rhs: Option<String>,
1941 rhs_tactics: RhsTactics,
1942 ) -> Option<String> {
1945 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
1947 Some(format!(" {}", new_str))
1950 // Expression did not fit on the same line as the identifier.
1951 // Try splitting the line and see if that works better.
1952 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1953 let new_rhs = expr.rewrite(context, new_shape);
1954 let new_indent_str = &shape
1956 .block_indent(context.config)
1957 .to_string_with_newline(context.config);
1959 match (orig_rhs, new_rhs) {
1960 (Some(ref orig_rhs), Some(ref new_rhs))
1961 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1964 Some(format!(" {}", orig_rhs))
1966 (Some(ref orig_rhs), Some(ref new_rhs))
1967 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1969 Some(format!("{}{}", new_indent_str, new_rhs))
1971 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1972 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
1973 let shape = shape.infinite_width();
1974 expr.rewrite(context, shape).map(|s| format!(" {}", s))
1976 (None, None) => None,
1977 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1983 fn shape_from_rhs_tactic(
1984 context: &RewriteContext<'_>,
1986 rhs_tactic: RhsTactics,
1987 ) -> Option<Shape> {
1989 RhsTactics::ForceNextLineWithoutIndent => shape
1990 .with_max_width(context.config)
1991 .sub_width(shape.indent.width()),
1992 RhsTactics::Default | RhsTactics::AllowOverflow => {
1993 Shape::indented(shape.indent.block_indent(context.config), context.config)
1994 .sub_width(shape.rhs_overhead(context.config))
1999 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2000 /// original's line formatting.
2002 /// It is considered better if:
2003 /// 1. the tactic is ForceNextLineWithoutIndent
2004 /// 2. next_line_rhs doesn't have newlines
2005 /// 3. the original line has more newlines than next_line_rhs
2006 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2008 pub(crate) fn prefer_next_line(
2010 next_line_rhs: &str,
2011 rhs_tactics: RhsTactics,
2013 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2014 || !next_line_rhs.contains('\n')
2015 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2016 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2017 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2018 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2021 fn rewrite_expr_addrof(
2022 context: &RewriteContext<'_>,
2023 mutability: ast::Mutability,
2026 ) -> Option<String> {
2027 let operator_str = match mutability {
2028 ast::Mutability::Immutable => "&",
2029 ast::Mutability::Mutable => "&mut ",
2031 rewrite_unary_prefix(context, operator_str, expr, shape)
2034 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2036 ast::ExprKind::MethodCall(..) => true,
2037 ast::ExprKind::AddrOf(_, ref expr)
2038 | ast::ExprKind::Box(ref expr)
2039 | ast::ExprKind::Cast(ref expr, _)
2040 | ast::ExprKind::Try(ref expr)
2041 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2048 use super::last_line_offsetted;
2051 fn test_last_line_offsetted() {
2052 let lines = "one\n two";
2053 assert_eq!(last_line_offsetted(2, lines), true);
2054 assert_eq!(last_line_offsetted(4, lines), false);
2055 assert_eq!(last_line_offsetted(6, lines), false);
2057 let lines = "one two";
2058 assert_eq!(last_line_offsetted(2, lines), false);
2059 assert_eq!(last_line_offsetted(0, lines), false);
2061 let lines = "\ntwo";
2062 assert_eq!(last_line_offsetted(2, lines), false);
2063 assert_eq!(last_line_offsetted(0, lines), false);
2065 let lines = "one\n two three";
2066 assert_eq!(last_line_offsetted(2, lines), true);
2067 let lines = "one\n two three";
2068 assert_eq!(last_line_offsetted(2, lines), false);