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