]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
0c57f111761bf006975388bab1680ef03e9589db
[rust.git] / src / patterns.rs
1 use rustc_span::{BytePos, Span};
2 use syntax::ast::{self, BindingMode, FieldPat, Pat, PatKind, RangeEnd, RangeSyntax};
3 use syntax::ptr;
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) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat),
235             PatKind::Paren(ref pat) => pat
236                 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
237                 .map(|inner_pat| format!("({})", inner_pat)),
238         }
239     }
240 }
241
242 fn rewrite_struct_pat(
243     path: &ast::Path,
244     fields: &[ast::FieldPat],
245     ellipsis: bool,
246     span: Span,
247     context: &RewriteContext<'_>,
248     shape: Shape,
249 ) -> Option<String> {
250     // 2 =  ` {`
251     let path_shape = shape.sub_width(2)?;
252     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
253
254     if fields.is_empty() && !ellipsis {
255         return Some(format!("{} {{}}", path_str));
256     }
257
258     let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
259
260     // 3 = ` { `, 2 = ` }`.
261     let (h_shape, v_shape) =
262         struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
263
264     let items = itemize_list(
265         context.snippet_provider,
266         fields.iter(),
267         terminator,
268         ",",
269         |f| {
270             if f.attrs.is_empty() {
271                 f.span.lo()
272             } else {
273                 f.attrs.first().unwrap().span.lo()
274             }
275         },
276         |f| f.span.hi(),
277         |f| f.rewrite(context, v_shape),
278         context.snippet_provider.span_after(span, "{"),
279         span.hi(),
280         false,
281     );
282     let item_vec = items.collect::<Vec<_>>();
283
284     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
285     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
286     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
287
288     let mut fields_str = write_list(&item_vec, &fmt)?;
289     let one_line_width = h_shape.map_or(0, |shape| shape.width);
290
291     if ellipsis {
292         if fields_str.contains('\n') || fields_str.len() > one_line_width {
293             // Add a missing trailing comma.
294             if context.config.trailing_comma() == SeparatorTactic::Never {
295                 fields_str.push_str(",");
296             }
297             fields_str.push_str("\n");
298             fields_str.push_str(&nested_shape.indent.to_string(context.config));
299             fields_str.push_str("..");
300         } else {
301             if !fields_str.is_empty() {
302                 // there are preceding struct fields being matched on
303                 if tactic == DefinitiveListTactic::Vertical {
304                     // if the tactic is Vertical, write_list already added a trailing ,
305                     fields_str.push_str(" ");
306                 } else {
307                     fields_str.push_str(", ");
308                 }
309             }
310             fields_str.push_str("..");
311         }
312     }
313
314     // ast::Pat doesn't have attrs so use &[]
315     let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
316     Some(format!("{} {{{}}}", path_str, fields_str))
317 }
318
319 impl Rewrite for FieldPat {
320     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
321         let hi_pos = if let Some(last) = self.attrs.last() {
322             last.span.hi()
323         } else {
324             self.pat.span.lo()
325         };
326
327         let attrs_str = if self.attrs.is_empty() {
328             String::from("")
329         } else {
330             self.attrs.rewrite(context, shape)?
331         };
332
333         let pat_str = self.pat.rewrite(context, shape)?;
334         if self.is_shorthand {
335             combine_strs_with_missing_comments(
336                 context,
337                 &attrs_str,
338                 &pat_str,
339                 mk_sp(hi_pos, self.pat.span.lo()),
340                 shape,
341                 false,
342             )
343         } else {
344             let nested_shape = shape.block_indent(context.config.tab_spaces());
345             let id_str = rewrite_ident(context, self.ident);
346             let one_line_width = id_str.len() + 2 + pat_str.len();
347             let pat_and_id_str = if one_line_width <= shape.width {
348                 format!("{}: {}", id_str, pat_str)
349             } else {
350                 format!(
351                     "{}:\n{}{}",
352                     id_str,
353                     nested_shape.indent.to_string(context.config),
354                     self.pat.rewrite(context, nested_shape)?
355                 )
356             };
357             combine_strs_with_missing_comments(
358                 context,
359                 &attrs_str,
360                 &pat_and_id_str,
361                 mk_sp(hi_pos, self.pat.span.lo()),
362                 nested_shape,
363                 false,
364             )
365         }
366     }
367 }
368
369 #[derive(Debug)]
370 pub(crate) enum TuplePatField<'a> {
371     Pat(&'a ptr::P<ast::Pat>),
372     Dotdot(Span),
373 }
374
375 impl<'a> Rewrite for TuplePatField<'a> {
376     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
377         match *self {
378             TuplePatField::Pat(p) => p.rewrite(context, shape),
379             TuplePatField::Dotdot(_) => Some("..".to_string()),
380         }
381     }
382 }
383
384 impl<'a> Spanned for TuplePatField<'a> {
385     fn span(&self) -> Span {
386         match *self {
387             TuplePatField::Pat(p) => p.span(),
388             TuplePatField::Dotdot(span) => span,
389         }
390     }
391 }
392
393 impl<'a> TuplePatField<'a> {
394     fn is_dotdot(&self) -> bool {
395         match self {
396             TuplePatField::Pat(pat) => match pat.kind {
397                 ast::PatKind::Rest => true,
398                 _ => false,
399             },
400             TuplePatField::Dotdot(_) => true,
401         }
402     }
403 }
404
405 pub(crate) fn can_be_overflowed_pat(
406     context: &RewriteContext<'_>,
407     pat: &TuplePatField<'_>,
408     len: usize,
409 ) -> bool {
410     match *pat {
411         TuplePatField::Pat(pat) => match pat.kind {
412             ast::PatKind::Path(..)
413             | ast::PatKind::Tuple(..)
414             | ast::PatKind::Struct(..)
415             | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
416             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
417                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
418             }
419             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
420             _ => false,
421         },
422         TuplePatField::Dotdot(..) => false,
423     }
424 }
425
426 fn rewrite_tuple_pat(
427     pats: &[ptr::P<ast::Pat>],
428     path_str: Option<String>,
429     span: Span,
430     context: &RewriteContext<'_>,
431     shape: Shape,
432 ) -> Option<String> {
433     let mut pat_vec: Vec<_> = pats.iter().map(|x| TuplePatField::Pat(x)).collect();
434
435     if pat_vec.is_empty() {
436         return Some(format!("{}()", path_str.unwrap_or_default()));
437     }
438     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
439     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
440     {
441         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
442         let sp = pat_vec[new_item_count - 1].span();
443         let snippet = context.snippet(sp);
444         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
445         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
446         (
447             &pat_vec[..new_item_count],
448             mk_sp(span.lo(), lo + BytePos(1)),
449         )
450     } else {
451         (&pat_vec[..], span)
452     };
453
454     let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
455     let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
456     let path_str = path_str.unwrap_or_default();
457
458     overflow::rewrite_with_parens(
459         &context,
460         &path_str,
461         pat_vec.iter(),
462         shape,
463         span,
464         context.config.max_width(),
465         if add_comma {
466             Some(SeparatorTactic::Always)
467         } else {
468             None
469         },
470     )
471 }
472
473 fn count_wildcard_suffix_len(
474     context: &RewriteContext<'_>,
475     patterns: &[TuplePatField<'_>],
476     span: Span,
477     shape: Shape,
478 ) -> usize {
479     let mut suffix_len = 0;
480
481     let items: Vec<_> = itemize_list(
482         context.snippet_provider,
483         patterns.iter(),
484         ")",
485         ",",
486         |item| item.span().lo(),
487         |item| item.span().hi(),
488         |item| item.rewrite(context, shape),
489         context.snippet_provider.span_after(span, "("),
490         span.hi() - BytePos(1),
491         false,
492     )
493     .collect();
494
495     for item in items.iter().rev().take_while(|i| match i.item {
496         Some(ref internal_string) if internal_string == "_" => true,
497         _ => false,
498     }) {
499         suffix_len += 1;
500
501         if item.has_comment() {
502             break;
503         }
504     }
505
506     suffix_len
507 }