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, semicolon_for_stmt, 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 impl Rewrite for ast::Stmt {
572 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
573 skip_out_of_file_lines_range!(context, self.span());
575 let result = match self.node {
576 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
577 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
578 let suffix = if semicolon_for_stmt(context, self) {
584 let shape = shape.sub_width(suffix.len())?;
585 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
587 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
589 result.and_then(|res| recover_comment_removed(res, self.span(), context))
593 // Rewrite condition if the given expression has one.
594 pub(crate) fn rewrite_cond(
595 context: &RewriteContext<'_>,
598 ) -> Option<String> {
600 ast::ExprKind::Match(ref cond, _) => {
602 let cond_shape = match context.config.indent_style() {
603 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
604 IndentStyle::Block => shape.offset_left(8)?,
606 cond.rewrite(context, cond_shape)
608 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
610 String::from("\n") + &shape.indent.block_only().to_string(context.config);
612 .rewrite_cond(context, shape, &alt_block_sep)
613 .and_then(|rw| Some(rw.0))
618 // Abstraction over control flow expressions
620 struct ControlFlow<'a> {
621 cond: Option<&'a ast::Expr>,
622 block: &'a ast::Block,
623 else_block: Option<&'a ast::Expr>,
624 label: Option<ast::Label>,
625 pats: Vec<&'a ast::Pat>,
629 allow_single_line: bool,
630 // HACK: `true` if this is an `if` expression in an `else if`.
635 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
637 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
641 else_block.as_ref().map(|e| &**e),
642 expr_type == ExprType::SubExpression,
646 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
647 Some(ControlFlow::new_if(
649 ptr_vec_to_ref_vec(pat),
651 else_block.as_ref().map(|e| &**e),
652 expr_type == ExprType::SubExpression,
657 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
658 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
660 ast::ExprKind::Loop(ref block, label) => {
661 Some(ControlFlow::new_loop(block, label, expr.span))
663 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
670 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
671 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
677 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
678 if pats.is_empty() { "" } else { "let" }
681 impl<'a> ControlFlow<'a> {
684 pats: Vec<&'a ast::Pat>,
685 block: &'a ast::Block,
686 else_block: Option<&'a ast::Expr>,
687 allow_single_line: bool,
690 ) -> ControlFlow<'a> {
691 let matcher = choose_matcher(&pats);
707 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
717 allow_single_line: false,
724 pats: Vec<&'a ast::Pat>,
726 block: &'a ast::Block,
727 label: Option<ast::Label>,
729 ) -> ControlFlow<'a> {
730 let matcher = choose_matcher(&pats);
740 allow_single_line: false,
749 block: &'a ast::Block,
750 label: Option<ast::Label>,
752 ) -> ControlFlow<'a> {
762 allow_single_line: false,
768 fn rewrite_single_line(
771 context: &RewriteContext<'_>,
773 ) -> Option<String> {
774 assert!(self.allow_single_line);
775 let else_block = self.else_block?;
776 let fixed_cost = self.keyword.len() + " { } else { }".len();
778 if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
779 if !is_simple_block(self.block, None, context.source_map)
780 || !is_simple_block(else_node, None, context.source_map)
781 || pat_expr_str.contains('\n')
786 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
787 let expr = &self.block.stmts[0];
788 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
790 let new_width = new_width.checked_sub(if_str.len())?;
791 let else_expr = &else_node.stmts[0];
792 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
794 if if_str.contains('\n') || else_str.contains('\n') {
798 let result = format!(
799 "{} {} {{ {} }} else {{ {} }}",
800 self.keyword, pat_expr_str, if_str, else_str
803 if result.len() <= width {
812 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
814 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
815 let mut leading_whitespaces = 0;
816 for c in pat_str.chars().rev() {
819 _ if c.is_whitespace() => leading_whitespaces += 1,
820 _ => leading_whitespaces = 0,
823 leading_whitespaces > start_column
826 impl<'a> ControlFlow<'a> {
829 context: &RewriteContext<'_>,
833 ) -> Option<String> {
834 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
836 let cond_shape = shape.offset_left(offset)?;
837 if !self.pats.is_empty() {
838 let matcher = if self.matcher.is_empty() {
839 self.matcher.to_owned()
841 format!("{} ", self.matcher)
843 let pat_shape = cond_shape
844 .offset_left(matcher.len())?
845 .sub_width(self.connector.len())?;
846 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
847 let result = format!("{}{}{}", matcher, pat_string, self.connector);
848 return rewrite_assign_rhs(context, result, expr, cond_shape);
851 let expr_rw = expr.rewrite(context, cond_shape);
852 // The expression may (partially) fit on the current line.
853 // We do not allow splitting between `if` and condition.
854 if self.keyword == "if" || expr_rw.is_some() {
858 // The expression won't fit on the current line, jump to next.
859 let nested_shape = shape
860 .block_indent(context.config.tab_spaces())
861 .with_max_width(context.config);
862 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
863 expr.rewrite(context, nested_shape)
864 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
869 context: &RewriteContext<'_>,
872 ) -> Option<(String, usize)> {
873 // Do not take the rhs overhead from the upper expressions into account
874 // when rewriting pattern.
875 let new_width = context.budget(shape.used_width());
876 let fresh_shape = Shape {
880 let constr_shape = if self.nested_if {
881 // We are part of an if-elseif-else chain. Our constraints are tightened.
882 // 7 = "} else " .len()
883 fresh_shape.offset_left(7)?
888 let label_string = rewrite_label(self.label);
889 // 1 = space after keyword.
890 let offset = self.keyword.len() + label_string.len() + 1;
892 let pat_expr_string = match self.cond {
893 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
894 None => String::new(),
898 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
904 let one_line_budget = context
907 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
908 let force_newline_brace = (pat_expr_string.contains('\n')
909 || pat_expr_string.len() > one_line_budget)
910 && (!last_line_extendable(&pat_expr_string)
911 || last_line_offsetted(shape.used_width(), &pat_expr_string));
913 // Try to format if-else on single line.
914 if self.allow_single_line
918 .single_line_if_else_max_width
921 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
923 if let Some(cond_str) = trial {
928 .single_line_if_else_max_width
930 return Some((cond_str, 0));
935 let cond_span = if let Some(cond) = self.cond {
938 mk_sp(self.block.span.lo(), self.block.span.lo())
941 // `for event in event`
942 // Do not include label in the span.
945 .map_or(self.span.lo(), |label| label.ident.span.hi());
946 let between_kwd_cond = mk_sp(
949 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
950 if self.pats.is_empty() {
952 } else if self.matcher.is_empty() {
953 self.pats[0].span.lo()
957 .span_before(self.span, self.matcher.trim())
961 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
963 let after_cond_comment =
964 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
966 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
968 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
969 || force_newline_brace
976 let used_width = if pat_expr_string.contains('\n') {
977 last_line_width(&pat_expr_string)
979 // 2 = spaces after keyword and condition.
980 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
988 between_kwd_cond_comment.as_ref().map_or(
989 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
997 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1004 impl<'a> Rewrite for ControlFlow<'a> {
1005 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1006 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1008 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1009 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1010 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1011 if used_width == 0 {
1012 return Some(cond_str);
1015 let block_width = shape.width.saturating_sub(used_width);
1016 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1017 // we should avoid the single line case.
1018 let block_width = if self.else_block.is_some() || self.nested_if {
1023 let block_shape = Shape {
1028 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1030 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1031 context.is_if_else_block.replace(old_val);
1035 let mut result = format!("{}{}", cond_str, block_str);
1037 if let Some(else_block) = self.else_block {
1038 let shape = Shape::indented(shape.indent, context.config);
1039 let mut last_in_chain = false;
1040 let rewrite = match else_block.node {
1041 // If the else expression is another if-else expression, prevent it
1042 // from being formatted on a single line.
1043 // Note how we're passing the original shape, as the
1044 // cost of "else" should not cascade.
1045 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1046 ControlFlow::new_if(
1048 ptr_vec_to_ref_vec(pat),
1050 next_else_block.as_ref().map(|e| &**e),
1053 mk_sp(else_block.span.lo(), self.span.hi()),
1055 .rewrite(context, shape)
1057 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1058 ControlFlow::new_if(
1062 next_else_block.as_ref().map(|e| &**e),
1065 mk_sp(else_block.span.lo(), self.span.hi()),
1067 .rewrite(context, shape)
1070 last_in_chain = true;
1071 // When rewriting a block, the width is only used for single line
1072 // blocks, passing 1 lets us avoid that.
1073 let else_shape = Shape {
1074 width: min(1, shape.width),
1077 format_expr(else_block, ExprType::Statement, context, else_shape)
1081 let between_kwd_else_block = mk_sp(
1082 self.block.span.hi(),
1085 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1087 let between_kwd_else_block_comment =
1088 extract_comment(between_kwd_else_block, context, shape);
1090 let after_else = mk_sp(
1093 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1094 else_block.span.lo(),
1096 let after_else_comment = extract_comment(after_else, context, shape);
1098 let between_sep = match context.config.control_brace_style() {
1099 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1102 ControlBraceStyle::AlwaysSameLine => " ",
1104 let after_sep = match context.config.control_brace_style() {
1105 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1109 result.push_str(&format!(
1111 between_kwd_else_block_comment
1113 .map_or(between_sep, |s| &**s),
1114 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1116 result.push_str(&rewrite?);
1123 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1125 Some(label) => Cow::from(format!("{}: ", label.ident)),
1126 None => Cow::from(""),
1130 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1131 match rewrite_missing_comment(span, shape, context) {
1132 Some(ref comment) if !comment.is_empty() => Some(format!(
1133 "{indent}{}{indent}",
1135 indent = shape.indent.to_string_with_newline(context.config)
1141 pub(crate) fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1142 let snippet = source_map.span_to_snippet(block.span).unwrap();
1143 contains_comment(&snippet)
1146 // Checks that a block contains no statements, an expression and no comments or
1148 // FIXME: incorrectly returns false when comment is contained completely within
1150 pub(crate) fn is_simple_block(
1152 attrs: Option<&[ast::Attribute]>,
1153 source_map: &SourceMap,
1155 (block.stmts.len() == 1
1156 && stmt_is_expr(&block.stmts[0])
1157 && !block_contains_comment(block, source_map)
1158 && attrs.map_or(true, |a| a.is_empty()))
1161 /// Checks whether a block contains at most one statement or expression, and no
1162 /// comments or attributes.
1163 pub(crate) fn is_simple_block_stmt(
1165 attrs: Option<&[ast::Attribute]>,
1166 source_map: &SourceMap,
1168 block.stmts.len() <= 1
1169 && !block_contains_comment(block, source_map)
1170 && attrs.map_or(true, |a| a.is_empty())
1173 /// Checks whether a block contains no statements, expressions, comments, or
1174 /// inner attributes.
1175 pub(crate) fn is_empty_block(
1177 attrs: Option<&[ast::Attribute]>,
1178 source_map: &SourceMap,
1180 block.stmts.is_empty()
1181 && !block_contains_comment(block, source_map)
1182 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1185 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1187 ast::StmtKind::Expr(..) => true,
1192 pub(crate) fn stmt_is_if(stmt: &ast::Stmt) -> bool {
1194 ast::StmtKind::Expr(ref e) => match e.node {
1195 ast::ExprKind::If(..) => true,
1202 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1203 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1210 pub(crate) fn rewrite_multiple_patterns(
1211 context: &RewriteContext<'_>,
1214 ) -> Option<String> {
1217 .map(|p| p.rewrite(context, shape))
1218 .collect::<Option<Vec<_>>>()?;
1220 let use_mixed_layout = pats
1222 .zip(pat_strs.iter())
1223 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1224 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1225 let tactic = if use_mixed_layout {
1226 DefinitiveListTactic::Mixed
1230 ListTactic::HorizontalVertical,
1231 Separator::VerticalBar,
1235 let fmt = ListFormatting::new(shape, context.config)
1238 .separator_place(context.config.binop_separator())
1239 .ends_with_newline(false);
1240 write_list(&items, &fmt)
1243 pub(crate) fn rewrite_literal(
1244 context: &RewriteContext<'_>,
1247 ) -> Option<String> {
1249 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1251 context.snippet(l.span).to_owned(),
1252 context.config.max_width(),
1258 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1259 let string_lit = context.snippet(span);
1261 if !context.config.format_strings() {
1265 .all(|line| line.ends_with('\\'))
1267 let new_indent = shape.visual_indent(1).indent;
1268 let indented_string_lit = String::from(
1274 new_indent.to_string(context.config),
1278 .collect::<Vec<_>>()
1282 return if context.config.version() == Version::Two {
1283 Some(indented_string_lit)
1285 wrap_str(indented_string_lit, context.config.max_width(), shape)
1288 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1292 // Remove the quote characters.
1293 let str_lit = &string_lit[1..string_lit.len() - 1];
1297 &StringFormat::new(shape.visual_indent(0), context.config),
1298 shape.width.saturating_sub(2),
1302 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1303 if context.inside_macro() {
1304 if span_ends_with_comma(context, span) {
1305 Some(SeparatorTactic::Always)
1307 Some(SeparatorTactic::Never)
1314 pub(crate) fn rewrite_call(
1315 context: &RewriteContext<'_>,
1317 args: &[ptr::P<ast::Expr>],
1320 ) -> Option<String> {
1321 overflow::rewrite_with_parens(
1327 context.config.width_heuristics().fn_call_width,
1328 choose_separator_tactic(context, span),
1332 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1334 ast::ExprKind::Lit(..) => true,
1335 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1336 ast::ExprKind::AddrOf(_, ref expr)
1337 | ast::ExprKind::Box(ref expr)
1338 | ast::ExprKind::Cast(ref expr, _)
1339 | ast::ExprKind::Field(ref expr, _)
1340 | ast::ExprKind::Try(ref expr)
1341 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1342 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1343 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1344 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1350 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1351 lists.iter().all(OverflowableItem::is_simple)
1354 pub(crate) fn can_be_overflowed_expr(
1355 context: &RewriteContext<'_>,
1360 _ if !expr.attrs.is_empty() => false,
1361 ast::ExprKind::Match(..) => {
1362 (context.use_block_indent() && args_len == 1)
1363 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1364 || context.config.overflow_delimited_expr()
1366 ast::ExprKind::If(..)
1367 | ast::ExprKind::IfLet(..)
1368 | ast::ExprKind::ForLoop(..)
1369 | ast::ExprKind::Loop(..)
1370 | ast::ExprKind::While(..)
1371 | ast::ExprKind::WhileLet(..) => {
1372 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1375 // Handle always block-like expressions
1376 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1378 // Handle `[]` and `{}`-like expressions
1379 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1380 context.config.overflow_delimited_expr()
1381 || (context.use_block_indent() && args_len == 1)
1383 ast::ExprKind::Mac(ref macro_) => {
1384 match (macro_.node.delim, context.config.overflow_delimited_expr()) {
1385 (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
1386 _ => context.use_block_indent() && args_len == 1,
1390 // Handle parenthetical expressions
1391 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1392 context.use_block_indent() && args_len == 1
1395 // Handle unary-like expressions
1396 ast::ExprKind::AddrOf(_, ref expr)
1397 | ast::ExprKind::Box(ref expr)
1398 | ast::ExprKind::Try(ref expr)
1399 | ast::ExprKind::Unary(_, ref expr)
1400 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1405 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1407 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1408 ast::ExprKind::AddrOf(_, ref expr)
1409 | ast::ExprKind::Box(ref expr)
1410 | ast::ExprKind::Try(ref expr)
1411 | ast::ExprKind::Unary(_, ref expr)
1412 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1417 /// Returns `true` if a function call or a method call represented by the given span ends with a
1418 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1419 /// comma from macro can potentially break the code.
1420 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1421 let mut result: bool = Default::default();
1422 let mut prev_char: char = Default::default();
1423 let closing_delimiters = &[')', '}', ']'];
1425 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1427 _ if kind.is_comment() || c.is_whitespace() => continue,
1428 c if closing_delimiters.contains(&c) => {
1429 result &= !closing_delimiters.contains(&prev_char);
1431 ',' => result = true,
1432 _ => result = false,
1441 context: &RewriteContext<'_>,
1442 mut subexpr: &ast::Expr,
1445 ) -> Option<String> {
1446 debug!("rewrite_paren, shape: {:?}", shape);
1448 // Extract comments within parens.
1451 let mut pre_comment;
1452 let mut post_comment;
1453 let remove_nested_parens = context.config.remove_nested_parens();
1456 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1457 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1458 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1459 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1461 // Remove nested parens if there are no comments.
1462 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1463 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1464 span = subexpr.span;
1465 subexpr = subsubexpr;
1474 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1475 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1476 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1477 if fits_single_line {
1478 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1480 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1484 fn rewrite_paren_in_multi_line(
1485 context: &RewriteContext<'_>,
1486 subexpr: &ast::Expr,
1490 ) -> Option<String> {
1491 let nested_indent = shape.indent.block_indent(context.config);
1492 let nested_shape = Shape::indented(nested_indent, context.config);
1493 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1494 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1495 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1497 let mut result = String::with_capacity(subexpr_str.len() * 2);
1499 if !pre_comment.is_empty() {
1500 result.push_str(&nested_indent.to_string_with_newline(context.config));
1501 result.push_str(&pre_comment);
1503 result.push_str(&nested_indent.to_string_with_newline(context.config));
1504 result.push_str(&subexpr_str);
1505 if !post_comment.is_empty() {
1506 result.push_str(&nested_indent.to_string_with_newline(context.config));
1507 result.push_str(&post_comment);
1509 result.push_str(&shape.indent.to_string_with_newline(context.config));
1518 context: &RewriteContext<'_>,
1520 ) -> Option<String> {
1521 let expr_str = expr.rewrite(context, shape)?;
1523 let offset = last_line_width(&expr_str) + 1;
1524 let rhs_overhead = shape.rhs_overhead(context.config);
1525 let index_shape = if expr_str.contains('\n') {
1526 Shape::legacy(context.config.max_width(), shape.indent)
1527 .offset_left(offset)
1528 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1530 match context.config.indent_style() {
1531 IndentStyle::Block => shape
1532 .offset_left(offset)
1533 .and_then(|shape| shape.sub_width(1)),
1534 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1537 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1539 // Return if index fits in a single line.
1540 match orig_index_rw {
1541 Some(ref index_str) if !index_str.contains('\n') => {
1542 return Some(format!("{}[{}]", expr_str, index_str));
1547 // Try putting index on the next line and see if it fits in a single line.
1548 let indent = shape.indent.block_indent(context.config);
1549 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1550 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1551 let new_index_rw = index.rewrite(context, index_shape);
1552 match (orig_index_rw, new_index_rw) {
1553 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1556 indent.to_string_with_newline(context.config),
1559 (None, Some(ref new_index_str)) => Some(format!(
1562 indent.to_string_with_newline(context.config),
1565 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1570 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1575 fields.iter().all(|field| !field.is_shorthand)
1578 fn rewrite_struct_lit<'a>(
1579 context: &RewriteContext<'_>,
1581 fields: &'a [ast::Field],
1582 base: Option<&'a ast::Expr>,
1583 attrs: &[ast::Attribute],
1586 ) -> Option<String> {
1587 debug!("rewrite_struct_lit: shape {:?}", shape);
1589 enum StructLitField<'a> {
1590 Regular(&'a ast::Field),
1591 Base(&'a ast::Expr),
1595 let path_shape = shape.sub_width(2)?;
1596 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1598 if fields.is_empty() && base.is_none() {
1599 return Some(format!("{} {{}}", path_str));
1602 // Foo { a: Foo } - indent is +3, width is -5.
1603 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1605 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1606 let body_lo = context.snippet_provider.span_after(span, "{");
1607 let fields_str = if struct_lit_can_be_aligned(fields, base)
1608 && context.config.struct_field_align_threshold() > 0
1610 rewrite_with_alignment(
1614 mk_sp(body_lo, span.hi()),
1618 let field_iter = fields
1620 .map(StructLitField::Regular)
1621 .chain(base.into_iter().map(StructLitField::Base));
1623 let span_lo = |item: &StructLitField<'_>| match *item {
1624 StructLitField::Regular(field) => field.span().lo(),
1625 StructLitField::Base(expr) => {
1626 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1627 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1628 let pos = snippet.find_uncommented("..").unwrap();
1629 last_field_hi + BytePos(pos as u32)
1632 let span_hi = |item: &StructLitField<'_>| match *item {
1633 StructLitField::Regular(field) => field.span().hi(),
1634 StructLitField::Base(expr) => expr.span.hi(),
1636 let rewrite = |item: &StructLitField<'_>| match *item {
1637 StructLitField::Regular(field) => {
1638 // The 1 taken from the v_budget is for the comma.
1639 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1641 StructLitField::Base(expr) => {
1643 expr.rewrite(context, v_shape.offset_left(2)?)
1644 .map(|s| format!("..{}", s))
1648 let items = itemize_list(
1649 context.snippet_provider,
1660 let item_vec = items.collect::<Vec<_>>();
1662 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1663 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1665 let ends_with_comma = span_ends_with_comma(context, span);
1666 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1668 let fmt = struct_lit_formatting(
1672 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1675 write_list(&item_vec, &fmt)?
1679 wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
1680 Some(format!("{} {{{}}}", path_str, fields_str))
1682 // FIXME if context.config.indent_style() == Visual, but we run out
1683 // of space, we should fall back to BlockIndent.
1686 pub(crate) fn wrap_struct_field(
1687 context: &RewriteContext<'_>,
1688 attrs: &[ast::Attribute],
1691 nested_shape: Shape,
1692 one_line_width: usize,
1693 ) -> Option<String> {
1694 let should_vertical = context.config.indent_style() == IndentStyle::Block
1695 && (fields_str.contains('\n')
1696 || !context.config.struct_lit_single_line()
1697 || fields_str.len() > one_line_width);
1699 let inner_attrs = &inner_attributes(attrs);
1700 if inner_attrs.is_empty() {
1701 if should_vertical {
1704 nested_shape.indent.to_string_with_newline(context.config),
1706 shape.indent.to_string_with_newline(context.config)
1709 // One liner or visual indent.
1710 Some(format!(" {} ", fields_str))
1715 nested_shape.indent.to_string_with_newline(context.config),
1716 inner_attrs.rewrite(context, shape)?,
1717 nested_shape.indent.to_string_with_newline(context.config),
1719 shape.indent.to_string_with_newline(context.config)
1724 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1725 colon_spaces(config)
1728 pub(crate) fn rewrite_field(
1729 context: &RewriteContext<'_>,
1732 prefix_max_width: usize,
1733 ) -> Option<String> {
1734 if contains_skip(&field.attrs) {
1735 return Some(context.snippet(field.span()).to_owned());
1737 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1738 if !attrs_str.is_empty() {
1739 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1741 let name = context.snippet(field.ident.span);
1742 if field.is_shorthand {
1743 Some(attrs_str + name)
1745 let mut separator = String::from(struct_lit_field_separator(context.config));
1746 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1747 separator.push(' ');
1749 let overhead = name.len() + separator.len();
1750 let expr_shape = shape.offset_left(overhead)?;
1751 let expr = field.expr.rewrite(context, expr_shape);
1754 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1755 Some(attrs_str + name)
1757 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1759 let expr_offset = shape.indent.block_indent(context.config);
1762 .rewrite(context, Shape::indented(expr_offset, context.config));
1768 expr_offset.to_string(context.config),
1777 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1778 context: &RewriteContext<'_>,
1779 mut items: impl Iterator<Item = &'a T>,
1782 is_singleton_tuple: bool,
1783 ) -> Option<String> {
1784 // In case of length 1, need a trailing comma
1785 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1786 if is_singleton_tuple {
1788 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1792 .rewrite(context, nested_shape)
1793 .map(|s| format!("({},)", s));
1796 let list_lo = context.snippet_provider.span_after(span, "(");
1797 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1798 let items = itemize_list(
1799 context.snippet_provider,
1803 |item| item.span().lo(),
1804 |item| item.span().hi(),
1805 |item| item.rewrite(context, nested_shape),
1807 span.hi() - BytePos(1),
1810 let item_vec: Vec<_> = items.collect();
1811 let tactic = definitive_tactic(
1813 ListTactic::HorizontalVertical,
1817 let fmt = ListFormatting::new(nested_shape, context.config)
1819 .ends_with_newline(false);
1820 let list_str = write_list(&item_vec, &fmt)?;
1822 Some(format!("({})", list_str))
1825 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1826 context: &'a RewriteContext<'_>,
1827 items: impl Iterator<Item = &'a T>,
1830 is_singleton_tuple: bool,
1831 ) -> Option<String> {
1832 debug!("rewrite_tuple {:?}", shape);
1833 if context.use_block_indent() {
1834 // We use the same rule as function calls for rewriting tuples.
1835 let force_tactic = if context.inside_macro() {
1836 if span_ends_with_comma(context, span) {
1837 Some(SeparatorTactic::Always)
1839 Some(SeparatorTactic::Never)
1841 } else if is_singleton_tuple {
1842 Some(SeparatorTactic::Always)
1846 overflow::rewrite_with_parens(
1852 context.config.width_heuristics().fn_call_width,
1856 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1860 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1861 context: &RewriteContext<'_>,
1865 ) -> Option<String> {
1867 .rewrite(context, shape.offset_left(prefix.len())?)
1868 .map(|r| format!("{}{}", prefix, r))
1871 // FIXME: this is probably not correct for multi-line Rewrites. we should
1872 // subtract suffix.len() from the last line budget, not the first!
1873 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1874 context: &RewriteContext<'_>,
1878 ) -> Option<String> {
1880 .rewrite(context, shape.sub_width(suffix.len())?)
1887 fn rewrite_unary_op(
1888 context: &RewriteContext<'_>,
1892 ) -> Option<String> {
1893 // For some reason, an UnOp is not spanned like BinOp!
1894 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1897 fn rewrite_assignment(
1898 context: &RewriteContext<'_>,
1901 op: Option<&ast::BinOp>,
1903 ) -> Option<String> {
1904 let operator_str = match op {
1905 Some(op) => context.snippet(op.span),
1909 // 1 = space between lhs and operator.
1910 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1911 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1913 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1916 /// Controls where to put the rhs.
1917 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1918 pub(crate) enum RhsTactics {
1921 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1922 ForceNextLineWithoutIndent,
1923 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1928 // The left hand side must contain everything up to, and including, the
1929 // assignment operator.
1930 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1931 context: &RewriteContext<'_>,
1935 ) -> Option<String> {
1936 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1939 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1940 context: &RewriteContext<'_>,
1944 rhs_tactics: RhsTactics,
1945 ) -> Option<String> {
1946 let lhs = lhs.into();
1947 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1948 shape.indent.width()
1952 // 1 = space between operator and rhs.
1953 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1955 offset: shape.offset + last_line_width + 1,
1958 let rhs = choose_rhs(
1962 ex.rewrite(context, orig_shape),
1968 fn choose_rhs<R: Rewrite>(
1969 context: &RewriteContext<'_>,
1972 orig_rhs: Option<String>,
1973 rhs_tactics: RhsTactics,
1974 ) -> Option<String> {
1976 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
1977 Some(format!(" {}", new_str))
1980 // Expression did not fit on the same line as the identifier.
1981 // Try splitting the line and see if that works better.
1982 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1983 let new_rhs = expr.rewrite(context, new_shape);
1984 let new_indent_str = &shape
1986 .block_indent(context.config)
1987 .to_string_with_newline(context.config);
1989 match (orig_rhs, new_rhs) {
1990 (Some(ref orig_rhs), Some(ref new_rhs))
1991 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1994 Some(format!(" {}", orig_rhs))
1996 (Some(ref orig_rhs), Some(ref new_rhs))
1997 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1999 Some(format!("{}{}", new_indent_str, new_rhs))
2001 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2002 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2003 let shape = shape.infinite_width();
2004 expr.rewrite(context, shape).map(|s| format!(" {}", s))
2006 (None, None) => None,
2007 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
2013 fn shape_from_rhs_tactic(
2014 context: &RewriteContext<'_>,
2016 rhs_tactic: RhsTactics,
2017 ) -> Option<Shape> {
2019 RhsTactics::ForceNextLineWithoutIndent => shape
2020 .with_max_width(context.config)
2021 .sub_width(shape.indent.width()),
2022 RhsTactics::Default | RhsTactics::AllowOverflow => {
2023 Shape::indented(shape.indent.block_indent(context.config), context.config)
2024 .sub_width(shape.rhs_overhead(context.config))
2029 pub(crate) fn prefer_next_line(
2031 next_line_rhs: &str,
2032 rhs_tactics: RhsTactics,
2034 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2035 || !next_line_rhs.contains('\n')
2036 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2037 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2038 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2039 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2042 fn rewrite_expr_addrof(
2043 context: &RewriteContext<'_>,
2044 mutability: ast::Mutability,
2047 ) -> Option<String> {
2048 let operator_str = match mutability {
2049 ast::Mutability::Immutable => "&",
2050 ast::Mutability::Mutable => "&mut ",
2052 rewrite_unary_prefix(context, operator_str, expr, shape)
2055 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2057 ast::ExprKind::MethodCall(..) => true,
2058 ast::ExprKind::AddrOf(_, ref expr)
2059 | ast::ExprKind::Box(ref expr)
2060 | ast::ExprKind::Cast(ref expr, _)
2061 | ast::ExprKind::Try(ref expr)
2062 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2069 use super::last_line_offsetted;
2072 fn test_last_line_offsetted() {
2073 let lines = "one\n two";
2074 assert_eq!(last_line_offsetted(2, lines), true);
2075 assert_eq!(last_line_offsetted(4, lines), false);
2076 assert_eq!(last_line_offsetted(6, lines), false);
2078 let lines = "one two";
2079 assert_eq!(last_line_offsetted(2, lines), false);
2080 assert_eq!(last_line_offsetted(0, lines), false);
2082 let lines = "\ntwo";
2083 assert_eq!(last_line_offsetted(2, lines), false);
2084 assert_eq!(last_line_offsetted(0, lines), false);
2086 let lines = "one\n two three";
2087 assert_eq!(last_line_offsetted(2, lines), true);
2088 let lines = "one\n two three";
2089 assert_eq!(last_line_offsetted(2, lines), false);