]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/patterns.rs
Auto merge of #104219 - bryangarza:async-track-caller-dup, r=eholk
[rust.git] / src / tools / rustfmt / src / patterns.rs
1 use rustc_ast::ast::{
2     self, BindingAnnotation, ByRef, Pat, PatField, PatKind, RangeEnd, RangeSyntax,
3 };
4 use rustc_ast::ptr;
5 use rustc_span::{BytePos, Span};
6
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};
11 use crate::lists::{
12     definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
13     struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
14 };
15 use crate::macros::{rewrite_macro, MacroPosition};
16 use crate::overflow;
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};
24
25 /// Returns `true` if the given pattern is "short".
26 /// A short pattern is defined by the following grammar:
27 ///
28 /// `[small, ntp]`:
29 ///     - single token
30 ///     - `&[single-line, ntp]`
31 ///
32 /// `[small]`:
33 ///     - `[small, ntp]`
34 ///     - unary tuple constructor `([small, ntp])`
35 ///     - `&[small]`
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)
39 }
40
41 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
42     match pat.kind {
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
53         }
54         ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
55             is_short_pattern_inner(&*p)
56         }
57         PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)),
58     }
59 }
60
61 struct RangeOperand<'a>(&'a Option<ptr::P<ast::Expr>>);
62
63 impl<'a> Rewrite for RangeOperand<'a> {
64     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
65         match &self.0 {
66             None => Some("".to_owned()),
67             Some(ref exp) => exp.rewrite(context, shape),
68         }
69     }
70 }
71
72 impl Rewrite for Pat {
73     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
74         match self.kind {
75             PatKind::Or(ref pats) => {
76                 let pat_strs = pats
77                     .iter()
78                     .map(|p| p.rewrite(context, shape))
79                     .collect::<Option<Vec<_>>>()?;
80
81                 let use_mixed_layout = pats
82                     .iter()
83                     .zip(pat_strs.iter())
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
88                 } else {
89                     definitive_tactic(
90                         &items,
91                         ListTactic::HorizontalVertical,
92                         Separator::VerticalBar,
93                         shape.width,
94                     )
95                 };
96                 let fmt = ListFormatting::new(shape, context.config)
97                     .tactic(tactic)
98                     .separator(" |")
99                     .separator_place(context.config.binop_separator())
100                     .ends_with_newline(false);
101                 write_list(&items, &fmt)
102             }
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 {
106                     ByRef::Yes => "ref",
107                     ByRef::No => "",
108                 };
109                 let mut_infix = format_mutability(mutability).trim();
110                 let id_str = rewrite_ident(context, ident);
111                 let sub_pat = match *sub_pat {
112                     Some(ref p) => {
113                         // 2 - `@ `.
114                         let width = shape
115                             .width
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(
119                             context,
120                             "@",
121                             &p.rewrite(context, Shape::legacy(width, shape.indent))?,
122                             mk_sp(lo, p.span.lo()),
123                             shape,
124                             true,
125                         )?
126                     }
127                     None => "".to_owned(),
128                 };
129
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");
134                     (
135                         context.snippet_provider.span_after(self.span, "mut"),
136                         combine_strs_with_missing_comments(
137                             context,
138                             prefix,
139                             mut_infix,
140                             mk_sp(lo, hi),
141                             shape,
142                             true,
143                         )?,
144                     )
145                 } else if !prefix.is_empty() {
146                     (
147                         context.snippet_provider.span_after(self.span, "ref"),
148                         prefix.to_owned(),
149                     )
150                 } else if !mut_infix.is_empty() {
151                     (
152                         context.snippet_provider.span_after(self.span, "mut"),
153                         mut_infix.to_owned(),
154                     )
155                 } else {
156                     (self.span.lo(), "".to_owned())
157                 };
158
159                 let next = if !sub_pat.is_empty() {
160                     let hi = context.snippet_provider.span_before(self.span, "@");
161                     combine_strs_with_missing_comments(
162                         context,
163                         id_str,
164                         &sub_pat,
165                         mk_sp(ident.span.hi(), hi),
166                         shape,
167                         true,
168                     )?
169                 } else {
170                     id_str.to_owned()
171                 };
172
173                 combine_strs_with_missing_comments(
174                     context,
175                     &first,
176                     &next,
177                     mk_sp(first_lo, ident.span.lo()),
178                     shape,
179                     true,
180                 )
181             }
182             PatKind::Wild => {
183                 if 1 <= shape.width {
184                     Some("_".to_owned())
185                 } else {
186                     None
187                 }
188             }
189             PatKind::Rest => {
190                 if 1 <= shape.width {
191                     Some("..".to_owned())
192                 } else {
193                     None
194                 }
195             }
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 => "..",
201                 };
202                 let infix = if context.config.spaces_around_ranges() {
203                     let lhs_spacing = match lhs {
204                         None => "",
205                         Some(_) => " ",
206                     };
207                     let rhs_spacing = match rhs {
208                         None => "",
209                         Some(_) => " ",
210                     };
211                     format!("{}{}{}", lhs_spacing, infix, rhs_spacing)
212                 } else {
213                     infix.to_owned()
214                 };
215                 rewrite_pair(
216                     &RangeOperand(lhs),
217                     &RangeOperand(rhs),
218                     PairParts::infix(&infix),
219                     context,
220                     shape,
221                     SeparatorPlace::Front,
222                 )
223             }
224             PatKind::Ref(ref pat, mutability) => {
225                 let prefix = format!("&{}", format_mutability(mutability));
226                 rewrite_unary_prefix(context, &prefix, &**pat, shape)
227             }
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)
231             }
232             PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
233                 let path_str =
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)
236             }
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
240                     .iter()
241                     .map(|p| {
242                         if let Some(rw) = p.rewrite(context, shape) {
243                             rw
244                         } else {
245                             context.snippet(p.span).to_string()
246                         }
247                     })
248                     .collect();
249                 Some(format!("[{}]", rw.join(", ")))
250             }
251             PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
252                 context,
253                 "",
254                 slice_pat.iter(),
255                 shape,
256                 self.span,
257                 None,
258                 None,
259             ),
260             PatKind::Struct(ref qself, ref path, ref fields, ellipsis) => {
261                 rewrite_struct_pat(qself, path, fields, ellipsis, self.span, context, shape)
262             }
263             PatKind::MacCall(ref mac) => {
264                 rewrite_macro(mac, None, context, shape, MacroPosition::Pat)
265             }
266             PatKind::Paren(ref pat) => pat
267                 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
268                 .map(|inner_pat| format!("({})", inner_pat)),
269         }
270     }
271 }
272
273 fn rewrite_struct_pat(
274     qself: &Option<ast::QSelf>,
275     path: &ast::Path,
276     fields: &[ast::PatField],
277     ellipsis: bool,
278     span: Span,
279     context: &RewriteContext<'_>,
280     shape: Shape,
281 ) -> Option<String> {
282     // 2 =  ` {`
283     let path_shape = shape.sub_width(2)?;
284     let path_str = rewrite_path(context, PathContext::Expr, qself.as_ref(), path, path_shape)?;
285
286     if fields.is_empty() && !ellipsis {
287         return Some(format!("{} {{}}", path_str));
288     }
289
290     let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
291
292     // 3 = ` { `, 2 = ` }`.
293     let (h_shape, v_shape) =
294         struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
295
296     let items = itemize_list(
297         context.snippet_provider,
298         fields.iter(),
299         terminator,
300         ",",
301         |f| {
302             if f.attrs.is_empty() {
303                 f.span.lo()
304             } else {
305                 f.attrs.first().unwrap().span.lo()
306             }
307         },
308         |f| f.span.hi(),
309         |f| f.rewrite(context, v_shape),
310         context.snippet_provider.span_after(span, "{"),
311         span.hi(),
312         false,
313     );
314     let item_vec = items.collect::<Vec<_>>();
315
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);
319
320     let mut fields_str = write_list(&item_vec, &fmt)?;
321     let one_line_width = h_shape.map_or(0, |shape| shape.width);
322
323     let has_trailing_comma = fmt.needs_trailing_separator();
324
325     if ellipsis {
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(',');
330             }
331             fields_str.push('\n');
332             fields_str.push_str(&nested_shape.indent.to_string(context.config));
333         } else {
334             if !fields_str.is_empty() {
335                 // there are preceding struct fields being matched on
336                 if has_trailing_comma {
337                     fields_str.push(' ');
338                 } else {
339                     fields_str.push_str(", ");
340                 }
341             }
342         }
343         fields_str.push_str("..");
344     }
345
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))
349 }
350
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() {
354             last.span.hi()
355         } else {
356             self.pat.span.lo()
357         };
358
359         let attrs_str = if self.attrs.is_empty() {
360             String::from("")
361         } else {
362             self.attrs.rewrite(context, shape)?
363         };
364
365         let pat_str = self.pat.rewrite(context, shape)?;
366         if self.is_shorthand {
367             combine_strs_with_missing_comments(
368                 context,
369                 &attrs_str,
370                 &pat_str,
371                 mk_sp(hi_pos, self.pat.span.lo()),
372                 shape,
373                 false,
374             )
375         } else {
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)
381             } else {
382                 format!(
383                     "{}:\n{}{}",
384                     id_str,
385                     nested_shape.indent.to_string(context.config),
386                     self.pat.rewrite(context, nested_shape)?
387                 )
388             };
389             combine_strs_with_missing_comments(
390                 context,
391                 &attrs_str,
392                 &pat_and_id_str,
393                 mk_sp(hi_pos, self.pat.span.lo()),
394                 nested_shape,
395                 false,
396             )
397         }
398     }
399 }
400
401 #[derive(Debug)]
402 pub(crate) enum TuplePatField<'a> {
403     Pat(&'a ptr::P<ast::Pat>),
404     Dotdot(Span),
405 }
406
407 impl<'a> Rewrite for TuplePatField<'a> {
408     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
409         match *self {
410             TuplePatField::Pat(p) => p.rewrite(context, shape),
411             TuplePatField::Dotdot(_) => Some("..".to_string()),
412         }
413     }
414 }
415
416 impl<'a> Spanned for TuplePatField<'a> {
417     fn span(&self) -> Span {
418         match *self {
419             TuplePatField::Pat(p) => p.span(),
420             TuplePatField::Dotdot(span) => span,
421         }
422     }
423 }
424
425 impl<'a> TuplePatField<'a> {
426     fn is_dotdot(&self) -> bool {
427         match self {
428             TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest),
429             TuplePatField::Dotdot(_) => true,
430         }
431     }
432 }
433
434 pub(crate) fn can_be_overflowed_pat(
435     context: &RewriteContext<'_>,
436     pat: &TuplePatField<'_>,
437     len: usize,
438 ) -> bool {
439     match *pat {
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)
447             }
448             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
449             _ => false,
450         },
451         TuplePatField::Dotdot(..) => false,
452     }
453 }
454
455 fn rewrite_tuple_pat(
456     pats: &[ptr::P<ast::Pat>],
457     path_str: Option<String>,
458     span: Span,
459     context: &RewriteContext<'_>,
460     shape: Shape,
461 ) -> Option<String> {
462     if pats.is_empty() {
463         return Some(format!("{}()", path_str.unwrap_or_default()));
464     }
465     let mut pat_vec: Vec<_> = pats.iter().map(TuplePatField::Pat).collect();
466
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
469     {
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));
475         (
476             &pat_vec[..new_item_count],
477             mk_sp(span.lo(), lo + BytePos(1)),
478         )
479     } else {
480         (&pat_vec[..], span)
481     };
482
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();
486
487     overflow::rewrite_with_parens(
488         context,
489         &path_str,
490         pat_vec.iter(),
491         shape,
492         span,
493         context.config.max_width(),
494         if add_comma {
495             Some(SeparatorTactic::Always)
496         } else {
497             None
498         },
499     )
500 }
501
502 fn count_wildcard_suffix_len(
503     context: &RewriteContext<'_>,
504     patterns: &[TuplePatField<'_>],
505     span: Span,
506     shape: Shape,
507 ) -> usize {
508     let mut suffix_len = 0;
509
510     let items: Vec<_> = itemize_list(
511         context.snippet_provider,
512         patterns.iter(),
513         ")",
514         ",",
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),
520         false,
521     )
522     .collect();
523
524     for item in items
525         .iter()
526         .rev()
527         .take_while(|i| matches!(i.item, Some(ref internal_string) if internal_string == "_"))
528     {
529         suffix_len += 1;
530
531         if item.has_comment() {
532             break;
533         }
534     }
535
536     suffix_len
537 }