1 use super::{ForceCollect, Parser, PathStyle, TrailingToken};
3 InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, RemoveLet,
5 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
6 use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor};
8 use rustc_ast::token::{self, Delimiter};
10 self as ast, AttrVec, BindingAnnotation, ByRef, Expr, ExprKind, MacCall, Mutability, Pat,
11 PatField, PatKind, Path, QSelf, RangeEnd, RangeSyntax,
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};
19 pub(super) type Expected = Option<&'static str>;
21 /// `Expected` for function and lambda parameter patterns.
22 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
24 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
26 /// Whether or not to recover a `,` when parsing or-patterns.
27 #[derive(PartialEq, Copy, Clone)]
28 pub enum RecoverComma {
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 {
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 {
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)]
51 /// We recovered from a trailing vert.
53 /// We ate an `|` (or `||` and recovered).
55 /// We did not eat anything (i.e. the current token is not `|` or `||`).
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)
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.
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(
82 rt: CommaRecoveryMode,
83 ) -> PResult<'a, P<Pat>> {
84 self.parse_pat_allow_top_alt_inner(expected, rc, ra, rt).map(|(pat, _)| pat)
87 /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
89 fn parse_pat_allow_top_alt_inner(
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).
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),
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)?;
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.
119 // Check if the user wrote `foo:bar` instead of `foo::bar`.
120 if ra == RecoverColon::Yes {
122 self.maybe_recover_colon_colon_in_pat_typo_or_anon_enum(first_pat, expected);
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
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));
132 return Ok((first_pat, trailing_vert));
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];
139 match self.eat_or_separator(Some(lo)) {
140 EatOrResult::AteOr => {}
141 EatOrResult::None => break,
142 EatOrResult::TrailingVert => {
143 trailing_vert = true;
147 let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
148 err.span_label(lo, WHILE_PARSING_OR_MSG);
151 if rc == RecoverComma::Yes {
152 self.maybe_recover_unexpected_comma(pat.span, rt)?;
156 let or_pattern_span = lo.to(self.prev_token.span);
158 Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
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).
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.
167 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
169 pub(super) fn parse_pat_before_ty(
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(
182 CommaRecoveryMode::LikelyTuple,
184 let colon = self.eat(&token::Colon);
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);
195 let msg = "wrap the pattern in parentheses";
196 let fix = format!("({})", pprust::pat_to_string(&pat));
201 // We already emitted an error and suggestion to remove the trailing vert. Don't
203 self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
205 self.struct_span_err(pat.span, &msg)
206 .span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
214 /// Parse the pattern for a function or function pointer parameter, followed by a colon.
216 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
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
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 `||`");
232 self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
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);
245 } else if self.eat(&token::BinOp(token::Or)) {
252 /// Recover if `|` or `||` is the current token and we have one of the
253 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
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| {
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 | }`.
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");
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");
289 "use a single `|` to separate multiple alternative patterns",
291 Applicability::MachineApplicable,
293 if let Some(lo) = lo {
294 err.span_label(lo, WHILE_PARSING_OR_MSG);
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));
305 &format!("remove the `{}`", pprust::token_to_string(&self.token)),
307 Applicability::MachineApplicable,
309 if let Some(lo) = lo {
310 err.span_label(lo, WHILE_PARSING_OR_MSG);
312 if let token::OrOr = self.token.kind {
313 err.note("alternatives in or-patterns are separated with `|`, not `||`");
318 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
320 fn parse_pat_with_range_pat(
322 allow_range_pat: bool,
324 ) -> PResult<'a, P<Pat>> {
325 maybe_recover_from_interpolated_ty_qpath!(self, true);
326 maybe_whole!(self, NtPat, |x| x);
328 let mut lo = self.token.span;
330 if self.token.is_keyword(kw::Let) && self.look_ahead(1, |tok| tok.can_begin_pattern()) {
332 self.sess.emit_err(RemoveLet { span: lo });
333 lo = self.token.span;
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(
347 CommaRecoveryMode::EitherTupleOrPipe,
351 } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
352 // A rest pattern `..`.
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) {
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) {
372 let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
374 if let Some(re) = self.parse_range_end() {
375 self.parse_pat_range_begin_with(const_expr, re)?
377 PatKind::Lit(const_expr)
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)?;
391 // Parse an unqualified path
392 (None, self.parse_path(PathStyle::Expr)?)
394 let span = lo.to(self.prev_token.span);
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)?
406 PatKind::Path(qself, path)
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))
415 // Recover a `'a` as a `'a'` literal
416 let lt = self.expect_lifetime();
418 self.recover_unclosed_char(lt.ident, Parser::mk_token_lit_char, |self_| {
419 let expected = expected.unwrap_or("pattern");
421 "expected {}, found {}",
423 super::token_descr(&self_.token)
426 let mut err = self_.struct_span_err(self_.token.span, &msg);
427 err.span_label(self_.token.span, format!("expected {}", expected));
430 PatKind::Lit(self.mk_expr(lo, ExprKind::Lit(lit)))
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),
438 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
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)?;
446 if !allow_range_pat {
447 self.ban_pat_range_if_ambiguous(&pat)
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(); // `...`
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(
464 "for a rest pattern, use `..` instead of `...`",
466 Applicability::MachineApplicable,
472 /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
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.
478 /// Consult `parse_pat_ident` for the `binding` grammar.
480 /// The notion of intersection patterns are found in
481 /// e.g. [F#][and] where they are called AND-patterns.
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.
490 // At this point we attempt to parse `@ $pat_rhs` and emit an error.
492 let mut rhs = self.parse_pat_no_top_alt(None)?;
493 let sp = lhs.span.to(rhs.span);
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.
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")
508 pprust::pat_to_string(&rhs),
509 Applicability::MachineApplicable,
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`")
526 /// Ban a range pattern if it has an ambiguous interpretation.
527 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
531 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
533 PatKind::Range(..) => {}
537 self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
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,
548 /// Parse `&pat` / `&mut pat`.
549 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
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))
557 fn recover_lifetime_in_deref_pat(&mut self) {
558 if let token::Lifetime(name) = self.token.kind {
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)
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(
575 CommaRecoveryMode::LikelyTuple,
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())
584 PatKind::Tuple(fields)
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;
592 if self.eat_keyword(kw::Ref) {
593 return self.recover_mut_ref_ident(mut_span);
596 self.recover_additional_muts();
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();
605 // Parse the pattern we hope to be an identifier.
606 let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
608 // If we don't have `mut $ident (@ pat)?`, error.
609 if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) = &mut pat.kind
611 // Don't recurse into the subpattern.
612 // `mut` on the outer binding doesn't affect the inner bindings.
613 *m = Mutability::Mut;
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);
620 Ok(pat.into_inner().kind)
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")
630 "try switching the order",
632 Applicability::MachineApplicable,
636 self.parse_pat_ident(BindingAnnotation::REF_MUT)
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 {
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), ..) =
649 *m = Mutability::Mut;
651 noop_visit_pat(pat, self);
655 let mut add_mut = AddMut(false);
656 add_mut.visit_pat(pat);
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")
667 ("`mut` must be followed by a named binding", "remove the `mut` prefix")
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`")
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 {
683 let span = lo.to(self.prev_token.span);
684 self.struct_span_err(span, "`mut` on a binding may not be repeated")
687 "remove the additional `mut`s",
689 Applicability::MachineApplicable,
694 /// Parse macro invocation
695 fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
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))
702 fn fatal_unexpected_non_pat(
704 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
706 ) -> PResult<'a, P<Pat>> {
709 let expected = expected.unwrap_or("pattern");
710 let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
712 let mut err = self.struct_span_err(self.token.span, &msg);
713 err.span_label(self.token.span, format!("expected {}", expected));
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));
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) {
734 Some(respan(self.prev_token.span, re))
737 /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
738 /// `$begin $form` has already been parsed.
739 fn parse_pat_range_begin_with(
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()?)
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();
755 Ok(PatKind::Range(Some(begin), end, re))
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();
768 token::Eq if no_space => {
769 let span_with_eq = span.to(tok.span);
771 // Ensure the user doesn't receive unhelpful unexpected token errors
773 if self.is_pat_range_end_start(0) {
774 let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
777 self.error_inclusive_range_with_extra_equals(span_with_eq);
779 token::Gt if no_space => {
780 self.error_inclusive_range_match_arrow(span);
782 _ => self.error_inclusive_range_with_no_end(span),
786 fn error_inclusive_range_with_extra_equals(&self, span: Span) {
787 self.sess.emit_err(InclusiveRangeExtraEquals { span });
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 });
795 fn error_inclusive_range_with_no_end(&self, span: Span) {
796 self.sess.emit_err(InclusiveRangeNoEnd { span });
799 /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
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(
812 Applicability::MachineApplicable,
816 Ok(PatKind::Range(None, Some(end), re))
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`.
827 || t.is_lifetime() // recover `'a` instead of `'a'`
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)?;
841 // Parse an unqualified path
842 (None, self.parse_path(PathStyle::Expr)?)
844 let hi = self.prev_token.span;
845 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
847 self.parse_literal_maybe_minus()
851 /// Is this the start of a pattern beginning with a path?
852 fn is_start_of_pat_with_path(&mut self) -> bool {
854 // Just for recovery (see `can_be_ident`).
855 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
858 /// Would `parse_pat_ident` be appropriate here?
859 fn can_be_ident_pat(&mut self) -> bool {
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.
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"))?)
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) {
891 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
894 Ok(PatKind::Ident(binding_annotation, ident, sub))
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> {
900 // Feature gate the use of qualified paths in patterns
901 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
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");
911 Ok(PatKind::Struct(qself, path, fields, etc))
914 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
915 fn parse_pat_tuple_struct(
917 qself: Option<P<QSelf>>,
919 ) -> PResult<'a, PatKind> {
920 let (fields, _) = self.parse_paren_comma_seq(|p| {
921 p.parse_pat_allow_top_alt(
925 CommaRecoveryMode::EitherTupleOrPipe,
929 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
931 Ok(PatKind::TupleStruct(qself, path, fields))
934 /// Are we sure this could not possibly be the start of a pattern?
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 {
945 token::OpenDelim(Delimiter::Brace),
946 token::CloseDelim(Delimiter::Brace),
947 token::CloseDelim(Delimiter::Parenthesis),
949 .contains(&self.token.kind)
953 fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
954 let box_span = self.prev_token.span;
956 if self.isnt_pattern_start() {
957 self.struct_span_err(
959 format!("expected pattern, found {}", super::token_descr(&self.token)),
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",
966 Applicability::MaybeIncorrect,
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"))?)
978 Ok(PatKind::Ident(BindingAnnotation::NONE, Ident::new(kw::Box, box_span), sub))
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))
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();
990 let mut ate_comma = true;
991 let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
992 let mut etc_span = None;
994 while self.token != token::CloseDelim(Delimiter::Brace) {
995 let attrs = match self.parse_outer_attributes() {
998 if let Some(mut delayed) = delayed_err {
1004 let lo = self.token.span;
1006 // check that a comma comes after every field
1008 let err = self.struct_span_err(self.token.span, "expected `,`");
1009 if let Some(mut delayed) = delayed_err {
1016 if self.check(&token::DotDot) || self.token == token::DotDotDot {
1018 let mut etc_sp = self.token.span;
1020 self.recover_one_fewer_dotdot();
1021 self.bump(); // `..` || `...`
1023 if self.token == token::CloseDelim(Delimiter::Brace) {
1024 etc_span = Some(etc_sp);
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);
1031 err.span_label(self.token.span, "expected `}`");
1032 let mut comma_sp = None;
1033 if self.token == token::Comma {
1035 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
1036 etc_sp = etc_sp.to(nw_span);
1039 "`..` must be at the end and cannot have a trailing comma",
1041 comma_sp = Some(self.token.span);
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(
1052 "remove this comma",
1054 Applicability::MachineApplicable,
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
1064 if let Some(mut delayed_err) = delayed_err {
1068 delayed_err = Some(err);
1071 if let Some(mut err) = delayed_err {
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),
1083 if let Some(mut delayed_err) = delayed_err.take() {
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))
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",
1103 (etc_span, String::new()),
1104 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1106 Applicability::MachineApplicable,
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 {
1121 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
1124 "to omit remaining fields, use one fewer `.`",
1126 Applicability::MachineApplicable,
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.
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()?;
1138 let pat = self.parse_pat_allow_top_alt(
1142 CommaRecoveryMode::EitherTupleOrPipe,
1145 (pat, fieldname, false)
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;
1155 let mutability = match is_mut {
1156 false => Mutability::Not,
1157 true => Mutability::Mut,
1159 let ann = BindingAnnotation(ByRef::from(is_ref), mutability);
1160 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), ann, fieldname);
1162 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1163 (subpat, fieldname, true)
1171 id: ast::DUMMY_NODE_ID,
1173 is_placeholder: false,
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))
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 })