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