2 self, BindingAnnotation, ByRef, Pat, PatField, PatKind, RangeEnd, RangeSyntax,
5 use rustc_span::{BytePos, Span};
7 use crate::comment::{combine_strs_with_missing_comments, FindUncommented};
8 use crate::config::lists::*;
9 use crate::config::Version;
10 use crate::expr::{can_be_overflowed_expr, rewrite_unary_prefix, wrap_struct_field};
12 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
13 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
15 use crate::macros::{rewrite_macro, MacroPosition};
17 use crate::pairs::{rewrite_pair, PairParts};
18 use crate::rewrite::{Rewrite, RewriteContext};
19 use crate::shape::Shape;
20 use crate::source_map::SpanUtils;
21 use crate::spanned::Spanned;
22 use crate::types::{rewrite_path, PathContext};
23 use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident};
25 /// Returns `true` if the given pattern is "short".
26 /// A short pattern is defined by the following grammar:
30 /// - `&[single-line, ntp]`
34 /// - unary tuple constructor `([small, ntp])`
36 pub(crate) fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
37 // We also require that the pattern is reasonably 'small' with its literal width.
38 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
41 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
43 ast::PatKind::Rest | ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
44 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
45 ast::PatKind::Struct(..)
46 | ast::PatKind::MacCall(..)
47 | ast::PatKind::Slice(..)
48 | ast::PatKind::Path(..)
49 | ast::PatKind::Range(..) => false,
50 ast::PatKind::Tuple(ref subpats) => subpats.len() <= 1,
51 ast::PatKind::TupleStruct(_, ref path, ref subpats) => {
52 path.segments.len() <= 1 && subpats.len() <= 1
54 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
55 is_short_pattern_inner(&*p)
57 PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)),
61 struct RangeOperand<'a>(&'a Option<ptr::P<ast::Expr>>);
63 impl<'a> Rewrite for RangeOperand<'a> {
64 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
66 None => Some("".to_owned()),
67 Some(ref exp) => exp.rewrite(context, shape),
72 impl Rewrite for Pat {
73 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
75 PatKind::Or(ref pats) => {
78 .map(|p| p.rewrite(context, shape))
79 .collect::<Option<Vec<_>>>()?;
81 let use_mixed_layout = pats
84 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
85 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
86 let tactic = if use_mixed_layout {
87 DefinitiveListTactic::Mixed
91 ListTactic::HorizontalVertical,
92 Separator::VerticalBar,
96 let fmt = ListFormatting::new(shape, context.config)
99 .separator_place(context.config.binop_separator())
100 .ends_with_newline(false);
101 write_list(&items, &fmt)
103 PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
104 PatKind::Ident(BindingAnnotation(by_ref, mutability), ident, ref sub_pat) => {
105 let prefix = match by_ref {
109 let mut_infix = format_mutability(mutability).trim();
110 let id_str = rewrite_ident(context, ident);
111 let sub_pat = match *sub_pat {
116 .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 2)?;
117 let lo = context.snippet_provider.span_after(self.span, "@");
118 combine_strs_with_missing_comments(
121 &p.rewrite(context, Shape::legacy(width, shape.indent))?,
122 mk_sp(lo, p.span.lo()),
127 None => "".to_owned(),
130 // combine prefix and mut
131 let (first_lo, first) = if !prefix.is_empty() && !mut_infix.is_empty() {
132 let hi = context.snippet_provider.span_before(self.span, "mut");
133 let lo = context.snippet_provider.span_after(self.span, "ref");
135 context.snippet_provider.span_after(self.span, "mut"),
136 combine_strs_with_missing_comments(
145 } else if !prefix.is_empty() {
147 context.snippet_provider.span_after(self.span, "ref"),
150 } else if !mut_infix.is_empty() {
152 context.snippet_provider.span_after(self.span, "mut"),
153 mut_infix.to_owned(),
156 (self.span.lo(), "".to_owned())
159 let next = if !sub_pat.is_empty() {
160 let hi = context.snippet_provider.span_before(self.span, "@");
161 combine_strs_with_missing_comments(
165 mk_sp(ident.span.hi(), hi),
173 combine_strs_with_missing_comments(
177 mk_sp(first_lo, ident.span.lo()),
183 if 1 <= shape.width {
190 if 1 <= shape.width {
191 Some("..".to_owned())
196 PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
197 let infix = match end_kind.node {
198 RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
199 RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
200 RangeEnd::Excluded => "..",
202 let infix = if context.config.spaces_around_ranges() {
203 let lhs_spacing = match lhs {
207 let rhs_spacing = match rhs {
211 format!("{}{}{}", lhs_spacing, infix, rhs_spacing)
218 PairParts::infix(&infix),
221 SeparatorPlace::Front,
224 PatKind::Ref(ref pat, mutability) => {
225 let prefix = format!("&{}", format_mutability(mutability));
226 rewrite_unary_prefix(context, &prefix, &**pat, shape)
228 PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape),
229 PatKind::Path(ref q_self, ref path) => {
230 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
232 PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
234 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)?;
235 rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
237 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
238 PatKind::Slice(ref slice_pat) if context.config.version() == Version::One => {
239 let rw: Vec<String> = slice_pat
242 if let Some(rw) = p.rewrite(context, shape) {
245 context.snippet(p.span).to_string()
249 Some(format!("[{}]", rw.join(", ")))
251 PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
260 PatKind::Struct(ref qself, ref path, ref fields, ellipsis) => {
261 rewrite_struct_pat(qself, path, fields, ellipsis, self.span, context, shape)
263 PatKind::MacCall(ref mac) => {
264 rewrite_macro(mac, None, context, shape, MacroPosition::Pat)
266 PatKind::Paren(ref pat) => pat
267 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
268 .map(|inner_pat| format!("({})", inner_pat)),
273 fn rewrite_struct_pat(
274 qself: &Option<ast::QSelf>,
276 fields: &[ast::PatField],
279 context: &RewriteContext<'_>,
281 ) -> Option<String> {
283 let path_shape = shape.sub_width(2)?;
284 let path_str = rewrite_path(context, PathContext::Expr, qself.as_ref(), path, path_shape)?;
286 if fields.is_empty() && !ellipsis {
287 return Some(format!("{} {{}}", path_str));
290 let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
292 // 3 = ` { `, 2 = ` }`.
293 let (h_shape, v_shape) =
294 struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
296 let items = itemize_list(
297 context.snippet_provider,
302 if f.attrs.is_empty() {
305 f.attrs.first().unwrap().span.lo()
309 |f| f.rewrite(context, v_shape),
310 context.snippet_provider.span_after(span, "{"),
314 let item_vec = items.collect::<Vec<_>>();
316 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
317 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
318 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
320 let mut fields_str = write_list(&item_vec, &fmt)?;
321 let one_line_width = h_shape.map_or(0, |shape| shape.width);
323 let has_trailing_comma = fmt.needs_trailing_separator();
326 if fields_str.contains('\n') || fields_str.len() > one_line_width {
327 // Add a missing trailing comma.
328 if !has_trailing_comma {
329 fields_str.push(',');
331 fields_str.push('\n');
332 fields_str.push_str(&nested_shape.indent.to_string(context.config));
334 if !fields_str.is_empty() {
335 // there are preceding struct fields being matched on
336 if has_trailing_comma {
337 fields_str.push(' ');
339 fields_str.push_str(", ");
343 fields_str.push_str("..");
346 // ast::Pat doesn't have attrs so use &[]
347 let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
348 Some(format!("{} {{{}}}", path_str, fields_str))
351 impl Rewrite for PatField {
352 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
353 let hi_pos = if let Some(last) = self.attrs.last() {
359 let attrs_str = if self.attrs.is_empty() {
362 self.attrs.rewrite(context, shape)?
365 let pat_str = self.pat.rewrite(context, shape)?;
366 if self.is_shorthand {
367 combine_strs_with_missing_comments(
371 mk_sp(hi_pos, self.pat.span.lo()),
376 let nested_shape = shape.block_indent(context.config.tab_spaces());
377 let id_str = rewrite_ident(context, self.ident);
378 let one_line_width = id_str.len() + 2 + pat_str.len();
379 let pat_and_id_str = if one_line_width <= shape.width {
380 format!("{}: {}", id_str, pat_str)
385 nested_shape.indent.to_string(context.config),
386 self.pat.rewrite(context, nested_shape)?
389 combine_strs_with_missing_comments(
393 mk_sp(hi_pos, self.pat.span.lo()),
402 pub(crate) enum TuplePatField<'a> {
403 Pat(&'a ptr::P<ast::Pat>),
407 impl<'a> Rewrite for TuplePatField<'a> {
408 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
410 TuplePatField::Pat(p) => p.rewrite(context, shape),
411 TuplePatField::Dotdot(_) => Some("..".to_string()),
416 impl<'a> Spanned for TuplePatField<'a> {
417 fn span(&self) -> Span {
419 TuplePatField::Pat(p) => p.span(),
420 TuplePatField::Dotdot(span) => span,
425 impl<'a> TuplePatField<'a> {
426 fn is_dotdot(&self) -> bool {
428 TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest),
429 TuplePatField::Dotdot(_) => true,
434 pub(crate) fn can_be_overflowed_pat(
435 context: &RewriteContext<'_>,
436 pat: &TuplePatField<'_>,
440 TuplePatField::Pat(pat) => match pat.kind {
441 ast::PatKind::Path(..)
442 | ast::PatKind::Tuple(..)
443 | ast::PatKind::Struct(..)
444 | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
445 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
446 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
448 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
451 TuplePatField::Dotdot(..) => false,
455 fn rewrite_tuple_pat(
456 pats: &[ptr::P<ast::Pat>],
457 path_str: Option<String>,
459 context: &RewriteContext<'_>,
461 ) -> Option<String> {
463 return Some(format!("{}()", path_str.unwrap_or_default()));
465 let mut pat_vec: Vec<_> = pats.iter().map(TuplePatField::Pat).collect();
467 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
468 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
470 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
471 let sp = pat_vec[new_item_count - 1].span();
472 let snippet = context.snippet(sp);
473 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
474 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp_lo_plus_one(lo));
476 &pat_vec[..new_item_count],
477 mk_sp(span.lo(), lo + BytePos(1)),
483 let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
484 let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
485 let path_str = path_str.unwrap_or_default();
487 overflow::rewrite_with_parens(
493 context.config.max_width(),
495 Some(SeparatorTactic::Always)
502 fn count_wildcard_suffix_len(
503 context: &RewriteContext<'_>,
504 patterns: &[TuplePatField<'_>],
508 let mut suffix_len = 0;
510 let items: Vec<_> = itemize_list(
511 context.snippet_provider,
515 |item| item.span().lo(),
516 |item| item.span().hi(),
517 |item| item.rewrite(context, shape),
518 context.snippet_provider.span_after(span, "("),
519 span.hi() - BytePos(1),
527 .take_while(|i| matches!(i.item, Some(ref internal_string) if internal_string == "_"))
531 if item.has_comment() {