]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/patterns.rs
Rollup merge of #88794 - sunfishcode:sunfishcode/try-clone, r=joshtriplett
[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     let has_trailing_comma = fmt.needs_trailing_separator();
322
323     if ellipsis {
324         if fields_str.contains('\n') || fields_str.len() > one_line_width {
325             // Add a missing trailing comma.
326             if !has_trailing_comma {
327                 fields_str.push(',');
328             }
329             fields_str.push('\n');
330             fields_str.push_str(&nested_shape.indent.to_string(context.config));
331         } else {
332             if !fields_str.is_empty() {
333                 // there are preceding struct fields being matched on
334                 if has_trailing_comma {
335                     fields_str.push(' ');
336                 } else {
337                     fields_str.push_str(", ");
338                 }
339             }
340         }
341         fields_str.push_str("..");
342     }
343
344     // ast::Pat doesn't have attrs so use &[]
345     let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
346     Some(format!("{} {{{}}}", path_str, fields_str))
347 }
348
349 impl Rewrite for PatField {
350     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
351         let hi_pos = if let Some(last) = self.attrs.last() {
352             last.span.hi()
353         } else {
354             self.pat.span.lo()
355         };
356
357         let attrs_str = if self.attrs.is_empty() {
358             String::from("")
359         } else {
360             self.attrs.rewrite(context, shape)?
361         };
362
363         let pat_str = self.pat.rewrite(context, shape)?;
364         if self.is_shorthand {
365             combine_strs_with_missing_comments(
366                 context,
367                 &attrs_str,
368                 &pat_str,
369                 mk_sp(hi_pos, self.pat.span.lo()),
370                 shape,
371                 false,
372             )
373         } else {
374             let nested_shape = shape.block_indent(context.config.tab_spaces());
375             let id_str = rewrite_ident(context, self.ident);
376             let one_line_width = id_str.len() + 2 + pat_str.len();
377             let pat_and_id_str = if one_line_width <= shape.width {
378                 format!("{}: {}", id_str, pat_str)
379             } else {
380                 format!(
381                     "{}:\n{}{}",
382                     id_str,
383                     nested_shape.indent.to_string(context.config),
384                     self.pat.rewrite(context, nested_shape)?
385                 )
386             };
387             combine_strs_with_missing_comments(
388                 context,
389                 &attrs_str,
390                 &pat_and_id_str,
391                 mk_sp(hi_pos, self.pat.span.lo()),
392                 nested_shape,
393                 false,
394             )
395         }
396     }
397 }
398
399 #[derive(Debug)]
400 pub(crate) enum TuplePatField<'a> {
401     Pat(&'a ptr::P<ast::Pat>),
402     Dotdot(Span),
403 }
404
405 impl<'a> Rewrite for TuplePatField<'a> {
406     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
407         match *self {
408             TuplePatField::Pat(p) => p.rewrite(context, shape),
409             TuplePatField::Dotdot(_) => Some("..".to_string()),
410         }
411     }
412 }
413
414 impl<'a> Spanned for TuplePatField<'a> {
415     fn span(&self) -> Span {
416         match *self {
417             TuplePatField::Pat(p) => p.span(),
418             TuplePatField::Dotdot(span) => span,
419         }
420     }
421 }
422
423 impl<'a> TuplePatField<'a> {
424     fn is_dotdot(&self) -> bool {
425         match self {
426             TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest),
427             TuplePatField::Dotdot(_) => true,
428         }
429     }
430 }
431
432 pub(crate) fn can_be_overflowed_pat(
433     context: &RewriteContext<'_>,
434     pat: &TuplePatField<'_>,
435     len: usize,
436 ) -> bool {
437     match *pat {
438         TuplePatField::Pat(pat) => match pat.kind {
439             ast::PatKind::Path(..)
440             | ast::PatKind::Tuple(..)
441             | ast::PatKind::Struct(..)
442             | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
443             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
444                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
445             }
446             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
447             _ => false,
448         },
449         TuplePatField::Dotdot(..) => false,
450     }
451 }
452
453 fn rewrite_tuple_pat(
454     pats: &[ptr::P<ast::Pat>],
455     path_str: Option<String>,
456     span: Span,
457     context: &RewriteContext<'_>,
458     shape: Shape,
459 ) -> Option<String> {
460     if pats.is_empty() {
461         return Some(format!("{}()", path_str.unwrap_or_default()));
462     }
463     let mut pat_vec: Vec<_> = pats.iter().map(TuplePatField::Pat).collect();
464
465     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
466     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
467     {
468         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
469         let sp = pat_vec[new_item_count - 1].span();
470         let snippet = context.snippet(sp);
471         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
472         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp_lo_plus_one(lo));
473         (
474             &pat_vec[..new_item_count],
475             mk_sp(span.lo(), lo + BytePos(1)),
476         )
477     } else {
478         (&pat_vec[..], span)
479     };
480
481     let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
482     let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
483     let path_str = path_str.unwrap_or_default();
484
485     overflow::rewrite_with_parens(
486         context,
487         &path_str,
488         pat_vec.iter(),
489         shape,
490         span,
491         context.config.max_width(),
492         if add_comma {
493             Some(SeparatorTactic::Always)
494         } else {
495             None
496         },
497     )
498 }
499
500 fn count_wildcard_suffix_len(
501     context: &RewriteContext<'_>,
502     patterns: &[TuplePatField<'_>],
503     span: Span,
504     shape: Shape,
505 ) -> usize {
506     let mut suffix_len = 0;
507
508     let items: Vec<_> = itemize_list(
509         context.snippet_provider,
510         patterns.iter(),
511         ")",
512         ",",
513         |item| item.span().lo(),
514         |item| item.span().hi(),
515         |item| item.rewrite(context, shape),
516         context.snippet_provider.span_after(span, "("),
517         span.hi() - BytePos(1),
518         false,
519     )
520     .collect();
521
522     for item in items
523         .iter()
524         .rev()
525         .take_while(|i| matches!(i.item, Some(ref internal_string) if internal_string == "_"))
526     {
527         suffix_len += 1;
528
529         if item.has_comment() {
530             break;
531         }
532     }
533
534     suffix_len
535 }