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, path, shape)
232 PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
233 let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?;
234 rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
236 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
237 PatKind::Slice(ref slice_pat) if context.config.version() == Version::One => {
238 let rw: Vec<String> = slice_pat
241 if let Some(rw) = p.rewrite(context, shape) {
244 context.snippet(p.span).to_string()
248 Some(format!("[{}]", rw.join(", ")))
250 PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
259 PatKind::Struct(ref qself, ref path, ref fields, ellipsis) => {
260 rewrite_struct_pat(qself, path, fields, ellipsis, self.span, context, shape)
262 PatKind::MacCall(ref mac) => {
263 rewrite_macro(mac, None, context, shape, MacroPosition::Pat)
265 PatKind::Paren(ref pat) => pat
266 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
267 .map(|inner_pat| format!("({})", inner_pat)),
272 fn rewrite_struct_pat(
273 qself: &Option<ptr::P<ast::QSelf>>,
275 fields: &[ast::PatField],
278 context: &RewriteContext<'_>,
280 ) -> Option<String> {
282 let path_shape = shape.sub_width(2)?;
283 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
285 if fields.is_empty() && !ellipsis {
286 return Some(format!("{} {{}}", path_str));
289 let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
291 // 3 = ` { `, 2 = ` }`.
292 let (h_shape, v_shape) =
293 struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
295 let items = itemize_list(
296 context.snippet_provider,
301 if f.attrs.is_empty() {
304 f.attrs.first().unwrap().span.lo()
308 |f| f.rewrite(context, v_shape),
309 context.snippet_provider.span_after(span, "{"),
313 let item_vec = items.collect::<Vec<_>>();
315 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
316 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
317 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
319 let mut fields_str = write_list(&item_vec, &fmt)?;
320 let one_line_width = h_shape.map_or(0, |shape| shape.width);
322 let has_trailing_comma = fmt.needs_trailing_separator();
325 if fields_str.contains('\n') || fields_str.len() > one_line_width {
326 // Add a missing trailing comma.
327 if !has_trailing_comma {
328 fields_str.push(',');
330 fields_str.push('\n');
331 fields_str.push_str(&nested_shape.indent.to_string(context.config));
333 if !fields_str.is_empty() {
334 // there are preceding struct fields being matched on
335 if has_trailing_comma {
336 fields_str.push(' ');
338 fields_str.push_str(", ");
342 fields_str.push_str("..");
345 // ast::Pat doesn't have attrs so use &[]
346 let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
347 Some(format!("{} {{{}}}", path_str, fields_str))
350 impl Rewrite for PatField {
351 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
352 let hi_pos = if let Some(last) = self.attrs.last() {
358 let attrs_str = if self.attrs.is_empty() {
361 self.attrs.rewrite(context, shape)?
364 let pat_str = self.pat.rewrite(context, shape)?;
365 if self.is_shorthand {
366 combine_strs_with_missing_comments(
370 mk_sp(hi_pos, self.pat.span.lo()),
375 let nested_shape = shape.block_indent(context.config.tab_spaces());
376 let id_str = rewrite_ident(context, self.ident);
377 let one_line_width = id_str.len() + 2 + pat_str.len();
378 let pat_and_id_str = if one_line_width <= shape.width {
379 format!("{}: {}", id_str, pat_str)
384 nested_shape.indent.to_string(context.config),
385 self.pat.rewrite(context, nested_shape)?
388 combine_strs_with_missing_comments(
392 mk_sp(hi_pos, self.pat.span.lo()),
401 pub(crate) enum TuplePatField<'a> {
402 Pat(&'a ptr::P<ast::Pat>),
406 impl<'a> Rewrite for TuplePatField<'a> {
407 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
409 TuplePatField::Pat(p) => p.rewrite(context, shape),
410 TuplePatField::Dotdot(_) => Some("..".to_string()),
415 impl<'a> Spanned for TuplePatField<'a> {
416 fn span(&self) -> Span {
418 TuplePatField::Pat(p) => p.span(),
419 TuplePatField::Dotdot(span) => span,
424 impl<'a> TuplePatField<'a> {
425 fn is_dotdot(&self) -> bool {
427 TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest),
428 TuplePatField::Dotdot(_) => true,
433 pub(crate) fn can_be_overflowed_pat(
434 context: &RewriteContext<'_>,
435 pat: &TuplePatField<'_>,
439 TuplePatField::Pat(pat) => match pat.kind {
440 ast::PatKind::Path(..)
441 | ast::PatKind::Tuple(..)
442 | ast::PatKind::Struct(..)
443 | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
444 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
445 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
447 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
450 TuplePatField::Dotdot(..) => false,
454 fn rewrite_tuple_pat(
455 pats: &[ptr::P<ast::Pat>],
456 path_str: Option<String>,
458 context: &RewriteContext<'_>,
460 ) -> Option<String> {
462 return Some(format!("{}()", path_str.unwrap_or_default()));
464 let mut pat_vec: Vec<_> = pats.iter().map(TuplePatField::Pat).collect();
466 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
467 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
469 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
470 let sp = pat_vec[new_item_count - 1].span();
471 let snippet = context.snippet(sp);
472 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
473 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp_lo_plus_one(lo));
475 &pat_vec[..new_item_count],
476 mk_sp(span.lo(), lo + BytePos(1)),
482 let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
483 let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
484 let path_str = path_str.unwrap_or_default();
486 overflow::rewrite_with_parens(
492 context.config.max_width(),
494 Some(SeparatorTactic::Always)
501 fn count_wildcard_suffix_len(
502 context: &RewriteContext<'_>,
503 patterns: &[TuplePatField<'_>],
507 let mut suffix_len = 0;
509 let items: Vec<_> = itemize_list(
510 context.snippet_provider,
514 |item| item.span().lo(),
515 |item| item.span().hi(),
516 |item| item.rewrite(context, shape),
517 context.snippet_provider.span_after(span, "("),
518 span.hi() - BytePos(1),
526 .take_while(|i| matches!(i.item, Some(ref internal_string) if internal_string == "_"))
530 if item.has_comment() {