]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/pat.rs
Test drop_tracking_mir before querying generator.
[rust.git] / compiler / rustc_parse / src / parser / pat.rs
1 use super::{ForceCollect, Parser, PathStyle, TrailingToken};
2 use crate::errors::RemoveLet;
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
4 use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor};
5 use rustc_ast::ptr::P;
6 use rustc_ast::token::{self, Delimiter};
7 use rustc_ast::{
8     self as ast, AttrVec, BindingAnnotation, ByRef, Expr, ExprKind, MacCall, Mutability, Pat,
9     PatField, PatKind, Path, QSelf, RangeEnd, RangeSyntax,
10 };
11 use rustc_ast_pretty::pprust;
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
13 use rustc_session::errors::ExprParenthesesNeeded;
14 use rustc_span::source_map::{respan, Span, Spanned};
15 use rustc_span::symbol::{kw, sym, Ident};
16
17 pub(super) type Expected = Option<&'static str>;
18
19 /// `Expected` for function and lambda parameter patterns.
20 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
21
22 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
23
24 /// Whether or not to recover a `,` when parsing or-patterns.
25 #[derive(PartialEq, Copy, Clone)]
26 pub enum RecoverComma {
27     Yes,
28     No,
29 }
30
31 /// Whether or not to recover a `:` when parsing patterns that were meant to be paths.
32 #[derive(PartialEq, Copy, Clone)]
33 pub enum RecoverColon {
34     Yes,
35     No,
36 }
37
38 /// Whether or not to recover a `a, b` when parsing patterns as `(a, b)` or that *and* `a | b`.
39 #[derive(PartialEq, Copy, Clone)]
40 pub enum CommaRecoveryMode {
41     LikelyTuple,
42     EitherTupleOrPipe,
43 }
44
45 /// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
46 /// emitting duplicate diagnostics.
47 #[derive(Debug, Clone, Copy)]
48 enum EatOrResult {
49     /// We recovered from a trailing vert.
50     TrailingVert,
51     /// We ate an `|` (or `||` and recovered).
52     AteOr,
53     /// We did not eat anything (i.e. the current token is not `|` or `||`).
54     None,
55 }
56
57 impl<'a> Parser<'a> {
58     /// Parses a pattern.
59     ///
60     /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
61     /// at the top level. Used when parsing the parameters of lambda expressions,
62     /// functions, function pointers, and `pat` macro fragments.
63     pub fn parse_pat_no_top_alt(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
64         self.parse_pat_with_range_pat(true, expected)
65     }
66
67     /// Parses a pattern.
68     ///
69     /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
70     /// Used for parsing patterns in all cases when `pat<no_top_alt>` is not used.
71     ///
72     /// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
73     /// a leading vert is allowed in nested or-patterns, too. This allows us to
74     /// simplify the grammar somewhat.
75     pub fn parse_pat_allow_top_alt(
76         &mut self,
77         expected: Expected,
78         rc: RecoverComma,
79         ra: RecoverColon,
80         rt: CommaRecoveryMode,
81     ) -> PResult<'a, P<Pat>> {
82         self.parse_pat_allow_top_alt_inner(expected, rc, ra, rt).map(|(pat, _)| pat)
83     }
84
85     /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
86     /// recovered).
87     fn parse_pat_allow_top_alt_inner(
88         &mut self,
89         expected: Expected,
90         rc: RecoverComma,
91         ra: RecoverColon,
92         rt: CommaRecoveryMode,
93     ) -> PResult<'a, (P<Pat>, bool)> {
94         // Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
95         // suggestions (which bothers rustfix).
96         //
97         // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
98         let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
99             EatOrResult::AteOr => (Some(self.prev_token.span), false),
100             EatOrResult::TrailingVert => (None, true),
101             EatOrResult::None => (None, false),
102         };
103
104         // Parse the first pattern (`p_0`).
105         let mut first_pat = self.parse_pat_no_top_alt(expected)?;
106         if rc == RecoverComma::Yes {
107             self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
108         }
109
110         // If the next token is not a `|`,
111         // this is not an or-pattern and we should exit here.
112         if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
113             // If we parsed a leading `|` which should be gated,
114             // then we should really gate the leading `|`.
115             // This complicated procedure is done purely for diagnostics UX.
116
117             // Check if the user wrote `foo:bar` instead of `foo::bar`.
118             if ra == RecoverColon::Yes {
119                 first_pat =
120                     self.maybe_recover_colon_colon_in_pat_typo_or_anon_enum(first_pat, expected);
121             }
122
123             if let Some(leading_vert_span) = leading_vert_span {
124                 // If there was a leading vert, treat this as an or-pattern. This improves
125                 // diagnostics.
126                 let span = leading_vert_span.to(self.prev_token.span);
127                 return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
128             }
129
130             return Ok((first_pat, trailing_vert));
131         }
132
133         // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
134         let lo = leading_vert_span.unwrap_or(first_pat.span);
135         let mut pats = vec![first_pat];
136         loop {
137             match self.eat_or_separator(Some(lo)) {
138                 EatOrResult::AteOr => {}
139                 EatOrResult::None => break,
140                 EatOrResult::TrailingVert => {
141                     trailing_vert = true;
142                     break;
143                 }
144             }
145             let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
146                 err.span_label(lo, WHILE_PARSING_OR_MSG);
147                 err
148             })?;
149             if rc == RecoverComma::Yes {
150                 self.maybe_recover_unexpected_comma(pat.span, rt)?;
151             }
152             pats.push(pat);
153         }
154         let or_pattern_span = lo.to(self.prev_token.span);
155
156         Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
157     }
158
159     /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
160     /// type annotation (e.g. for `let` bindings or `fn` params).
161     ///
162     /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
163     /// eat the `Colon` token if one is present.
164     ///
165     /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
166     /// otherwise).
167     pub(super) fn parse_pat_before_ty(
168         &mut self,
169         expected: Expected,
170         rc: RecoverComma,
171         syntax_loc: &str,
172     ) -> PResult<'a, (P<Pat>, bool)> {
173         // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
174         // or-patterns so that we can detect when a user tries to use it. This allows us to print a
175         // better error message.
176         let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(
177             expected,
178             rc,
179             RecoverColon::No,
180             CommaRecoveryMode::LikelyTuple,
181         )?;
182         let colon = self.eat(&token::Colon);
183
184         if let PatKind::Or(pats) = &pat.kind {
185             let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc);
186             let (help, fix) = if pats.len() == 1 {
187                 // If all we have is a leading vert, then print a special message. This is the case
188                 // if `parse_pat_allow_top_alt` returns an or-pattern with one variant.
189                 let msg = "remove the `|`";
190                 let fix = pprust::pat_to_string(&pat);
191                 (msg, fix)
192             } else {
193                 let msg = "wrap the pattern in parentheses";
194                 let fix = format!("({})", pprust::pat_to_string(&pat));
195                 (msg, fix)
196             };
197
198             if trailing_vert {
199                 // We already emitted an error and suggestion to remove the trailing vert. Don't
200                 // emit again.
201                 self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
202             } else {
203                 self.struct_span_err(pat.span, &msg)
204                     .span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
205                     .emit();
206             }
207         }
208
209         Ok((pat, colon))
210     }
211
212     /// Parse the pattern for a function or function pointer parameter, followed by a colon.
213     ///
214     /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
215     /// otherwise).
216     pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
217         // In order to get good UX, we first recover in the case of a leading vert for an illegal
218         // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
219         // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
220         // separately.
221         if let token::OrOr = self.token.kind {
222             let span = self.token.span;
223             let mut err = self.struct_span_err(span, "unexpected `||` before function parameter");
224             err.span_suggestion(span, "remove the `||`", "", Applicability::MachineApplicable);
225             err.note("alternatives in or-patterns are separated with `|`, not `||`");
226             err.emit();
227             self.bump();
228         }
229
230         self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
231     }
232
233     /// Eat the or-pattern `|` separator.
234     /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
235     fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
236         if self.recover_trailing_vert(lo) {
237             EatOrResult::TrailingVert
238         } else if matches!(self.token.kind, token::OrOr) {
239             // Found `||`; Recover and pretend we parsed `|`.
240             self.ban_unexpected_or_or(lo);
241             self.bump();
242             EatOrResult::AteOr
243         } else if self.eat(&token::BinOp(token::Or)) {
244             EatOrResult::AteOr
245         } else {
246             EatOrResult::None
247         }
248     }
249
250     /// Recover if `|` or `||` is the current token and we have one of the
251     /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
252     ///
253     /// These tokens all indicate that we reached the end of the or-pattern
254     /// list and can now reliably say that the `|` was an illegal trailing vert.
255     /// Note that there are more tokens such as `@` for which we know that the `|`
256     /// is an illegal parse. However, the user's intent is less clear in that case.
257     fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
258         let is_end_ahead = self.look_ahead(1, |token| {
259             matches!(
260                 &token.uninterpolate().kind,
261                 token::FatArrow // e.g. `a | => 0,`.
262                 | token::Ident(kw::If, false) // e.g. `a | if expr`.
263                 | token::Eq // e.g. `let a | = 0`.
264                 | token::Semi // e.g. `let a |;`.
265                 | token::Colon // e.g. `let a | :`.
266                 | token::Comma // e.g. `let (a |,)`.
267                 | token::CloseDelim(Delimiter::Bracket) // e.g. `let [a | ]`.
268                 | token::CloseDelim(Delimiter::Parenthesis) // e.g. `let (a | )`.
269                 | token::CloseDelim(Delimiter::Brace) // e.g. `let A { f: a | }`.
270             )
271         });
272         match (is_end_ahead, &self.token.kind) {
273             (true, token::BinOp(token::Or) | token::OrOr) => {
274                 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
275                 self.bump();
276                 true
277             }
278             _ => false,
279         }
280     }
281
282     /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
283     fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
284         let mut err = self.struct_span_err(self.token.span, "unexpected token `||` in pattern");
285         err.span_suggestion(
286             self.token.span,
287             "use a single `|` to separate multiple alternative patterns",
288             "|",
289             Applicability::MachineApplicable,
290         );
291         if let Some(lo) = lo {
292             err.span_label(lo, WHILE_PARSING_OR_MSG);
293         }
294         err.emit();
295     }
296
297     /// A `|` or possibly `||` token shouldn't be here. Ban it.
298     fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
299         let span = self.token.span;
300         let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
301         err.span_suggestion(
302             span,
303             &format!("remove the `{}`", pprust::token_to_string(&self.token)),
304             "",
305             Applicability::MachineApplicable,
306         );
307         if let Some(lo) = lo {
308             err.span_label(lo, WHILE_PARSING_OR_MSG);
309         }
310         if let token::OrOr = self.token.kind {
311             err.note("alternatives in or-patterns are separated with `|`, not `||`");
312         }
313         err.emit();
314     }
315
316     /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
317     /// allowed).
318     fn parse_pat_with_range_pat(
319         &mut self,
320         allow_range_pat: bool,
321         expected: Expected,
322     ) -> PResult<'a, P<Pat>> {
323         maybe_recover_from_interpolated_ty_qpath!(self, true);
324         maybe_whole!(self, NtPat, |x| x);
325
326         let mut lo = self.token.span;
327
328         if self.token.is_keyword(kw::Let) && self.look_ahead(1, |tok| tok.can_begin_pattern()) {
329             self.bump();
330             self.sess.emit_err(RemoveLet { span: lo });
331             lo = self.token.span;
332         }
333
334         let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
335             self.parse_pat_deref(expected)?
336         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
337             self.parse_pat_tuple_or_parens()?
338         } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
339             // Parse `[pat, pat,...]` as a slice pattern.
340             let (pats, _) = self.parse_delim_comma_seq(Delimiter::Bracket, |p| {
341                 p.parse_pat_allow_top_alt(
342                     None,
343                     RecoverComma::No,
344                     RecoverColon::No,
345                     CommaRecoveryMode::EitherTupleOrPipe,
346                 )
347             })?;
348             PatKind::Slice(pats)
349         } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
350             // A rest pattern `..`.
351             self.bump(); // `..`
352             PatKind::Rest
353         } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
354             self.recover_dotdotdot_rest_pat(lo)
355         } else if let Some(form) = self.parse_range_end() {
356             self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
357         } else if self.eat_keyword(kw::Underscore) {
358             // Parse _
359             PatKind::Wild
360         } else if self.eat_keyword(kw::Mut) {
361             self.parse_pat_ident_mut()?
362         } else if self.eat_keyword(kw::Ref) {
363             // Parse ref ident @ pat / ref mut ident @ pat
364             let mutbl = self.parse_mutability();
365             self.parse_pat_ident(BindingAnnotation(ByRef::Yes, mutbl))?
366         } else if self.eat_keyword(kw::Box) {
367             self.parse_pat_box()?
368         } else if self.check_inline_const(0) {
369             // Parse `const pat`
370             let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
371
372             if let Some(re) = self.parse_range_end() {
373                 self.parse_pat_range_begin_with(const_expr, re)?
374             } else {
375                 PatKind::Lit(const_expr)
376             }
377         } else if self.can_be_ident_pat() {
378             // Parse `ident @ pat`
379             // This can give false positives and parse nullary enums,
380             // they are dealt with later in resolve.
381             self.parse_pat_ident(BindingAnnotation::NONE)?
382         } else if self.is_start_of_pat_with_path() {
383             // Parse pattern starting with a path
384             let (qself, path) = if self.eat_lt() {
385                 // Parse a qualified path
386                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
387                 (Some(qself), path)
388             } else {
389                 // Parse an unqualified path
390                 (None, self.parse_path(PathStyle::Expr)?)
391             };
392             let span = lo.to(self.prev_token.span);
393
394             if qself.is_none() && self.check(&token::Not) {
395                 self.parse_pat_mac_invoc(path)?
396             } else if let Some(form) = self.parse_range_end() {
397                 let begin = self.mk_expr(span, ExprKind::Path(qself, path));
398                 self.parse_pat_range_begin_with(begin, form)?
399             } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
400                 self.parse_pat_struct(qself, path)?
401             } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
402                 self.parse_pat_tuple_struct(qself, path)?
403             } else {
404                 PatKind::Path(qself, path)
405             }
406         } else if matches!(self.token.kind, token::Lifetime(_))
407             // In pattern position, we're totally fine with using "next token isn't colon"
408             // as a heuristic. We could probably just always try to recover if it's a lifetime,
409             // because we never have `'a: label {}` in a pattern position anyways, but it does
410             // keep us from suggesting something like `let 'a: Ty = ..` => `let 'a': Ty = ..`
411             && !self.look_ahead(1, |token| matches!(token.kind, token::Colon))
412         {
413             // Recover a `'a` as a `'a'` literal
414             let lt = self.expect_lifetime();
415             let (lit, _) =
416                 self.recover_unclosed_char(lt.ident, Parser::mk_token_lit_char, |self_| {
417                     let expected = expected.unwrap_or("pattern");
418                     let msg = format!(
419                         "expected {}, found {}",
420                         expected,
421                         super::token_descr(&self_.token)
422                     );
423
424                     let mut err = self_.struct_span_err(self_.token.span, &msg);
425                     err.span_label(self_.token.span, format!("expected {}", expected));
426                     err
427                 });
428             PatKind::Lit(self.mk_expr(lo, ExprKind::Lit(lit)))
429         } else {
430             // Try to parse everything else as literal with optional minus
431             match self.parse_literal_maybe_minus() {
432                 Ok(begin) => match self.parse_range_end() {
433                     Some(form) => self.parse_pat_range_begin_with(begin, form)?,
434                     None => PatKind::Lit(begin),
435                 },
436                 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
437             }
438         };
439
440         let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
441         let pat = self.maybe_recover_from_bad_qpath(pat)?;
442         let pat = self.recover_intersection_pat(pat)?;
443
444         if !allow_range_pat {
445             self.ban_pat_range_if_ambiguous(&pat)
446         }
447
448         Ok(pat)
449     }
450
451     /// Recover from a typoed `...` pattern that was encountered
452     /// Ref: Issue #70388
453     fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
454         // A typoed rest pattern `...`.
455         self.bump(); // `...`
456
457         // The user probably mistook `...` for a rest pattern `..`.
458         self.struct_span_err(lo, "unexpected `...`")
459             .span_label(lo, "not a valid pattern")
460             .span_suggestion_short(
461                 lo,
462                 "for a rest pattern, use `..` instead of `...`",
463                 "..",
464                 Applicability::MachineApplicable,
465             )
466             .emit();
467         PatKind::Rest
468     }
469
470     /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
471     ///
472     /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
473     /// should already have been parsed by now at this point,
474     /// if the next token is `@` then we can try to parse the more general form.
475     ///
476     /// Consult `parse_pat_ident` for the `binding` grammar.
477     ///
478     /// The notion of intersection patterns are found in
479     /// e.g. [F#][and] where they are called AND-patterns.
480     ///
481     /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
482     fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
483         if self.token.kind != token::At {
484             // Next token is not `@` so it's not going to be an intersection pattern.
485             return Ok(lhs);
486         }
487
488         // At this point we attempt to parse `@ $pat_rhs` and emit an error.
489         self.bump(); // `@`
490         let mut rhs = self.parse_pat_no_top_alt(None)?;
491         let sp = lhs.span.to(rhs.span);
492
493         if let PatKind::Ident(_, _, sub @ None) = &mut rhs.kind {
494             // The user inverted the order, so help them fix that.
495             let lhs_span = lhs.span;
496             // Move the LHS into the RHS as a subpattern.
497             // The RHS is now the full pattern.
498             *sub = Some(lhs);
499
500             self.struct_span_err(sp, "pattern on wrong side of `@`")
501                 .span_label(lhs_span, "pattern on the left, should be on the right")
502                 .span_label(rhs.span, "binding on the right, should be on the left")
503                 .span_suggestion(
504                     sp,
505                     "switch the order",
506                     pprust::pat_to_string(&rhs),
507                     Applicability::MachineApplicable,
508                 )
509                 .emit();
510         } else {
511             // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
512             rhs.kind = PatKind::Wild;
513             self.struct_span_err(sp, "left-hand side of `@` must be a binding")
514                 .span_label(lhs.span, "interpreted as a pattern, not a binding")
515                 .span_label(rhs.span, "also a pattern")
516                 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
517                 .emit();
518         }
519
520         rhs.span = sp;
521         Ok(rhs)
522     }
523
524     /// Ban a range pattern if it has an ambiguous interpretation.
525     fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
526         match pat.kind {
527             PatKind::Range(
528                 ..,
529                 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
530             ) => return,
531             PatKind::Range(..) => {}
532             _ => return,
533         }
534
535         self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
536             .span_suggestion(
537                 pat.span,
538                 "add parentheses to clarify the precedence",
539                 format!("({})", pprust::pat_to_string(&pat)),
540                 // "ambiguous interpretation" implies that we have to be guessing
541                 Applicability::MaybeIncorrect,
542             )
543             .emit();
544     }
545
546     /// Parse `&pat` / `&mut pat`.
547     fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
548         self.expect_and()?;
549         self.recover_lifetime_in_deref_pat();
550         let mutbl = self.parse_mutability();
551         let subpat = self.parse_pat_with_range_pat(false, expected)?;
552         Ok(PatKind::Ref(subpat, mutbl))
553     }
554
555     fn recover_lifetime_in_deref_pat(&mut self) {
556         if let token::Lifetime(name) = self.token.kind {
557             self.bump(); // `'a`
558
559             let span = self.prev_token.span;
560             self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
561                 .span_suggestion(span, "remove the lifetime", "", Applicability::MachineApplicable)
562                 .emit();
563         }
564     }
565
566     /// Parse a tuple or parenthesis pattern.
567     fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
568         let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
569             p.parse_pat_allow_top_alt(
570                 None,
571                 RecoverComma::No,
572                 RecoverColon::No,
573                 CommaRecoveryMode::LikelyTuple,
574             )
575         })?;
576
577         // Here, `(pat,)` is a tuple pattern.
578         // For backward compatibility, `(..)` is a tuple pattern as well.
579         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
580             PatKind::Paren(fields.into_iter().next().unwrap())
581         } else {
582             PatKind::Tuple(fields)
583         })
584     }
585
586     /// Parse a mutable binding with the `mut` token already eaten.
587     fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
588         let mut_span = self.prev_token.span;
589
590         if self.eat_keyword(kw::Ref) {
591             return self.recover_mut_ref_ident(mut_span);
592         }
593
594         self.recover_additional_muts();
595
596         // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
597         if let token::Interpolated(nt) = &self.token.kind {
598             if let token::NtPat(_) = **nt {
599                 self.expected_ident_found().emit();
600             }
601         }
602
603         // Parse the pattern we hope to be an identifier.
604         let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
605
606         // If we don't have `mut $ident (@ pat)?`, error.
607         if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) = &mut pat.kind
608         {
609             // Don't recurse into the subpattern.
610             // `mut` on the outer binding doesn't affect the inner bindings.
611             *m = Mutability::Mut;
612         } else {
613             // Add `mut` to any binding in the parsed pattern.
614             let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
615             self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
616         }
617
618         Ok(pat.into_inner().kind)
619     }
620
621     /// Recover on `mut ref? ident @ pat` and suggest
622     /// that the order of `mut` and `ref` is incorrect.
623     fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
624         let mutref_span = lo.to(self.prev_token.span);
625         self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
626             .span_suggestion(
627                 mutref_span,
628                 "try switching the order",
629                 "ref mut",
630                 Applicability::MachineApplicable,
631             )
632             .emit();
633
634         self.parse_pat_ident(BindingAnnotation::REF_MUT)
635     }
636
637     /// Turn all by-value immutable bindings in a pattern into mutable bindings.
638     /// Returns `true` if any change was made.
639     fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
640         struct AddMut(bool);
641         impl MutVisitor for AddMut {
642             fn visit_pat(&mut self, pat: &mut P<Pat>) {
643                 if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) =
644                     &mut pat.kind
645                 {
646                     self.0 = true;
647                     *m = Mutability::Mut;
648                 }
649                 noop_visit_pat(pat, self);
650             }
651         }
652
653         let mut add_mut = AddMut(false);
654         add_mut.visit_pat(pat);
655         add_mut.0
656     }
657
658     /// Error on `mut $pat` where `$pat` is not an ident.
659     fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
660         let span = lo.to(pat.span);
661         let fix = pprust::pat_to_string(&pat);
662         let (problem, suggestion) = if changed_any_binding {
663             ("`mut` must be attached to each individual binding", "add `mut` to each binding")
664         } else {
665             ("`mut` must be followed by a named binding", "remove the `mut` prefix")
666         };
667         self.struct_span_err(span, problem)
668             .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
669             .note("`mut` may be followed by `variable` and `variable @ pattern`")
670             .emit();
671     }
672
673     /// Eat any extraneous `mut`s and error + recover if we ate any.
674     fn recover_additional_muts(&mut self) {
675         let lo = self.token.span;
676         while self.eat_keyword(kw::Mut) {}
677         if lo == self.token.span {
678             return;
679         }
680
681         let span = lo.to(self.prev_token.span);
682         self.struct_span_err(span, "`mut` on a binding may not be repeated")
683             .span_suggestion(
684                 span,
685                 "remove the additional `mut`s",
686                 "",
687                 Applicability::MachineApplicable,
688             )
689             .emit();
690     }
691
692     /// Parse macro invocation
693     fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
694         self.bump();
695         let args = self.parse_delim_args()?;
696         let mac = P(MacCall { path, args, prior_type_ascription: self.last_type_ascription });
697         Ok(PatKind::MacCall(mac))
698     }
699
700     fn fatal_unexpected_non_pat(
701         &mut self,
702         err: DiagnosticBuilder<'a, ErrorGuaranteed>,
703         expected: Expected,
704     ) -> PResult<'a, P<Pat>> {
705         err.cancel();
706
707         let expected = expected.unwrap_or("pattern");
708         let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
709
710         let mut err = self.struct_span_err(self.token.span, &msg);
711         err.span_label(self.token.span, format!("expected {}", expected));
712
713         let sp = self.sess.source_map().start_point(self.token.span);
714         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
715             err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
716         }
717
718         Err(err)
719     }
720
721     /// Parses the range pattern end form `".." | "..." | "..=" ;`.
722     fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
723         let re = if self.eat(&token::DotDotDot) {
724             RangeEnd::Included(RangeSyntax::DotDotDot)
725         } else if self.eat(&token::DotDotEq) {
726             RangeEnd::Included(RangeSyntax::DotDotEq)
727         } else if self.eat(&token::DotDot) {
728             RangeEnd::Excluded
729         } else {
730             return None;
731         };
732         Some(respan(self.prev_token.span, re))
733     }
734
735     /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
736     /// `$begin $form` has already been parsed.
737     fn parse_pat_range_begin_with(
738         &mut self,
739         begin: P<Expr>,
740         re: Spanned<RangeEnd>,
741     ) -> PResult<'a, PatKind> {
742         let end = if self.is_pat_range_end_start(0) {
743             // Parsing e.g. `X..=Y`.
744             Some(self.parse_pat_range_end()?)
745         } else {
746             // Parsing e.g. `X..`.
747             if let RangeEnd::Included(_) = re.node {
748                 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
749                 self.inclusive_range_with_incorrect_end(re.span);
750             }
751             None
752         };
753         Ok(PatKind::Range(Some(begin), end, re))
754     }
755
756     pub(super) fn inclusive_range_with_incorrect_end(&mut self, span: Span) {
757         let tok = &self.token;
758
759         // If the user typed "..==" instead of "..=", we want to give them
760         // a specific error message telling them to use "..=".
761         // Otherwise, we assume that they meant to type a half open exclusive
762         // range and give them an error telling them to do that instead.
763         if matches!(tok.kind, token::Eq) && tok.span.lo() == span.hi() {
764             let span_with_eq = span.to(tok.span);
765
766             // Ensure the user doesn't receive unhelpful unexpected token errors
767             self.bump();
768             if self.is_pat_range_end_start(0) {
769                 let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
770             }
771
772             self.error_inclusive_range_with_extra_equals(span_with_eq);
773         } else {
774             self.error_inclusive_range_with_no_end(span);
775         }
776     }
777
778     fn error_inclusive_range_with_extra_equals(&self, span: Span) {
779         self.struct_span_err(span, "unexpected `=` after inclusive range")
780             .span_suggestion_short(span, "use `..=` instead", "..=", Applicability::MaybeIncorrect)
781             .note("inclusive ranges end with a single equals sign (`..=`)")
782             .emit();
783     }
784
785     fn error_inclusive_range_with_no_end(&self, span: Span) {
786         struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
787             .span_suggestion_short(span, "use `..` instead", "..", Applicability::MachineApplicable)
788             .note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
789             .emit();
790     }
791
792     /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
793     ///
794     /// The form `...X` is prohibited to reduce confusion with the potential
795     /// expression syntax `...expr` for splatting in expressions.
796     fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
797         let end = self.parse_pat_range_end()?;
798         if let RangeEnd::Included(syn @ RangeSyntax::DotDotDot) = &mut re.node {
799             *syn = RangeSyntax::DotDotEq;
800             self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
801                 .span_suggestion_short(
802                     re.span,
803                     "use `..=` instead",
804                     "..=",
805                     Applicability::MachineApplicable,
806                 )
807                 .emit();
808         }
809         Ok(PatKind::Range(None, Some(end), re))
810     }
811
812     /// Is the token `dist` away from the current suitable as the start of a range patterns end?
813     fn is_pat_range_end_start(&self, dist: usize) -> bool {
814         self.check_inline_const(dist)
815             || self.look_ahead(dist, |t| {
816                 t.is_path_start() // e.g. `MY_CONST`;
817                 || t.kind == token::Dot // e.g. `.5` for recovery;
818                 || t.can_begin_literal_maybe_minus() // e.g. `42`.
819                 || t.is_whole_expr()
820                 || t.is_lifetime() // recover `'a` instead of `'a'`
821             })
822     }
823
824     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
825         if self.check_inline_const(0) {
826             self.parse_const_block(self.token.span, true)
827         } else if self.check_path() {
828             let lo = self.token.span;
829             let (qself, path) = if self.eat_lt() {
830                 // Parse a qualified path
831                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
832                 (Some(qself), path)
833             } else {
834                 // Parse an unqualified path
835                 (None, self.parse_path(PathStyle::Expr)?)
836             };
837             let hi = self.prev_token.span;
838             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
839         } else {
840             self.parse_literal_maybe_minus()
841         }
842     }
843
844     /// Is this the start of a pattern beginning with a path?
845     fn is_start_of_pat_with_path(&mut self) -> bool {
846         self.check_path()
847         // Just for recovery (see `can_be_ident`).
848         || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
849     }
850
851     /// Would `parse_pat_ident` be appropriate here?
852     fn can_be_ident_pat(&mut self) -> bool {
853         self.check_ident()
854         && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
855         && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
856         // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
857         && !self.token.is_keyword(kw::In)
858         // Try to do something more complex?
859         && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(Delimiter::Parenthesis) // A tuple struct pattern.
860             | token::OpenDelim(Delimiter::Brace) // A struct pattern.
861             | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
862             | token::ModSep // A tuple / struct variant pattern.
863             | token::Not)) // A macro expanding to a pattern.
864     }
865
866     /// Parses `ident` or `ident @ pat`.
867     /// Used by the copy foo and ref foo patterns to give a good
868     /// error message when parsing mistakes like `ref foo(a, b)`.
869     fn parse_pat_ident(&mut self, binding_annotation: BindingAnnotation) -> PResult<'a, PatKind> {
870         let ident = self.parse_ident()?;
871         let sub = if self.eat(&token::At) {
872             Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
873         } else {
874             None
875         };
876
877         // Just to be friendly, if they write something like `ref Some(i)`,
878         // we end up here with `(` as the current token.
879         // This shortly leads to a parse error. Note that if there is no explicit
880         // binding mode then we do not end up here, because the lookahead
881         // will direct us over to `parse_enum_variant()`.
882         if self.token == token::OpenDelim(Delimiter::Parenthesis) {
883             return Err(self
884                 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
885         }
886
887         Ok(PatKind::Ident(binding_annotation, ident, sub))
888     }
889
890     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
891     fn parse_pat_struct(&mut self, qself: Option<P<QSelf>>, path: Path) -> PResult<'a, PatKind> {
892         if qself.is_some() {
893             // Feature gate the use of qualified paths in patterns
894             self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
895         }
896         self.bump();
897         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
898             e.span_label(path.span, "while parsing the fields for this pattern");
899             e.emit();
900             self.recover_stmt();
901             (vec![], true)
902         });
903         self.bump();
904         Ok(PatKind::Struct(qself, path, fields, etc))
905     }
906
907     /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
908     fn parse_pat_tuple_struct(
909         &mut self,
910         qself: Option<P<QSelf>>,
911         path: Path,
912     ) -> PResult<'a, PatKind> {
913         let (fields, _) = self.parse_paren_comma_seq(|p| {
914             p.parse_pat_allow_top_alt(
915                 None,
916                 RecoverComma::No,
917                 RecoverColon::No,
918                 CommaRecoveryMode::EitherTupleOrPipe,
919             )
920         })?;
921         if qself.is_some() {
922             self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
923         }
924         Ok(PatKind::TupleStruct(qself, path, fields))
925     }
926
927     /// Are we sure this could not possibly be the start of a pattern?
928     ///
929     /// Currently, this only accounts for tokens that can follow identifiers
930     /// in patterns, but this can be extended as necessary.
931     fn isnt_pattern_start(&self) -> bool {
932         [
933             token::Eq,
934             token::Colon,
935             token::Comma,
936             token::Semi,
937             token::At,
938             token::OpenDelim(Delimiter::Brace),
939             token::CloseDelim(Delimiter::Brace),
940             token::CloseDelim(Delimiter::Parenthesis),
941         ]
942         .contains(&self.token.kind)
943     }
944
945     /// Parses `box pat`
946     fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
947         let box_span = self.prev_token.span;
948
949         if self.isnt_pattern_start() {
950             self.struct_span_err(
951                 self.token.span,
952                 format!("expected pattern, found {}", super::token_descr(&self.token)),
953             )
954             .span_note(box_span, "`box` is a reserved keyword")
955             .span_suggestion_verbose(
956                 box_span.shrink_to_lo(),
957                 "escape `box` to use it as an identifier",
958                 "r#",
959                 Applicability::MaybeIncorrect,
960             )
961             .emit();
962
963             // We cannot use `parse_pat_ident()` since it will complain `box`
964             // is not an identifier.
965             let sub = if self.eat(&token::At) {
966                 Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
967             } else {
968                 None
969             };
970
971             Ok(PatKind::Ident(BindingAnnotation::NONE, Ident::new(kw::Box, box_span), sub))
972         } else {
973             let pat = self.parse_pat_with_range_pat(false, None)?;
974             self.sess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span));
975             Ok(PatKind::Box(pat))
976         }
977     }
978
979     /// Parses the fields of a struct-like pattern.
980     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
981         let mut fields = Vec::new();
982         let mut etc = false;
983         let mut ate_comma = true;
984         let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
985         let mut etc_span = None;
986
987         while self.token != token::CloseDelim(Delimiter::Brace) {
988             let attrs = match self.parse_outer_attributes() {
989                 Ok(attrs) => attrs,
990                 Err(err) => {
991                     if let Some(mut delayed) = delayed_err {
992                         delayed.emit();
993                     }
994                     return Err(err);
995                 }
996             };
997             let lo = self.token.span;
998
999             // check that a comma comes after every field
1000             if !ate_comma {
1001                 let err = self.struct_span_err(self.token.span, "expected `,`");
1002                 if let Some(mut delayed) = delayed_err {
1003                     delayed.emit();
1004                 }
1005                 return Err(err);
1006             }
1007             ate_comma = false;
1008
1009             if self.check(&token::DotDot) || self.token == token::DotDotDot {
1010                 etc = true;
1011                 let mut etc_sp = self.token.span;
1012
1013                 self.recover_one_fewer_dotdot();
1014                 self.bump(); // `..` || `...`
1015
1016                 if self.token == token::CloseDelim(Delimiter::Brace) {
1017                     etc_span = Some(etc_sp);
1018                     break;
1019                 }
1020                 let token_str = super::token_descr(&self.token);
1021                 let msg = &format!("expected `}}`, found {}", token_str);
1022                 let mut err = self.struct_span_err(self.token.span, msg);
1023
1024                 err.span_label(self.token.span, "expected `}`");
1025                 let mut comma_sp = None;
1026                 if self.token == token::Comma {
1027                     // Issue #49257
1028                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
1029                     etc_sp = etc_sp.to(nw_span);
1030                     err.span_label(
1031                         etc_sp,
1032                         "`..` must be at the end and cannot have a trailing comma",
1033                     );
1034                     comma_sp = Some(self.token.span);
1035                     self.bump();
1036                     ate_comma = true;
1037                 }
1038
1039                 etc_span = Some(etc_sp.until(self.token.span));
1040                 if self.token == token::CloseDelim(Delimiter::Brace) {
1041                     // If the struct looks otherwise well formed, recover and continue.
1042                     if let Some(sp) = comma_sp {
1043                         err.span_suggestion_short(
1044                             sp,
1045                             "remove this comma",
1046                             "",
1047                             Applicability::MachineApplicable,
1048                         );
1049                     }
1050                     err.emit();
1051                     break;
1052                 } else if self.token.is_ident() && ate_comma {
1053                     // Accept fields coming after `..,`.
1054                     // This way we avoid "pattern missing fields" errors afterwards.
1055                     // We delay this error until the end in order to have a span for a
1056                     // suggested fix.
1057                     if let Some(mut delayed_err) = delayed_err {
1058                         delayed_err.emit();
1059                         return Err(err);
1060                     } else {
1061                         delayed_err = Some(err);
1062                     }
1063                 } else {
1064                     if let Some(mut err) = delayed_err {
1065                         err.emit();
1066                     }
1067                     return Err(err);
1068                 }
1069             }
1070
1071             let field =
1072                 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1073                     let field = match this.parse_pat_field(lo, attrs) {
1074                         Ok(field) => Ok(field),
1075                         Err(err) => {
1076                             if let Some(mut delayed_err) = delayed_err.take() {
1077                                 delayed_err.emit();
1078                             }
1079                             return Err(err);
1080                         }
1081                     }?;
1082                     ate_comma = this.eat(&token::Comma);
1083                     // We just ate a comma, so there's no need to use
1084                     // `TrailingToken::Comma`
1085                     Ok((field, TrailingToken::None))
1086                 })?;
1087
1088             fields.push(field)
1089         }
1090
1091         if let Some(mut err) = delayed_err {
1092             if let Some(etc_span) = etc_span {
1093                 err.multipart_suggestion(
1094                     "move the `..` to the end of the field list",
1095                     vec![
1096                         (etc_span, String::new()),
1097                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1098                     ],
1099                     Applicability::MachineApplicable,
1100                 );
1101             }
1102             err.emit();
1103         }
1104         Ok((fields, etc))
1105     }
1106
1107     /// Recover on `...` as if it were `..` to avoid further errors.
1108     /// See issue #46718.
1109     fn recover_one_fewer_dotdot(&self) {
1110         if self.token != token::DotDotDot {
1111             return;
1112         }
1113
1114         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
1115             .span_suggestion(
1116                 self.token.span,
1117                 "to omit remaining fields, use one fewer `.`",
1118                 "..",
1119                 Applicability::MachineApplicable,
1120             )
1121             .emit();
1122     }
1123
1124     fn parse_pat_field(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, PatField> {
1125         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1126         let hi;
1127         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1128             // Parsing a pattern of the form `fieldname: pat`.
1129             let fieldname = self.parse_field_name()?;
1130             self.bump();
1131             let pat = self.parse_pat_allow_top_alt(
1132                 None,
1133                 RecoverComma::No,
1134                 RecoverColon::No,
1135                 CommaRecoveryMode::EitherTupleOrPipe,
1136             )?;
1137             hi = pat.span;
1138             (pat, fieldname, false)
1139         } else {
1140             // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1141             let is_box = self.eat_keyword(kw::Box);
1142             let boxed_span = self.token.span;
1143             let is_ref = self.eat_keyword(kw::Ref);
1144             let is_mut = self.eat_keyword(kw::Mut);
1145             let fieldname = self.parse_field_name()?;
1146             hi = self.prev_token.span;
1147
1148             let mutability = match is_mut {
1149                 false => Mutability::Not,
1150                 true => Mutability::Mut,
1151             };
1152             let ann = BindingAnnotation(ByRef::from(is_ref), mutability);
1153             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), ann, fieldname);
1154             let subpat =
1155                 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1156             (subpat, fieldname, true)
1157         };
1158
1159         Ok(PatField {
1160             ident: fieldname,
1161             pat: subpat,
1162             is_shorthand,
1163             attrs,
1164             id: ast::DUMMY_NODE_ID,
1165             span: lo.to(hi),
1166             is_placeholder: false,
1167         })
1168     }
1169
1170     pub(super) fn mk_pat_ident(&self, span: Span, ann: BindingAnnotation, ident: Ident) -> P<Pat> {
1171         self.mk_pat(span, PatKind::Ident(ann, ident, None))
1172     }
1173
1174     pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1175         P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
1176     }
1177 }