4 use itertools::Itertools;
5 use syntax::parse::token::DelimToken;
6 use syntax::source_map::{BytePos, SourceMap, Span};
7 use syntax::{ast, ptr};
9 use crate::chains::rewrite_chain;
12 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
13 rewrite_missing_comment, CharClasses, FindUncommented,
15 use crate::config::lists::*;
16 use crate::config::{Config, ControlBraceStyle, IndentStyle, Version};
18 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
19 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
21 use crate::macros::{rewrite_macro, MacroPosition};
22 use crate::matches::rewrite_match;
23 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
24 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
25 use crate::patterns::is_short_pattern;
26 use crate::rewrite::{Rewrite, RewriteContext};
27 use crate::shape::{Indent, Shape};
28 use crate::source_map::{LineRangeUtils, SpanUtils};
29 use crate::spanned::Spanned;
30 use crate::string::{rewrite_string, StringFormat};
31 use crate::types::{rewrite_path, PathContext};
33 colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
34 last_line_extendable, last_line_width, mk_sp, outer_attributes, ptr_vec_to_ref_vec,
35 semicolon_for_expr, semicolon_for_stmt, wrap_str,
37 use crate::vertical::rewrite_with_alignment;
38 use crate::visitor::FmtVisitor;
40 impl Rewrite for ast::Expr {
41 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
42 format_expr(self, ExprType::SubExpression, context, shape)
46 #[derive(Copy, Clone, PartialEq)]
55 context: &RewriteContext<'_>,
58 skip_out_of_file_lines_range!(context, expr.span);
60 if contains_skip(&*expr.attrs) {
61 return Some(context.snippet(expr.span()).to_owned());
63 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
69 let expr_rw = match expr.node {
70 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
76 choose_separator_tactic(context, expr.span),
79 ast::ExprKind::Lit(ref l) => rewrite_literal(context, l, shape),
80 ast::ExprKind::Call(ref callee, ref args) => {
81 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
82 let callee_str = callee.rewrite(context, shape)?;
83 rewrite_call(context, &callee_str, args, inner_span, shape)
85 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
86 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
87 // FIXME: format comments between operands and operator
88 rewrite_all_pairs(expr, shape, context).or_else(|| {
92 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
95 context.config.binop_separator(),
99 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
100 ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
104 base.as_ref().map(|e| &**e),
108 ast::ExprKind::Tup(ref items) => {
109 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
111 ast::ExprKind::If(..)
112 | ast::ExprKind::IfLet(..)
113 | ast::ExprKind::ForLoop(..)
114 | ast::ExprKind::Loop(..)
115 | ast::ExprKind::While(..)
116 | ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
117 .and_then(|control_flow| control_flow.rewrite(context, shape)),
118 ast::ExprKind::Block(ref block, opt_label) => {
120 ExprType::Statement => {
121 if is_unsafe_block(block) {
122 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
123 } else if let rw @ Some(_) =
124 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
126 // Rewrite block without trying to put it in a single line.
129 let prefix = block_prefix(context, block, shape)?;
131 rewrite_block_with_visitor(
142 ExprType::SubExpression => {
143 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
147 ast::ExprKind::Match(ref cond, ref arms) => {
148 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
150 ast::ExprKind::Path(ref qself, ref path) => {
151 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
153 ast::ExprKind::Assign(ref lhs, ref rhs) => {
154 rewrite_assignment(context, lhs, rhs, None, shape)
156 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
157 rewrite_assignment(context, lhs, rhs, Some(op), shape)
159 ast::ExprKind::Continue(ref opt_label) => {
160 let id_str = match *opt_label {
161 Some(label) => format!(" {}", label.ident),
162 None => String::new(),
164 Some(format!("continue{}", id_str))
166 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
167 let id_str = match *opt_label {
168 Some(label) => format!(" {}", label.ident),
169 None => String::new(),
172 if let Some(ref expr) = *opt_expr {
173 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
175 Some(format!("break{}", id_str))
178 ast::ExprKind::Yield(ref opt_expr) => {
179 if let Some(ref expr) = *opt_expr {
180 rewrite_unary_prefix(context, "yield ", &**expr, shape)
182 Some("yield".to_string())
185 ast::ExprKind::Closure(capture, asyncness, movability, ref fn_decl, ref body, _) => {
186 closures::rewrite_closure(
187 capture, asyncness, movability, fn_decl, body, expr.span, context, shape,
190 ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) => {
191 rewrite_chain(expr, context, shape)
193 ast::ExprKind::Mac(ref mac) => {
194 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
196 context.snippet(expr.span).to_owned(),
197 context.config.max_width(),
202 ast::ExprKind::Ret(None) => Some("return".to_owned()),
203 ast::ExprKind::Ret(Some(ref expr)) => {
204 rewrite_unary_prefix(context, "return ", &**expr, shape)
206 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
207 ast::ExprKind::AddrOf(mutability, ref expr) => {
208 rewrite_expr_addrof(context, mutability, expr, shape)
210 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
213 PairParts::infix(" as "),
216 SeparatorPlace::Front,
218 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
221 PairParts::infix(": "),
224 SeparatorPlace::Back,
226 ast::ExprKind::Index(ref expr, ref index) => {
227 rewrite_index(&**expr, &**index, context, shape)
229 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
232 PairParts::new("[", "; ", "]"),
235 SeparatorPlace::Back,
237 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
238 let delim = match limits {
239 ast::RangeLimits::HalfOpen => "..",
240 ast::RangeLimits::Closed => "..=",
243 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
245 ast::ExprKind::Lit(ref lit) => match lit.node {
246 ast::LitKind::FloatUnsuffixed(..) => {
247 context.snippet(lit.span).ends_with('.')
255 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
257 // Don't format `.. ..` into `....`, which is invalid.
259 // This check is unnecessary for `lhs`, because a range
260 // starting from another range needs parentheses as `(x ..) ..`
261 // (`x .. ..` is a range from `x` to `..`).
262 ast::ExprKind::Range(None, _, _) => true,
267 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
268 let space_if = |b: bool| if b { " " } else { "" };
272 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
274 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
278 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
279 (Some(lhs), Some(rhs)) => {
280 let sp_delim = if context.config.spaces_around_ranges() {
281 format!(" {} ", delim)
283 default_sp_delim(Some(lhs), Some(rhs))
288 PairParts::infix(&sp_delim),
291 context.config.binop_separator(),
294 (None, Some(rhs)) => {
295 let sp_delim = if context.config.spaces_around_ranges() {
296 format!("{} ", delim)
298 default_sp_delim(None, Some(rhs))
300 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
302 (Some(lhs), None) => {
303 let sp_delim = if context.config.spaces_around_ranges() {
304 format!(" {}", delim)
306 default_sp_delim(Some(lhs), None)
308 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
310 (None, None) => Some(delim.to_owned()),
313 // We do not format these expressions yet, but they should still
314 // satisfy our width restrictions.
315 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
316 ast::ExprKind::TryBlock(ref block) => {
317 if let rw @ Some(_) =
318 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
323 let budget = shape.width.saturating_sub(9);
332 Shape::legacy(budget, shape.indent)
337 ast::ExprKind::ObsoleteInPlace(ref lhs, ref rhs) => lhs
338 .rewrite(context, shape)
340 .and_then(|lhs| rewrite_assign_rhs(context, lhs, &**rhs, shape)),
341 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
342 let mover = if capture_by == ast::CaptureBy::Value {
347 if let rw @ Some(_) = rewrite_single_line_block(
349 format!("{}{}", "async ", mover).as_str(),
358 let budget = shape.width.saturating_sub(6);
368 Shape::legacy(budget, shape.indent)
373 ast::ExprKind::Err => None,
377 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
378 .and_then(|expr_str| {
379 let attrs = outer_attributes(&expr.attrs);
380 let attrs_str = attrs.rewrite(context, shape)?;
382 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
385 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
389 pub fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
391 exprs: impl Iterator<Item = &'a T>,
393 context: &'a RewriteContext<'_>,
395 force_separator_tactic: Option<SeparatorTactic>,
396 delim_token: Option<DelimToken>,
397 ) -> Option<String> {
398 overflow::rewrite_with_square_brackets(
404 force_separator_tactic,
409 fn rewrite_empty_block(
410 context: &RewriteContext<'_>,
412 attrs: Option<&[ast::Attribute]>,
413 label: Option<ast::Label>,
416 ) -> Option<String> {
417 if !block.stmts.is_empty() {
421 let label_str = rewrite_label(label);
422 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
426 if !block_contains_comment(block, context.source_map) && shape.width >= 2 {
427 return Some(format!("{}{}{{}}", prefix, label_str));
430 // If a block contains only a single-line comment, then leave it on one line.
431 let user_str = context.snippet(block.span);
432 let user_str = user_str.trim();
433 if user_str.starts_with('{') && user_str.ends_with('}') {
434 let comment_str = user_str[1..user_str.len() - 1].trim();
435 if block.stmts.is_empty()
436 && !comment_str.contains('\n')
437 && !comment_str.starts_with("//")
438 && comment_str.len() + 4 <= shape.width
440 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
447 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
448 Some(match block.rules {
449 ast::BlockCheckMode::Unsafe(..) => {
450 let snippet = context.snippet(block.span);
451 let open_pos = snippet.find_uncommented("{")?;
452 // Extract comment between unsafe and block start.
453 let trimmed = &snippet[6..open_pos].trim();
455 if !trimmed.is_empty() {
456 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
457 let budget = shape.width.checked_sub(9)?;
463 Shape::legacy(budget, shape.indent + 7),
471 ast::BlockCheckMode::Default => String::new(),
475 fn rewrite_single_line_block(
476 context: &RewriteContext<'_>,
479 attrs: Option<&[ast::Attribute]>,
480 label: Option<ast::Label>,
482 ) -> Option<String> {
483 if is_simple_block(block, attrs, context.source_map) {
484 let expr_shape = shape.offset_left(last_line_width(prefix))?;
485 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
486 let label_str = rewrite_label(label);
487 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
488 if result.len() <= shape.width && !result.contains('\n') {
495 pub fn rewrite_block_with_visitor(
496 context: &RewriteContext<'_>,
499 attrs: Option<&[ast::Attribute]>,
500 label: Option<ast::Label>,
503 ) -> Option<String> {
504 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
508 let mut visitor = FmtVisitor::from_context(context);
509 visitor.block_indent = shape.indent;
510 visitor.is_if_else_block = context.is_if_else_block();
511 match (block.rules, label) {
512 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
513 let snippet = context.snippet(block.span);
514 let open_pos = snippet.find_uncommented("{")?;
515 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
517 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
520 let inner_attrs = attrs.map(inner_attributes);
521 let label_str = rewrite_label(label);
522 visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
523 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
526 impl Rewrite for ast::Block {
527 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
528 rewrite_block(self, None, None, context, shape)
534 attrs: Option<&[ast::Attribute]>,
535 label: Option<ast::Label>,
536 context: &RewriteContext<'_>,
538 ) -> Option<String> {
539 let prefix = block_prefix(context, block, shape)?;
541 // shape.width is used only for the single line case: either the empty block `{}`,
542 // or an unsafe expression `unsafe { e }`.
543 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
547 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
548 if let Some(ref result_str) = result {
549 if result_str.lines().count() <= 3 {
550 if let rw @ Some(_) =
551 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
561 impl Rewrite for ast::Stmt {
562 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
563 skip_out_of_file_lines_range!(context, self.span());
565 let result = match self.node {
566 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
567 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
568 let suffix = if semicolon_for_stmt(context, self) {
574 let shape = shape.sub_width(suffix.len())?;
575 format_expr(ex, ExprType::Statement, context, shape).map(|s| s + suffix)
577 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
579 result.and_then(|res| recover_comment_removed(res, self.span(), context))
583 // Rewrite condition if the given expression has one.
585 context: &RewriteContext<'_>,
588 ) -> Option<String> {
590 ast::ExprKind::Match(ref cond, _) => {
592 let cond_shape = match context.config.indent_style() {
593 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
594 IndentStyle::Block => shape.offset_left(8)?,
596 cond.rewrite(context, cond_shape)
598 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
600 String::from("\n") + &shape.indent.block_only().to_string(context.config);
602 .rewrite_cond(context, shape, &alt_block_sep)
603 .and_then(|rw| Some(rw.0))
608 // Abstraction over control flow expressions
610 struct ControlFlow<'a> {
611 cond: Option<&'a ast::Expr>,
612 block: &'a ast::Block,
613 else_block: Option<&'a ast::Expr>,
614 label: Option<ast::Label>,
615 pats: Vec<&'a ast::Pat>,
619 allow_single_line: bool,
620 // HACK: `true` if this is an `if` expression in an `else if`.
625 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
627 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
631 else_block.as_ref().map(|e| &**e),
632 expr_type == ExprType::SubExpression,
636 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
637 Some(ControlFlow::new_if(
639 ptr_vec_to_ref_vec(pat),
641 else_block.as_ref().map(|e| &**e),
642 expr_type == ExprType::SubExpression,
647 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
648 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
650 ast::ExprKind::Loop(ref block, label) => {
651 Some(ControlFlow::new_loop(block, label, expr.span))
653 ast::ExprKind::While(ref cond, ref block, label) => Some(ControlFlow::new_while(
660 ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
661 ControlFlow::new_while(ptr_vec_to_ref_vec(pat), cond, block, label, expr.span),
667 fn choose_matcher(pats: &[&ast::Pat]) -> &'static str {
668 if pats.is_empty() { "" } else { "let" }
671 impl<'a> ControlFlow<'a> {
674 pats: Vec<&'a ast::Pat>,
675 block: &'a ast::Block,
676 else_block: Option<&'a ast::Expr>,
677 allow_single_line: bool,
680 ) -> ControlFlow<'a> {
681 let matcher = choose_matcher(&pats);
697 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
707 allow_single_line: false,
714 pats: Vec<&'a ast::Pat>,
716 block: &'a ast::Block,
717 label: Option<ast::Label>,
719 ) -> ControlFlow<'a> {
720 let matcher = choose_matcher(&pats);
730 allow_single_line: false,
739 block: &'a ast::Block,
740 label: Option<ast::Label>,
742 ) -> ControlFlow<'a> {
752 allow_single_line: false,
758 fn rewrite_single_line(
761 context: &RewriteContext<'_>,
763 ) -> Option<String> {
764 assert!(self.allow_single_line);
765 let else_block = self.else_block?;
766 let fixed_cost = self.keyword.len() + " { } else { }".len();
768 if let ast::ExprKind::Block(ref else_node, _) = else_block.node {
769 if !is_simple_block(self.block, None, context.source_map)
770 || !is_simple_block(else_node, None, context.source_map)
771 || pat_expr_str.contains('\n')
776 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
777 let expr = &self.block.stmts[0];
778 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
780 let new_width = new_width.checked_sub(if_str.len())?;
781 let else_expr = &else_node.stmts[0];
782 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
784 if if_str.contains('\n') || else_str.contains('\n') {
788 let result = format!(
789 "{} {} {{ {} }} else {{ {} }}",
790 self.keyword, pat_expr_str, if_str, else_str
793 if result.len() <= width {
802 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
804 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
805 let mut leading_whitespaces = 0;
806 for c in pat_str.chars().rev() {
809 _ if c.is_whitespace() => leading_whitespaces += 1,
810 _ => leading_whitespaces = 0,
813 leading_whitespaces > start_column
816 impl<'a> ControlFlow<'a> {
819 context: &RewriteContext<'_>,
823 ) -> Option<String> {
824 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pats, expr);
826 let cond_shape = shape.offset_left(offset)?;
827 if !self.pats.is_empty() {
828 let matcher = if self.matcher.is_empty() {
829 self.matcher.to_owned()
831 format!("{} ", self.matcher)
833 let pat_shape = cond_shape
834 .offset_left(matcher.len())?
835 .sub_width(self.connector.len())?;
836 let pat_string = rewrite_multiple_patterns(context, &self.pats, pat_shape)?;
837 let result = format!("{}{}{}", matcher, pat_string, self.connector);
838 return rewrite_assign_rhs(context, result, expr, cond_shape);
841 let expr_rw = expr.rewrite(context, cond_shape);
842 // The expression may (partially) fit on the current line.
843 // We do not allow splitting between `if` and condition.
844 if self.keyword == "if" || expr_rw.is_some() {
848 // The expression won't fit on the current line, jump to next.
849 let nested_shape = shape
850 .block_indent(context.config.tab_spaces())
851 .with_max_width(context.config);
852 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
853 expr.rewrite(context, nested_shape)
854 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
859 context: &RewriteContext<'_>,
862 ) -> Option<(String, usize)> {
863 // Do not take the rhs overhead from the upper expressions into account
864 // when rewriting pattern.
865 let new_width = context.budget(shape.used_width());
866 let fresh_shape = Shape {
870 let constr_shape = if self.nested_if {
871 // We are part of an if-elseif-else chain. Our constraints are tightened.
872 // 7 = "} else " .len()
873 fresh_shape.offset_left(7)?
878 let label_string = rewrite_label(self.label);
879 // 1 = space after keyword.
880 let offset = self.keyword.len() + label_string.len() + 1;
882 let pat_expr_string = match self.cond {
883 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
884 None => String::new(),
888 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
894 let one_line_budget = context
897 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
898 let force_newline_brace = (pat_expr_string.contains('\n')
899 || pat_expr_string.len() > one_line_budget)
900 && (!last_line_extendable(&pat_expr_string)
901 || last_line_offsetted(shape.used_width(), &pat_expr_string));
903 // Try to format if-else on single line.
904 if self.allow_single_line
908 .single_line_if_else_max_width
911 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
913 if let Some(cond_str) = trial {
918 .single_line_if_else_max_width
920 return Some((cond_str, 0));
925 let cond_span = if let Some(cond) = self.cond {
928 mk_sp(self.block.span.lo(), self.block.span.lo())
931 // `for event in event`
932 // Do not include label in the span.
935 .map_or(self.span.lo(), |label| label.ident.span.hi());
936 let between_kwd_cond = mk_sp(
939 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
940 if self.pats.is_empty() {
942 } else if self.matcher.is_empty() {
943 self.pats[0].span.lo()
947 .span_before(self.span, self.matcher.trim())
951 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
953 let after_cond_comment =
954 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
956 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
958 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
959 || force_newline_brace
966 let used_width = if pat_expr_string.contains('\n') {
967 last_line_width(&pat_expr_string)
969 // 2 = spaces after keyword and condition.
970 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
978 between_kwd_cond_comment.as_ref().map_or(
979 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
987 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
994 impl<'a> Rewrite for ControlFlow<'a> {
995 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
996 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
998 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
999 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1000 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1001 if used_width == 0 {
1002 return Some(cond_str);
1005 let block_width = shape.width.saturating_sub(used_width);
1006 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1007 // we should avoid the single line case.
1008 let block_width = if self.else_block.is_some() || self.nested_if {
1013 let block_shape = Shape {
1018 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1020 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1021 context.is_if_else_block.replace(old_val);
1025 let mut result = format!("{}{}", cond_str, block_str);
1027 if let Some(else_block) = self.else_block {
1028 let shape = Shape::indented(shape.indent, context.config);
1029 let mut last_in_chain = false;
1030 let rewrite = match else_block.node {
1031 // If the else expression is another if-else expression, prevent it
1032 // from being formatted on a single line.
1033 // Note how we're passing the original shape, as the
1034 // cost of "else" should not cascade.
1035 ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref next_else_block) => {
1036 ControlFlow::new_if(
1038 ptr_vec_to_ref_vec(pat),
1040 next_else_block.as_ref().map(|e| &**e),
1043 mk_sp(else_block.span.lo(), self.span.hi()),
1045 .rewrite(context, shape)
1047 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1048 ControlFlow::new_if(
1052 next_else_block.as_ref().map(|e| &**e),
1055 mk_sp(else_block.span.lo(), self.span.hi()),
1057 .rewrite(context, shape)
1060 last_in_chain = true;
1061 // When rewriting a block, the width is only used for single line
1062 // blocks, passing 1 lets us avoid that.
1063 let else_shape = Shape {
1064 width: min(1, shape.width),
1067 format_expr(else_block, ExprType::Statement, context, else_shape)
1071 let between_kwd_else_block = mk_sp(
1072 self.block.span.hi(),
1075 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1077 let between_kwd_else_block_comment =
1078 extract_comment(between_kwd_else_block, context, shape);
1080 let after_else = mk_sp(
1083 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1084 else_block.span.lo(),
1086 let after_else_comment = extract_comment(after_else, context, shape);
1088 let between_sep = match context.config.control_brace_style() {
1089 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1092 ControlBraceStyle::AlwaysSameLine => " ",
1094 let after_sep = match context.config.control_brace_style() {
1095 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1099 result.push_str(&format!(
1101 between_kwd_else_block_comment
1103 .map_or(between_sep, |s| &**s),
1104 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1106 result.push_str(&rewrite?);
1113 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1115 Some(label) => Cow::from(format!("{}: ", label.ident)),
1116 None => Cow::from(""),
1120 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1121 match rewrite_missing_comment(span, shape, context) {
1122 Some(ref comment) if !comment.is_empty() => Some(format!(
1123 "{indent}{}{indent}",
1125 indent = shape.indent.to_string_with_newline(context.config)
1131 pub fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool {
1132 let snippet = source_map.span_to_snippet(block.span).unwrap();
1133 contains_comment(&snippet)
1136 // Checks that a block contains no statements, an expression and no comments or
1138 // FIXME: incorrectly returns false when comment is contained completely within
1140 pub fn is_simple_block(
1142 attrs: Option<&[ast::Attribute]>,
1143 source_map: &SourceMap,
1145 (block.stmts.len() == 1
1146 && stmt_is_expr(&block.stmts[0])
1147 && !block_contains_comment(block, source_map)
1148 && attrs.map_or(true, |a| a.is_empty()))
1151 /// Checks whether a block contains at most one statement or expression, and no
1152 /// comments or attributes.
1153 pub fn is_simple_block_stmt(
1155 attrs: Option<&[ast::Attribute]>,
1156 source_map: &SourceMap,
1158 block.stmts.len() <= 1
1159 && !block_contains_comment(block, source_map)
1160 && attrs.map_or(true, |a| a.is_empty())
1163 /// Checks whether a block contains no statements, expressions, comments, or
1164 /// inner attributes.
1165 pub fn is_empty_block(
1167 attrs: Option<&[ast::Attribute]>,
1168 source_map: &SourceMap,
1170 block.stmts.is_empty()
1171 && !block_contains_comment(block, source_map)
1172 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1175 pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1177 ast::StmtKind::Expr(..) => true,
1182 pub(crate) fn stmt_is_if(stmt: &ast::Stmt) -> bool {
1184 ast::StmtKind::Expr(ref e) => match e.node {
1185 ast::ExprKind::If(..) => true,
1192 pub fn is_unsafe_block(block: &ast::Block) -> bool {
1193 if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1200 pub fn rewrite_multiple_patterns(
1201 context: &RewriteContext<'_>,
1204 ) -> Option<String> {
1207 .map(|p| p.rewrite(context, shape))
1208 .collect::<Option<Vec<_>>>()?;
1210 let use_mixed_layout = pats
1212 .zip(pat_strs.iter())
1213 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
1214 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
1215 let tactic = if use_mixed_layout {
1216 DefinitiveListTactic::Mixed
1220 ListTactic::HorizontalVertical,
1221 Separator::VerticalBar,
1225 let fmt = ListFormatting::new(shape, context.config)
1228 .separator_place(context.config.binop_separator())
1229 .ends_with_newline(false);
1230 write_list(&items, &fmt)
1233 pub fn rewrite_literal(context: &RewriteContext<'_>, l: &ast::Lit, shape: Shape) -> Option<String> {
1235 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1237 context.snippet(l.span).to_owned(),
1238 context.config.max_width(),
1244 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1245 let string_lit = context.snippet(span);
1247 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)
1350 || context.config.overflow_delimited_expr()
1352 ast::ExprKind::If(..)
1353 | ast::ExprKind::IfLet(..)
1354 | ast::ExprKind::ForLoop(..)
1355 | ast::ExprKind::Loop(..)
1356 | ast::ExprKind::While(..)
1357 | ast::ExprKind::WhileLet(..) => {
1358 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1361 // Handle always block-like expressions
1362 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1364 // Handle `[]` and `{}`-like expressions
1365 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1366 context.config.overflow_delimited_expr()
1367 || (context.use_block_indent() && args_len == 1)
1369 ast::ExprKind::Mac(ref macro_) => {
1370 match (macro_.node.delim, context.config.overflow_delimited_expr()) {
1371 (ast::MacDelimiter::Bracket, true) | (ast::MacDelimiter::Brace, true) => true,
1372 _ => context.use_block_indent() && args_len == 1,
1376 // Handle parenthetical expressions
1377 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1378 context.use_block_indent() && args_len == 1
1381 // Handle unary-like expressions
1382 ast::ExprKind::AddrOf(_, ref expr)
1383 | ast::ExprKind::Box(ref expr)
1384 | ast::ExprKind::Try(ref expr)
1385 | ast::ExprKind::Unary(_, ref expr)
1386 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1391 pub fn is_nested_call(expr: &ast::Expr) -> bool {
1393 ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true,
1394 ast::ExprKind::AddrOf(_, ref expr)
1395 | ast::ExprKind::Box(ref expr)
1396 | ast::ExprKind::Try(ref expr)
1397 | ast::ExprKind::Unary(_, ref expr)
1398 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1403 /// Returns `true` if a function call or a method call represented by the given span ends with a
1404 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1405 /// comma from macro can potentially break the code.
1406 pub fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1407 let mut result: bool = Default::default();
1408 let mut prev_char: char = Default::default();
1409 let closing_delimiters = &[')', '}', ']'];
1411 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1413 _ if kind.is_comment() || c.is_whitespace() => continue,
1414 c if closing_delimiters.contains(&c) => {
1415 result &= !closing_delimiters.contains(&prev_char);
1417 ',' => result = true,
1418 _ => result = false,
1427 context: &RewriteContext<'_>,
1428 mut subexpr: &ast::Expr,
1431 ) -> Option<String> {
1432 debug!("rewrite_paren, shape: {:?}", shape);
1434 // Extract comments within parens.
1437 let mut pre_comment;
1438 let mut post_comment;
1439 let remove_nested_parens = context.config.remove_nested_parens();
1442 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1443 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1444 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1445 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1447 // Remove nested parens if there are no comments.
1448 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.node {
1449 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1450 span = subexpr.span;
1451 subexpr = subsubexpr;
1460 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1461 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1462 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1463 if fits_single_line {
1464 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1466 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1470 fn rewrite_paren_in_multi_line(
1471 context: &RewriteContext<'_>,
1472 subexpr: &ast::Expr,
1476 ) -> Option<String> {
1477 let nested_indent = shape.indent.block_indent(context.config);
1478 let nested_shape = Shape::indented(nested_indent, context.config);
1479 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1480 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1481 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1483 let mut result = String::with_capacity(subexpr_str.len() * 2);
1485 if !pre_comment.is_empty() {
1486 result.push_str(&nested_indent.to_string_with_newline(context.config));
1487 result.push_str(&pre_comment);
1489 result.push_str(&nested_indent.to_string_with_newline(context.config));
1490 result.push_str(&subexpr_str);
1491 if !post_comment.is_empty() {
1492 result.push_str(&nested_indent.to_string_with_newline(context.config));
1493 result.push_str(&post_comment);
1495 result.push_str(&shape.indent.to_string_with_newline(context.config));
1504 context: &RewriteContext<'_>,
1506 ) -> Option<String> {
1507 let expr_str = expr.rewrite(context, shape)?;
1509 let offset = last_line_width(&expr_str) + 1;
1510 let rhs_overhead = shape.rhs_overhead(context.config);
1511 let index_shape = if expr_str.contains('\n') {
1512 Shape::legacy(context.config.max_width(), shape.indent)
1513 .offset_left(offset)
1514 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1516 match context.config.indent_style() {
1517 IndentStyle::Block => shape
1518 .offset_left(offset)
1519 .and_then(|shape| shape.sub_width(1)),
1520 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1523 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1525 // Return if index fits in a single line.
1526 match orig_index_rw {
1527 Some(ref index_str) if !index_str.contains('\n') => {
1528 return Some(format!("{}[{}]", expr_str, index_str));
1533 // Try putting index on the next line and see if it fits in a single line.
1534 let indent = shape.indent.block_indent(context.config);
1535 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1536 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1537 let new_index_rw = index.rewrite(context, index_shape);
1538 match (orig_index_rw, new_index_rw) {
1539 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1542 indent.to_string_with_newline(context.config),
1545 (None, Some(ref new_index_str)) => Some(format!(
1548 indent.to_string_with_newline(context.config),
1551 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1556 fn struct_lit_can_be_aligned(fields: &[ast::Field], base: Option<&ast::Expr>) -> bool {
1561 fields.iter().all(|field| !field.is_shorthand)
1564 fn rewrite_struct_lit<'a>(
1565 context: &RewriteContext<'_>,
1567 fields: &'a [ast::Field],
1568 base: Option<&'a ast::Expr>,
1571 ) -> Option<String> {
1572 debug!("rewrite_struct_lit: shape {:?}", shape);
1574 enum StructLitField<'a> {
1575 Regular(&'a ast::Field),
1576 Base(&'a ast::Expr),
1580 let path_shape = shape.sub_width(2)?;
1581 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
1583 if fields.is_empty() && base.is_none() {
1584 return Some(format!("{} {{}}", path_str));
1587 // Foo { a: Foo } - indent is +3, width is -5.
1588 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1590 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1591 let body_lo = context.snippet_provider.span_after(span, "{");
1592 let fields_str = if struct_lit_can_be_aligned(fields, base)
1593 && context.config.struct_field_align_threshold() > 0
1595 rewrite_with_alignment(
1599 mk_sp(body_lo, span.hi()),
1603 let field_iter = fields
1605 .map(StructLitField::Regular)
1606 .chain(base.into_iter().map(StructLitField::Base));
1608 let span_lo = |item: &StructLitField<'_>| match *item {
1609 StructLitField::Regular(field) => field.span().lo(),
1610 StructLitField::Base(expr) => {
1611 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1612 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1613 let pos = snippet.find_uncommented("..").unwrap();
1614 last_field_hi + BytePos(pos as u32)
1617 let span_hi = |item: &StructLitField<'_>| match *item {
1618 StructLitField::Regular(field) => field.span().hi(),
1619 StructLitField::Base(expr) => expr.span.hi(),
1621 let rewrite = |item: &StructLitField<'_>| match *item {
1622 StructLitField::Regular(field) => {
1623 // The 1 taken from the v_budget is for the comma.
1624 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1626 StructLitField::Base(expr) => {
1628 expr.rewrite(context, v_shape.offset_left(2)?)
1629 .map(|s| format!("..{}", s))
1633 let items = itemize_list(
1634 context.snippet_provider,
1645 let item_vec = items.collect::<Vec<_>>();
1647 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1648 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1650 let ends_with_comma = span_ends_with_comma(context, span);
1651 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1653 let fmt = struct_lit_formatting(
1657 force_no_trailing_comma || base.is_some() || !context.use_block_indent(),
1660 write_list(&item_vec, &fmt)?
1663 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
1664 Some(format!("{} {{{}}}", path_str, fields_str))
1666 // FIXME if context.config.indent_style() == Visual, but we run out
1667 // of space, we should fall back to BlockIndent.
1670 pub fn wrap_struct_field(
1671 context: &RewriteContext<'_>,
1674 nested_shape: Shape,
1675 one_line_width: usize,
1677 if context.config.indent_style() == IndentStyle::Block
1678 && (fields_str.contains('\n')
1679 || !context.config.struct_lit_single_line()
1680 || fields_str.len() > one_line_width)
1684 nested_shape.indent.to_string_with_newline(context.config),
1686 shape.indent.to_string_with_newline(context.config)
1689 // One liner or visual indent.
1690 format!(" {} ", fields_str)
1694 pub fn struct_lit_field_separator(config: &Config) -> &str {
1695 colon_spaces(config)
1698 pub fn rewrite_field(
1699 context: &RewriteContext<'_>,
1702 prefix_max_width: usize,
1703 ) -> Option<String> {
1704 if contains_skip(&field.attrs) {
1705 return Some(context.snippet(field.span()).to_owned());
1707 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1708 if !attrs_str.is_empty() {
1709 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1711 let name = context.snippet(field.ident.span);
1712 if field.is_shorthand {
1713 Some(attrs_str + name)
1715 let mut separator = String::from(struct_lit_field_separator(context.config));
1716 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1717 separator.push(' ');
1719 let overhead = name.len() + separator.len();
1720 let expr_shape = shape.offset_left(overhead)?;
1721 let expr = field.expr.rewrite(context, expr_shape);
1724 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1725 Some(attrs_str + name)
1727 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1729 let expr_offset = shape.indent.block_indent(context.config);
1732 .rewrite(context, Shape::indented(expr_offset, context.config));
1738 expr_offset.to_string(context.config),
1747 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1748 context: &RewriteContext<'_>,
1749 mut items: impl Iterator<Item = &'a T>,
1752 is_singleton_tuple: bool,
1753 ) -> Option<String> {
1754 // In case of length 1, need a trailing comma
1755 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1756 if is_singleton_tuple {
1758 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1762 .rewrite(context, nested_shape)
1763 .map(|s| format!("({},)", s));
1766 let list_lo = context.snippet_provider.span_after(span, "(");
1767 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1768 let items = itemize_list(
1769 context.snippet_provider,
1773 |item| item.span().lo(),
1774 |item| item.span().hi(),
1775 |item| item.rewrite(context, nested_shape),
1777 span.hi() - BytePos(1),
1780 let item_vec: Vec<_> = items.collect();
1781 let tactic = definitive_tactic(
1783 ListTactic::HorizontalVertical,
1787 let fmt = ListFormatting::new(nested_shape, context.config)
1789 .ends_with_newline(false);
1790 let list_str = write_list(&item_vec, &fmt)?;
1792 Some(format!("({})", list_str))
1795 pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1796 context: &'a RewriteContext<'_>,
1797 items: impl Iterator<Item = &'a T>,
1800 is_singleton_tuple: bool,
1801 ) -> Option<String> {
1802 debug!("rewrite_tuple {:?}", shape);
1803 if context.use_block_indent() {
1804 // We use the same rule as function calls for rewriting tuples.
1805 let force_tactic = if context.inside_macro() {
1806 if span_ends_with_comma(context, span) {
1807 Some(SeparatorTactic::Always)
1809 Some(SeparatorTactic::Never)
1811 } else if is_singleton_tuple {
1812 Some(SeparatorTactic::Always)
1816 overflow::rewrite_with_parens(
1822 context.config.width_heuristics().fn_call_width,
1826 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1830 pub fn rewrite_unary_prefix<R: Rewrite>(
1831 context: &RewriteContext<'_>,
1835 ) -> Option<String> {
1837 .rewrite(context, shape.offset_left(prefix.len())?)
1838 .map(|r| format!("{}{}", prefix, r))
1841 // FIXME: this is probably not correct for multi-line Rewrites. we should
1842 // subtract suffix.len() from the last line budget, not the first!
1843 pub fn rewrite_unary_suffix<R: Rewrite>(
1844 context: &RewriteContext<'_>,
1848 ) -> Option<String> {
1850 .rewrite(context, shape.sub_width(suffix.len())?)
1857 fn rewrite_unary_op(
1858 context: &RewriteContext<'_>,
1862 ) -> Option<String> {
1863 // For some reason, an UnOp is not spanned like BinOp!
1864 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1867 fn rewrite_assignment(
1868 context: &RewriteContext<'_>,
1871 op: Option<&ast::BinOp>,
1873 ) -> Option<String> {
1874 let operator_str = match op {
1875 Some(op) => context.snippet(op.span),
1879 // 1 = space between lhs and operator.
1880 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1881 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1883 rewrite_assign_rhs(context, lhs_str, rhs, shape)
1886 /// Controls where to put the rhs.
1887 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1888 pub enum RhsTactics {
1891 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1892 ForceNextLineWithoutIndent,
1895 // The left hand side must contain everything up to, and including, the
1896 // assignment operator.
1897 pub fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1898 context: &RewriteContext<'_>,
1902 ) -> Option<String> {
1903 rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default)
1906 pub fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
1907 context: &RewriteContext<'_>,
1911 rhs_tactics: RhsTactics,
1912 ) -> Option<String> {
1913 let lhs = lhs.into();
1914 let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
1915 shape.indent.width()
1919 // 1 = space between operator and rhs.
1920 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1922 offset: shape.offset + last_line_width + 1,
1925 let rhs = choose_rhs(
1929 ex.rewrite(context, orig_shape),
1935 fn choose_rhs<R: Rewrite>(
1936 context: &RewriteContext<'_>,
1939 orig_rhs: Option<String>,
1940 rhs_tactics: RhsTactics,
1941 ) -> Option<String> {
1943 Some(ref new_str) if !new_str.contains('\n') && new_str.len() <= shape.width => {
1944 Some(format!(" {}", new_str))
1947 // Expression did not fit on the same line as the identifier.
1948 // Try splitting the line and see if that works better.
1949 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
1950 let new_rhs = expr.rewrite(context, new_shape);
1951 let new_indent_str = &shape
1953 .block_indent(context.config)
1954 .to_string_with_newline(context.config);
1956 match (orig_rhs, new_rhs) {
1957 (Some(ref orig_rhs), Some(ref new_rhs))
1958 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
1961 Some(format!(" {}", orig_rhs))
1963 (Some(ref orig_rhs), Some(ref new_rhs))
1964 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
1966 Some(format!("{}{}", new_indent_str, new_rhs))
1968 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
1969 (None, None) => None,
1970 (Some(orig_rhs), _) => Some(format!(" {}", orig_rhs)),
1976 fn shape_from_rhs_tactic(
1977 context: &RewriteContext<'_>,
1979 rhs_tactic: RhsTactics,
1980 ) -> Option<Shape> {
1982 RhsTactics::ForceNextLineWithoutIndent => shape
1983 .with_max_width(context.config)
1984 .sub_width(shape.indent.width()),
1985 RhsTactics::Default => {
1986 Shape::indented(shape.indent.block_indent(context.config), context.config)
1987 .sub_width(shape.rhs_overhead(context.config))
1992 pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool {
1993 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
1994 || !next_line_rhs.contains('\n')
1995 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
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, '{')
1998 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2001 fn rewrite_expr_addrof(
2002 context: &RewriteContext<'_>,
2003 mutability: ast::Mutability,
2006 ) -> Option<String> {
2007 let operator_str = match mutability {
2008 ast::Mutability::Immutable => "&",
2009 ast::Mutability::Mutable => "&mut ",
2011 rewrite_unary_prefix(context, operator_str, expr, shape)
2014 pub fn is_method_call(expr: &ast::Expr) -> bool {
2016 ast::ExprKind::MethodCall(..) => true,
2017 ast::ExprKind::AddrOf(_, ref expr)
2018 | ast::ExprKind::Box(ref expr)
2019 | ast::ExprKind::Cast(ref expr, _)
2020 | ast::ExprKind::Try(ref expr)
2021 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2028 use super::last_line_offsetted;
2031 fn test_last_line_offsetted() {
2032 let lines = "one\n two";
2033 assert_eq!(last_line_offsetted(2, lines), true);
2034 assert_eq!(last_line_offsetted(4, lines), false);
2035 assert_eq!(last_line_offsetted(6, lines), false);
2037 let lines = "one two";
2038 assert_eq!(last_line_offsetted(2, lines), false);
2039 assert_eq!(last_line_offsetted(0, lines), false);
2041 let lines = "\ntwo";
2042 assert_eq!(last_line_offsetted(2, lines), false);
2043 assert_eq!(last_line_offsetted(0, lines), false);
2045 let lines = "one\n two three";
2046 assert_eq!(last_line_offsetted(2, lines), true);
2047 let lines = "one\n two three";
2048 assert_eq!(last_line_offsetted(2, lines), false);