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