3 use std::collections::HashMap;
5 use itertools::Itertools;
6 use rustc_ast::token::{DelimToken, LitKind};
7 use rustc_ast::{ast, ptr};
8 use rustc_span::{BytePos, Span};
10 use crate::chains::rewrite_chain;
13 combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
14 rewrite_missing_comment, CharClasses, FindUncommented,
16 use crate::config::lists::*;
17 use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, Version};
19 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
20 struct_lit_tactic, write_list, ListFormatting, Separator,
22 use crate::macros::{rewrite_macro, MacroPosition};
23 use crate::matches::rewrite_match;
24 use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
25 use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
26 use crate::rewrite::{QueryId, 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, semicolon_for_expr,
35 unicode_str_width, 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)]
47 pub(crate) enum ExprType {
52 pub(crate) fn format_expr(
55 context: &RewriteContext<'_>,
58 // when max_width is tight, we should check all possible formattings, in order to find
59 // if we can fit expression in the limit. Doing it recursively takes exponential time
60 // relative to input size, and people hit it with rustfmt takes minutes in #4476 #4867 #5128
61 // By memoization of format_expr function, we format each pair of expression and shape
62 // only once, so worst case execution time becomes O(n*max_width^3).
63 if context.inside_macro() || context.is_macro_def {
64 // span ids are not unique in macros, so we don't memoize result of them.
65 return format_expr_inner(expr, expr_type, context, shape);
68 let query_id = QueryId {
72 if let Some(map) = context.memoize.take() {
73 if let Some(r) = map.get(&query_id) {
75 context.memoize.set(Some(map)); // restore map in the memoize cell for other users
78 context.memoize.set(Some(map));
81 context.memoize.set(Some(HashMap::default()));
82 clean = true; // We got None, so we are the top level called function. When
83 // this function finishes, no one is interested in what is in the map, because
84 // all of them are sub expressions of this top level expression, and this is
85 // done. So we should clean up memoize map to save some memory.
88 let r = format_expr_inner(expr, expr_type, context, shape);
90 context.memoize.set(None);
92 if let Some(mut map) = context.memoize.take() {
93 map.insert(query_id, r.clone()); // insert the result in the memoize map
94 context.memoize.set(Some(map)); // so it won't be computed again
100 fn format_expr_inner(
103 context: &RewriteContext<'_>,
105 ) -> Option<String> {
106 skip_out_of_file_lines_range!(context, expr.span);
108 if contains_skip(&*expr.attrs) {
109 return Some(context.snippet(expr.span()).to_owned());
111 let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
117 let expr_rw = match expr.kind {
118 ast::ExprKind::Array(ref expr_vec) => rewrite_array(
124 choose_separator_tactic(context, expr.span),
127 ast::ExprKind::Lit(ref l) => {
128 if let Some(expr_rw) = rewrite_literal(context, l, shape) {
131 if let LitKind::StrRaw(_) = l.token.kind {
132 Some(context.snippet(l.span).trim().into())
138 ast::ExprKind::Call(ref callee, ref args) => {
139 let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
140 let callee_str = callee.rewrite(context, shape)?;
141 rewrite_call(context, &callee_str, args, inner_span, shape)
143 ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
144 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
145 // FIXME: format comments between operands and operator
146 rewrite_all_pairs(expr, shape, context).or_else(|| {
150 PairParts::infix(&format!(" {} ", context.snippet(op.span))),
153 context.config.binop_separator(),
157 ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
158 ast::ExprKind::Struct(ref struct_expr) => {
159 let ast::StructExpr {
176 ast::ExprKind::Tup(ref items) => {
177 rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
179 ast::ExprKind::Let(..) => None,
180 ast::ExprKind::If(..)
181 | ast::ExprKind::ForLoop(..)
182 | ast::ExprKind::Loop(..)
183 | ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
184 .and_then(|control_flow| control_flow.rewrite(context, shape)),
185 ast::ExprKind::ConstBlock(ref anon_const) => {
186 Some(format!("const {}", anon_const.rewrite(context, shape)?))
188 ast::ExprKind::Block(ref block, opt_label) => {
190 ExprType::Statement => {
191 if is_unsafe_block(block) {
192 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
193 } else if let rw @ Some(_) =
194 rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
196 // Rewrite block without trying to put it in a single line.
199 let prefix = block_prefix(context, block, shape)?;
201 rewrite_block_with_visitor(
212 ExprType::SubExpression => {
213 rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
217 ast::ExprKind::Match(ref cond, ref arms) => {
218 rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
220 ast::ExprKind::Path(ref qself, ref path) => {
221 rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
223 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
224 rewrite_assignment(context, lhs, rhs, None, shape)
226 ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
227 rewrite_assignment(context, lhs, rhs, Some(op), shape)
229 ast::ExprKind::Continue(ref opt_label) => {
230 let id_str = match *opt_label {
231 Some(label) => format!(" {}", label.ident),
232 None => String::new(),
234 Some(format!("continue{}", id_str))
236 ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
237 let id_str = match *opt_label {
238 Some(label) => format!(" {}", label.ident),
239 None => String::new(),
242 if let Some(ref expr) = *opt_expr {
243 rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
245 Some(format!("break{}", id_str))
248 ast::ExprKind::Yield(ref opt_expr) => {
249 if let Some(ref expr) = *opt_expr {
250 rewrite_unary_prefix(context, "yield ", &**expr, shape)
252 Some("yield".to_string())
255 ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => {
256 closures::rewrite_closure(
257 capture, is_async, movability, fn_decl, body, expr.span, context, shape,
260 ast::ExprKind::Try(..)
261 | ast::ExprKind::Field(..)
262 | ast::ExprKind::MethodCall(..)
263 | ast::ExprKind::Await(_) => rewrite_chain(expr, context, shape),
264 ast::ExprKind::MacCall(ref mac) => {
265 rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
267 context.snippet(expr.span).to_owned(),
268 context.config.max_width(),
273 ast::ExprKind::Ret(None) => Some("return".to_owned()),
274 ast::ExprKind::Ret(Some(ref expr)) => {
275 rewrite_unary_prefix(context, "return ", &**expr, shape)
277 ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
278 ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
279 rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
281 ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
284 PairParts::infix(" as "),
287 SeparatorPlace::Front,
289 ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
292 PairParts::infix(": "),
295 SeparatorPlace::Back,
297 ast::ExprKind::Index(ref expr, ref index) => {
298 rewrite_index(&**expr, &**index, context, shape)
300 ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
303 PairParts::new("[", "; ", "]"),
306 SeparatorPlace::Back,
308 ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
309 let delim = match limits {
310 ast::RangeLimits::HalfOpen => "..",
311 ast::RangeLimits::Closed => "..=",
314 fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool {
316 ast::ExprKind::Lit(ref lit) => match lit.kind {
317 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
318 context.snippet(lit.span).ends_with('.')
322 ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
327 fn needs_space_after_range(rhs: &ast::Expr) -> bool {
328 // Don't format `.. ..` into `....`, which is invalid.
330 // This check is unnecessary for `lhs`, because a range
331 // starting from another range needs parentheses as `(x ..) ..`
332 // (`x .. ..` is a range from `x` to `..`).
333 matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
336 let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
337 let space_if = |b: bool| if b { " " } else { "" };
341 lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
343 rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
347 match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
348 (Some(lhs), Some(rhs)) => {
349 let sp_delim = if context.config.spaces_around_ranges() {
350 format!(" {} ", delim)
352 default_sp_delim(Some(lhs), Some(rhs))
357 PairParts::infix(&sp_delim),
360 context.config.binop_separator(),
363 (None, Some(rhs)) => {
364 let sp_delim = if context.config.spaces_around_ranges() {
365 format!("{} ", delim)
367 default_sp_delim(None, Some(rhs))
369 rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
371 (Some(lhs), None) => {
372 let sp_delim = if context.config.spaces_around_ranges() {
373 format!(" {}", delim)
375 default_sp_delim(Some(lhs), None)
377 rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
379 (None, None) => Some(delim.to_owned()),
382 // We do not format these expressions yet, but they should still
383 // satisfy our width restrictions.
384 // Style Guide RFC for InlineAsm variant pending
385 // https://github.com/rust-dev-tools/fmt-rfcs/issues/152
386 ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
387 ast::ExprKind::TryBlock(ref block) => {
388 if let rw @ Some(_) =
389 rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
394 let budget = shape.width.saturating_sub(9);
403 Shape::legacy(budget, shape.indent)
408 ast::ExprKind::Async(capture_by, _node_id, ref block) => {
409 let mover = if capture_by == ast::CaptureBy::Value {
414 if let rw @ Some(_) = rewrite_single_line_block(
416 format!("{}{}", "async ", mover).as_str(),
425 let budget = shape.width.saturating_sub(6);
435 Shape::legacy(budget, shape.indent)
440 ast::ExprKind::Underscore => Some("_".to_owned()),
441 ast::ExprKind::Err => None,
445 .and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
446 .and_then(|expr_str| {
447 let attrs = outer_attributes(&expr.attrs);
448 let attrs_str = attrs.rewrite(context, shape)?;
450 attrs.last().map_or(expr.span.lo(), |attr| attr.span.hi()),
453 combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
457 pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
459 exprs: impl Iterator<Item = &'a T>,
461 context: &'a RewriteContext<'_>,
463 force_separator_tactic: Option<SeparatorTactic>,
464 delim_token: Option<DelimToken>,
465 ) -> Option<String> {
466 overflow::rewrite_with_square_brackets(
472 force_separator_tactic,
477 fn rewrite_empty_block(
478 context: &RewriteContext<'_>,
480 attrs: Option<&[ast::Attribute]>,
481 label: Option<ast::Label>,
484 ) -> Option<String> {
485 if block_has_statements(block) {
489 let label_str = rewrite_label(label);
490 if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
494 if !block_contains_comment(context, block) && shape.width >= 2 {
495 return Some(format!("{}{}{{}}", prefix, label_str));
498 // If a block contains only a single-line comment, then leave it on one line.
499 let user_str = context.snippet(block.span);
500 let user_str = user_str.trim();
501 if user_str.starts_with('{') && user_str.ends_with('}') {
502 let comment_str = user_str[1..user_str.len() - 1].trim();
503 if block.stmts.is_empty()
504 && !comment_str.contains('\n')
505 && !comment_str.starts_with("//")
506 && comment_str.len() + 4 <= shape.width
508 return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str));
515 fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option<String> {
516 Some(match block.rules {
517 ast::BlockCheckMode::Unsafe(..) => {
518 let snippet = context.snippet(block.span);
519 let open_pos = snippet.find_uncommented("{")?;
520 // Extract comment between unsafe and block start.
521 let trimmed = &snippet[6..open_pos].trim();
523 if !trimmed.is_empty() {
524 // 9 = "unsafe {".len(), 7 = "unsafe ".len()
525 let budget = shape.width.checked_sub(9)?;
531 Shape::legacy(budget, shape.indent + 7),
539 ast::BlockCheckMode::Default => String::new(),
543 fn rewrite_single_line_block(
544 context: &RewriteContext<'_>,
547 attrs: Option<&[ast::Attribute]>,
548 label: Option<ast::Label>,
550 ) -> Option<String> {
551 if is_simple_block(context, block, attrs) {
552 let expr_shape = shape.offset_left(last_line_width(prefix))?;
553 let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
554 let label_str = rewrite_label(label);
555 let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
556 if result.len() <= shape.width && !result.contains('\n') {
563 pub(crate) fn rewrite_block_with_visitor(
564 context: &RewriteContext<'_>,
567 attrs: Option<&[ast::Attribute]>,
568 label: Option<ast::Label>,
571 ) -> Option<String> {
572 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
576 let mut visitor = FmtVisitor::from_context(context);
577 visitor.block_indent = shape.indent;
578 visitor.is_if_else_block = context.is_if_else_block();
579 match (block.rules, label) {
580 (ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
581 let snippet = context.snippet(block.span);
582 let open_pos = snippet.find_uncommented("{")?;
583 visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
585 (ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
588 let inner_attrs = attrs.map(inner_attributes);
589 let label_str = rewrite_label(label);
590 visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
591 let visitor_context = visitor.get_context();
595 .append(&mut visitor_context.skipped_range.borrow_mut());
596 Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
599 impl Rewrite for ast::Block {
600 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
601 rewrite_block(self, None, None, context, shape)
607 attrs: Option<&[ast::Attribute]>,
608 label: Option<ast::Label>,
609 context: &RewriteContext<'_>,
611 ) -> Option<String> {
612 let prefix = block_prefix(context, block, shape)?;
614 // shape.width is used only for the single line case: either the empty block `{}`,
615 // or an unsafe expression `unsafe { e }`.
616 if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, &prefix, shape) {
620 let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
621 if let Some(ref result_str) = result {
622 if result_str.lines().count() <= 3 {
623 if let rw @ Some(_) =
624 rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
634 // Rewrite condition if the given expression has one.
635 pub(crate) fn rewrite_cond(
636 context: &RewriteContext<'_>,
639 ) -> Option<String> {
641 ast::ExprKind::Match(ref cond, _) => {
643 let cond_shape = match context.config.indent_style() {
644 IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
645 IndentStyle::Block => shape.offset_left(8)?,
647 cond.rewrite(context, cond_shape)
649 _ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
651 String::from("\n") + &shape.indent.block_only().to_string(context.config);
653 .rewrite_cond(context, shape, &alt_block_sep)
659 // Abstraction over control flow expressions
661 struct ControlFlow<'a> {
662 cond: Option<&'a ast::Expr>,
663 block: &'a ast::Block,
664 else_block: Option<&'a ast::Expr>,
665 label: Option<ast::Label>,
666 pat: Option<&'a ast::Pat>,
670 allow_single_line: bool,
671 // HACK: `true` if this is an `if` expression in an `else if`.
676 fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
678 ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
683 // FIXME: Refactor this.
684 fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
686 ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
687 let (pat, cond) = extract_pats_and_cond(cond);
688 Some(ControlFlow::new_if(
692 else_block.as_ref().map(|e| &**e),
693 expr_type == ExprType::SubExpression,
698 ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
699 Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
701 ast::ExprKind::Loop(ref block, label) => {
702 Some(ControlFlow::new_loop(block, label, expr.span))
704 ast::ExprKind::While(ref cond, ref block, label) => {
705 let (pat, cond) = extract_pats_and_cond(cond);
706 Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
712 fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
713 pat.map_or("", |_| "let")
716 impl<'a> ControlFlow<'a> {
719 pat: Option<&'a ast::Pat>,
720 block: &'a ast::Block,
721 else_block: Option<&'a ast::Expr>,
722 allow_single_line: bool,
725 ) -> ControlFlow<'a> {
726 let matcher = choose_matcher(pat);
742 fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
752 allow_single_line: false,
759 pat: Option<&'a ast::Pat>,
761 block: &'a ast::Block,
762 label: Option<ast::Label>,
764 ) -> ControlFlow<'a> {
765 let matcher = choose_matcher(pat);
775 allow_single_line: false,
784 block: &'a ast::Block,
785 label: Option<ast::Label>,
787 ) -> ControlFlow<'a> {
797 allow_single_line: false,
803 fn rewrite_single_line(
806 context: &RewriteContext<'_>,
808 ) -> Option<String> {
809 assert!(self.allow_single_line);
810 let else_block = self.else_block?;
811 let fixed_cost = self.keyword.len() + " { } else { }".len();
813 if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
814 if !is_simple_block(context, self.block, None)
815 || !is_simple_block(context, else_node, None)
816 || pat_expr_str.contains('\n')
821 let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
822 let expr = &self.block.stmts[0];
823 let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
825 let new_width = new_width.checked_sub(if_str.len())?;
826 let else_expr = &else_node.stmts[0];
827 let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
829 if if_str.contains('\n') || else_str.contains('\n') {
833 let result = format!(
834 "{} {} {{ {} }} else {{ {} }}",
835 self.keyword, pat_expr_str, if_str, else_str
838 if result.len() <= width {
847 /// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
849 fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
850 let mut leading_whitespaces = 0;
851 for c in pat_str.chars().rev() {
854 _ if c.is_whitespace() => leading_whitespaces += 1,
855 _ => leading_whitespaces = 0,
858 leading_whitespaces > start_column
861 impl<'a> ControlFlow<'a> {
864 context: &RewriteContext<'_>,
868 ) -> Option<String> {
869 debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
871 let cond_shape = shape.offset_left(offset)?;
872 if let Some(pat) = self.pat {
873 let matcher = if self.matcher.is_empty() {
874 self.matcher.to_owned()
876 format!("{} ", self.matcher)
878 let pat_shape = cond_shape
879 .offset_left(matcher.len())?
880 .sub_width(self.connector.len())?;
881 let pat_string = pat.rewrite(context, pat_shape)?;
882 let comments_lo = context
884 .span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
885 let comments_span = mk_sp(comments_lo, expr.span.lo());
886 return rewrite_assign_rhs_with_comments(
888 &format!("{}{}{}", matcher, pat_string, self.connector),
891 &RhsAssignKind::Expr(&expr.kind, expr.span),
898 let expr_rw = expr.rewrite(context, cond_shape);
899 // The expression may (partially) fit on the current line.
900 // We do not allow splitting between `if` and condition.
901 if self.keyword == "if" || expr_rw.is_some() {
905 // The expression won't fit on the current line, jump to next.
906 let nested_shape = shape
907 .block_indent(context.config.tab_spaces())
908 .with_max_width(context.config);
909 let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
910 expr.rewrite(context, nested_shape)
911 .map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
916 context: &RewriteContext<'_>,
919 ) -> Option<(String, usize)> {
920 // Do not take the rhs overhead from the upper expressions into account
921 // when rewriting pattern.
922 let new_width = context.budget(shape.used_width());
923 let fresh_shape = Shape {
927 let constr_shape = if self.nested_if {
928 // We are part of an if-elseif-else chain. Our constraints are tightened.
929 // 7 = "} else " .len()
930 fresh_shape.offset_left(7)?
935 let label_string = rewrite_label(self.label);
936 // 1 = space after keyword.
937 let offset = self.keyword.len() + label_string.len() + 1;
939 let pat_expr_string = match self.cond {
940 Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
941 None => String::new(),
945 if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
951 let one_line_budget = context
954 .saturating_sub(constr_shape.used_width() + offset + brace_overhead);
955 let force_newline_brace = (pat_expr_string.contains('\n')
956 || pat_expr_string.len() > one_line_budget)
957 && (!last_line_extendable(&pat_expr_string)
958 || last_line_offsetted(shape.used_width(), &pat_expr_string));
960 // Try to format if-else on single line.
961 if self.allow_single_line && context.config.single_line_if_else_max_width() > 0 {
962 let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
964 if let Some(cond_str) = trial {
965 if cond_str.len() <= context.config.single_line_if_else_max_width() {
966 return Some((cond_str, 0));
971 let cond_span = if let Some(cond) = self.cond {
974 mk_sp(self.block.span.lo(), self.block.span.lo())
977 // `for event in event`
978 // Do not include label in the span.
981 .map_or(self.span.lo(), |label| label.ident.span.hi());
982 let between_kwd_cond = mk_sp(
985 .span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
986 if self.pat.is_none() {
988 } else if self.matcher.is_empty() {
989 self.pat.unwrap().span.lo()
993 .span_before(self.span, self.matcher.trim())
997 let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
999 let after_cond_comment =
1000 extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
1002 let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
1004 } else if context.config.control_brace_style() == ControlBraceStyle::AlwaysNextLine
1005 || force_newline_brace
1012 let used_width = if pat_expr_string.contains('\n') {
1013 last_line_width(&pat_expr_string)
1015 // 2 = spaces after keyword and condition.
1016 label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
1024 between_kwd_cond_comment.as_ref().map_or(
1025 if pat_expr_string.is_empty() || pat_expr_string.starts_with('\n') {
1033 after_cond_comment.as_ref().map_or(block_sep, |s| &**s)
1040 impl<'a> Rewrite for ControlFlow<'a> {
1041 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1042 debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
1044 let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
1045 let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
1046 // If `used_width` is 0, it indicates that whole control flow is written in a single line.
1047 if used_width == 0 {
1048 return Some(cond_str);
1051 let block_width = shape.width.saturating_sub(used_width);
1052 // This is used only for the empty block case: `{}`. So, we use 1 if we know
1053 // we should avoid the single line case.
1054 let block_width = if self.else_block.is_some() || self.nested_if {
1059 let block_shape = Shape {
1064 let old_val = context.is_if_else_block.replace(self.else_block.is_some());
1066 rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
1067 context.is_if_else_block.replace(old_val);
1071 let mut result = format!("{}{}", cond_str, block_str);
1073 if let Some(else_block) = self.else_block {
1074 let shape = Shape::indented(shape.indent, context.config);
1075 let mut last_in_chain = false;
1076 let rewrite = match else_block.kind {
1077 // If the else expression is another if-else expression, prevent it
1078 // from being formatted on a single line.
1079 // Note how we're passing the original shape, as the
1080 // cost of "else" should not cascade.
1081 ast::ExprKind::If(ref cond, ref if_block, ref next_else_block) => {
1082 let (pats, cond) = extract_pats_and_cond(cond);
1083 ControlFlow::new_if(
1087 next_else_block.as_ref().map(|e| &**e),
1090 mk_sp(else_block.span.lo(), self.span.hi()),
1092 .rewrite(context, shape)
1095 last_in_chain = true;
1096 // When rewriting a block, the width is only used for single line
1097 // blocks, passing 1 lets us avoid that.
1098 let else_shape = Shape {
1099 width: min(1, shape.width),
1102 format_expr(else_block, ExprType::Statement, context, else_shape)
1106 let between_kwd_else_block = mk_sp(
1107 self.block.span.hi(),
1110 .span_before(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1112 let between_kwd_else_block_comment =
1113 extract_comment(between_kwd_else_block, context, shape);
1115 let after_else = mk_sp(
1118 .span_after(mk_sp(self.block.span.hi(), else_block.span.lo()), "else"),
1119 else_block.span.lo(),
1121 let after_else_comment = extract_comment(after_else, context, shape);
1123 let between_sep = match context.config.control_brace_style() {
1124 ControlBraceStyle::AlwaysNextLine | ControlBraceStyle::ClosingNextLine => {
1127 ControlBraceStyle::AlwaysSameLine => " ",
1129 let after_sep = match context.config.control_brace_style() {
1130 ControlBraceStyle::AlwaysNextLine if last_in_chain => &*alt_block_sep,
1134 result.push_str(&format!(
1136 between_kwd_else_block_comment
1138 .map_or(between_sep, |s| &**s),
1139 after_else_comment.as_ref().map_or(after_sep, |s| &**s),
1141 result.push_str(&rewrite?);
1148 fn rewrite_label(opt_label: Option<ast::Label>) -> Cow<'static, str> {
1150 Some(label) => Cow::from(format!("{}: ", label.ident)),
1151 None => Cow::from(""),
1155 fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1156 match rewrite_missing_comment(span, shape, context) {
1157 Some(ref comment) if !comment.is_empty() => Some(format!(
1158 "{indent}{}{indent}",
1160 indent = shape.indent.to_string_with_newline(context.config)
1166 pub(crate) fn block_contains_comment(context: &RewriteContext<'_>, block: &ast::Block) -> bool {
1167 contains_comment(context.snippet(block.span))
1170 // Checks that a block contains no statements, an expression and no comments or
1172 // FIXME: incorrectly returns false when comment is contained completely within
1174 pub(crate) fn is_simple_block(
1175 context: &RewriteContext<'_>,
1177 attrs: Option<&[ast::Attribute]>,
1179 block.stmts.len() == 1
1180 && stmt_is_expr(&block.stmts[0])
1181 && !block_contains_comment(context, block)
1182 && attrs.map_or(true, |a| a.is_empty())
1185 /// Checks whether a block contains at most one statement or expression, and no
1186 /// comments or attributes.
1187 pub(crate) fn is_simple_block_stmt(
1188 context: &RewriteContext<'_>,
1190 attrs: Option<&[ast::Attribute]>,
1192 block.stmts.len() <= 1
1193 && !block_contains_comment(context, block)
1194 && attrs.map_or(true, |a| a.is_empty())
1197 fn block_has_statements(block: &ast::Block) -> bool {
1201 .any(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
1204 /// Checks whether a block contains no statements, expressions, comments, or
1205 /// inner attributes.
1206 pub(crate) fn is_empty_block(
1207 context: &RewriteContext<'_>,
1209 attrs: Option<&[ast::Attribute]>,
1211 !block_has_statements(block)
1212 && !block_contains_comment(context, block)
1213 && attrs.map_or(true, |a| inner_attributes(a).is_empty())
1216 pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1217 matches!(stmt.kind, ast::StmtKind::Expr(..))
1220 pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1221 matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
1224 pub(crate) fn rewrite_literal(
1225 context: &RewriteContext<'_>,
1228 ) -> Option<String> {
1230 ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape),
1231 ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape),
1233 context.snippet(l.span).to_owned(),
1234 context.config.max_width(),
1240 fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option<String> {
1241 let string_lit = context.snippet(span);
1243 if !context.config.format_strings() {
1247 .all(|line| line.ends_with('\\'))
1248 && context.config.version() == Version::Two
1250 return Some(string_lit.to_owned());
1252 return wrap_str(string_lit.to_owned(), context.config.max_width(), shape);
1256 // Remove the quote characters.
1257 let str_lit = &string_lit[1..string_lit.len() - 1];
1261 &StringFormat::new(shape.visual_indent(0), context.config),
1262 shape.width.saturating_sub(2),
1266 fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option<String> {
1267 let span = lit.span;
1268 let symbol = lit.token.symbol.as_str();
1270 if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
1271 let hex_lit = match context.config.hex_literal_case() {
1272 HexLiteralCase::Preserve => None,
1273 HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
1274 HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
1276 if let Some(hex_lit) = hex_lit {
1281 lit.token.suffix.map_or(String::new(), |s| s.to_string())
1283 context.config.max_width(),
1290 context.snippet(span).to_owned(),
1291 context.config.max_width(),
1296 fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option<SeparatorTactic> {
1297 if context.inside_macro() {
1298 if span_ends_with_comma(context, span) {
1299 Some(SeparatorTactic::Always)
1301 Some(SeparatorTactic::Never)
1308 pub(crate) fn rewrite_call(
1309 context: &RewriteContext<'_>,
1311 args: &[ptr::P<ast::Expr>],
1314 ) -> Option<String> {
1315 overflow::rewrite_with_parens(
1321 context.config.fn_call_width(),
1322 choose_separator_tactic(context, span),
1326 pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool {
1328 ast::ExprKind::Lit(..) => true,
1329 ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1,
1330 ast::ExprKind::AddrOf(_, _, ref expr)
1331 | ast::ExprKind::Box(ref expr)
1332 | ast::ExprKind::Cast(ref expr, _)
1333 | ast::ExprKind::Field(ref expr, _)
1334 | ast::ExprKind::Try(ref expr)
1335 | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr),
1336 ast::ExprKind::Index(ref lhs, ref rhs) => is_simple_expr(lhs) && is_simple_expr(rhs),
1337 ast::ExprKind::Repeat(ref lhs, ref rhs) => {
1338 is_simple_expr(lhs) && is_simple_expr(&*rhs.value)
1344 pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool {
1345 lists.iter().all(OverflowableItem::is_simple)
1348 pub(crate) fn can_be_overflowed_expr(
1349 context: &RewriteContext<'_>,
1354 _ if !expr.attrs.is_empty() => false,
1355 ast::ExprKind::Match(..) => {
1356 (context.use_block_indent() && args_len == 1)
1357 || (context.config.indent_style() == IndentStyle::Visual && args_len > 1)
1358 || context.config.overflow_delimited_expr()
1360 ast::ExprKind::If(..)
1361 | ast::ExprKind::ForLoop(..)
1362 | ast::ExprKind::Loop(..)
1363 | ast::ExprKind::While(..) => {
1364 context.config.combine_control_expr() && context.use_block_indent() && args_len == 1
1367 // Handle always block-like expressions
1368 ast::ExprKind::Async(..) | ast::ExprKind::Block(..) | ast::ExprKind::Closure(..) => true,
1370 // Handle `[]` and `{}`-like expressions
1371 ast::ExprKind::Array(..) | ast::ExprKind::Struct(..) => {
1372 context.config.overflow_delimited_expr()
1373 || (context.use_block_indent() && args_len == 1)
1375 ast::ExprKind::MacCall(ref mac) => {
1377 rustc_ast::ast::MacDelimiter::from_token(mac.args.delim()),
1378 context.config.overflow_delimited_expr(),
1380 (Some(ast::MacDelimiter::Bracket), true)
1381 | (Some(ast::MacDelimiter::Brace), true) => true,
1382 _ => context.use_block_indent() && args_len == 1,
1386 // Handle parenthetical expressions
1387 ast::ExprKind::Call(..) | ast::ExprKind::MethodCall(..) | ast::ExprKind::Tup(..) => {
1388 context.use_block_indent() && args_len == 1
1391 // Handle unary-like expressions
1392 ast::ExprKind::AddrOf(_, _, ref expr)
1393 | ast::ExprKind::Box(ref expr)
1394 | ast::ExprKind::Try(ref expr)
1395 | ast::ExprKind::Unary(_, ref expr)
1396 | ast::ExprKind::Cast(ref expr, _) => can_be_overflowed_expr(context, expr, args_len),
1401 pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool {
1403 ast::ExprKind::Call(..) | ast::ExprKind::MacCall(..) => true,
1404 ast::ExprKind::AddrOf(_, _, ref expr)
1405 | ast::ExprKind::Box(ref expr)
1406 | ast::ExprKind::Try(ref expr)
1407 | ast::ExprKind::Unary(_, ref expr)
1408 | ast::ExprKind::Cast(ref expr, _) => is_nested_call(expr),
1413 /// Returns `true` if a function call or a method call represented by the given span ends with a
1414 /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
1415 /// comma from macro can potentially break the code.
1416 pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool {
1417 let mut result: bool = Default::default();
1418 let mut prev_char: char = Default::default();
1419 let closing_delimiters = &[')', '}', ']'];
1421 for (kind, c) in CharClasses::new(context.snippet(span).chars()) {
1423 _ if kind.is_comment() || c.is_whitespace() => continue,
1424 c if closing_delimiters.contains(&c) => {
1425 result &= !closing_delimiters.contains(&prev_char);
1427 ',' => result = true,
1428 _ => result = false,
1437 context: &RewriteContext<'_>,
1438 mut subexpr: &ast::Expr,
1441 ) -> Option<String> {
1442 debug!("rewrite_paren, shape: {:?}", shape);
1444 // Extract comments within parens.
1447 let mut pre_comment;
1448 let mut post_comment;
1449 let remove_nested_parens = context.config.remove_nested_parens();
1452 pre_span = mk_sp(span.lo() + BytePos(1), subexpr.span.lo());
1453 post_span = mk_sp(subexpr.span.hi(), span.hi() - BytePos(1));
1454 pre_comment = rewrite_missing_comment(pre_span, shape, context)?;
1455 post_comment = rewrite_missing_comment(post_span, shape, context)?;
1457 // Remove nested parens if there are no comments.
1458 if let ast::ExprKind::Paren(ref subsubexpr) = subexpr.kind {
1459 if remove_nested_parens && pre_comment.is_empty() && post_comment.is_empty() {
1460 span = subexpr.span;
1461 subexpr = subsubexpr;
1470 let sub_shape = shape.offset_left(1)?.sub_width(1)?;
1471 let subexpr_str = subexpr.rewrite(context, sub_shape)?;
1472 let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//");
1473 if fits_single_line {
1474 Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment))
1476 rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span)
1480 fn rewrite_paren_in_multi_line(
1481 context: &RewriteContext<'_>,
1482 subexpr: &ast::Expr,
1486 ) -> Option<String> {
1487 let nested_indent = shape.indent.block_indent(context.config);
1488 let nested_shape = Shape::indented(nested_indent, context.config);
1489 let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?;
1490 let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?;
1491 let subexpr_str = subexpr.rewrite(context, nested_shape)?;
1493 let mut result = String::with_capacity(subexpr_str.len() * 2);
1495 if !pre_comment.is_empty() {
1496 result.push_str(&nested_indent.to_string_with_newline(context.config));
1497 result.push_str(&pre_comment);
1499 result.push_str(&nested_indent.to_string_with_newline(context.config));
1500 result.push_str(&subexpr_str);
1501 if !post_comment.is_empty() {
1502 result.push_str(&nested_indent.to_string_with_newline(context.config));
1503 result.push_str(&post_comment);
1505 result.push_str(&shape.indent.to_string_with_newline(context.config));
1514 context: &RewriteContext<'_>,
1516 ) -> Option<String> {
1517 let expr_str = expr.rewrite(context, shape)?;
1519 let offset = last_line_width(&expr_str) + 1;
1520 let rhs_overhead = shape.rhs_overhead(context.config);
1521 let index_shape = if expr_str.contains('\n') {
1522 Shape::legacy(context.config.max_width(), shape.indent)
1523 .offset_left(offset)
1524 .and_then(|shape| shape.sub_width(1 + rhs_overhead))
1526 match context.config.indent_style() {
1527 IndentStyle::Block => shape
1528 .offset_left(offset)
1529 .and_then(|shape| shape.sub_width(1)),
1530 IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
1533 let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1535 // Return if index fits in a single line.
1536 match orig_index_rw {
1537 Some(ref index_str) if !index_str.contains('\n') => {
1538 return Some(format!("{}[{}]", expr_str, index_str));
1543 // Try putting index on the next line and see if it fits in a single line.
1544 let indent = shape.indent.block_indent(context.config);
1545 let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1546 let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1547 let new_index_rw = index.rewrite(context, index_shape);
1548 match (orig_index_rw, new_index_rw) {
1549 (_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1552 indent.to_string_with_newline(context.config),
1555 (None, Some(ref new_index_str)) => Some(format!(
1558 indent.to_string_with_newline(context.config),
1561 (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)),
1566 fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool {
1567 !has_base && fields.iter().all(|field| !field.is_shorthand)
1570 fn rewrite_struct_lit<'a>(
1571 context: &RewriteContext<'_>,
1573 qself: Option<&ast::QSelf>,
1574 fields: &'a [ast::ExprField],
1575 struct_rest: &ast::StructRest,
1576 attrs: &[ast::Attribute],
1579 ) -> Option<String> {
1580 debug!("rewrite_struct_lit: shape {:?}", shape);
1582 enum StructLitField<'a> {
1583 Regular(&'a ast::ExprField),
1584 Base(&'a ast::Expr),
1589 let path_shape = shape.sub_width(2)?;
1590 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
1592 let has_base_or_rest = match struct_rest {
1593 ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)),
1594 ast::StructRest::Rest(_) if fields.is_empty() => {
1595 return Some(format!("{} {{ .. }}", path_str));
1597 ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
1601 // Foo { a: Foo } - indent is +3, width is -5.
1602 let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
1604 let one_line_width = h_shape.map_or(0, |shape| shape.width);
1605 let body_lo = context.snippet_provider.span_after(span, "{");
1606 let fields_str = if struct_lit_can_be_aligned(fields, has_base_or_rest)
1607 && context.config.struct_field_align_threshold() > 0
1609 rewrite_with_alignment(
1613 mk_sp(body_lo, span.hi()),
1617 let field_iter = fields.iter().map(StructLitField::Regular).chain(
1619 ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)),
1620 ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)),
1621 ast::StructRest::None => None,
1626 let span_lo = |item: &StructLitField<'_>| match *item {
1627 StructLitField::Regular(field) => field.span().lo(),
1628 StructLitField::Base(expr) => {
1629 let last_field_hi = fields.last().map_or(span.lo(), |field| field.span.hi());
1630 let snippet = context.snippet(mk_sp(last_field_hi, expr.span.lo()));
1631 let pos = snippet.find_uncommented("..").unwrap();
1632 last_field_hi + BytePos(pos as u32)
1634 StructLitField::Rest(span) => span.lo(),
1636 let span_hi = |item: &StructLitField<'_>| match *item {
1637 StructLitField::Regular(field) => field.span().hi(),
1638 StructLitField::Base(expr) => expr.span.hi(),
1639 StructLitField::Rest(span) => span.hi(),
1641 let rewrite = |item: &StructLitField<'_>| match *item {
1642 StructLitField::Regular(field) => {
1643 // The 1 taken from the v_budget is for the comma.
1644 rewrite_field(context, field, v_shape.sub_width(1)?, 0)
1646 StructLitField::Base(expr) => {
1648 expr.rewrite(context, v_shape.offset_left(2)?)
1649 .map(|s| format!("..{}", s))
1651 StructLitField::Rest(_) => Some("..".to_owned()),
1654 let items = itemize_list(
1655 context.snippet_provider,
1666 let item_vec = items.collect::<Vec<_>>();
1668 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
1669 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
1671 let ends_with_comma = span_ends_with_comma(context, span);
1672 let force_no_trailing_comma = context.inside_macro() && !ends_with_comma;
1674 let fmt = struct_lit_formatting(
1678 force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
1681 write_list(&item_vec, &fmt)?
1685 wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
1686 Some(format!("{} {{{}}}", path_str, fields_str))
1688 // FIXME if context.config.indent_style() == Visual, but we run out
1689 // of space, we should fall back to BlockIndent.
1692 pub(crate) fn wrap_struct_field(
1693 context: &RewriteContext<'_>,
1694 attrs: &[ast::Attribute],
1697 nested_shape: Shape,
1698 one_line_width: usize,
1699 ) -> Option<String> {
1700 let should_vertical = context.config.indent_style() == IndentStyle::Block
1701 && (fields_str.contains('\n')
1702 || !context.config.struct_lit_single_line()
1703 || fields_str.len() > one_line_width);
1705 let inner_attrs = &inner_attributes(attrs);
1706 if inner_attrs.is_empty() {
1707 if should_vertical {
1710 nested_shape.indent.to_string_with_newline(context.config),
1712 shape.indent.to_string_with_newline(context.config)
1715 // One liner or visual indent.
1716 Some(format!(" {} ", fields_str))
1721 nested_shape.indent.to_string_with_newline(context.config),
1722 inner_attrs.rewrite(context, shape)?,
1723 nested_shape.indent.to_string_with_newline(context.config),
1725 shape.indent.to_string_with_newline(context.config)
1730 pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
1731 colon_spaces(config)
1734 pub(crate) fn rewrite_field(
1735 context: &RewriteContext<'_>,
1736 field: &ast::ExprField,
1738 prefix_max_width: usize,
1739 ) -> Option<String> {
1740 if contains_skip(&field.attrs) {
1741 return Some(context.snippet(field.span()).to_owned());
1743 let mut attrs_str = field.attrs.rewrite(context, shape)?;
1744 if !attrs_str.is_empty() {
1745 attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
1747 let name = context.snippet(field.ident.span);
1748 if field.is_shorthand {
1749 Some(attrs_str + name)
1751 let mut separator = String::from(struct_lit_field_separator(context.config));
1752 for _ in 0..prefix_max_width.saturating_sub(name.len()) {
1753 separator.push(' ');
1755 let overhead = name.len() + separator.len();
1756 let expr_shape = shape.offset_left(overhead)?;
1757 let expr = field.expr.rewrite(context, expr_shape);
1760 Some(ref e) if e.as_str() == name && context.config.use_field_init_shorthand() => {
1761 Some(attrs_str + name)
1763 Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)),
1765 let expr_offset = shape.indent.block_indent(context.config);
1768 .rewrite(context, Shape::indented(expr_offset, context.config));
1774 expr_offset.to_string(context.config),
1783 fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
1784 context: &RewriteContext<'_>,
1785 mut items: impl Iterator<Item = &'a T>,
1788 is_singleton_tuple: bool,
1789 ) -> Option<String> {
1790 // In case of length 1, need a trailing comma
1791 debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
1792 if is_singleton_tuple {
1794 let nested_shape = shape.sub_width(3)?.visual_indent(1);
1798 .rewrite(context, nested_shape)
1799 .map(|s| format!("({},)", s));
1802 let list_lo = context.snippet_provider.span_after(span, "(");
1803 let nested_shape = shape.sub_width(2)?.visual_indent(1);
1804 let items = itemize_list(
1805 context.snippet_provider,
1809 |item| item.span().lo(),
1810 |item| item.span().hi(),
1811 |item| item.rewrite(context, nested_shape),
1813 span.hi() - BytePos(1),
1816 let item_vec: Vec<_> = items.collect();
1817 let tactic = definitive_tactic(
1819 ListTactic::HorizontalVertical,
1823 let fmt = ListFormatting::new(nested_shape, context.config)
1825 .ends_with_newline(false);
1826 let list_str = write_list(&item_vec, &fmt)?;
1828 Some(format!("({})", list_str))
1831 pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
1832 context: &'a RewriteContext<'_>,
1833 items: impl Iterator<Item = &'a T>,
1836 is_singleton_tuple: bool,
1837 ) -> Option<String> {
1838 debug!("rewrite_tuple {:?}", shape);
1839 if context.use_block_indent() {
1840 // We use the same rule as function calls for rewriting tuples.
1841 let force_tactic = if context.inside_macro() {
1842 if span_ends_with_comma(context, span) {
1843 Some(SeparatorTactic::Always)
1845 Some(SeparatorTactic::Never)
1847 } else if is_singleton_tuple {
1848 Some(SeparatorTactic::Always)
1852 overflow::rewrite_with_parens(
1858 context.config.fn_call_width(),
1862 rewrite_tuple_in_visual_indent_style(context, items, span, shape, is_singleton_tuple)
1866 pub(crate) fn rewrite_unary_prefix<R: Rewrite>(
1867 context: &RewriteContext<'_>,
1871 ) -> Option<String> {
1873 .rewrite(context, shape.offset_left(prefix.len())?)
1874 .map(|r| format!("{}{}", prefix, r))
1877 // FIXME: this is probably not correct for multi-line Rewrites. we should
1878 // subtract suffix.len() from the last line budget, not the first!
1879 pub(crate) fn rewrite_unary_suffix<R: Rewrite>(
1880 context: &RewriteContext<'_>,
1884 ) -> Option<String> {
1886 .rewrite(context, shape.sub_width(suffix.len())?)
1893 fn rewrite_unary_op(
1894 context: &RewriteContext<'_>,
1898 ) -> Option<String> {
1899 // For some reason, an UnOp is not spanned like BinOp!
1900 rewrite_unary_prefix(context, ast::UnOp::to_string(op), expr, shape)
1903 pub(crate) enum RhsAssignKind<'ast> {
1904 Expr(&'ast ast::ExprKind, Span),
1909 impl<'ast> RhsAssignKind<'ast> {
1910 // TODO(calebcartwright)
1911 // Preemptive addition for handling RHS with chains, not yet utilized.
1912 // It may make more sense to construct the chain first and then check
1913 // whether there are actually chain elements.
1915 fn is_chain(&self) -> bool {
1917 RhsAssignKind::Expr(kind, _) => {
1920 ast::ExprKind::Try(..)
1921 | ast::ExprKind::Field(..)
1922 | ast::ExprKind::MethodCall(..)
1923 | ast::ExprKind::Await(_)
1931 fn rewrite_assignment(
1932 context: &RewriteContext<'_>,
1935 op: Option<&ast::BinOp>,
1937 ) -> Option<String> {
1938 let operator_str = match op {
1939 Some(op) => context.snippet(op.span),
1943 // 1 = space between lhs and operator.
1944 let lhs_shape = shape.sub_width(operator_str.len() + 1)?;
1945 let lhs_str = format!("{} {}", lhs.rewrite(context, lhs_shape)?, operator_str);
1951 &RhsAssignKind::Expr(&rhs.kind, rhs.span),
1956 /// Controls where to put the rhs.
1957 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1958 pub(crate) enum RhsTactics {
1961 /// Put the rhs on the next line if it uses multiple line, without extra indentation.
1962 ForceNextLineWithoutIndent,
1963 /// Allow overflowing max width if neither `Default` nor `ForceNextLineWithoutIndent`
1968 // The left hand side must contain everything up to, and including, the
1969 // assignment operator.
1970 pub(crate) fn rewrite_assign_rhs<S: Into<String>, R: Rewrite>(
1971 context: &RewriteContext<'_>,
1974 rhs_kind: &RhsAssignKind<'_>,
1976 ) -> Option<String> {
1977 rewrite_assign_rhs_with(context, lhs, ex, shape, rhs_kind, RhsTactics::Default)
1980 pub(crate) fn rewrite_assign_rhs_expr<R: Rewrite>(
1981 context: &RewriteContext<'_>,
1985 rhs_kind: &RhsAssignKind<'_>,
1986 rhs_tactics: RhsTactics,
1987 ) -> Option<String> {
1988 let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
1989 shape.indent.width()
1993 // 1 = space between operator and rhs.
1994 let orig_shape = shape.offset_left(last_line_width + 1).unwrap_or(Shape {
1996 offset: shape.offset + last_line_width + 1,
1999 let has_rhs_comment = if let Some(offset) = lhs.find_last_uncommented("=") {
2000 lhs.trim_end().len() > offset + 1
2009 ex.rewrite(context, orig_shape),
2016 pub(crate) fn rewrite_assign_rhs_with<S: Into<String>, R: Rewrite>(
2017 context: &RewriteContext<'_>,
2021 rhs_kind: &RhsAssignKind<'_>,
2022 rhs_tactics: RhsTactics,
2023 ) -> Option<String> {
2024 let lhs = lhs.into();
2025 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2029 pub(crate) fn rewrite_assign_rhs_with_comments<S: Into<String>, R: Rewrite>(
2030 context: &RewriteContext<'_>,
2034 rhs_kind: &RhsAssignKind<'_>,
2035 rhs_tactics: RhsTactics,
2038 ) -> Option<String> {
2039 let lhs = lhs.into();
2040 let contains_comment = contains_comment(context.snippet(between_span));
2041 let shape = if contains_comment {
2042 shape.block_left(context.config.tab_spaces())?
2046 let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?;
2048 if contains_comment {
2049 let rhs = rhs.trim_start();
2050 combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
2056 fn choose_rhs<R: Rewrite>(
2057 context: &RewriteContext<'_>,
2060 orig_rhs: Option<String>,
2061 _rhs_kind: &RhsAssignKind<'_>,
2062 rhs_tactics: RhsTactics,
2063 has_rhs_comment: bool,
2064 ) -> Option<String> {
2066 Some(ref new_str) if new_str.is_empty() => Some(String::new()),
2068 if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
2070 Some(format!(" {}", new_str))
2073 // Expression did not fit on the same line as the identifier.
2074 // Try splitting the line and see if that works better.
2075 let new_shape = shape_from_rhs_tactic(context, shape, rhs_tactics)?;
2076 let new_rhs = expr.rewrite(context, new_shape);
2077 let new_indent_str = &shape
2079 .block_indent(context.config)
2080 .to_string_with_newline(context.config);
2081 let before_space_str = if has_rhs_comment { "" } else { " " };
2083 match (orig_rhs, new_rhs) {
2084 (Some(ref orig_rhs), Some(ref new_rhs))
2085 if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape)
2088 Some(format!("{}{}", before_space_str, orig_rhs))
2090 (Some(ref orig_rhs), Some(ref new_rhs))
2091 if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) =>
2093 Some(format!("{}{}", new_indent_str, new_rhs))
2095 (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)),
2096 (None, None) if rhs_tactics == RhsTactics::AllowOverflow => {
2097 let shape = shape.infinite_width();
2098 expr.rewrite(context, shape)
2099 .map(|s| format!("{}{}", before_space_str, s))
2101 (None, None) => None,
2102 (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)),
2108 fn shape_from_rhs_tactic(
2109 context: &RewriteContext<'_>,
2111 rhs_tactic: RhsTactics,
2112 ) -> Option<Shape> {
2114 RhsTactics::ForceNextLineWithoutIndent => shape
2115 .with_max_width(context.config)
2116 .sub_width(shape.indent.width()),
2117 RhsTactics::Default | RhsTactics::AllowOverflow => {
2118 Shape::indented(shape.indent.block_indent(context.config), context.config)
2119 .sub_width(shape.rhs_overhead(context.config))
2124 /// Returns true if formatting next_line_rhs is better on a new line when compared to the
2125 /// original's line formatting.
2127 /// It is considered better if:
2128 /// 1. the tactic is ForceNextLineWithoutIndent
2129 /// 2. next_line_rhs doesn't have newlines
2130 /// 3. the original line has more newlines than next_line_rhs
2131 /// 4. the original formatting of the first line ends with `(`, `{`, or `[` and next_line_rhs
2133 pub(crate) fn prefer_next_line(
2135 next_line_rhs: &str,
2136 rhs_tactics: RhsTactics,
2138 rhs_tactics == RhsTactics::ForceNextLineWithoutIndent
2139 || !next_line_rhs.contains('\n')
2140 || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1
2141 || first_line_ends_with(orig_rhs, '(') && !first_line_ends_with(next_line_rhs, '(')
2142 || first_line_ends_with(orig_rhs, '{') && !first_line_ends_with(next_line_rhs, '{')
2143 || first_line_ends_with(orig_rhs, '[') && !first_line_ends_with(next_line_rhs, '[')
2146 fn rewrite_expr_addrof(
2147 context: &RewriteContext<'_>,
2148 borrow_kind: ast::BorrowKind,
2149 mutability: ast::Mutability,
2152 ) -> Option<String> {
2153 let operator_str = match (mutability, borrow_kind) {
2154 (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
2155 (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
2156 (ast::Mutability::Mut, ast::BorrowKind::Ref) => "&mut ",
2157 (ast::Mutability::Mut, ast::BorrowKind::Raw) => "&raw mut ",
2159 rewrite_unary_prefix(context, operator_str, expr, shape)
2162 pub(crate) fn is_method_call(expr: &ast::Expr) -> bool {
2164 ast::ExprKind::MethodCall(..) => true,
2165 ast::ExprKind::AddrOf(_, _, ref expr)
2166 | ast::ExprKind::Box(ref expr)
2167 | ast::ExprKind::Cast(ref expr, _)
2168 | ast::ExprKind::Try(ref expr)
2169 | ast::ExprKind::Unary(_, ref expr) => is_method_call(expr),
2176 use super::last_line_offsetted;
2179 fn test_last_line_offsetted() {
2180 let lines = "one\n two";
2181 assert_eq!(last_line_offsetted(2, lines), true);
2182 assert_eq!(last_line_offsetted(4, lines), false);
2183 assert_eq!(last_line_offsetted(6, lines), false);
2185 let lines = "one two";
2186 assert_eq!(last_line_offsetted(2, lines), false);
2187 assert_eq!(last_line_offsetted(0, lines), false);
2189 let lines = "\ntwo";
2190 assert_eq!(last_line_offsetted(2, lines), false);
2191 assert_eq!(last_line_offsetted(0, lines), false);
2193 let lines = "one\n two three";
2194 assert_eq!(last_line_offsetted(2, lines), true);
2195 let lines = "one\n two three";
2196 assert_eq!(last_line_offsetted(2, lines), false);