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