1 use super::{ForceCollect, Parser, PathStyle, TrailingToken};
3 AmbiguousRangePattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed,
4 DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt,
5 ExpectedCommaAfterPatternField, InclusiveRangeExtraEquals, InclusiveRangeMatchArrow,
6 InclusiveRangeNoEnd, InvalidMutInPattern, PatternOnWrongSideOfAt, RefMutOrderIncorrect,
7 RemoveLet, RepeatedMutInPattern, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg,
8 TrailingVertNotAllowed, UnexpectedLifetimeInPattern, UnexpectedVertVertBeforeFunctionParam,
9 UnexpectedVertVertInPattern,
11 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
12 use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor};
13 use rustc_ast::ptr::P;
14 use rustc_ast::token::{self, Delimiter};
16 self as ast, AttrVec, BindingAnnotation, ByRef, Expr, ExprKind, MacCall, Mutability, Pat,
17 PatField, PatKind, Path, QSelf, RangeEnd, RangeSyntax,
19 use rustc_ast_pretty::pprust;
21 fluent, Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, PResult,
23 use rustc_session::errors::ExprParenthesesNeeded;
24 use rustc_span::source_map::{respan, Span, Spanned};
25 use rustc_span::symbol::{kw, sym, Ident};
27 #[derive(PartialEq, Copy, Clone)]
36 // FIXME(#100717): migrate users of this to proper localization
37 fn to_string_or_fallback(expected: Option<Expected>) -> &'static str {
39 Some(Expected::ParameterName) => "parameter name",
40 Some(Expected::ArgumentName) => "argument name",
41 Some(Expected::Identifier) => "identifier",
42 Some(Expected::BindingPattern) => "binding pattern",
48 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
50 /// Whether or not to recover a `,` when parsing or-patterns.
51 #[derive(PartialEq, Copy, Clone)]
52 pub enum RecoverComma {
57 /// Whether or not to recover a `:` when parsing patterns that were meant to be paths.
58 #[derive(PartialEq, Copy, Clone)]
59 pub enum RecoverColon {
64 /// Whether or not to recover a `a, b` when parsing patterns as `(a, b)` or that *and* `a | b`.
65 #[derive(PartialEq, Copy, Clone)]
66 pub enum CommaRecoveryMode {
71 /// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
72 /// emitting duplicate diagnostics.
73 #[derive(Debug, Clone, Copy)]
75 /// We recovered from a trailing vert.
77 /// We ate an `|` (or `||` and recovered).
79 /// We did not eat anything (i.e. the current token is not `|` or `||`).
83 /// The syntax location of a given pattern. Used for diagnostics.
84 pub(super) enum PatternLocation {
92 /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
93 /// at the top level. Used when parsing the parameters of lambda expressions,
94 /// functions, function pointers, and `pat` macro fragments.
95 pub fn parse_pat_no_top_alt(&mut self, expected: Option<Expected>) -> PResult<'a, P<Pat>> {
96 self.parse_pat_with_range_pat(true, expected)
101 /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
102 /// Used for parsing patterns in all cases when `pat<no_top_alt>` is not used.
104 /// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
105 /// a leading vert is allowed in nested or-patterns, too. This allows us to
106 /// simplify the grammar somewhat.
107 pub fn parse_pat_allow_top_alt(
109 expected: Option<Expected>,
112 rt: CommaRecoveryMode,
113 ) -> PResult<'a, P<Pat>> {
114 self.parse_pat_allow_top_alt_inner(expected, rc, ra, rt).map(|(pat, _)| pat)
117 /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
119 fn parse_pat_allow_top_alt_inner(
121 expected: Option<Expected>,
124 rt: CommaRecoveryMode,
125 ) -> PResult<'a, (P<Pat>, bool)> {
126 // Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
127 // suggestions (which bothers rustfix).
129 // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
130 let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
131 EatOrResult::AteOr => (Some(self.prev_token.span), false),
132 EatOrResult::TrailingVert => (None, true),
133 EatOrResult::None => (None, false),
136 // Parse the first pattern (`p_0`).
137 let mut first_pat = self.parse_pat_no_top_alt(expected)?;
138 if rc == RecoverComma::Yes {
139 self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
142 // If the next token is not a `|`,
143 // this is not an or-pattern and we should exit here.
144 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
145 // If we parsed a leading `|` which should be gated,
146 // then we should really gate the leading `|`.
147 // This complicated procedure is done purely for diagnostics UX.
149 // Check if the user wrote `foo:bar` instead of `foo::bar`.
150 if ra == RecoverColon::Yes {
151 first_pat = self.maybe_recover_colon_colon_in_pat_typo(first_pat, expected);
154 if let Some(leading_vert_span) = leading_vert_span {
155 // If there was a leading vert, treat this as an or-pattern. This improves
157 let span = leading_vert_span.to(self.prev_token.span);
158 return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
161 return Ok((first_pat, trailing_vert));
164 // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
165 let lo = leading_vert_span.unwrap_or(first_pat.span);
166 let mut pats = vec![first_pat];
168 match self.eat_or_separator(Some(lo)) {
169 EatOrResult::AteOr => {}
170 EatOrResult::None => break,
171 EatOrResult::TrailingVert => {
172 trailing_vert = true;
176 let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
177 err.span_label(lo, WHILE_PARSING_OR_MSG);
180 if rc == RecoverComma::Yes {
181 self.maybe_recover_unexpected_comma(pat.span, rt)?;
185 let or_pattern_span = lo.to(self.prev_token.span);
187 Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
190 /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
191 /// type annotation (e.g. for `let` bindings or `fn` params).
193 /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
194 /// eat the `Colon` token if one is present.
196 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
198 pub(super) fn parse_pat_before_ty(
200 expected: Option<Expected>,
202 syntax_loc: PatternLocation,
203 ) -> PResult<'a, (P<Pat>, bool)> {
204 // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
205 // or-patterns so that we can detect when a user tries to use it. This allows us to print a
206 // better error message.
207 let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(
211 CommaRecoveryMode::LikelyTuple,
213 let colon = self.eat(&token::Colon);
215 if let PatKind::Or(pats) = &pat.kind {
219 // We already emitted an error and suggestion to remove the trailing vert. Don't
222 // FIXME(#100717): pass `TopLevelOrPatternNotAllowed::* { sub: None }` to
223 // `delay_span_bug()` instead of fluent message
224 self.sess.span_diagnostic.delay_span_bug(
227 PatternLocation::LetBinding => {
228 fluent::parse_or_pattern_not_allowed_in_let_binding
230 PatternLocation::FunctionParameter => {
231 fluent::parse_or_pattern_not_allowed_in_fn_parameters
236 let pat = pprust::pat_to_string(&pat);
237 let sub = if pats.len() == 1 {
238 Some(TopLevelOrPatternNotAllowedSugg::RemoveLeadingVert { span, pat })
240 Some(TopLevelOrPatternNotAllowedSugg::WrapInParens { span, pat })
243 self.sess.emit_err(match syntax_loc {
244 PatternLocation::LetBinding => {
245 TopLevelOrPatternNotAllowed::LetBinding { span, sub }
247 PatternLocation::FunctionParameter => {
248 TopLevelOrPatternNotAllowed::FunctionParameter { span, sub }
257 /// Parse the pattern for a function or function pointer parameter, followed by a colon.
259 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
261 pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
262 // In order to get good UX, we first recover in the case of a leading vert for an illegal
263 // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
264 // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
266 if let token::OrOr = self.token.kind {
267 self.sess.emit_err(UnexpectedVertVertBeforeFunctionParam { span: self.token.span });
271 self.parse_pat_before_ty(
272 Some(Expected::ParameterName),
274 PatternLocation::FunctionParameter,
278 /// Eat the or-pattern `|` separator.
279 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
280 fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
281 if self.recover_trailing_vert(lo) {
282 EatOrResult::TrailingVert
283 } else if matches!(self.token.kind, token::OrOr) {
284 // Found `||`; Recover and pretend we parsed `|`.
285 self.sess.emit_err(UnexpectedVertVertInPattern { span: self.token.span, start: lo });
288 } else if self.eat(&token::BinOp(token::Or)) {
295 /// Recover if `|` or `||` is the current token and we have one of the
296 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
298 /// These tokens all indicate that we reached the end of the or-pattern
299 /// list and can now reliably say that the `|` was an illegal trailing vert.
300 /// Note that there are more tokens such as `@` for which we know that the `|`
301 /// is an illegal parse. However, the user's intent is less clear in that case.
302 fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
303 let is_end_ahead = self.look_ahead(1, |token| {
305 &token.uninterpolate().kind,
306 token::FatArrow // e.g. `a | => 0,`.
307 | token::Ident(kw::If, false) // e.g. `a | if expr`.
308 | token::Eq // e.g. `let a | = 0`.
309 | token::Semi // e.g. `let a |;`.
310 | token::Colon // e.g. `let a | :`.
311 | token::Comma // e.g. `let (a |,)`.
312 | token::CloseDelim(Delimiter::Bracket) // e.g. `let [a | ]`.
313 | token::CloseDelim(Delimiter::Parenthesis) // e.g. `let (a | )`.
314 | token::CloseDelim(Delimiter::Brace) // e.g. `let A { f: a | }`.
317 match (is_end_ahead, &self.token.kind) {
318 (true, token::BinOp(token::Or) | token::OrOr) => {
319 // A `|` or possibly `||` token shouldn't be here. Ban it.
320 self.sess.emit_err(TrailingVertNotAllowed {
321 span: self.token.span,
323 token: self.token.clone(),
324 note_double_vert: matches!(self.token.kind, token::OrOr).then_some(()),
333 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
335 fn parse_pat_with_range_pat(
337 allow_range_pat: bool,
338 expected: Option<Expected>,
339 ) -> PResult<'a, P<Pat>> {
340 maybe_recover_from_interpolated_ty_qpath!(self, true);
341 maybe_whole!(self, NtPat, |x| x);
343 let mut lo = self.token.span;
345 if self.token.is_keyword(kw::Let) && self.look_ahead(1, |tok| tok.can_begin_pattern()) {
347 self.sess.emit_err(RemoveLet { span: lo });
348 lo = self.token.span;
351 let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
352 self.parse_pat_deref(expected)?
353 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
354 self.parse_pat_tuple_or_parens()?
355 } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
356 // Parse `[pat, pat,...]` as a slice pattern.
357 let (pats, _) = self.parse_delim_comma_seq(Delimiter::Bracket, |p| {
358 p.parse_pat_allow_top_alt(
362 CommaRecoveryMode::EitherTupleOrPipe,
366 } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
367 // A rest pattern `..`.
370 } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
371 self.recover_dotdotdot_rest_pat(lo)
372 } else if let Some(form) = self.parse_range_end() {
373 self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
374 } else if self.eat_keyword(kw::Underscore) {
377 } else if self.eat_keyword(kw::Mut) {
378 self.parse_pat_ident_mut()?
379 } else if self.eat_keyword(kw::Ref) {
380 // Parse ref ident @ pat / ref mut ident @ pat
381 let mutbl = self.parse_mutability();
382 self.parse_pat_ident(BindingAnnotation(ByRef::Yes, mutbl))?
383 } else if self.eat_keyword(kw::Box) {
384 self.parse_pat_box()?
385 } else if self.check_inline_const(0) {
387 let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
389 if let Some(re) = self.parse_range_end() {
390 self.parse_pat_range_begin_with(const_expr, re)?
392 PatKind::Lit(const_expr)
394 } else if self.can_be_ident_pat() {
395 // Parse `ident @ pat`
396 // This can give false positives and parse nullary enums,
397 // they are dealt with later in resolve.
398 self.parse_pat_ident(BindingAnnotation::NONE)?
399 } else if self.is_start_of_pat_with_path() {
400 // Parse pattern starting with a path
401 let (qself, path) = if self.eat_lt() {
402 // Parse a qualified path
403 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
406 // Parse an unqualified path
407 (None, self.parse_path(PathStyle::Expr)?)
409 let span = lo.to(self.prev_token.span);
411 if qself.is_none() && self.check(&token::Not) {
412 self.parse_pat_mac_invoc(path)?
413 } else if let Some(form) = self.parse_range_end() {
414 let begin = self.mk_expr(span, ExprKind::Path(qself, path));
415 self.parse_pat_range_begin_with(begin, form)?
416 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
417 self.parse_pat_struct(qself, path)?
418 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
419 self.parse_pat_tuple_struct(qself, path)?
421 PatKind::Path(qself, path)
423 } else if matches!(self.token.kind, token::Lifetime(_))
424 // In pattern position, we're totally fine with using "next token isn't colon"
425 // as a heuristic. We could probably just always try to recover if it's a lifetime,
426 // because we never have `'a: label {}` in a pattern position anyways, but it does
427 // keep us from suggesting something like `let 'a: Ty = ..` => `let 'a': Ty = ..`
428 && !self.look_ahead(1, |token| matches!(token.kind, token::Colon))
430 // Recover a `'a` as a `'a'` literal
431 let lt = self.expect_lifetime();
433 self.recover_unclosed_char(lt.ident, Parser::mk_token_lit_char, |self_| {
434 let expected = Expected::to_string_or_fallback(expected);
436 "expected {}, found {}",
438 super::token_descr(&self_.token)
441 let mut err = self_.struct_span_err(self_.token.span, &msg);
442 err.span_label(self_.token.span, format!("expected {}", expected));
445 PatKind::Lit(self.mk_expr(lo, ExprKind::Lit(lit)))
447 // Try to parse everything else as literal with optional minus
448 match self.parse_literal_maybe_minus() {
449 Ok(begin) => match self.parse_range_end() {
450 Some(form) => self.parse_pat_range_begin_with(begin, form)?,
451 None => PatKind::Lit(begin),
453 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
457 let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
458 let pat = self.maybe_recover_from_bad_qpath(pat)?;
459 let pat = self.recover_intersection_pat(pat)?;
461 if !allow_range_pat {
462 self.ban_pat_range_if_ambiguous(&pat)
468 /// Recover from a typoed `...` pattern that was encountered
469 /// Ref: Issue #70388
470 fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
471 // A typoed rest pattern `...`.
472 self.bump(); // `...`
474 // The user probably mistook `...` for a rest pattern `..`.
475 self.sess.emit_err(DotDotDotRestPattern { span: lo });
479 /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
481 /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
482 /// should already have been parsed by now at this point,
483 /// if the next token is `@` then we can try to parse the more general form.
485 /// Consult `parse_pat_ident` for the `binding` grammar.
487 /// The notion of intersection patterns are found in
488 /// e.g. [F#][and] where they are called AND-patterns.
490 /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
491 fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
492 if self.token.kind != token::At {
493 // Next token is not `@` so it's not going to be an intersection pattern.
497 // At this point we attempt to parse `@ $pat_rhs` and emit an error.
499 let mut rhs = self.parse_pat_no_top_alt(None)?;
500 let whole_span = lhs.span.to(rhs.span);
502 if let PatKind::Ident(_, _, sub @ None) = &mut rhs.kind {
503 // The user inverted the order, so help them fix that.
504 let lhs_span = lhs.span;
505 // Move the LHS into the RHS as a subpattern.
506 // The RHS is now the full pattern.
509 self.sess.emit_err(PatternOnWrongSideOfAt {
511 whole_pat: pprust::pat_to_string(&rhs),
516 // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
517 rhs.kind = PatKind::Wild;
518 self.sess.emit_err(ExpectedBindingLeftOfAt {
525 rhs.span = whole_span;
529 /// Ban a range pattern if it has an ambiguous interpretation.
530 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
534 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
536 PatKind::Range(..) => {}
541 .emit_err(AmbiguousRangePattern { span: pat.span, pat: pprust::pat_to_string(&pat) });
544 /// Parse `&pat` / `&mut pat`.
545 fn parse_pat_deref(&mut self, expected: Option<Expected>) -> PResult<'a, PatKind> {
547 if let token::Lifetime(name) = self.token.kind {
551 .emit_err(UnexpectedLifetimeInPattern { span: self.prev_token.span, symbol: name });
554 let mutbl = self.parse_mutability();
555 let subpat = self.parse_pat_with_range_pat(false, expected)?;
556 Ok(PatKind::Ref(subpat, mutbl))
559 /// Parse a tuple or parenthesis pattern.
560 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
561 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
562 p.parse_pat_allow_top_alt(
566 CommaRecoveryMode::LikelyTuple,
570 // Here, `(pat,)` is a tuple pattern.
571 // For backward compatibility, `(..)` is a tuple pattern as well.
572 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
573 PatKind::Paren(fields.into_iter().next().unwrap())
575 PatKind::Tuple(fields)
579 /// Parse a mutable binding with the `mut` token already eaten.
580 fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
581 let mut_span = self.prev_token.span;
583 if self.eat_keyword(kw::Ref) {
584 self.sess.emit_err(RefMutOrderIncorrect { span: mut_span.to(self.prev_token.span) });
585 return self.parse_pat_ident(BindingAnnotation::REF_MUT);
588 self.recover_additional_muts();
590 // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
591 if let token::Interpolated(nt) = &self.token.kind {
592 if let token::NtPat(_) = **nt {
593 self.expected_ident_found().emit();
597 // Parse the pattern we hope to be an identifier.
598 let mut pat = self.parse_pat_no_top_alt(Some(Expected::Identifier))?;
600 // If we don't have `mut $ident (@ pat)?`, error.
601 if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) = &mut pat.kind
603 // Don't recurse into the subpattern.
604 // `mut` on the outer binding doesn't affect the inner bindings.
605 *m = Mutability::Mut;
607 // Add `mut` to any binding in the parsed pattern.
608 let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
609 self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
612 Ok(pat.into_inner().kind)
615 /// Turn all by-value immutable bindings in a pattern into mutable bindings.
616 /// Returns `true` if any change was made.
617 fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
619 impl MutVisitor for AddMut {
620 fn visit_pat(&mut self, pat: &mut P<Pat>) {
621 if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) =
625 *m = Mutability::Mut;
627 noop_visit_pat(pat, self);
631 let mut add_mut = AddMut(false);
632 add_mut.visit_pat(pat);
636 /// Error on `mut $pat` where `$pat` is not an ident.
637 fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
638 let span = lo.to(pat.span);
639 let pat = pprust::pat_to_string(&pat);
641 self.sess.emit_err(if changed_any_binding {
642 InvalidMutInPattern::NestedIdent { span, pat }
644 InvalidMutInPattern::NonIdent { span, pat }
648 /// Eat any extraneous `mut`s and error + recover if we ate any.
649 fn recover_additional_muts(&mut self) {
650 let lo = self.token.span;
651 while self.eat_keyword(kw::Mut) {}
652 if lo == self.token.span {
656 self.sess.emit_err(RepeatedMutInPattern { span: lo.to(self.prev_token.span) });
659 /// Parse macro invocation
660 fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
662 let args = self.parse_delim_args()?;
663 let mac = P(MacCall { path, args, prior_type_ascription: self.last_type_ascription });
664 Ok(PatKind::MacCall(mac))
667 fn fatal_unexpected_non_pat(
669 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
670 expected: Option<Expected>,
671 ) -> PResult<'a, P<Pat>> {
674 let expected = Expected::to_string_or_fallback(expected);
675 let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
677 let mut err = self.struct_span_err(self.token.span, &msg);
678 err.span_label(self.token.span, format!("expected {}", expected));
680 let sp = self.sess.source_map().start_point(self.token.span);
681 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
682 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
688 /// Parses the range pattern end form `".." | "..." | "..=" ;`.
689 fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
690 let re = if self.eat(&token::DotDotDot) {
691 RangeEnd::Included(RangeSyntax::DotDotDot)
692 } else if self.eat(&token::DotDotEq) {
693 RangeEnd::Included(RangeSyntax::DotDotEq)
694 } else if self.eat(&token::DotDot) {
699 Some(respan(self.prev_token.span, re))
702 /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
703 /// `$begin $form` has already been parsed.
704 fn parse_pat_range_begin_with(
707 re: Spanned<RangeEnd>,
708 ) -> PResult<'a, PatKind> {
709 let end = if self.is_pat_range_end_start(0) {
710 // Parsing e.g. `X..=Y`.
711 Some(self.parse_pat_range_end()?)
713 // Parsing e.g. `X..`.
714 if let RangeEnd::Included(_) = re.node {
715 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
716 self.inclusive_range_with_incorrect_end();
720 Ok(PatKind::Range(Some(begin), end, re))
723 pub(super) fn inclusive_range_with_incorrect_end(&mut self) {
724 let tok = &self.token;
725 let span = self.prev_token.span;
726 // If the user typed "..==" instead of "..=", we want to give them
727 // a specific error message telling them to use "..=".
728 // If they typed "..=>", suggest they use ".. =>".
729 // Otherwise, we assume that they meant to type a half open exclusive
730 // range and give them an error telling them to do that instead.
731 let no_space = tok.span.lo() == span.hi();
733 token::Eq if no_space => {
734 let span_with_eq = span.to(tok.span);
736 // Ensure the user doesn't receive unhelpful unexpected token errors
738 if self.is_pat_range_end_start(0) {
739 let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
742 self.sess.emit_err(InclusiveRangeExtraEquals { span: span_with_eq });
744 token::Gt if no_space => {
745 let after_pat = span.with_hi(span.hi() - rustc_span::BytePos(1)).shrink_to_hi();
746 self.sess.emit_err(InclusiveRangeMatchArrow { span, arrow: tok.span, after_pat });
749 self.sess.emit_err(InclusiveRangeNoEnd { span });
754 /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
756 /// The form `...X` is prohibited to reduce confusion with the potential
757 /// expression syntax `...expr` for splatting in expressions.
758 fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
759 let end = self.parse_pat_range_end()?;
760 if let RangeEnd::Included(syn @ RangeSyntax::DotDotDot) = &mut re.node {
761 *syn = RangeSyntax::DotDotEq;
762 self.sess.emit_err(DotDotDotRangeToPatternNotAllowed { span: re.span });
764 Ok(PatKind::Range(None, Some(end), re))
767 /// Is the token `dist` away from the current suitable as the start of a range patterns end?
768 fn is_pat_range_end_start(&self, dist: usize) -> bool {
769 self.check_inline_const(dist)
770 || self.look_ahead(dist, |t| {
771 t.is_path_start() // e.g. `MY_CONST`;
772 || t.kind == token::Dot // e.g. `.5` for recovery;
773 || t.can_begin_literal_maybe_minus() // e.g. `42`.
775 || t.is_lifetime() // recover `'a` instead of `'a'`
779 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
780 if self.check_inline_const(0) {
781 self.parse_const_block(self.token.span, true)
782 } else if self.check_path() {
783 let lo = self.token.span;
784 let (qself, path) = if self.eat_lt() {
785 // Parse a qualified path
786 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
789 // Parse an unqualified path
790 (None, self.parse_path(PathStyle::Expr)?)
792 let hi = self.prev_token.span;
793 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
795 self.parse_literal_maybe_minus()
799 /// Is this the start of a pattern beginning with a path?
800 fn is_start_of_pat_with_path(&mut self) -> bool {
802 // Just for recovery (see `can_be_ident`).
803 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
806 /// Would `parse_pat_ident` be appropriate here?
807 fn can_be_ident_pat(&mut self) -> bool {
809 && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
810 && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
811 // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
812 && !self.token.is_keyword(kw::In)
813 // Try to do something more complex?
814 && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(Delimiter::Parenthesis) // A tuple struct pattern.
815 | token::OpenDelim(Delimiter::Brace) // A struct pattern.
816 | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
817 | token::ModSep // A tuple / struct variant pattern.
818 | token::Not)) // A macro expanding to a pattern.
821 /// Parses `ident` or `ident @ pat`.
822 /// Used by the copy foo and ref foo patterns to give a good
823 /// error message when parsing mistakes like `ref foo(a, b)`.
824 fn parse_pat_ident(&mut self, binding_annotation: BindingAnnotation) -> PResult<'a, PatKind> {
825 let ident = self.parse_ident()?;
826 let sub = if self.eat(&token::At) {
827 Some(self.parse_pat_no_top_alt(Some(Expected::BindingPattern))?)
832 // Just to be friendly, if they write something like `ref Some(i)`,
833 // we end up here with `(` as the current token.
834 // This shortly leads to a parse error. Note that if there is no explicit
835 // binding mode then we do not end up here, because the lookahead
836 // will direct us over to `parse_enum_variant()`.
837 if self.token == token::OpenDelim(Delimiter::Parenthesis) {
838 return Err(EnumPatternInsteadOfIdentifier { span: self.prev_token.span }
839 .into_diagnostic(&self.sess.span_diagnostic));
842 Ok(PatKind::Ident(binding_annotation, ident, sub))
845 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
846 fn parse_pat_struct(&mut self, qself: Option<P<QSelf>>, path: Path) -> PResult<'a, PatKind> {
848 // Feature gate the use of qualified paths in patterns
849 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
852 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
853 e.span_label(path.span, "while parsing the fields for this pattern");
859 Ok(PatKind::Struct(qself, path, fields, etc))
862 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
863 fn parse_pat_tuple_struct(
865 qself: Option<P<QSelf>>,
867 ) -> PResult<'a, PatKind> {
868 let (fields, _) = self.parse_paren_comma_seq(|p| {
869 p.parse_pat_allow_top_alt(
873 CommaRecoveryMode::EitherTupleOrPipe,
877 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
879 Ok(PatKind::TupleStruct(qself, path, fields))
882 /// Are we sure this could not possibly be the start of a pattern?
884 /// Currently, this only accounts for tokens that can follow identifiers
885 /// in patterns, but this can be extended as necessary.
886 fn isnt_pattern_start(&self) -> bool {
893 token::OpenDelim(Delimiter::Brace),
894 token::CloseDelim(Delimiter::Brace),
895 token::CloseDelim(Delimiter::Parenthesis),
897 .contains(&self.token.kind)
901 fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
902 let box_span = self.prev_token.span;
904 if self.isnt_pattern_start() {
905 self.struct_span_err(
907 format!("expected pattern, found {}", super::token_descr(&self.token)),
909 .span_note(box_span, "`box` is a reserved keyword")
910 .span_suggestion_verbose(
911 box_span.shrink_to_lo(),
912 "escape `box` to use it as an identifier",
914 Applicability::MaybeIncorrect,
918 // We cannot use `parse_pat_ident()` since it will complain `box`
919 // is not an identifier.
920 let sub = if self.eat(&token::At) {
921 Some(self.parse_pat_no_top_alt(Some(Expected::BindingPattern))?)
926 Ok(PatKind::Ident(BindingAnnotation::NONE, Ident::new(kw::Box, box_span), sub))
928 let pat = self.parse_pat_with_range_pat(false, None)?;
929 self.sess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span));
930 Ok(PatKind::Box(pat))
934 /// Parses the fields of a struct-like pattern.
935 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
936 let mut fields = Vec::new();
938 let mut ate_comma = true;
939 let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
940 let mut etc_span = None;
942 while self.token != token::CloseDelim(Delimiter::Brace) {
943 let attrs = match self.parse_outer_attributes() {
946 if let Some(mut delayed) = delayed_err {
952 let lo = self.token.span;
954 // check that a comma comes after every field
956 let err = ExpectedCommaAfterPatternField { span: self.token.span }
957 .into_diagnostic(&self.sess.span_diagnostic);
958 if let Some(mut delayed) = delayed_err {
965 if self.check(&token::DotDot)
966 || self.check_noexpect(&token::DotDotDot)
967 || self.check_keyword(kw::Underscore)
970 let mut etc_sp = self.token.span;
972 self.recover_bad_dot_dot();
973 self.bump(); // `..` || `...` || `_`
975 if self.token == token::CloseDelim(Delimiter::Brace) {
976 etc_span = Some(etc_sp);
979 let token_str = super::token_descr(&self.token);
980 let msg = &format!("expected `}}`, found {}", token_str);
981 let mut err = self.struct_span_err(self.token.span, msg);
983 err.span_label(self.token.span, "expected `}`");
984 let mut comma_sp = None;
985 if self.token == token::Comma {
987 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
988 etc_sp = etc_sp.to(nw_span);
991 "`..` must be at the end and cannot have a trailing comma",
993 comma_sp = Some(self.token.span);
998 etc_span = Some(etc_sp.until(self.token.span));
999 if self.token == token::CloseDelim(Delimiter::Brace) {
1000 // If the struct looks otherwise well formed, recover and continue.
1001 if let Some(sp) = comma_sp {
1002 err.span_suggestion_short(
1004 "remove this comma",
1006 Applicability::MachineApplicable,
1011 } else if self.token.is_ident() && ate_comma {
1012 // Accept fields coming after `..,`.
1013 // This way we avoid "pattern missing fields" errors afterwards.
1014 // We delay this error until the end in order to have a span for a
1016 if let Some(mut delayed_err) = delayed_err {
1020 delayed_err = Some(err);
1023 if let Some(mut err) = delayed_err {
1031 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1032 let field = match this.parse_pat_field(lo, attrs) {
1033 Ok(field) => Ok(field),
1035 if let Some(mut delayed_err) = delayed_err.take() {
1041 ate_comma = this.eat(&token::Comma);
1042 // We just ate a comma, so there's no need to use
1043 // `TrailingToken::Comma`
1044 Ok((field, TrailingToken::None))
1050 if let Some(mut err) = delayed_err {
1051 if let Some(etc_span) = etc_span {
1052 err.multipart_suggestion(
1053 "move the `..` to the end of the field list",
1055 (etc_span, String::new()),
1056 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1058 Applicability::MachineApplicable,
1066 /// Recover on `...` or `_` as if it were `..` to avoid further errors.
1067 /// See issue #46718.
1068 fn recover_bad_dot_dot(&self) {
1069 if self.token == token::DotDot {
1073 let token_str = pprust::token_to_string(&self.token);
1074 self.sess.emit_err(DotDotDotForRemainingFields { span: self.token.span, token_str });
1077 fn parse_pat_field(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, PatField> {
1078 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1080 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1081 // Parsing a pattern of the form `fieldname: pat`.
1082 let fieldname = self.parse_field_name()?;
1084 let pat = self.parse_pat_allow_top_alt(
1088 CommaRecoveryMode::EitherTupleOrPipe,
1091 (pat, fieldname, false)
1093 // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1094 let is_box = self.eat_keyword(kw::Box);
1095 let boxed_span = self.token.span;
1096 let is_ref = self.eat_keyword(kw::Ref);
1097 let is_mut = self.eat_keyword(kw::Mut);
1098 let fieldname = self.parse_field_name()?;
1099 hi = self.prev_token.span;
1101 let mutability = match is_mut {
1102 false => Mutability::Not,
1103 true => Mutability::Mut,
1105 let ann = BindingAnnotation(ByRef::from(is_ref), mutability);
1106 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), ann, fieldname);
1108 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1109 (subpat, fieldname, true)
1117 id: ast::DUMMY_NODE_ID,
1119 is_placeholder: false,
1123 pub(super) fn mk_pat_ident(&self, span: Span, ann: BindingAnnotation, ident: Ident) -> P<Pat> {
1124 self.mk_pat(span, PatKind::Ident(ann, ident, None))
1127 pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1128 P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })