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};
5 use rustc_ast::token::{self, Delimiter};
7 self as ast, AttrVec, Attribute, BindingMode, Expr, ExprKind, MacCall, Mutability, Pat,
8 PatField, PatKind, Path, QSelf, RangeEnd, RangeSyntax,
10 use rustc_ast_pretty::pprust;
11 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
12 use rustc_span::source_map::{respan, Span, Spanned};
13 use rustc_span::symbol::{kw, sym, Ident};
15 pub(super) type Expected = Option<&'static str>;
17 /// `Expected` for function and lambda parameter patterns.
18 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
20 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
22 /// Whether or not to recover a `,` when parsing or-patterns.
23 #[derive(PartialEq, Copy, Clone)]
24 pub enum RecoverComma {
29 /// Whether or not to recover a `:` when parsing patterns that were meant to be paths.
30 #[derive(PartialEq, Copy, Clone)]
31 pub enum RecoverColon {
36 /// Whether or not to recover a `a, b` when parsing patterns as `(a, b)` or that *and* `a | b`.
37 #[derive(PartialEq, Copy, Clone)]
38 pub enum CommaRecoveryMode {
43 /// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
44 /// emitting duplicate diagnostics.
45 #[derive(Debug, Clone, Copy)]
47 /// We recovered from a trailing vert.
49 /// We ate an `|` (or `||` and recovered).
51 /// We did not eat anything (i.e. the current token is not `|` or `||`).
58 /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
59 /// at the top level. Used when parsing the parameters of lambda expressions,
60 /// functions, function pointers, and `pat` macro fragments.
61 pub fn parse_pat_no_top_alt(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
62 self.parse_pat_with_range_pat(true, expected)
67 /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
68 /// Used for parsing patterns in all cases when `pat<no_top_alt>` is not used.
70 /// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
71 /// a leading vert is allowed in nested or-patterns, too. This allows us to
72 /// simplify the grammar somewhat.
73 pub fn parse_pat_allow_top_alt(
78 rt: CommaRecoveryMode,
79 ) -> PResult<'a, P<Pat>> {
80 self.parse_pat_allow_top_alt_inner(expected, rc, ra, rt).map(|(pat, _)| pat)
83 /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
85 fn parse_pat_allow_top_alt_inner(
90 rt: CommaRecoveryMode,
91 ) -> PResult<'a, (P<Pat>, bool)> {
92 // Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
93 // suggestions (which bothers rustfix).
95 // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
96 let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
97 EatOrResult::AteOr => (Some(self.prev_token.span), false),
98 EatOrResult::TrailingVert => (None, true),
99 EatOrResult::None => (None, false),
102 // Parse the first pattern (`p_0`).
103 let mut first_pat = self.parse_pat_no_top_alt(expected)?;
104 if rc == RecoverComma::Yes {
105 self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
108 // If the next token is not a `|`,
109 // this is not an or-pattern and we should exit here.
110 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
111 // If we parsed a leading `|` which should be gated,
112 // then we should really gate the leading `|`.
113 // This complicated procedure is done purely for diagnostics UX.
115 // Check if the user wrote `foo:bar` instead of `foo::bar`.
116 if ra == RecoverColon::Yes {
117 first_pat = self.maybe_recover_colon_colon_in_pat_typo(first_pat, expected);
120 if let Some(leading_vert_span) = leading_vert_span {
121 // If there was a leading vert, treat this as an or-pattern. This improves
123 let span = leading_vert_span.to(self.prev_token.span);
124 return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
127 return Ok((first_pat, trailing_vert));
130 // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
131 let lo = leading_vert_span.unwrap_or(first_pat.span);
132 let mut pats = vec![first_pat];
134 match self.eat_or_separator(Some(lo)) {
135 EatOrResult::AteOr => {}
136 EatOrResult::None => break,
137 EatOrResult::TrailingVert => {
138 trailing_vert = true;
142 let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
143 err.span_label(lo, WHILE_PARSING_OR_MSG);
146 if rc == RecoverComma::Yes {
147 self.maybe_recover_unexpected_comma(pat.span, rt)?;
151 let or_pattern_span = lo.to(self.prev_token.span);
153 Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
156 /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
157 /// type annotation (e.g. for `let` bindings or `fn` params).
159 /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
160 /// eat the `Colon` token if one is present.
162 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
164 pub(super) fn parse_pat_before_ty(
169 ) -> PResult<'a, (P<Pat>, bool)> {
170 // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
171 // or-patterns so that we can detect when a user tries to use it. This allows us to print a
172 // better error message.
173 let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(
177 CommaRecoveryMode::LikelyTuple,
179 let colon = self.eat(&token::Colon);
181 if let PatKind::Or(pats) = &pat.kind {
182 let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc);
183 let (help, fix) = if pats.len() == 1 {
184 // If all we have is a leading vert, then print a special message. This is the case
185 // if `parse_pat_allow_top_alt` returns an or-pattern with one variant.
186 let msg = "remove the `|`";
187 let fix = pprust::pat_to_string(&pat);
190 let msg = "wrap the pattern in parentheses";
191 let fix = format!("({})", pprust::pat_to_string(&pat));
196 // We already emitted an error and suggestion to remove the trailing vert. Don't
198 self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
200 self.struct_span_err(pat.span, &msg)
201 .span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
209 /// Parse the pattern for a function or function pointer parameter, followed by a colon.
211 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
213 pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
214 // In order to get good UX, we first recover in the case of a leading vert for an illegal
215 // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
216 // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
218 if let token::OrOr = self.token.kind {
219 let span = self.token.span;
220 let mut err = self.struct_span_err(span, "unexpected `||` before function parameter");
221 err.span_suggestion(span, "remove the `||`", "", Applicability::MachineApplicable);
222 err.note("alternatives in or-patterns are separated with `|`, not `||`");
227 self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
230 /// Eat the or-pattern `|` separator.
231 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
232 fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
233 if self.recover_trailing_vert(lo) {
234 EatOrResult::TrailingVert
235 } else if matches!(self.token.kind, token::OrOr) {
236 // Found `||`; Recover and pretend we parsed `|`.
237 self.ban_unexpected_or_or(lo);
240 } else if self.eat(&token::BinOp(token::Or)) {
247 /// Recover if `|` or `||` is the current token and we have one of the
248 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
250 /// These tokens all indicate that we reached the end of the or-pattern
251 /// list and can now reliably say that the `|` was an illegal trailing vert.
252 /// Note that there are more tokens such as `@` for which we know that the `|`
253 /// is an illegal parse. However, the user's intent is less clear in that case.
254 fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
255 let is_end_ahead = self.look_ahead(1, |token| {
257 &token.uninterpolate().kind,
258 token::FatArrow // e.g. `a | => 0,`.
259 | token::Ident(kw::If, false) // e.g. `a | if expr`.
260 | token::Eq // e.g. `let a | = 0`.
261 | token::Semi // e.g. `let a |;`.
262 | token::Colon // e.g. `let a | :`.
263 | token::Comma // e.g. `let (a |,)`.
264 | token::CloseDelim(Delimiter::Bracket) // e.g. `let [a | ]`.
265 | token::CloseDelim(Delimiter::Parenthesis) // e.g. `let (a | )`.
266 | token::CloseDelim(Delimiter::Brace) // e.g. `let A { f: a | }`.
269 match (is_end_ahead, &self.token.kind) {
270 (true, token::BinOp(token::Or) | token::OrOr) => {
271 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
279 /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
280 fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
281 let mut err = self.struct_span_err(self.token.span, "unexpected token `||` in pattern");
284 "use a single `|` to separate multiple alternative patterns",
286 Applicability::MachineApplicable,
288 if let Some(lo) = lo {
289 err.span_label(lo, WHILE_PARSING_OR_MSG);
294 /// A `|` or possibly `||` token shouldn't be here. Ban it.
295 fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
296 let span = self.token.span;
297 let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
300 &format!("remove the `{}`", pprust::token_to_string(&self.token)),
302 Applicability::MachineApplicable,
304 if let Some(lo) = lo {
305 err.span_label(lo, WHILE_PARSING_OR_MSG);
307 if let token::OrOr = self.token.kind {
308 err.note("alternatives in or-patterns are separated with `|`, not `||`");
313 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
315 fn parse_pat_with_range_pat(
317 allow_range_pat: bool,
319 ) -> PResult<'a, P<Pat>> {
320 maybe_recover_from_interpolated_ty_qpath!(self, true);
321 maybe_whole!(self, NtPat, |x| x);
323 let lo = self.token.span;
325 let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
326 self.parse_pat_deref(expected)?
327 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
328 self.parse_pat_tuple_or_parens()?
329 } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
330 // Parse `[pat, pat,...]` as a slice pattern.
331 let (pats, _) = self.parse_delim_comma_seq(Delimiter::Bracket, |p| {
332 p.parse_pat_allow_top_alt(
336 CommaRecoveryMode::EitherTupleOrPipe,
340 } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
341 // A rest pattern `..`.
344 } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
345 self.recover_dotdotdot_rest_pat(lo)
346 } else if let Some(form) = self.parse_range_end() {
347 self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
348 } else if self.eat_keyword(kw::Underscore) {
351 } else if self.eat_keyword(kw::Mut) {
352 self.parse_pat_ident_mut()?
353 } else if self.eat_keyword(kw::Ref) {
354 // Parse ref ident @ pat / ref mut ident @ pat
355 let mutbl = self.parse_mutability();
356 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
357 } else if self.eat_keyword(kw::Box) {
358 self.parse_pat_box()?
359 } else if self.check_inline_const(0) {
361 let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
363 if let Some(re) = self.parse_range_end() {
364 self.parse_pat_range_begin_with(const_expr, re)?
366 PatKind::Lit(const_expr)
368 } else if self.can_be_ident_pat() {
369 // Parse `ident @ pat`
370 // This can give false positives and parse nullary enums,
371 // they are dealt with later in resolve.
372 self.parse_pat_ident(BindingMode::ByValue(Mutability::Not))?
373 } else if self.is_start_of_pat_with_path() {
374 // Parse pattern starting with a path
375 let (qself, path) = if self.eat_lt() {
376 // Parse a qualified path
377 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
380 // Parse an unqualified path
381 (None, self.parse_path(PathStyle::Expr)?)
383 let span = lo.to(self.prev_token.span);
385 if qself.is_none() && self.check(&token::Not) {
386 self.parse_pat_mac_invoc(path)?
387 } else if let Some(form) = self.parse_range_end() {
388 let begin = self.mk_expr(span, ExprKind::Path(qself, path), AttrVec::new());
389 self.parse_pat_range_begin_with(begin, form)?
390 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
391 self.parse_pat_struct(qself, path)?
392 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
393 self.parse_pat_tuple_struct(qself, path)?
395 PatKind::Path(qself, path)
398 // Try to parse everything else as literal with optional minus
399 match self.parse_literal_maybe_minus() {
400 Ok(begin) => match self.parse_range_end() {
401 Some(form) => self.parse_pat_range_begin_with(begin, form)?,
402 None => PatKind::Lit(begin),
404 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
408 let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
409 let pat = self.maybe_recover_from_bad_qpath(pat)?;
410 let pat = self.recover_intersection_pat(pat)?;
412 if !allow_range_pat {
413 self.ban_pat_range_if_ambiguous(&pat)
419 /// Recover from a typoed `...` pattern that was encountered
420 /// Ref: Issue #70388
421 fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
422 // A typoed rest pattern `...`.
423 self.bump(); // `...`
425 // The user probably mistook `...` for a rest pattern `..`.
426 self.struct_span_err(lo, "unexpected `...`")
427 .span_label(lo, "not a valid pattern")
428 .span_suggestion_short(
430 "for a rest pattern, use `..` instead of `...`",
432 Applicability::MachineApplicable,
438 /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
440 /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
441 /// should already have been parsed by now at this point,
442 /// if the next token is `@` then we can try to parse the more general form.
444 /// Consult `parse_pat_ident` for the `binding` grammar.
446 /// The notion of intersection patterns are found in
447 /// e.g. [F#][and] where they are called AND-patterns.
449 /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
450 fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
451 if self.token.kind != token::At {
452 // Next token is not `@` so it's not going to be an intersection pattern.
456 // At this point we attempt to parse `@ $pat_rhs` and emit an error.
458 let mut rhs = self.parse_pat_no_top_alt(None)?;
459 let sp = lhs.span.to(rhs.span);
461 if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
462 // The user inverted the order, so help them fix that.
463 let mut applicability = Applicability::MachineApplicable;
464 // FIXME(bindings_after_at): Remove this code when stabilizing the feature.
465 lhs.walk(&mut |p| match p.kind {
466 // `check_match` is unhappy if the subpattern has a binding anywhere.
467 PatKind::Ident(..) => {
468 applicability = Applicability::MaybeIncorrect;
469 false // Short-circuit.
474 let lhs_span = lhs.span;
475 // Move the LHS into the RHS as a subpattern.
476 // The RHS is now the full pattern.
479 self.struct_span_err(sp, "pattern on wrong side of `@`")
480 .span_label(lhs_span, "pattern on the left, should be on the right")
481 .span_label(rhs.span, "binding on the right, should be on the left")
482 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
485 // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
486 rhs.kind = PatKind::Wild;
487 self.struct_span_err(sp, "left-hand side of `@` must be a binding")
488 .span_label(lhs.span, "interpreted as a pattern, not a binding")
489 .span_label(rhs.span, "also a pattern")
490 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
498 /// Ban a range pattern if it has an ambiguous interpretation.
499 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
503 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
505 PatKind::Range(..) => {}
509 self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
512 "add parentheses to clarify the precedence",
513 format!("({})", pprust::pat_to_string(&pat)),
514 // "ambiguous interpretation" implies that we have to be guessing
515 Applicability::MaybeIncorrect,
520 /// Parse `&pat` / `&mut pat`.
521 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
523 self.recover_lifetime_in_deref_pat();
524 let mutbl = self.parse_mutability();
525 let subpat = self.parse_pat_with_range_pat(false, expected)?;
526 Ok(PatKind::Ref(subpat, mutbl))
529 fn recover_lifetime_in_deref_pat(&mut self) {
530 if let token::Lifetime(name) = self.token.kind {
533 let span = self.prev_token.span;
534 self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
535 .span_suggestion(span, "remove the lifetime", "", Applicability::MachineApplicable)
540 /// Parse a tuple or parenthesis pattern.
541 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
542 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
543 p.parse_pat_allow_top_alt(
547 CommaRecoveryMode::LikelyTuple,
551 // Here, `(pat,)` is a tuple pattern.
552 // For backward compatibility, `(..)` is a tuple pattern as well.
553 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
554 PatKind::Paren(fields.into_iter().next().unwrap())
556 PatKind::Tuple(fields)
560 /// Parse a mutable binding with the `mut` token already eaten.
561 fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
562 let mut_span = self.prev_token.span;
564 if self.eat_keyword(kw::Ref) {
565 return self.recover_mut_ref_ident(mut_span);
568 self.recover_additional_muts();
570 // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
571 if let token::Interpolated(ref nt) = self.token.kind {
572 if let token::NtPat(_) = **nt {
573 self.expected_ident_found().emit();
577 // Parse the pattern we hope to be an identifier.
578 let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
580 // If we don't have `mut $ident (@ pat)?`, error.
581 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind {
582 // Don't recurse into the subpattern.
583 // `mut` on the outer binding doesn't affect the inner bindings.
584 *m = Mutability::Mut;
586 // Add `mut` to any binding in the parsed pattern.
587 let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
588 self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
591 Ok(pat.into_inner().kind)
594 /// Recover on `mut ref? ident @ pat` and suggest
595 /// that the order of `mut` and `ref` is incorrect.
596 fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
597 let mutref_span = lo.to(self.prev_token.span);
598 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
601 "try switching the order",
603 Applicability::MachineApplicable,
607 self.parse_pat_ident(BindingMode::ByRef(Mutability::Mut))
610 /// Turn all by-value immutable bindings in a pattern into mutable bindings.
611 /// Returns `true` if any change was made.
612 fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
614 impl MutVisitor for AddMut {
615 fn visit_pat(&mut self, pat: &mut P<Pat>) {
616 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind
619 *m = Mutability::Mut;
621 noop_visit_pat(pat, self);
625 let mut add_mut = AddMut(false);
626 add_mut.visit_pat(pat);
630 /// Error on `mut $pat` where `$pat` is not an ident.
631 fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
632 let span = lo.to(pat.span);
633 let fix = pprust::pat_to_string(&pat);
634 let (problem, suggestion) = if changed_any_binding {
635 ("`mut` must be attached to each individual binding", "add `mut` to each binding")
637 ("`mut` must be followed by a named binding", "remove the `mut` prefix")
639 self.struct_span_err(span, problem)
640 .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
641 .note("`mut` may be followed by `variable` and `variable @ pattern`")
645 /// Eat any extraneous `mut`s and error + recover if we ate any.
646 fn recover_additional_muts(&mut self) {
647 let lo = self.token.span;
648 while self.eat_keyword(kw::Mut) {}
649 if lo == self.token.span {
653 let span = lo.to(self.prev_token.span);
654 self.struct_span_err(span, "`mut` on a binding may not be repeated")
657 "remove the additional `mut`s",
659 Applicability::MachineApplicable,
664 /// Parse macro invocation
665 fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
667 let args = self.parse_mac_args()?;
668 let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
669 Ok(PatKind::MacCall(mac))
672 fn fatal_unexpected_non_pat(
674 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
676 ) -> PResult<'a, P<Pat>> {
679 let expected = expected.unwrap_or("pattern");
680 let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
682 let mut err = self.struct_span_err(self.token.span, &msg);
683 err.span_label(self.token.span, format!("expected {}", expected));
685 let sp = self.sess.source_map().start_point(self.token.span);
686 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
687 self.sess.expr_parentheses_needed(&mut err, *sp);
693 /// Parses the range pattern end form `".." | "..." | "..=" ;`.
694 fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
695 let re = if self.eat(&token::DotDotDot) {
696 RangeEnd::Included(RangeSyntax::DotDotDot)
697 } else if self.eat(&token::DotDotEq) {
698 RangeEnd::Included(RangeSyntax::DotDotEq)
699 } else if self.eat(&token::DotDot) {
704 Some(respan(self.prev_token.span, re))
707 /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
708 /// `$begin $form` has already been parsed.
709 fn parse_pat_range_begin_with(
712 re: Spanned<RangeEnd>,
713 ) -> PResult<'a, PatKind> {
714 let end = if self.is_pat_range_end_start(0) {
715 // Parsing e.g. `X..=Y`.
716 Some(self.parse_pat_range_end()?)
718 // Parsing e.g. `X..`.
719 if let RangeEnd::Included(_) = re.node {
720 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
721 self.inclusive_range_with_incorrect_end(re.span);
725 Ok(PatKind::Range(Some(begin), end, re))
728 pub(super) fn inclusive_range_with_incorrect_end(&mut self, span: Span) {
729 let tok = &self.token;
731 // If the user typed "..==" instead of "..=", we want to give them
732 // a specific error message telling them to use "..=".
733 // Otherwise, we assume that they meant to type a half open exclusive
734 // range and give them an error telling them to do that instead.
735 if matches!(tok.kind, token::Eq) && tok.span.lo() == span.hi() {
736 let span_with_eq = span.to(tok.span);
738 // Ensure the user doesn't receive unhelpful unexpected token errors
740 if self.is_pat_range_end_start(0) {
741 let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
744 self.error_inclusive_range_with_extra_equals(span_with_eq);
746 self.error_inclusive_range_with_no_end(span);
750 fn error_inclusive_range_with_extra_equals(&self, span: Span) {
751 self.struct_span_err(span, "unexpected `=` after inclusive range")
752 .span_suggestion_short(span, "use `..=` instead", "..=", Applicability::MaybeIncorrect)
753 .note("inclusive ranges end with a single equals sign (`..=`)")
757 fn error_inclusive_range_with_no_end(&self, span: Span) {
758 struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
759 .span_suggestion_short(span, "use `..` instead", "..", Applicability::MachineApplicable)
760 .note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
764 /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
766 /// The form `...X` is prohibited to reduce confusion with the potential
767 /// expression syntax `...expr` for splatting in expressions.
768 fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
769 let end = self.parse_pat_range_end()?;
770 self.sess.gated_spans.gate(sym::half_open_range_patterns, re.span.to(self.prev_token.span));
771 if let RangeEnd::Included(ref mut syn @ RangeSyntax::DotDotDot) = &mut re.node {
772 *syn = RangeSyntax::DotDotEq;
773 self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
774 .span_suggestion_short(
778 Applicability::MachineApplicable,
782 Ok(PatKind::Range(None, Some(end), re))
785 /// Is the token `dist` away from the current suitable as the start of a range patterns end?
786 fn is_pat_range_end_start(&self, dist: usize) -> bool {
787 self.check_inline_const(dist)
788 || self.look_ahead(dist, |t| {
789 t.is_path_start() // e.g. `MY_CONST`;
790 || t.kind == token::Dot // e.g. `.5` for recovery;
791 || t.can_begin_literal_maybe_minus() // e.g. `42`.
796 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
797 if self.check_inline_const(0) {
798 self.parse_const_block(self.token.span, true)
799 } else if self.check_path() {
800 let lo = self.token.span;
801 let (qself, path) = if self.eat_lt() {
802 // Parse a qualified path
803 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
806 // Parse an unqualified path
807 (None, self.parse_path(PathStyle::Expr)?)
809 let hi = self.prev_token.span;
810 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), AttrVec::new()))
812 self.parse_literal_maybe_minus()
816 /// Is this the start of a pattern beginning with a path?
817 fn is_start_of_pat_with_path(&mut self) -> bool {
819 // Just for recovery (see `can_be_ident`).
820 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
823 /// Would `parse_pat_ident` be appropriate here?
824 fn can_be_ident_pat(&mut self) -> bool {
826 && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
827 && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
828 // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
829 && !self.token.is_keyword(kw::In)
830 // Try to do something more complex?
831 && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(Delimiter::Parenthesis) // A tuple struct pattern.
832 | token::OpenDelim(Delimiter::Brace) // A struct pattern.
833 | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
834 | token::ModSep // A tuple / struct variant pattern.
835 | token::Not)) // A macro expanding to a pattern.
838 /// Parses `ident` or `ident @ pat`.
839 /// Used by the copy foo and ref foo patterns to give a good
840 /// error message when parsing mistakes like `ref foo(a, b)`.
841 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
842 let ident = self.parse_ident()?;
843 let sub = if self.eat(&token::At) {
844 Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
849 // Just to be friendly, if they write something like `ref Some(i)`,
850 // we end up here with `(` as the current token.
851 // This shortly leads to a parse error. Note that if there is no explicit
852 // binding mode then we do not end up here, because the lookahead
853 // will direct us over to `parse_enum_variant()`.
854 if self.token == token::OpenDelim(Delimiter::Parenthesis) {
856 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
859 Ok(PatKind::Ident(binding_mode, ident, sub))
862 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
863 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
865 // Feature gate the use of qualified paths in patterns
866 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
869 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
870 e.span_label(path.span, "while parsing the fields for this pattern");
876 Ok(PatKind::Struct(qself, path, fields, etc))
879 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
880 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
881 let (fields, _) = self.parse_paren_comma_seq(|p| {
882 p.parse_pat_allow_top_alt(
886 CommaRecoveryMode::EitherTupleOrPipe,
890 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
892 Ok(PatKind::TupleStruct(qself, path, fields))
895 /// Are we sure this could not possibly be the start of a pattern?
897 /// Currently, this only accounts for tokens that can follow identifiers
898 /// in patterns, but this can be extended as necessary.
899 fn isnt_pattern_start(&self) -> bool {
906 token::OpenDelim(Delimiter::Brace),
907 token::CloseDelim(Delimiter::Brace),
908 token::CloseDelim(Delimiter::Parenthesis),
910 .contains(&self.token.kind)
914 fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
915 let box_span = self.prev_token.span;
917 if self.isnt_pattern_start() {
918 self.struct_span_err(
920 format!("expected pattern, found {}", super::token_descr(&self.token)),
922 .span_note(box_span, "`box` is a reserved keyword")
923 .span_suggestion_verbose(
924 box_span.shrink_to_lo(),
925 "escape `box` to use it as an identifier",
927 Applicability::MaybeIncorrect,
931 // We cannot use `parse_pat_ident()` since it will complain `box`
932 // is not an identifier.
933 let sub = if self.eat(&token::At) {
934 Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
940 BindingMode::ByValue(Mutability::Not),
941 Ident::new(kw::Box, box_span),
945 let pat = self.parse_pat_with_range_pat(false, None)?;
946 self.sess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span));
947 Ok(PatKind::Box(pat))
951 /// Parses the fields of a struct-like pattern.
952 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
953 let mut fields = Vec::new();
955 let mut ate_comma = true;
956 let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
957 let mut etc_span = None;
959 while self.token != token::CloseDelim(Delimiter::Brace) {
960 let attrs = match self.parse_outer_attributes() {
963 if let Some(mut delayed) = delayed_err {
969 let lo = self.token.span;
971 // check that a comma comes after every field
973 let err = self.struct_span_err(self.token.span, "expected `,`");
974 if let Some(mut delayed) = delayed_err {
981 if self.check(&token::DotDot) || self.token == token::DotDotDot {
983 let mut etc_sp = self.token.span;
985 self.recover_one_fewer_dotdot();
986 self.bump(); // `..` || `...`
988 if self.token == token::CloseDelim(Delimiter::Brace) {
989 etc_span = Some(etc_sp);
992 let token_str = super::token_descr(&self.token);
993 let msg = &format!("expected `}}`, found {}", token_str);
994 let mut err = self.struct_span_err(self.token.span, msg);
996 err.span_label(self.token.span, "expected `}`");
997 let mut comma_sp = None;
998 if self.token == token::Comma {
1000 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
1001 etc_sp = etc_sp.to(nw_span);
1004 "`..` must be at the end and cannot have a trailing comma",
1006 comma_sp = Some(self.token.span);
1011 etc_span = Some(etc_sp.until(self.token.span));
1012 if self.token == token::CloseDelim(Delimiter::Brace) {
1013 // If the struct looks otherwise well formed, recover and continue.
1014 if let Some(sp) = comma_sp {
1015 err.span_suggestion_short(
1017 "remove this comma",
1019 Applicability::MachineApplicable,
1024 } else if self.token.is_ident() && ate_comma {
1025 // Accept fields coming after `..,`.
1026 // This way we avoid "pattern missing fields" errors afterwards.
1027 // We delay this error until the end in order to have a span for a
1029 if let Some(mut delayed_err) = delayed_err {
1033 delayed_err = Some(err);
1036 if let Some(mut err) = delayed_err {
1044 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1045 let field = match this.parse_pat_field(lo, attrs) {
1046 Ok(field) => Ok(field),
1048 if let Some(mut delayed_err) = delayed_err.take() {
1054 ate_comma = this.eat(&token::Comma);
1055 // We just ate a comma, so there's no need to use
1056 // `TrailingToken::Comma`
1057 Ok((field, TrailingToken::None))
1063 if let Some(mut err) = delayed_err {
1064 if let Some(etc_span) = etc_span {
1065 err.multipart_suggestion(
1066 "move the `..` to the end of the field list",
1068 (etc_span, String::new()),
1069 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1071 Applicability::MachineApplicable,
1079 /// Recover on `...` as if it were `..` to avoid further errors.
1080 /// See issue #46718.
1081 fn recover_one_fewer_dotdot(&self) {
1082 if self.token != token::DotDotDot {
1086 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
1089 "to omit remaining fields, use one fewer `.`",
1091 Applicability::MachineApplicable,
1096 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, PatField> {
1097 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1099 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1100 // Parsing a pattern of the form `fieldname: pat`.
1101 let fieldname = self.parse_field_name()?;
1103 let pat = self.parse_pat_allow_top_alt(
1107 CommaRecoveryMode::EitherTupleOrPipe,
1110 (pat, fieldname, false)
1112 // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1113 let is_box = self.eat_keyword(kw::Box);
1114 let boxed_span = self.token.span;
1115 let is_ref = self.eat_keyword(kw::Ref);
1116 let is_mut = self.eat_keyword(kw::Mut);
1117 let fieldname = self.parse_field_name()?;
1118 hi = self.prev_token.span;
1120 let bind_type = match (is_ref, is_mut) {
1121 (true, true) => BindingMode::ByRef(Mutability::Mut),
1122 (true, false) => BindingMode::ByRef(Mutability::Not),
1123 (false, true) => BindingMode::ByValue(Mutability::Mut),
1124 (false, false) => BindingMode::ByValue(Mutability::Not),
1127 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
1129 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1130 (subpat, fieldname, true)
1137 attrs: attrs.into(),
1138 id: ast::DUMMY_NODE_ID,
1140 is_placeholder: false,
1144 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1145 self.mk_pat(span, PatKind::Ident(bm, ident, None))
1148 pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1149 P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })