1use rustc_ast::ast::{self, BindingMode, ByRef, Pat, PatField, PatKind, RangeEnd, RangeSyntax};
2use rustc_ast::ptr;
3use rustc_span::{BytePos, Span};
4
5use crate::comment::{FindUncommented, combine_strs_with_missing_comments};
6use crate::config::StyleEdition;
7use crate::config::lists::*;
8use crate::expr::{can_be_overflowed_expr, rewrite_unary_prefix, wrap_struct_field};
9use crate::lists::{
10 ListFormatting, ListItem, Separator, definitive_tactic, itemize_list, shape_for_tactic,
11 struct_lit_formatting, struct_lit_shape, struct_lit_tactic, write_list,
12};
13use crate::macros::{MacroPosition, rewrite_macro};
14use crate::overflow;
15use crate::pairs::{PairParts, rewrite_pair};
16use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
17use crate::shape::Shape;
18use crate::source_map::SpanUtils;
19use crate::spanned::Spanned;
20use crate::types::{PathContext, rewrite_path};
21use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident};
22
23pub(crate) fn is_short_pattern(
35 context: &RewriteContext<'_>,
36 pat: &ast::Pat,
37 pat_str: &str,
38) -> bool {
39 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(context, pat)
41}
42
43fn is_short_pattern_inner(context: &RewriteContext<'_>, pat: &ast::Pat) -> bool {
44 match &pat.kind {
45 ast::PatKind::Rest | ast::PatKind::Never | ast::PatKind::Wild | ast::PatKind::Err(_) => {
46 true
47 }
48 ast::PatKind::Expr(expr) => match &expr.kind {
49 ast::ExprKind::Lit(_) => true,
50 ast::ExprKind::Unary(ast::UnOp::Neg, expr) => match &expr.kind {
51 ast::ExprKind::Lit(_) => true,
52 _ => unreachable!(),
53 },
54 ast::ExprKind::ConstBlock(_) | ast::ExprKind::Path(..) => {
55 context.config.style_edition() <= StyleEdition::Edition2024
56 }
57 _ => unreachable!(),
58 },
59 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
60 ast::PatKind::Struct(..)
61 | ast::PatKind::MacCall(..)
62 | ast::PatKind::Slice(..)
63 | ast::PatKind::Path(..)
64 | ast::PatKind::Range(..)
65 | ast::PatKind::Guard(..) => false,
66 ast::PatKind::Tuple(ref subpats) => subpats.len() <= 1,
67 ast::PatKind::TupleStruct(_, ref path, ref subpats) => {
68 path.segments.len() <= 1 && subpats.len() <= 1
69 }
70 ast::PatKind::Box(ref p)
71 | PatKind::Deref(ref p)
72 | ast::PatKind::Ref(ref p, _)
73 | ast::PatKind::Paren(ref p) => is_short_pattern_inner(context, &*p),
74 PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(context, p)),
75 }
76}
77
78pub(crate) struct RangeOperand<'a, T> {
79 pub operand: &'a Option<ptr::P<T>>,
80 pub span: Span,
81}
82
83impl<'a, T: Rewrite> Rewrite for RangeOperand<'a, T> {
84 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
85 self.rewrite_result(context, shape).ok()
86 }
87
88 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
89 match &self.operand {
90 None => Ok("".to_owned()),
91 Some(ref exp) => exp.rewrite_result(context, shape),
92 }
93 }
94}
95
96impl Rewrite for Pat {
97 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
98 self.rewrite_result(context, shape).ok()
99 }
100
101 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
102 match self.kind {
103 PatKind::Or(ref pats) => {
104 let pat_strs = pats
105 .iter()
106 .map(|p| p.rewrite_result(context, shape))
107 .collect::<Result<Vec<_>, RewriteError>>()?;
108
109 let use_mixed_layout = pats
110 .iter()
111 .zip(pat_strs.iter())
112 .all(|(pat, pat_str)| is_short_pattern(context, pat, pat_str));
113 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
114 let tactic = if use_mixed_layout {
115 DefinitiveListTactic::Mixed
116 } else {
117 definitive_tactic(
118 &items,
119 ListTactic::HorizontalVertical,
120 Separator::VerticalBar,
121 shape.width,
122 )
123 };
124 let fmt = ListFormatting::new(shape, context.config)
125 .tactic(tactic)
126 .separator(" |")
127 .separator_place(context.config.binop_separator())
128 .ends_with_newline(false);
129 write_list(&items, &fmt)
130 }
131 PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
132 PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => {
133 let mut_prefix = format_mutability(mutability).trim();
134
135 let (ref_kw, mut_infix) = match by_ref {
136 ByRef::Yes(rmutbl) => ("ref", format_mutability(rmutbl).trim()),
137 ByRef::No => ("", ""),
138 };
139 let id_str = rewrite_ident(context, ident);
140 let sub_pat = match *sub_pat {
141 Some(ref p) => {
142 let width = shape
144 .width
145 .checked_sub(
146 mut_prefix.len()
147 + ref_kw.len()
148 + mut_infix.len()
149 + id_str.len()
150 + 2,
151 )
152 .max_width_error(shape.width, p.span())?;
153 let lo = context.snippet_provider.span_after(self.span, "@");
154 combine_strs_with_missing_comments(
155 context,
156 "@",
157 &p.rewrite_result(context, Shape::legacy(width, shape.indent))?,
158 mk_sp(lo, p.span.lo()),
159 shape,
160 true,
161 )?
162 }
163 None => "".to_owned(),
164 };
165
166 let (first_lo, first) = match (mut_prefix.is_empty(), ref_kw.is_empty()) {
168 (false, false) => {
169 let lo = context.snippet_provider.span_after(self.span, "mut");
170 let hi = context.snippet_provider.span_before(self.span, "ref");
171 (
172 context.snippet_provider.span_after(self.span, "ref"),
173 combine_strs_with_missing_comments(
174 context,
175 mut_prefix,
176 ref_kw,
177 mk_sp(lo, hi),
178 shape,
179 true,
180 )?,
181 )
182 }
183 (false, true) => (
184 context.snippet_provider.span_after(self.span, "mut"),
185 mut_prefix.to_owned(),
186 ),
187 (true, false) => (
188 context.snippet_provider.span_after(self.span, "ref"),
189 ref_kw.to_owned(),
190 ),
191 (true, true) => (self.span.lo(), "".to_owned()),
192 };
193
194 let (second_lo, second) = match (first.is_empty(), mut_infix.is_empty()) {
196 (false, false) => {
197 let lo = context.snippet_provider.span_after(self.span, "ref");
198 let end_span = mk_sp(first_lo, self.span.hi());
199 let hi = context.snippet_provider.span_before(end_span, "mut");
200 (
201 context.snippet_provider.span_after(end_span, "mut"),
202 combine_strs_with_missing_comments(
203 context,
204 &first,
205 mut_infix,
206 mk_sp(lo, hi),
207 shape,
208 true,
209 )?,
210 )
211 }
212 (false, true) => (first_lo, first),
213 (true, false) => unreachable!("mut_infix necessarily follows a ref"),
214 (true, true) => (self.span.lo(), "".to_owned()),
215 };
216
217 let next = if !sub_pat.is_empty() {
218 let hi = context.snippet_provider.span_before(self.span, "@");
219 combine_strs_with_missing_comments(
220 context,
221 id_str,
222 &sub_pat,
223 mk_sp(ident.span.hi(), hi),
224 shape,
225 true,
226 )?
227 } else {
228 id_str.to_owned()
229 };
230
231 combine_strs_with_missing_comments(
232 context,
233 &second,
234 &next,
235 mk_sp(second_lo, ident.span.lo()),
236 shape,
237 true,
238 )
239 }
240 PatKind::Wild => {
241 if 1 <= shape.width {
242 Ok("_".to_owned())
243 } else {
244 Err(RewriteError::ExceedsMaxWidth {
245 configured_width: 1,
246 span: self.span,
247 })
248 }
249 }
250 PatKind::Rest => {
251 if 1 <= shape.width {
252 Ok("..".to_owned())
253 } else {
254 Err(RewriteError::ExceedsMaxWidth {
255 configured_width: 1,
256 span: self.span,
257 })
258 }
259 }
260 PatKind::Never => Err(RewriteError::Unknown),
261 PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
262 rewrite_range_pat(context, shape, lhs, rhs, end_kind, self.span)
263 }
264 PatKind::Ref(ref pat, mutability) => {
265 let prefix = format!("&{}", format_mutability(mutability));
266 rewrite_unary_prefix(context, &prefix, &**pat, shape)
267 }
268 PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape),
269 PatKind::Path(ref q_self, ref path) => {
270 rewrite_path(context, PathContext::Expr, q_self, path, shape)
271 }
272 PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
273 let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?;
274 rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
275 }
276 PatKind::Expr(ref expr) => expr.rewrite_result(context, shape),
277 PatKind::Slice(ref slice_pat)
278 if context.config.style_edition() <= StyleEdition::Edition2021 =>
279 {
280 let rw: Vec<String> = slice_pat
281 .iter()
282 .map(|p| {
283 if let Ok(rw) = p.rewrite_result(context, shape) {
284 rw
285 } else {
286 context.snippet(p.span).to_string()
287 }
288 })
289 .collect();
290 Ok(format!("[{}]", rw.join(", ")))
291 }
292 PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
293 context,
294 "",
295 slice_pat.iter(),
296 shape,
297 self.span,
298 None,
299 None,
300 ),
301 PatKind::Struct(ref qself, ref path, ref fields, rest) => rewrite_struct_pat(
302 qself,
303 path,
304 fields,
305 rest == ast::PatFieldsRest::Rest,
306 self.span,
307 context,
308 shape,
309 ),
310 PatKind::MacCall(ref mac) => {
311 rewrite_macro(mac, None, context, shape, MacroPosition::Pat)
312 }
313 PatKind::Paren(ref pat) => pat
314 .rewrite_result(
315 context,
316 shape
317 .offset_left(1)
318 .and_then(|s| s.sub_width(1))
319 .max_width_error(shape.width, self.span)?,
320 )
321 .map(|inner_pat| format!("({})", inner_pat)),
322 PatKind::Guard(..) => Ok(context.snippet(self.span).to_string()),
323 PatKind::Deref(_) => Err(RewriteError::Unknown),
324 PatKind::Err(_) => Err(RewriteError::Unknown),
325 }
326 }
327}
328
329pub fn rewrite_range_pat<T: Rewrite>(
330 context: &RewriteContext<'_>,
331 shape: Shape,
332 lhs: &Option<ptr::P<T>>,
333 rhs: &Option<ptr::P<T>>,
334 end_kind: &rustc_span::source_map::Spanned<RangeEnd>,
335 span: Span,
336) -> RewriteResult {
337 let infix = match end_kind.node {
338 RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
339 RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
340 RangeEnd::Excluded => "..",
341 };
342 let infix = if context.config.spaces_around_ranges() {
343 let lhs_spacing = match lhs {
344 None => "",
345 Some(_) => " ",
346 };
347 let rhs_spacing = match rhs {
348 None => "",
349 Some(_) => " ",
350 };
351 format!("{lhs_spacing}{infix}{rhs_spacing}")
352 } else {
353 infix.to_owned()
354 };
355 let lspan = span.with_hi(end_kind.span.lo());
356 let rspan = span.with_lo(end_kind.span.hi());
357 rewrite_pair(
358 &RangeOperand {
359 operand: lhs,
360 span: lspan,
361 },
362 &RangeOperand {
363 operand: rhs,
364 span: rspan,
365 },
366 PairParts::infix(&infix),
367 context,
368 shape,
369 SeparatorPlace::Front,
370 )
371}
372
373fn rewrite_struct_pat(
374 qself: &Option<ptr::P<ast::QSelf>>,
375 path: &ast::Path,
376 fields: &[ast::PatField],
377 ellipsis: bool,
378 span: Span,
379 context: &RewriteContext<'_>,
380 shape: Shape,
381) -> RewriteResult {
382 let path_shape = shape.sub_width(2).max_width_error(shape.width, span)?;
384 let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;
385
386 if fields.is_empty() && !ellipsis {
387 return Ok(format!("{path_str} {{}}"));
388 }
389
390 let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
391
392 let (h_shape, v_shape) =
394 struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)
395 .max_width_error(shape.width, span)?;
396
397 let items = itemize_list(
398 context.snippet_provider,
399 fields.iter(),
400 terminator,
401 ",",
402 |f| {
403 if f.attrs.is_empty() {
404 f.span.lo()
405 } else {
406 f.attrs.first().unwrap().span.lo()
407 }
408 },
409 |f| f.span.hi(),
410 |f| f.rewrite_result(context, v_shape),
411 context.snippet_provider.span_after(span, "{"),
412 span.hi(),
413 false,
414 );
415 let item_vec = items.collect::<Vec<_>>();
416
417 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
418 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
419 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
420
421 let mut fields_str = write_list(&item_vec, &fmt)?;
422 let one_line_width = h_shape.map_or(0, |shape| shape.width);
423
424 let has_trailing_comma = fmt.needs_trailing_separator();
425
426 if ellipsis {
427 if fields_str.contains('\n') || fields_str.len() > one_line_width {
428 if !has_trailing_comma {
430 fields_str.push(',');
431 }
432 fields_str.push('\n');
433 fields_str.push_str(&nested_shape.indent.to_string(context.config));
434 } else {
435 if !fields_str.is_empty() {
436 if has_trailing_comma {
438 fields_str.push(' ');
439 } else {
440 fields_str.push_str(", ");
441 }
442 }
443 }
444 fields_str.push_str("..");
445 }
446
447 let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
449 Ok(format!("{path_str} {{{fields_str}}}"))
450}
451
452impl Rewrite for PatField {
453 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
454 self.rewrite_result(context, shape).ok()
455 }
456
457 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
458 let hi_pos = if let Some(last) = self.attrs.last() {
459 last.span.hi()
460 } else {
461 self.pat.span.lo()
462 };
463
464 let attrs_str = if self.attrs.is_empty() {
465 String::from("")
466 } else {
467 self.attrs.rewrite_result(context, shape)?
468 };
469
470 let pat_str = self.pat.rewrite_result(context, shape)?;
471 if self.is_shorthand {
472 combine_strs_with_missing_comments(
473 context,
474 &attrs_str,
475 &pat_str,
476 mk_sp(hi_pos, self.pat.span.lo()),
477 shape,
478 false,
479 )
480 } else {
481 let nested_shape = shape.block_indent(context.config.tab_spaces());
482 let id_str = rewrite_ident(context, self.ident);
483 let one_line_width = id_str.len() + 2 + pat_str.len();
484 let pat_and_id_str = if one_line_width <= shape.width {
485 format!("{id_str}: {pat_str}")
486 } else {
487 format!(
488 "{}:\n{}{}",
489 id_str,
490 nested_shape.indent.to_string(context.config),
491 self.pat.rewrite_result(context, nested_shape)?
492 )
493 };
494 combine_strs_with_missing_comments(
495 context,
496 &attrs_str,
497 &pat_and_id_str,
498 mk_sp(hi_pos, self.pat.span.lo()),
499 nested_shape,
500 false,
501 )
502 }
503 }
504}
505
506#[derive(Debug)]
507pub(crate) enum TuplePatField<'a> {
508 Pat(&'a ptr::P<ast::Pat>),
509 Dotdot(Span),
510}
511
512impl<'a> Rewrite for TuplePatField<'a> {
513 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
514 self.rewrite_result(context, shape).ok()
515 }
516
517 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
518 match *self {
519 TuplePatField::Pat(p) => p.rewrite_result(context, shape),
520 TuplePatField::Dotdot(_) => Ok("..".to_string()),
521 }
522 }
523}
524
525impl<'a> Spanned for TuplePatField<'a> {
526 fn span(&self) -> Span {
527 match *self {
528 TuplePatField::Pat(p) => p.span(),
529 TuplePatField::Dotdot(span) => span,
530 }
531 }
532}
533
534impl<'a> TuplePatField<'a> {
535 fn is_dotdot(&self) -> bool {
536 match self {
537 TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest),
538 TuplePatField::Dotdot(_) => true,
539 }
540 }
541}
542
543pub(crate) fn can_be_overflowed_pat(
544 context: &RewriteContext<'_>,
545 pat: &TuplePatField<'_>,
546 len: usize,
547) -> bool {
548 match *pat {
549 TuplePatField::Pat(pat) => match pat.kind {
550 ast::PatKind::Path(..)
551 | ast::PatKind::Tuple(..)
552 | ast::PatKind::Struct(..)
553 | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
554 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
555 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
556 }
557 ast::PatKind::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
558 _ => false,
559 },
560 TuplePatField::Dotdot(..) => false,
561 }
562}
563
564fn rewrite_tuple_pat(
565 pats: &[ptr::P<ast::Pat>],
566 path_str: Option<String>,
567 span: Span,
568 context: &RewriteContext<'_>,
569 shape: Shape,
570) -> RewriteResult {
571 if pats.is_empty() {
572 return Ok(format!("{}()", path_str.unwrap_or_default()));
573 }
574 let mut pat_vec: Vec<_> = pats.iter().map(TuplePatField::Pat).collect();
575
576 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
577 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
578 {
579 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
580 let sp = pat_vec[new_item_count - 1].span();
581 let snippet = context.snippet(sp);
582 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
583 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp_lo_plus_one(lo));
584 (
585 &pat_vec[..new_item_count],
586 mk_sp(span.lo(), lo + BytePos(1)),
587 )
588 } else {
589 (&pat_vec[..], span)
590 };
591
592 let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
593 let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
594 let path_str = path_str.unwrap_or_default();
595
596 overflow::rewrite_with_parens(
597 context,
598 &path_str,
599 pat_vec.iter(),
600 shape,
601 span,
602 context.config.max_width(),
603 if add_comma {
604 Some(SeparatorTactic::Always)
605 } else {
606 None
607 },
608 )
609}
610
611fn count_wildcard_suffix_len(
612 context: &RewriteContext<'_>,
613 patterns: &[TuplePatField<'_>],
614 span: Span,
615 shape: Shape,
616) -> usize {
617 let mut suffix_len = 0;
618
619 let items: Vec<_> = itemize_list(
620 context.snippet_provider,
621 patterns.iter(),
622 ")",
623 ",",
624 |item| item.span().lo(),
625 |item| item.span().hi(),
626 |item| item.rewrite_result(context, shape),
627 context.snippet_provider.span_after(span, "("),
628 span.hi() - BytePos(1),
629 false,
630 )
631 .collect();
632
633 for item in items
634 .iter()
635 .rev()
636 .take_while(|i| matches!(i.item, Ok(ref internal_string) if internal_string == "_"))
637 {
638 suffix_len += 1;
639
640 if item.has_comment() {
641 break;
642 }
643 }
644
645 suffix_len
646}