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