]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/patterns.rs
Rollup merge of #90238 - GuillaumeGomez:mailmap-alias, r=Mark-Simulacrum
[rust.git] / src / tools / rustfmt / src / patterns.rs
1 use rustc_ast::ast::{self, BindingMode, Pat, PatField, PatKind, RangeEnd, RangeSyntax};
2 use rustc_ast::ptr;
3 use rustc_span::{BytePos, Span};
4
5 use crate::comment::{combine_strs_with_missing_comments, FindUncommented};
6 use crate::config::lists::*;
7 use crate::config::Version;
8 use crate::expr::{can_be_overflowed_expr, rewrite_unary_prefix, wrap_struct_field};
9 use crate::lists::{
10     definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
11     struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
12 };
13 use crate::macros::{rewrite_macro, MacroPosition};
14 use crate::overflow;
15 use crate::pairs::{rewrite_pair, PairParts};
16 use crate::rewrite::{Rewrite, RewriteContext};
17 use crate::shape::Shape;
18 use crate::source_map::SpanUtils;
19 use crate::spanned::Spanned;
20 use crate::types::{rewrite_path, PathContext};
21 use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident};
22
23 /// Returns `true` if the given pattern is "short".
24 /// A short pattern is defined by the following grammar:
25 ///
26 /// `[small, ntp]`:
27 ///     - single token
28 ///     - `&[single-line, ntp]`
29 ///
30 /// `[small]`:
31 ///     - `[small, ntp]`
32 ///     - unary tuple constructor `([small, ntp])`
33 ///     - `&[small]`
34 pub(crate) fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
35     // We also require that the pattern is reasonably 'small' with its literal width.
36     pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
37 }
38
39 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
40     match pat.kind {
41         ast::PatKind::Rest | ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
42         ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
43         ast::PatKind::Struct(..)
44         | ast::PatKind::MacCall(..)
45         | ast::PatKind::Slice(..)
46         | ast::PatKind::Path(..)
47         | ast::PatKind::Range(..) => false,
48         ast::PatKind::Tuple(ref subpats) => subpats.len() <= 1,
49         ast::PatKind::TupleStruct(_, ref path, ref subpats) => {
50             path.segments.len() <= 1 && subpats.len() <= 1
51         }
52         ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
53             is_short_pattern_inner(&*p)
54         }
55         PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)),
56     }
57 }
58
59 struct RangeOperand<'a>(&'a Option<ptr::P<ast::Expr>>);
60
61 impl<'a> Rewrite for RangeOperand<'a> {
62     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
63         match &self.0 {
64             None => Some("".to_owned()),
65             Some(ref exp) => exp.rewrite(context, shape),
66         }
67     }
68 }
69
70 impl Rewrite for Pat {
71     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
72         match self.kind {
73             PatKind::Or(ref pats) => {
74                 let pat_strs = pats
75                     .iter()
76                     .map(|p| p.rewrite(context, shape))
77                     .collect::<Option<Vec<_>>>()?;
78
79                 let use_mixed_layout = pats
80                     .iter()
81                     .zip(pat_strs.iter())
82                     .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
83                 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
84                 let tactic = if use_mixed_layout {
85                     DefinitiveListTactic::Mixed
86                 } else {
87                     definitive_tactic(
88                         &items,
89                         ListTactic::HorizontalVertical,
90                         Separator::VerticalBar,
91                         shape.width,
92                     )
93                 };
94                 let fmt = ListFormatting::new(shape, context.config)
95                     .tactic(tactic)
96                     .separator(" |")
97                     .separator_place(context.config.binop_separator())
98                     .ends_with_newline(false);
99                 write_list(&items, &fmt)
100             }
101             PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
102             PatKind::Ident(binding_mode, ident, ref sub_pat) => {
103                 let (prefix, mutability) = match binding_mode {
104                     BindingMode::ByRef(mutability) => ("ref", mutability),
105                     BindingMode::ByValue(mutability) => ("", mutability),
106                 };
107                 let mut_infix = format_mutability(mutability).trim();
108                 let id_str = rewrite_ident(context, ident);
109                 let sub_pat = match *sub_pat {
110                     Some(ref p) => {
111                         // 2 - `@ `.
112                         let width = shape
113                             .width
114                             .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 2)?;
115                         let lo = context.snippet_provider.span_after(self.span, "@");
116                         combine_strs_with_missing_comments(
117                             context,
118                             "@",
119                             &p.rewrite(context, Shape::legacy(width, shape.indent))?,
120                             mk_sp(lo, p.span.lo()),
121                             shape,
122                             true,
123                         )?
124                     }
125                     None => "".to_owned(),
126                 };
127
128                 // combine prefix and mut
129                 let (first_lo, first) = if !prefix.is_empty() && !mut_infix.is_empty() {
130                     let hi = context.snippet_provider.span_before(self.span, "mut");
131                     let lo = context.snippet_provider.span_after(self.span, "ref");
132                     (
133                         context.snippet_provider.span_after(self.span, "mut"),
134                         combine_strs_with_missing_comments(
135                             context,
136                             prefix,
137                             mut_infix,
138                             mk_sp(lo, hi),
139                             shape,
140                             true,
141                         )?,
142                     )
143                 } else if !prefix.is_empty() {
144                     (
145                         context.snippet_provider.span_after(self.span, "ref"),
146                         prefix.to_owned(),
147                     )
148                 } else if !mut_infix.is_empty() {
149                     (
150                         context.snippet_provider.span_after(self.span, "mut"),
151                         mut_infix.to_owned(),
152                     )
153                 } else {
154                     (self.span.lo(), "".to_owned())
155                 };
156
157                 let next = if !sub_pat.is_empty() {
158                     let hi = context.snippet_provider.span_before(self.span, "@");
159                     combine_strs_with_missing_comments(
160                         context,
161                         id_str,
162                         &sub_pat,
163                         mk_sp(ident.span.hi(), hi),
164                         shape,
165                         true,
166                     )?
167                 } else {
168                     id_str.to_owned()
169                 };
170
171                 combine_strs_with_missing_comments(
172                     context,
173                     &first,
174                     &next,
175                     mk_sp(first_lo, ident.span.lo()),
176                     shape,
177                     true,
178                 )
179             }
180             PatKind::Wild => {
181                 if 1 <= shape.width {
182                     Some("_".to_owned())
183                 } else {
184                     None
185                 }
186             }
187             PatKind::Rest => {
188                 if 1 <= shape.width {
189                     Some("..".to_owned())
190                 } else {
191                     None
192                 }
193             }
194             PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
195                 let infix = match end_kind.node {
196                     RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
197                     RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
198                     RangeEnd::Excluded => "..",
199                 };
200                 let infix = if context.config.spaces_around_ranges() {
201                     let lhs_spacing = match lhs {
202                         None => "",
203                         Some(_) => " ",
204                     };
205                     let rhs_spacing = match rhs {
206                         None => "",
207                         Some(_) => " ",
208                     };
209                     format!("{}{}{}", lhs_spacing, infix, rhs_spacing)
210                 } else {
211                     infix.to_owned()
212                 };
213                 rewrite_pair(
214                     &RangeOperand(lhs),
215                     &RangeOperand(rhs),
216                     PairParts::infix(&infix),
217                     context,
218                     shape,
219                     SeparatorPlace::Front,
220                 )
221             }
222             PatKind::Ref(ref pat, mutability) => {
223                 let prefix = format!("&{}", format_mutability(mutability));
224                 rewrite_unary_prefix(context, &prefix, &**pat, shape)
225             }
226             PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape),
227             PatKind::Path(ref q_self, ref path) => {
228                 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
229             }
230             PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
231                 let path_str =
232                     rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)?;
233                 rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
234             }
235             PatKind::Lit(ref expr) => expr.rewrite(context, shape),
236             PatKind::Slice(ref slice_pat) if context.config.version() == Version::One => {
237                 let rw: Vec<String> = slice_pat
238                     .iter()
239                     .map(|p| {
240                         if let Some(rw) = p.rewrite(context, shape) {
241                             rw
242                         } else {
243                             context.snippet(p.span).to_string()
244                         }
245                     })
246                     .collect();
247                 Some(format!("[{}]", rw.join(", ")))
248             }
249             PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
250                 context,
251                 "",
252                 slice_pat.iter(),
253                 shape,
254                 self.span,
255                 None,
256                 None,
257             ),
258             PatKind::Struct(ref qself, ref path, ref fields, ellipsis) => {
259                 rewrite_struct_pat(qself, path, fields, ellipsis, self.span, context, shape)
260             }
261             PatKind::MacCall(ref mac) => {
262                 rewrite_macro(mac, None, context, shape, MacroPosition::Pat)
263             }
264             PatKind::Paren(ref pat) => pat
265                 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
266                 .map(|inner_pat| format!("({})", inner_pat)),
267         }
268     }
269 }
270
271 fn rewrite_struct_pat(
272     qself: &Option<ast::QSelf>,
273     path: &ast::Path,
274     fields: &[ast::PatField],
275     ellipsis: bool,
276     span: Span,
277     context: &RewriteContext<'_>,
278     shape: Shape,
279 ) -> Option<String> {
280     // 2 =  ` {`
281     let path_shape = shape.sub_width(2)?;
282     let path_str = rewrite_path(context, PathContext::Expr, qself.as_ref(), path, path_shape)?;
283
284     if fields.is_empty() && !ellipsis {
285         return Some(format!("{} {{}}", path_str));
286     }
287
288     let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
289
290     // 3 = ` { `, 2 = ` }`.
291     let (h_shape, v_shape) =
292         struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
293
294     let items = itemize_list(
295         context.snippet_provider,
296         fields.iter(),
297         terminator,
298         ",",
299         |f| {
300             if f.attrs.is_empty() {
301                 f.span.lo()
302             } else {
303                 f.attrs.first().unwrap().span.lo()
304             }
305         },
306         |f| f.span.hi(),
307         |f| f.rewrite(context, v_shape),
308         context.snippet_provider.span_after(span, "{"),
309         span.hi(),
310         false,
311     );
312     let item_vec = items.collect::<Vec<_>>();
313
314     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
315     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
316     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
317
318     let mut fields_str = write_list(&item_vec, &fmt)?;
319     let one_line_width = h_shape.map_or(0, |shape| shape.width);
320
321     if ellipsis {
322         if fields_str.contains('\n') || fields_str.len() > one_line_width {
323             // Add a missing trailing comma.
324             if context.config.trailing_comma() == SeparatorTactic::Never {
325                 fields_str.push(',');
326             }
327             fields_str.push('\n');
328             fields_str.push_str(&nested_shape.indent.to_string(context.config));
329         } else {
330             if !fields_str.is_empty() {
331                 // there are preceding struct fields being matched on
332                 if tactic == DefinitiveListTactic::Vertical {
333                     // if the tactic is Vertical, write_list already added a trailing ,
334                     fields_str.push(' ');
335                 } else {
336                     fields_str.push_str(", ");
337                 }
338             }
339         }
340         fields_str.push_str("..");
341     }
342
343     // ast::Pat doesn't have attrs so use &[]
344     let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
345     Some(format!("{} {{{}}}", path_str, fields_str))
346 }
347
348 impl Rewrite for PatField {
349     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
350         let hi_pos = if let Some(last) = self.attrs.last() {
351             last.span.hi()
352         } else {
353             self.pat.span.lo()
354         };
355
356         let attrs_str = if self.attrs.is_empty() {
357             String::from("")
358         } else {
359             self.attrs.rewrite(context, shape)?
360         };
361
362         let pat_str = self.pat.rewrite(context, shape)?;
363         if self.is_shorthand {
364             combine_strs_with_missing_comments(
365                 context,
366                 &attrs_str,
367                 &pat_str,
368                 mk_sp(hi_pos, self.pat.span.lo()),
369                 shape,
370                 false,
371             )
372         } else {
373             let nested_shape = shape.block_indent(context.config.tab_spaces());
374             let id_str = rewrite_ident(context, self.ident);
375             let one_line_width = id_str.len() + 2 + pat_str.len();
376             let pat_and_id_str = if one_line_width <= shape.width {
377                 format!("{}: {}", id_str, pat_str)
378             } else {
379                 format!(
380                     "{}:\n{}{}",
381                     id_str,
382                     nested_shape.indent.to_string(context.config),
383                     self.pat.rewrite(context, nested_shape)?
384                 )
385             };
386             combine_strs_with_missing_comments(
387                 context,
388                 &attrs_str,
389                 &pat_and_id_str,
390                 mk_sp(hi_pos, self.pat.span.lo()),
391                 nested_shape,
392                 false,
393             )
394         }
395     }
396 }
397
398 #[derive(Debug)]
399 pub(crate) enum TuplePatField<'a> {
400     Pat(&'a ptr::P<ast::Pat>),
401     Dotdot(Span),
402 }
403
404 impl<'a> Rewrite for TuplePatField<'a> {
405     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
406         match *self {
407             TuplePatField::Pat(p) => p.rewrite(context, shape),
408             TuplePatField::Dotdot(_) => Some("..".to_string()),
409         }
410     }
411 }
412
413 impl<'a> Spanned for TuplePatField<'a> {
414     fn span(&self) -> Span {
415         match *self {
416             TuplePatField::Pat(p) => p.span(),
417             TuplePatField::Dotdot(span) => span,
418         }
419     }
420 }
421
422 impl<'a> TuplePatField<'a> {
423     fn is_dotdot(&self) -> bool {
424         match self {
425             TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest),
426             TuplePatField::Dotdot(_) => true,
427         }
428     }
429 }
430
431 pub(crate) fn can_be_overflowed_pat(
432     context: &RewriteContext<'_>,
433     pat: &TuplePatField<'_>,
434     len: usize,
435 ) -> bool {
436     match *pat {
437         TuplePatField::Pat(pat) => match pat.kind {
438             ast::PatKind::Path(..)
439             | ast::PatKind::Tuple(..)
440             | ast::PatKind::Struct(..)
441             | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
442             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
443                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
444             }
445             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
446             _ => false,
447         },
448         TuplePatField::Dotdot(..) => false,
449     }
450 }
451
452 fn rewrite_tuple_pat(
453     pats: &[ptr::P<ast::Pat>],
454     path_str: Option<String>,
455     span: Span,
456     context: &RewriteContext<'_>,
457     shape: Shape,
458 ) -> Option<String> {
459     let mut pat_vec: Vec<_> = pats.iter().map(|x| TuplePatField::Pat(x)).collect();
460
461     if pat_vec.is_empty() {
462         return Some(format!("{}()", path_str.unwrap_or_default()));
463     }
464     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
465     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
466     {
467         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
468         let sp = pat_vec[new_item_count - 1].span();
469         let snippet = context.snippet(sp);
470         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
471         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp_lo_plus_one(lo));
472         (
473             &pat_vec[..new_item_count],
474             mk_sp(span.lo(), lo + BytePos(1)),
475         )
476     } else {
477         (&pat_vec[..], span)
478     };
479
480     let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
481     let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
482     let path_str = path_str.unwrap_or_default();
483
484     overflow::rewrite_with_parens(
485         &context,
486         &path_str,
487         pat_vec.iter(),
488         shape,
489         span,
490         context.config.max_width(),
491         if add_comma {
492             Some(SeparatorTactic::Always)
493         } else {
494             None
495         },
496     )
497 }
498
499 fn count_wildcard_suffix_len(
500     context: &RewriteContext<'_>,
501     patterns: &[TuplePatField<'_>],
502     span: Span,
503     shape: Shape,
504 ) -> usize {
505     let mut suffix_len = 0;
506
507     let items: Vec<_> = itemize_list(
508         context.snippet_provider,
509         patterns.iter(),
510         ")",
511         ",",
512         |item| item.span().lo(),
513         |item| item.span().hi(),
514         |item| item.rewrite(context, shape),
515         context.snippet_provider.span_after(span, "("),
516         span.hi() - BytePos(1),
517         false,
518     )
519     .collect();
520
521     for item in items
522         .iter()
523         .rev()
524         .take_while(|i| matches!(i.item, Some(ref internal_string) if internal_string == "_"))
525     {
526         suffix_len += 1;
527
528         if item.has_comment() {
529             break;
530         }
531     }
532
533     suffix_len
534 }