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