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