4 use syntax::parse::token::DelimToken;
5 use syntax::source_map::{BytePos, SourceMap, Span};
6 use syntax::{ast, ptr};
8 use crate::chains::rewrite_chain;
11 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
12 rewrite_missing_comment, CharClasses, FindUncommented,
14 use crate::config::lists::*;
15 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
17 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
18 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
20 use crate::macros::{rewrite_macro, MacroPosition};
21 use crate::matches::rewrite_match;
22 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
23 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
24 use crate::patterns::is_short_pattern;
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::{Indent, Shape};
27 use crate::source_map::{LineRangeUtils, SpanUtils};
28 use crate::spanned::Spanned;
29 use crate::string::{rewrite_string, StringFormat};
30 use crate::types::{rewrite_path, PathContext};
32 colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
33 last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
34 semicolon_for_expr, semicolon_for_stmt, wrap_str,
36 use crate::vertical::rewrite_with_alignment;
37 use crate::visitor::FmtVisitor;
39 impl Rewrite for ast::Expr {
40 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
41 format_expr(self, ExprType::SubExpression, context, shape)
45 #[derive(Copy, Clone, PartialEq)]
54 context: &RewriteContext<'_>,
57 skip_out_of_file_lines_range!(context, expr.span);
59 if contains_skip(&*expr.attrs) {
60 return Some(context.snippet(expr.span()).to_owned());
62 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
68 let expr_rw = match expr.node {
69 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
75 choose_separator_tactic(context, expr.span),
78 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
79 ast::ExprKind::Call(ref callee, ref args) => {
80 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
81 let callee_str = callee.rewrite(context, shape)?;
82 rewrite_call(context, &callee_str, args, inner_span, shape)
84 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
85 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
86 // FIXME: format comments between operands and operator
87 rewrite_all_pairs(expr, shape, context).or_else(|| {
91 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
94 context.config.binop_separator(),
98 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
99 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
103 base.as_ref().map(|e| &**e),
107 ast::ExprKind::Tup(ref items) => {
108 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
110 ast::ExprKind::If(..)
111 | ast::ExprKind::IfLet(..)
112 | ast::ExprKind::ForLoop(..)
113 | ast::ExprKind::Loop(..)
114 | ast::ExprKind::While(..)
115 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
116 .and_then(|control_flow| control_flow.rewrite(context, shape)),
117 ast::ExprKind::Block(ref block, opt_label) => {
119 ExprType::Statement => {
120 if is_unsafe_block(block) {
121 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
122 } else if let rw @ Some(_) =
123 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
125 // Rewrite block without trying to put it in a single line.
128 let prefix = block_prefix(context, block, shape)?;
130 rewrite_block_with_visitor(
141 ExprType::SubExpression => {
142 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
146 ast::ExprKind::Match(ref cond, ref arms) => {
147 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
149 ast::ExprKind::Path(ref qself, ref path) => {
150 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
152 ast::ExprKind::Assign(ref lhs, ref rhs) => {
153 rewrite_assignment(context, lhs, rhs, None, shape)
155 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
156 rewrite_assignment(context, lhs, rhs, Some(op), shape)
158 ast::ExprKind::Continue(ref opt_label) => {
159 let id_str = match *opt_label {
160 Some(label) => format!(" {}", label.ident),
161 None => String::new(),
163 Some(format!("continue{}", id_str))
165 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
166 let id_str = match *opt_label {
167 Some(label) => format!(" {}", label.ident),
168 None => String::new(),
171 if let Some(ref expr) = *opt_expr {
172 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
174 Some(format!("break{}", id_str))
177 ast::ExprKind::Yield(ref opt_expr) => {
178 if let Some(ref expr) = *opt_expr {
179 rewrite_unary_prefix(context, "yield ", &**expr, shape)
181 Some("yield".to_string())
184 ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) => {
185 closures::rewrite_closure(
186 capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
189 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
190 rewrite_chain(expr, context, shape)
192 ast::ExprKind::Mac(ref mac) => {
193 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
195 context.snippet(expr.span).to_owned(),
196 context.config.max_width(),
201 ast::ExprKind::Ret(None) => Some("return".to_owned()),
202 ast::ExprKind::Ret(Some(ref expr)) => {
203 rewrite_unary_prefix(context, "return ", &**expr, shape)
205 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
206 ast::ExprKind::AddrOf(mutability, ref expr) => {
207 rewrite_expr_addrof(context, mutability, expr, shape)
209 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
212 PairParts::infix(" as "),
215 SeparatorPlace::Front,
217 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
220 PairParts::infix(": "),
223 SeparatorPlace::Back,
225 ast::ExprKind::Index(ref expr, ref index) => {
226 rewrite_index(&**expr, &**index, context, shape)
228 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
231 PairParts::new("[", "; ", "]"),
234 SeparatorPlace::Back,
236 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
237 let delim = match limits {
238 ast::RangeLimits::HalfOpen => "..",
239 ast::RangeLimits::Closed => "..=",
242 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
244 ast::ExprKind::Lit(ref lit) => match lit.node {
245 ast::LitKind::FloatUnsuffixed(..) => {
246 context.snippet(lit.span).ends_with('.')
254 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
256 // Don't format `.. ..` into `....`, which is invalid.
258 // This check is unnecessary for `lhs`, because a range
259 // starting from another range needs parentheses as `(x ..) ..`
260 // (`x .. ..` is a range from `x` to `..`).
261 ast::ExprKind::Range(None, _, _) => true,
266 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
267 let space_if = |b: bool| if b { " " } else { "" };
271 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
273 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
277 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
278 (Some(lhs), Some(rhs)) => {
279 let sp_delim = if context.config.spaces_around_ranges() {
280 format!(" {} ", delim)
282 default_sp_delim(Some(lhs), Some(rhs))
287 PairParts::infix(&sp_delim),
290 context.config.binop_separator(),
293 (None, Some(rhs)) => {
294 let sp_delim = if context.config.spaces_around_ranges() {
295 format!("{} ", delim)
297 default_sp_delim(None, Some(rhs))
299 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
301 (Some(lhs), None) => {
302 let sp_delim = if context.config.spaces_around_ranges() {
303 format!(" {}", delim)
305 default_sp_delim(Some(lhs), None)
307 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
309 (None, None) => Some(delim.to_owned()),
312 // We do not format these expressions yet, but they should still
313 // satisfy our width restrictions.
314 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
315 ast::ExprKind::TryBlock(ref block) => {
316 if let rw @ Some(_) =
317 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
322 let budget = shape.width.saturating_sub(9);
331 Shape::legacy(budget, shape.indent)
336 ast::ExprKind::ObsoleteInPlace(ref lhs, ref rhs) => lhs
337 .rewrite(context, shape)
339 .and_then(|lhs| rewrite_assign_rhs(context, lhs, &**rhs, shape)),
340 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
341 let mover = if capture_by == ast::CaptureBy::Value {
346 if let rw @ Some(_) = rewrite_single_line_block(
348 format!("{}{}", "async ", mover).as_str(),
357 let budget = shape.width.saturating_sub(6);
367 Shape::legacy(budget, shape.indent)
372 ast::ExprKind::Err => None,
376 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
377 .and_then(|expr_str| {
378 let attrs = outer_attributes(&expr.attrs);
379 let attrs_str = attrs.rewrite(context, shape)?;
381 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
384 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
388 pub fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
390 exprs: impl Iterator<Item = &'a T>,
392 context: &'a RewriteContext<'_>,
394 force_separator_tactic: Option<SeparatorTactic>,
395 delim_token: Option<DelimToken>,
396 ) -> Option<String> {
397 overflow::rewrite_with_square_brackets(
403 force_separator_tactic,
408 fn rewrite_empty_block(
409 context: &RewriteContext<'_>,
411 attrs: Option<&[ast::Attribute]>,
412 label: Option<ast::Label>,
415 ) -> Option<String> {
416 if !block.stmts.is_empty() {
420 let label_str = rewrite_label(label);
421 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
425 if !block_contains_comment(block, context.source_map) && shape.width >= 2 {
426 return Some(format!("{}{}{{}}", prefix, label_str));
429 // If a block contains only a single-line comment, then leave it on one line.
430 let user_str = context.snippet(block.span);
431 let user_str = user_str.trim();
432 if user_str.starts_with('{') && user_str.ends_with('}') {
433 let comment_str = user_str[1..user_str.len() - 1].trim();
434 if block.stmts.is_empty()
435 && !comment_str.contains('\n')
436 && !comment_str.starts_with("//")
437 && comment_str.len() + 4 <= shape.width
439 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
446 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
447 Some(match block.rules {
448 ast::BlockCheckMode::Unsafe(..) => {
449 let snippet = context.snippet(block.span);
450 let open_pos = snippet.find_uncommented("{")?;
451 // Extract comment between unsafe and block start.
452 let trimmed = &snippet[6..open_pos].trim();
454 if !trimmed.is_empty() {
455 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
456 let budget = shape.width.checked_sub(9)?;
462 Shape::legacy(budget, shape.indent + 7),
470 ast::BlockCheckMode::Default => String::new(),
474 fn rewrite_single_line_block(
475 context: &RewriteContext<'_>,
478 attrs: Option<&[ast::Attribute]>,
479 label: Option<ast::Label>,
481 ) -> Option<String> {
482 if is_simple_block(block, attrs, context.source_map) {
483 let expr_shape = shape.offset_left(last_line_width(prefix))?;
484 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
485 let label_str = rewrite_label(label);
486 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
487 if result.len() <= shape.width && !result.contains('\n') {
494 pub fn rewrite_block_with_visitor(
495 context: &RewriteContext<'_>,
498 attrs: Option<&[ast::Attribute]>,
499 label: Option<ast::Label>,
502 ) -> Option<String> {
503 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
507 let mut visitor = FmtVisitor::from_context(context);
508 visitor.block_indent = shape.indent;
509 visitor.is_if_else_block = context.is_if_else_block();
510 match (block.rules, label) {
511 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
512 let snippet = context.snippet(block.span);
513 let open_pos = snippet.find_uncommented("{")?;
514 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
516 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
519 let inner_attrs = attrs.map(inner_attributes);
520 let label_str = rewrite_label(label);
521 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
522 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
525 impl Rewrite for ast::Block {
526 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
527 rewrite_block(self, None, None, context, shape)
533 attrs: Option<&[ast::Attribute]>,
534 label: Option<ast::Label>,
535 context: &RewriteContext<'_>,
537 ) -> Option<String> {
538 let prefix = block_prefix(context, block, shape)?;
540 // shape.width is used only for the single line case: either the empty block `{}`,
541 // or an unsafe expression `unsafe { e }`.
542 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
546 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
547 if let Some(ref result_str) = result {
548 if result_str.lines().count() <= 3 {
549 if let rw @ Some(_) =
550 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
560 impl Rewrite for ast::Stmt {
561 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
562 skip_out_of_file_lines_range!(context, self.span());
564 let result = match self.node {
565 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
566 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
567 let suffix = if semicolon_for_stmt(context, self) {
573 let shape = shape.sub_width(suffix.len())?;
574 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
576 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
578 result.and_then(|res| recover_comment_removed(res, self.span(), context))
582 // Rewrite condition if the given expression has one.
584 context: &RewriteContext<'_>,
587 ) -> Option<String> {
589 ast::ExprKind::Match(ref cond, _) => {
591 let cond_shape = match context.config.indent_style() {
592 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
593 IndentStyle::Block => shape.offset_left(8)?,
595 cond.rewrite(context, cond_shape)
597 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
599 String::from("\n") + &shape.indent.block_only().to_string(context.config);
601 .rewrite_cond(context, shape, &alt_block_sep)
602 .and_then(|rw| Some(rw.0))
607 // Abstraction over control flow expressions
609 struct ControlFlow<'a> {
610 cond: Option<&'a ast::Expr>,
611 block: &'a ast::Block,
612 else_block: Option<&'a ast::Expr>,
613 label: Option<ast::Label>,
614 pats: Vec<&'a ast::Pat>,
618 allow_single_line: bool,
619 // HACK: `true` if this is an `if` expression in an `else if`.
624 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
626 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
630 else_block.as_ref().map(|e| &**e),
631 expr_type == ExprType::SubExpression,
635 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
636 Some(ControlFlow::new_if(
638 ptr_vec_to_ref_vec(pat),
640 else_block.as_ref().map(|e| &**e),
641 expr_type == ExprType::SubExpression,
646 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
647 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
649 ast::ExprKind::Loop(ref block, label) => {
650 Some(ControlFlow::new_loop(block, label, expr.span))
652 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
659 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
660 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
666 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
667 if pats.is_empty() { "" } else { "let" }
670 impl<'a> ControlFlow<'a> {
673 pats: Vec<&'a ast::Pat>,
674 block: &'a ast::Block,
675 else_block: Option<&'a ast::Expr>,
676 allow_single_line: bool,
679 ) -> ControlFlow<'a> {
680 let matcher = choose_matcher(&pats);
696 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
706 allow_single_line: false,
713 pats: Vec<&'a ast::Pat>,
715 block: &'a ast::Block,
716 label: Option<ast::Label>,
718 ) -> ControlFlow<'a> {
719 let matcher = choose_matcher(&pats);
729 allow_single_line: false,
738 block: &'a ast::Block,
739 label: Option<ast::Label>,
741 ) -> ControlFlow<'a> {
751 allow_single_line: false,
757 fn rewrite_single_line(
760 context: &RewriteContext<'_>,
762 ) -> Option<String> {
763 assert!(self.allow_single_line);
764 let else_block = self.else_block?;
765 let fixed_cost = self.keyword.len() + " { } else { }".len();
767 if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
768 if !is_simple_block(self.block, None, context.source_map)
769 || !is_simple_block(else_node, None, context.source_map)
770 || pat_expr_str.contains('\n')
775 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
776 let expr = &self.block.stmts[0];
777 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
779 let new_width = new_width.checked_sub(if_str.len())?;
780 let else_expr = &else_node.stmts[0];
781 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
783 if if_str.contains('\n') || else_str.contains('\n') {
787 let result = format!(
788 "{} {} {{ {} }} else {{ {} }}",
789 self.keyword, pat_expr_str, if_str, else_str
792 if result.len() <= width {
801 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
803 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
804 let mut leading_whitespaces = 0;
805 for c in pat_str.chars().rev() {
808 _ if c.is_whitespace() => leading_whitespaces += 1,
809 _ => leading_whitespaces = 0,
812 leading_whitespaces > start_column
815 impl<'a> ControlFlow<'a> {
818 context: &RewriteContext<'_>,
822 ) -> Option<String> {
823 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
825 let cond_shape = shape.offset_left(offset)?;
826 if !self.pats.is_empty() {
827 let matcher = if self.matcher.is_empty() {
828 self.matcher.to_owned()
830 format!("{} ", self.matcher)
832 let pat_shape = cond_shape
833 .offset_left(matcher.len())?
834 .sub_width(self.connector.len())?;
835 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
836 let result = format!("{}{}{}", matcher, pat_string, self.connector);
837 return rewrite_assign_rhs(context, result, expr, cond_shape);
840 let expr_rw = expr.rewrite(context, cond_shape);
841 // The expression may (partially) fit on the current line.
842 // We do not allow splitting between `if` and condition.
843 if self.keyword == "if" || expr_rw.is_some() {
847 // The expression won't fit on the current line, jump to next.
848 let nested_shape = shape
849 .block_indent(context.config.tab_spaces())
850 .with_max_width(context.config);
851 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
852 expr.rewrite(context, nested_shape)
853 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
858 context: &RewriteContext<'_>,
861 ) -> Option<(String, usize)> {
862 // Do not take the rhs overhead from the upper expressions into account
863 // when rewriting pattern.
864 let new_width = context.budget(shape.used_width());
865 let fresh_shape = Shape {
869 let constr_shape = if self.nested_if {
870 // We are part of an if-elseif-else chain. Our constraints are tightened.
871 // 7 = "} else " .len()
872 fresh_shape.offset_left(7)?
877 let label_string = rewrite_label(self.label);
878 // 1 = space after keyword.
879 let offset = self.keyword.len() + label_string.len() + 1;
881 let pat_expr_string = match self.cond {
882 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
883 None => String::new(),
887 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
893 let one_line_budget = context
896 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
897 let force_newline_brace = (pat_expr_string.contains('\n')
898 || pat_expr_string.len() > one_line_budget)
899 && (!last_line_extendable(&pat_expr_string)
900 || last_line_offsetted(shape.used_width(), &pat_expr_string));
902 // Try to format if-else on single line.
903 if self.allow_single_line
907 .single_line_if_else_max_width
910 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
912 if let Some(cond_str) = trial {
917 .single_line_if_else_max_width
919 return Some((cond_str, 0));
924 let cond_span = if let Some(cond) = self.cond {
927 mk_sp(self.block.span.lo(), self.block.span.lo())
930 // `for event in event`
931 // Do not include label in the span.
934 .map_or(self.span.lo(), |label| label.ident.span.hi());
935 let between_kwd_cond = mk_sp(
938 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
939 if self.pats.is_empty() {
941 } else if self.matcher.is_empty() {
942 self.pats[0].span.lo()
946 .span_before(self.span, self.matcher.trim())
950 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
952 let after_cond_comment =
953 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
955 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
957 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
958 || force_newline_brace
965 let used_width = if pat_expr_string.contains('\n') {
966 last_line_width(&pat_expr_string)
968 // 2 = spaces after keyword and condition.
969 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
977 between_kwd_cond_comment.as_ref().map_or(
978 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
986 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
993 impl<'a> Rewrite for ControlFlow<'a> {
994 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
995 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
997 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
998 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
999 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1000 if used_width == 0 {
1001 return Some(cond_str);
1004 let block_width = shape.width.saturating_sub(used_width);
1005 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1006 // we should avoid the single line case.
1007 let block_width = if self.else_block.is_some() || self.nested_if {
1012 let block_shape = Shape {
1017 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1019 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1020 context.is_if_else_block.replace(old_val);
1024 let mut result = format!("{}{}", cond_str, block_str);
1026 if let Some(else_block) = self.else_block {
1027 let shape = Shape::indented(shape.indent, context.config);
1028 let mut last_in_chain = false;
1029 let rewrite = match else_block.node {
1030 // If the else expression is another if-else expression, prevent it
1031 // from being formatted on a single line.
1032 // Note how we're passing the original shape, as the
1033 // cost of "else" should not cascade.
1034 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1035 ControlFlow::new_if(
1037 ptr_vec_to_ref_vec(pat),
1039 next_else_block.as_ref().map(|e| &**e),
1042 mk_sp(else_block.span.lo(), self.span.hi()),
1044 .rewrite(context, shape)
1046 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1047 ControlFlow::new_if(
1051 next_else_block.as_ref().map(|e| &**e),
1054 mk_sp(else_block.span.lo(), self.span.hi()),
1056 .rewrite(context, shape)
1059 last_in_chain = true;
1060 // When rewriting a block, the width is only used for single line
1061 // blocks, passing 1 lets us avoid that.
1062 let else_shape = Shape {
1063 width: min(1, shape.width),
1066 format_expr(else_block, ExprType::Statement, context, else_shape)
1070 let between_kwd_else_block = mk_sp(
1071 self.block.span.hi(),
1074 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1076 let between_kwd_else_block_comment =
1077 extract_comment(between_kwd_else_block, context, shape);
1079 let after_else = mk_sp(
1082 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1083 else_block.span.lo(),
1085 let after_else_comment = extract_comment(after_else, context, shape);
1087 let between_sep = match context.config.control_brace_style() {
1088 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1091 ControlBraceStyle::AlwaysSameLine => " ",
1093 let after_sep = match context.config.control_brace_style() {
1094 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1098 result.push_str(&format!(
1100 between_kwd_else_block_comment
1102 .map_or(between_sep, |s| &**s),
1103 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1105 result.push_str(&rewrite?);
1112 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1114 Some(label) => Cow::from(format!("{}: ", label.ident)),
1115 None => Cow::from(""),
1119 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1120 match rewrite_missing_comment(span, shape, context) {
1121 Some(ref comment) if !comment.is_empty() => Some(format!(
1122 "{indent}{}{indent}",
1124 indent = shape.indent.to_string_with_newline(context.config)
1130 pub fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1131 let snippet = source_map.span_to_snippet(block.span).unwrap();
1132 contains_comment(&snippet)
1135 // Checks that a block contains no statements, an expression and no comments or
1137 // FIXME: incorrectly returns false when comment is contained completely within
1139 pub fn is_simple_block(
1141 attrs: Option<&[ast::Attribute]>,
1142 source_map: &SourceMap,
1144 (block.stmts.len() == 1
1145 && stmt_is_expr(&block.stmts[0])
1146 && !block_contains_comment(block, source_map)
1147 && attrs.map_or(true, |a| a.is_empty()))
1150 /// Checks whether a block contains at most one statement or expression, and no
1151 /// comments or attributes.
1152 pub fn is_simple_block_stmt(
1154 attrs: Option<&[ast::Attribute]>,
1155 source_map: &SourceMap,
1157 block.stmts.len() <= 1
1158 && !block_contains_comment(block, source_map)
1159 && attrs.map_or(true, |a| a.is_empty())
1162 /// Checks whether a block contains no statements, expressions, comments, or
1163 /// inner attributes.
1164 pub fn is_empty_block(
1166 attrs: Option<&[ast::Attribute]>,
1167 source_map: &SourceMap,
1169 block.stmts.is_empty()
1170 && !block_contains_comment(block, source_map)
1171 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1174 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1176 ast::StmtKind::Expr(..) => true,
1181 pub(crate) fn stmt_is_if(stmt: &ast::Stmt) -> bool {
1183 ast::StmtKind::Expr(ref e) => match e.node {
1184 ast::ExprKind::If(..) => true,
1191 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1192 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1199 pub fn rewrite_multiple_patterns(
1200 context: &RewriteContext<'_>,
1203 ) -> Option<String> {
1206 .map(|p| p.rewrite(context, shape))
1207 .collect::<Option<Vec<_>>>()?;
1209 let use_mixed_layout = pats
1211 .zip(pat_strs.iter())
1212 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1213 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1214 let tactic = if use_mixed_layout {
1215 DefinitiveListTactic::Mixed
1219 ListTactic::HorizontalVertical,
1220 Separator::VerticalBar,
1224 let fmt = ListFormatting::new(shape, context.config)
1227 .separator_place(context.config.binop_separator())
1228 .ends_with_newline(false);
1229 write_list(&items, &fmt)
1232 pub fn rewrite_literal(context: &RewriteContext<'_>, l: &ast::Lit, shape: Shape) -> Option<String> {
1234 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1236 context.snippet(l.span).to_owned(),
1237 context.config.max_width(),
1243 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1244 let string_lit = context.snippet(span);
1246 if !context.config.format_strings() {
1251 .all(|line| line.ends_with('\\'))
1253 let new_indent = shape.visual_indent(1).indent;
1254 let indented_string_lit = String::from(
1260 new_indent.to_string(context.config),
1264 .collect::<Vec<_>>()
1268 return if context.config.version() == Version::Two {
1269 Some(indented_string_lit)
1271 wrap_str(indented_string_lit, context.config.max_width(), shape)
1274 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1278 // Remove the quote characters.
1279 let str_lit = &string_lit[1..string_lit.len() - 1];
1283 &StringFormat::new(shape.visual_indent(0), context.config),
1284 shape.width.saturating_sub(2),
1288 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1289 if context.inside_macro() {
1290 if span_ends_with_comma(context, span) {
1291 Some(SeparatorTactic::Always)
1293 Some(SeparatorTactic::Never)
1300 pub fn rewrite_call(
1301 context: &RewriteContext<'_>,
1303 args: &[ptr::P<ast::Expr>],
1306 ) -> Option<String> {
1307 overflow::rewrite_with_parens(
1313 context.config.width_heuristics().fn_call_width,
1314 choose_separator_tactic(context, span),
1318 pub fn is_simple_expr(expr: &ast::Expr) -> bool {
1320 ast::ExprKind::Lit(..) => true,
1321 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1322 ast::ExprKind::AddrOf(_, ref expr)
1323 | ast::ExprKind::Box(ref expr)
1324 | ast::ExprKind::Cast(ref expr, _)
1325 | ast::ExprKind::Field(ref expr, _)
1326 | ast::ExprKind::Try(ref expr)
1327 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1328 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1329 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1330 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1336 pub fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1337 lists.iter().all(OverflowableItem::is_simple)
1340 pub fn can_be_overflowed_expr(
1341 context: &RewriteContext<'_>,
1346 _ if !expr.attrs.is_empty() => false,
1347 ast::ExprKind::Match(..) => {
1348 (context.use_block_indent() && args_len == 1)
1349 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1351 ast::ExprKind::If(..)
1352 | ast::ExprKind::IfLet(..)
1353 | ast::ExprKind::ForLoop(..)
1354 | ast::ExprKind::Loop(..)
1355 | ast::ExprKind::While(..)
1356 | ast::ExprKind::WhileLet(..) => {
1357 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1360 // Handle always block-like expressions
1361 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1363 // Handle `[]` and `{}`-like expressions
1364 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1365 context.config.overflow_delimited_expr()
1366 || (context.use_block_indent() && args_len == 1)
1368 ast::ExprKind::Mac(ref macro_) => {
1369 match (macro_.node.delim, context.config.overflow_delimited_expr()) {
1370 (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
1371 _ => context.use_block_indent() && args_len == 1,
1375 // Handle parenthetical expressions
1376 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1377 context.use_block_indent() && args_len == 1
1380 // Handle unary-like expressions
1381 ast::ExprKind::AddrOf(_, ref expr)
1382 | ast::ExprKind::Box(ref expr)
1383 | ast::ExprKind::Try(ref expr)
1384 | ast::ExprKind::Unary(_, ref expr)
1385 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1390 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1392 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1393 ast::ExprKind::AddrOf(_, ref expr)
1394 | ast::ExprKind::Box(ref expr)
1395 | ast::ExprKind::Try(ref expr)
1396 | ast::ExprKind::Unary(_, ref expr)
1397 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1402 /// Returns `true` if a function call or a method call represented by the given span ends with a
1403 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1404 /// comma from macro can potentially break the code.
1405 pub fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1406 let mut result: bool = Default::default();
1407 let mut prev_char: char = Default::default();
1408 let closing_delimiters = &[')', '}', ']'];
1410 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1412 _ if kind.is_comment() || c.is_whitespace() => continue,
1413 c if closing_delimiters.contains(&c) => {
1414 result &= !closing_delimiters.contains(&prev_char);
1416 ',' => result = true,
1417 _ => result = false,
1426 context: &RewriteContext<'_>,
1427 mut subexpr: &ast::Expr,
1430 ) -> Option<String> {
1431 debug!("rewrite_paren, shape: {:?}", shape);
1433 // Extract comments within parens.
1436 let mut pre_comment;
1437 let mut post_comment;
1438 let remove_nested_parens = context.config.remove_nested_parens();
1441 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1442 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1443 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1444 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1446 // Remove nested parens if there are no comments.
1447 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1448 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1449 span = subexpr.span;
1450 subexpr = subsubexpr;
1459 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1460 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1461 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1462 if fits_single_line {
1463 Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment))
1465 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1469 fn rewrite_paren_in_multi_line(
1470 context: &RewriteContext<'_>,
1471 subexpr: &ast::Expr,
1475 ) -> Option<String> {
1476 let nested_indent = shape.indent.block_indent(context.config);
1477 let nested_shape = Shape::indented(nested_indent, context.config);
1478 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1479 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1480 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1482 let mut result = String::with_capacity(subexpr_str.len() * 2);
1484 if !pre_comment.is_empty() {
1485 result.push_str(&nested_indent.to_string_with_newline(context.config));
1486 result.push_str(&pre_comment);
1488 result.push_str(&nested_indent.to_string_with_newline(context.config));
1489 result.push_str(&subexpr_str);
1490 if !post_comment.is_empty() {
1491 result.push_str(&nested_indent.to_string_with_newline(context.config));
1492 result.push_str(&post_comment);
1494 result.push_str(&shape.indent.to_string_with_newline(context.config));
1503 context: &RewriteContext<'_>,
1505 ) -> Option<String> {
1506 let expr_str = expr.rewrite(context, shape)?;
1508 let offset = last_line_width(&expr_str) + 1;
1509 let rhs_overhead = shape.rhs_overhead(context.config);
1510 let index_shape = if expr_str.contains('\n') {
1511 Shape::legacy(context.config.max_width(), shape.indent)
1512 .offset_left(offset)
1513 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1515 match context.config.indent_style() {
1516 IndentStyle::Block => shape
1517 .offset_left(offset)
1518 .and_then(|shape| shape.sub_width(1)),
1519 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1522 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1524 // Return if index fits in a single line.
1525 match orig_index_rw {
1526 Some(ref index_str) if !index_str.contains('\n') => {
1527 return Some(format!("{}[{}]", expr_str, index_str));
1532 // Try putting index on the next line and see if it fits in a single line.
1533 let indent = shape.indent.block_indent(context.config);
1534 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1535 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1536 let new_index_rw = index.rewrite(context, index_shape);
1537 match (orig_index_rw, new_index_rw) {
1538 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1541 indent.to_string_with_newline(context.config),
1544 (None, Some(ref new_index_str)) => Some(format!(
1547 indent.to_string_with_newline(context.config),
1550 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1555 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1560 fields.iter().all(|field| !field.is_shorthand)
1563 fn rewrite_struct_lit<'a>(
1564 context: &RewriteContext<'_>,
1566 fields: &'a [ast::Field],
1567 base: Option<&'a ast::Expr>,
1570 ) -> Option<String> {
1571 debug!("rewrite_struct_lit: shape {:?}", shape);
1573 enum StructLitField<'a> {
1574 Regular(&'a ast::Field),
1575 Base(&'a ast::Expr),
1579 let path_shape = shape.sub_width(2)?;
1580 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1582 if fields.is_empty() && base.is_none() {
1583 return Some(format!("{} {{}}", path_str));
1586 // Foo { a: Foo } - indent is +3, width is -5.
1587 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1589 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1590 let body_lo = context.snippet_provider.span_after(span, "{");
1591 let fields_str = if struct_lit_can_be_aligned(fields, base)
1592 && context.config.struct_field_align_threshold() > 0
1594 rewrite_with_alignment(
1598 mk_sp(body_lo, span.hi()),
1602 let field_iter = fields
1604 .map(StructLitField::Regular)
1605 .chain(base.into_iter().map(StructLitField::Base));
1607 let span_lo = |item: &StructLitField<'_>| match *item {
1608 StructLitField::Regular(field) => field.span().lo(),
1609 StructLitField::Base(expr) => {
1610 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1611 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1612 let pos = snippet.find_uncommented("..").unwrap();
1613 last_field_hi + BytePos(pos as u32)
1616 let span_hi = |item: &StructLitField<'_>| match *item {
1617 StructLitField::Regular(field) => field.span().hi(),
1618 StructLitField::Base(expr) => expr.span.hi(),
1620 let rewrite = |item: &StructLitField<'_>| match *item {
1621 StructLitField::Regular(field) => {
1622 // The 1 taken from the v_budget is for the comma.
1623 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1625 StructLitField::Base(expr) => {
1627 expr.rewrite(context, v_shape.offset_left(2)?)
1628 .map(|s| format!("..{}", s))
1632 let items = itemize_list(
1633 context.snippet_provider,
1644 let item_vec = items.collect::<Vec<_>>();
1646 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1647 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1649 let ends_with_comma = span_ends_with_comma(context, span);
1650 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1652 let fmt = struct_lit_formatting(
1656 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1659 write_list(&item_vec, &fmt)?
1662 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1663 Some(format!("{} {{{}}}", path_str, fields_str))
1665 // FIXME if context.config.indent_style() == Visual, but we run out
1666 // of space, we should fall back to BlockIndent.
1669 pub fn wrap_struct_field(
1670 context: &RewriteContext<'_>,
1673 nested_shape: Shape,
1674 one_line_width: usize,
1676 if context.config.indent_style() == IndentStyle::Block
1677 && (fields_str.contains('\n')
1678 || !context.config.struct_lit_single_line()
1679 || fields_str.len() > one_line_width)
1683 nested_shape.indent.to_string_with_newline(context.config),
1685 shape.indent.to_string_with_newline(context.config)
1688 // One liner or visual indent.
1689 format!(" {} ", fields_str)
1693 pub fn struct_lit_field_separator(config: &Config) -> &str {
1694 colon_spaces(config.space_before_colon(), config.space_after_colon())
1697 pub fn rewrite_field(
1698 context: &RewriteContext<'_>,
1701 prefix_max_width: usize,
1702 ) -> Option<String> {
1703 if contains_skip(&field.attrs) {
1704 return Some(context.snippet(field.span()).to_owned());
1706 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1707 if !attrs_str.is_empty() {
1708 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1710 let name = context.snippet(field.ident.span);
1711 if field.is_shorthand {
1712 Some(attrs_str + name)
1714 let mut separator = String::from(struct_lit_field_separator(context.config));
1715 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1716 separator.push(' ');
1718 let overhead = name.len() + separator.len();
1719 let expr_shape = shape.offset_left(overhead)?;
1720 let expr = field.expr.rewrite(context, expr_shape);
1723 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1724 Some(attrs_str + name)
1726 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1728 let expr_offset = shape.indent.block_indent(context.config);
1731 .rewrite(context, Shape::indented(expr_offset, context.config));
1737 expr_offset.to_string(context.config),
1746 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1747 context: &RewriteContext<'_>,
1748 mut items: impl Iterator<Item = &'a T>,
1751 is_singleton_tuple: bool,
1752 ) -> Option<String> {
1753 // In case of length 1, need a trailing comma
1754 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1755 if is_singleton_tuple {
1757 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1761 .rewrite(context, nested_shape)
1762 .map(|s| format!("({},)", s));
1765 let list_lo = context.snippet_provider.span_after(span, "(");
1766 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1767 let items = itemize_list(
1768 context.snippet_provider,
1772 |item| item.span().lo(),
1773 |item| item.span().hi(),
1774 |item| item.rewrite(context, nested_shape),
1776 span.hi() - BytePos(1),
1779 let item_vec: Vec<_> = items.collect();
1780 let tactic = definitive_tactic(
1782 ListTactic::HorizontalVertical,
1786 let fmt = ListFormatting::new(nested_shape, context.config)
1788 .ends_with_newline(false);
1789 let list_str = write_list(&item_vec, &fmt)?;
1791 Some(format!("({})", list_str))
1794 pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1795 context: &'a RewriteContext<'_>,
1796 items: impl Iterator<Item = &'a T>,
1799 is_singleton_tuple: bool,
1800 ) -> Option<String> {
1801 debug!("rewrite_tuple {:?}", shape);
1802 if context.use_block_indent() {
1803 // We use the same rule as function calls for rewriting tuples.
1804 let force_tactic = if context.inside_macro() {
1805 if span_ends_with_comma(context, span) {
1806 Some(SeparatorTactic::Always)
1808 Some(SeparatorTactic::Never)
1810 } else if is_singleton_tuple {
1811 Some(SeparatorTactic::Always)
1815 overflow::rewrite_with_parens(
1821 context.config.width_heuristics().fn_call_width,
1825 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1829 pub fn rewrite_unary_prefix<R: Rewrite>(
1830 context: &RewriteContext<'_>,
1834 ) -> Option<String> {
1836 .rewrite(context, shape.offset_left(prefix.len())?)
1837 .map(|r| format!("{}{}", prefix, r))
1840 // FIXME: this is probably not correct for multi-line Rewrites. we should
1841 // subtract suffix.len() from the last line budget, not the first!
1842 pub fn rewrite_unary_suffix<R: Rewrite>(
1843 context: &RewriteContext<'_>,
1847 ) -> Option<String> {
1849 .rewrite(context, shape.sub_width(suffix.len())?)
1856 fn rewrite_unary_op(
1857 context: &RewriteContext<'_>,
1861 ) -> Option<String> {
1862 // For some reason, an UnOp is not spanned like BinOp!
1863 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1866 fn rewrite_assignment(
1867 context: &RewriteContext<'_>,
1870 op: Option<&ast::BinOp>,
1872 ) -> Option<String> {
1873 let operator_str = match op {
1874 Some(op) => context.snippet(op.span),
1878 // 1 = space between lhs and operator.
1879 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1880 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1882 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1885 /// Controls where to put the rhs.
1886 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1887 pub enum RhsTactics {
1890 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1891 ForceNextLineWithoutIndent,
1894 // The left hand side must contain everything up to, and including, the
1895 // assignment operator.
1896 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1897 context: &RewriteContext<'_>,
1901 ) -> Option<String> {
1902 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1905 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1906 context: &RewriteContext<'_>,
1910 rhs_tactics: RhsTactics,
1911 ) -> Option<String> {
1912 let lhs = lhs.into();
1913 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1914 shape.indent.width()
1918 // 1 = space between operator and rhs.
1919 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1921 offset: shape.offset + last_line_width + 1,
1924 let rhs = choose_rhs(
1928 ex.rewrite(context, orig_shape),
1934 fn choose_rhs<R: Rewrite>(
1935 context: &RewriteContext<'_>,
1938 orig_rhs: Option<String>,
1939 rhs_tactics: RhsTactics,
1940 ) -> Option<String> {
1942 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
1943 Some(format!(" {}", new_str))
1946 // Expression did not fit on the same line as the identifier.
1947 // Try splitting the line and see if that works better.
1948 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1949 let new_rhs = expr.rewrite(context, new_shape);
1950 let new_indent_str = &shape
1952 .block_indent(context.config)
1953 .to_string_with_newline(context.config);
1955 match (orig_rhs, new_rhs) {
1956 (Some(ref orig_rhs), Some(ref new_rhs))
1957 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1960 Some(format!(" {}", orig_rhs))
1962 (Some(ref orig_rhs), Some(ref new_rhs))
1963 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1965 Some(format!("{}{}", new_indent_str, new_rhs))
1967 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1968 (None, None) => None,
1969 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1975 fn shape_from_rhs_tactic(
1976 context: &RewriteContext<'_>,
1978 rhs_tactic: RhsTactics,
1979 ) -> Option<Shape> {
1981 RhsTactics::ForceNextLineWithoutIndent => shape
1982 .with_max_width(context.config)
1983 .sub_width(shape.indent.width()),
1984 RhsTactics::Default => {
1985 Shape::indented(shape.indent.block_indent(context.config), context.config)
1986 .sub_width(shape.rhs_overhead(context.config))
1991 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
1992 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1993 || !next_line_rhs.contains('\n')
1994 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
1995 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
1996 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
1997 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2000 fn rewrite_expr_addrof(
2001 context: &RewriteContext<'_>,
2002 mutability: ast::Mutability,
2005 ) -> Option<String> {
2006 let operator_str = match mutability {
2007 ast::Mutability::Immutable => "&",
2008 ast::Mutability::Mutable => "&mut ",
2010 rewrite_unary_prefix(context, operator_str, expr, shape)
2013 pub fn is_method_call(expr: &ast::Expr) -> bool {
2015 ast::ExprKind::MethodCall(..) => true,
2016 ast::ExprKind::AddrOf(_, ref expr)
2017 | ast::ExprKind::Box(ref expr)
2018 | ast::ExprKind::Cast(ref expr, _)
2019 | ast::ExprKind::Try(ref expr)
2020 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2027 use super::last_line_offsetted;
2030 fn test_last_line_offsetted() {
2031 let lines = "one\n two";
2032 assert_eq!(last_line_offsetted(2, lines), true);
2033 assert_eq!(last_line_offsetted(4, lines), false);
2034 assert_eq!(last_line_offsetted(6, lines), false);
2036 let lines = "one two";
2037 assert_eq!(last_line_offsetted(2, lines), false);
2038 assert_eq!(last_line_offsetted(0, lines), false);
2040 let lines = "\ntwo";
2041 assert_eq!(last_line_offsetted(2, lines), false);
2042 assert_eq!(last_line_offsetted(0, lines), false);
2044 let lines = "one\n two three";
2045 assert_eq!(last_line_offsetted(2, lines), true);
2046 let lines = "one\n two three";
2047 assert_eq!(last_line_offsetted(2, lines), false);