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};
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 first_pat = self.parse_pat_no_top_alt(expected)?;
104 self.maybe_recover_unexpected_comma(first_pat.span, rc, rt)?;
106 // If the next token is not a `|`,
107 // this is not an or-pattern and we should exit here.
108 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
109 // If we parsed a leading `|` which should be gated,
110 // then we should really gate the leading `|`.
111 // This complicated procedure is done purely for diagnostics UX.
113 // Check if the user wrote `foo:bar` instead of `foo::bar`.
114 let first_pat = self.maybe_recover_colon_colon_in_pat_typo(first_pat, ra, expected);
116 if let Some(leading_vert_span) = leading_vert_span {
117 // If there was a leading vert, treat this as an or-pattern. This improves
119 let span = leading_vert_span.to(self.prev_token.span);
120 return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
123 return Ok((first_pat, trailing_vert));
126 // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
127 let lo = leading_vert_span.unwrap_or(first_pat.span);
128 let mut pats = vec![first_pat];
130 match self.eat_or_separator(Some(lo)) {
131 EatOrResult::AteOr => {}
132 EatOrResult::None => break,
133 EatOrResult::TrailingVert => {
134 trailing_vert = true;
138 let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
139 err.span_label(lo, WHILE_PARSING_OR_MSG);
142 self.maybe_recover_unexpected_comma(pat.span, rc, rt)?;
145 let or_pattern_span = lo.to(self.prev_token.span);
147 Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
150 /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
151 /// type annotation (e.g. for `let` bindings or `fn` params).
153 /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
154 /// eat the `Colon` token if one is present.
156 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
158 pub(super) fn parse_pat_before_ty(
163 ) -> PResult<'a, (P<Pat>, bool)> {
164 // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
165 // or-patterns so that we can detect when a user tries to use it. This allows us to print a
166 // better error message.
167 let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(
171 CommaRecoveryMode::LikelyTuple,
173 let colon = self.eat(&token::Colon);
175 if let PatKind::Or(pats) = &pat.kind {
176 let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc);
177 let (help, fix) = if pats.len() == 1 {
178 // If all we have is a leading vert, then print a special message. This is the case
179 // if `parse_pat_allow_top_alt` returns an or-pattern with one variant.
180 let msg = "remove the `|`";
181 let fix = pprust::pat_to_string(&pat);
184 let msg = "wrap the pattern in parentheses";
185 let fix = format!("({})", pprust::pat_to_string(&pat));
190 // We already emitted an error and suggestion to remove the trailing vert. Don't
192 self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
194 self.struct_span_err(pat.span, &msg)
195 .span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
203 /// Parse the pattern for a function or function pointer parameter, followed by a colon.
205 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
207 pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
208 // In order to get good UX, we first recover in the case of a leading vert for an illegal
209 // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
210 // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
212 if let token::OrOr = self.token.kind {
213 let span = self.token.span;
214 let mut err = self.struct_span_err(span, "unexpected `||` before function parameter");
219 Applicability::MachineApplicable,
221 err.note("alternatives in or-patterns are separated with `|`, not `||`");
226 self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
229 /// Eat the or-pattern `|` separator.
230 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
231 fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
232 if self.recover_trailing_vert(lo) {
233 EatOrResult::TrailingVert
234 } else if matches!(self.token.kind, token::OrOr) {
235 // Found `||`; Recover and pretend we parsed `|`.
236 self.ban_unexpected_or_or(lo);
239 } else if self.eat(&token::BinOp(token::Or)) {
246 /// Recover if `|` or `||` is the current token and we have one of the
247 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
249 /// These tokens all indicate that we reached the end of the or-pattern
250 /// list and can now reliably say that the `|` was an illegal trailing vert.
251 /// Note that there are more tokens such as `@` for which we know that the `|`
252 /// is an illegal parse. However, the user's intent is less clear in that case.
253 fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
254 let is_end_ahead = self.look_ahead(1, |token| {
256 &token.uninterpolate().kind,
257 token::FatArrow // e.g. `a | => 0,`.
258 | token::Ident(kw::If, false) // e.g. `a | if expr`.
259 | token::Eq // e.g. `let a | = 0`.
260 | token::Semi // e.g. `let a |;`.
261 | token::Colon // e.g. `let a | :`.
262 | token::Comma // e.g. `let (a |,)`.
263 | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
264 | token::CloseDelim(token::Paren) // e.g. `let (a | )`.
265 | token::CloseDelim(token::Brace) // e.g. `let A { f: a | }`.
268 match (is_end_ahead, &self.token.kind) {
269 (true, token::BinOp(token::Or) | token::OrOr) => {
270 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
278 /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
279 fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
280 let mut err = self.struct_span_err(self.token.span, "unexpected token `||` in pattern");
283 "use a single `|` to separate multiple alternative patterns",
285 Applicability::MachineApplicable,
287 if let Some(lo) = lo {
288 err.span_label(lo, WHILE_PARSING_OR_MSG);
293 /// A `|` or possibly `||` token shouldn't be here. Ban it.
294 fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
295 let span = self.token.span;
296 let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
299 &format!("remove the `{}`", pprust::token_to_string(&self.token)),
301 Applicability::MachineApplicable,
303 if let Some(lo) = lo {
304 err.span_label(lo, WHILE_PARSING_OR_MSG);
306 if let token::OrOr = self.token.kind {
307 err.note("alternatives in or-patterns are separated with `|`, not `||`");
312 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
314 fn parse_pat_with_range_pat(
316 allow_range_pat: bool,
318 ) -> PResult<'a, P<Pat>> {
319 maybe_recover_from_interpolated_ty_qpath!(self, true);
320 maybe_whole!(self, NtPat, |x| x);
322 let lo = self.token.span;
324 let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
325 self.parse_pat_deref(expected)?
326 } else if self.check(&token::OpenDelim(token::Paren)) {
327 self.parse_pat_tuple_or_parens()?
328 } else if self.check(&token::OpenDelim(token::Bracket)) {
329 // Parse `[pat, pat,...]` as a slice pattern.
330 let (pats, _) = self.parse_delim_comma_seq(token::Bracket, |p| {
331 p.parse_pat_allow_top_alt(
335 CommaRecoveryMode::EitherTupleOrPipe,
339 } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
340 // A rest pattern `..`.
343 } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
344 self.recover_dotdotdot_rest_pat(lo)
345 } else if let Some(form) = self.parse_range_end() {
346 self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
347 } else if self.eat_keyword(kw::Underscore) {
350 } else if self.eat_keyword(kw::Mut) {
351 self.parse_pat_ident_mut()?
352 } else if self.eat_keyword(kw::Ref) {
353 // Parse ref ident @ pat / ref mut ident @ pat
354 let mutbl = self.parse_mutability();
355 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
356 } else if self.eat_keyword(kw::Box) {
358 let pat = self.parse_pat_with_range_pat(false, None)?;
359 self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_token.span));
361 } else if self.check_inline_const(0) {
363 let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
365 if let Some(re) = self.parse_range_end() {
366 self.parse_pat_range_begin_with(const_expr, re)?
368 PatKind::Lit(const_expr)
370 } else if self.can_be_ident_pat() {
371 // Parse `ident @ pat`
372 // This can give false positives and parse nullary enums,
373 // they are dealt with later in resolve.
374 self.parse_pat_ident(BindingMode::ByValue(Mutability::Not))?
375 } else if self.is_start_of_pat_with_path() {
376 // Parse pattern starting with a path
377 let (qself, path) = if self.eat_lt() {
378 // Parse a qualified path
379 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
382 // Parse an unqualified path
383 (None, self.parse_path(PathStyle::Expr)?)
385 let span = lo.to(self.prev_token.span);
387 if qself.is_none() && self.check(&token::Not) {
388 self.parse_pat_mac_invoc(path)?
389 } else if let Some(form) = self.parse_range_end() {
390 let begin = self.mk_expr(span, ExprKind::Path(qself, path), AttrVec::new());
391 self.parse_pat_range_begin_with(begin, form)?
392 } else if self.check(&token::OpenDelim(token::Brace)) {
393 self.parse_pat_struct(qself, path)?
394 } else if self.check(&token::OpenDelim(token::Paren)) {
395 self.parse_pat_tuple_struct(qself, path)?
397 PatKind::Path(qself, path)
400 // Try to parse everything else as literal with optional minus
401 match self.parse_literal_maybe_minus() {
402 Ok(begin) => match self.parse_range_end() {
403 Some(form) => self.parse_pat_range_begin_with(begin, form)?,
404 None => PatKind::Lit(begin),
406 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
410 let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
411 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
412 let pat = self.recover_intersection_pat(pat)?;
414 if !allow_range_pat {
415 self.ban_pat_range_if_ambiguous(&pat)
421 /// Recover from a typoed `...` pattern that was encountered
422 /// Ref: Issue #70388
423 fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
424 // A typoed rest pattern `...`.
425 self.bump(); // `...`
427 // The user probably mistook `...` for a rest pattern `..`.
428 self.struct_span_err(lo, "unexpected `...`")
429 .span_label(lo, "not a valid pattern")
430 .span_suggestion_short(
432 "for a rest pattern, use `..` instead of `...`",
434 Applicability::MachineApplicable,
440 /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
442 /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
443 /// should already have been parsed by now at this point,
444 /// if the next token is `@` then we can try to parse the more general form.
446 /// Consult `parse_pat_ident` for the `binding` grammar.
448 /// The notion of intersection patterns are found in
449 /// e.g. [F#][and] where they are called AND-patterns.
451 /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
452 fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
453 if self.token.kind != token::At {
454 // Next token is not `@` so it's not going to be an intersection pattern.
458 // At this point we attempt to parse `@ $pat_rhs` and emit an error.
460 let mut rhs = self.parse_pat_no_top_alt(None)?;
461 let sp = lhs.span.to(rhs.span);
463 if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
464 // The user inverted the order, so help them fix that.
465 let mut applicability = Applicability::MachineApplicable;
466 // FIXME(bindings_after_at): Remove this code when stabilizing the feature.
467 lhs.walk(&mut |p| match p.kind {
468 // `check_match` is unhappy if the subpattern has a binding anywhere.
469 PatKind::Ident(..) => {
470 applicability = Applicability::MaybeIncorrect;
471 false // Short-circuit.
476 let lhs_span = lhs.span;
477 // Move the LHS into the RHS as a subpattern.
478 // The RHS is now the full pattern.
481 self.struct_span_err(sp, "pattern on wrong side of `@`")
482 .span_label(lhs_span, "pattern on the left, should be on the right")
483 .span_label(rhs.span, "binding on the right, should be on the left")
484 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
487 // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
488 rhs.kind = PatKind::Wild;
489 self.struct_span_err(sp, "left-hand side of `@` must be a binding")
490 .span_label(lhs.span, "interpreted as a pattern, not a binding")
491 .span_label(rhs.span, "also a pattern")
492 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
500 /// Ban a range pattern if it has an ambiguous interpretation.
501 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
505 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
507 PatKind::Range(..) => {}
511 self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
514 "add parentheses to clarify the precedence",
515 format!("({})", pprust::pat_to_string(&pat)),
516 // "ambiguous interpretation" implies that we have to be guessing
517 Applicability::MaybeIncorrect,
522 /// Parse `&pat` / `&mut pat`.
523 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
525 self.recover_lifetime_in_deref_pat();
526 let mutbl = self.parse_mutability();
527 let subpat = self.parse_pat_with_range_pat(false, expected)?;
528 Ok(PatKind::Ref(subpat, mutbl))
531 fn recover_lifetime_in_deref_pat(&mut self) {
532 if let token::Lifetime(name) = self.token.kind {
535 let span = self.prev_token.span;
536 self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
539 "remove the lifetime",
541 Applicability::MachineApplicable,
547 /// Parse a tuple or parenthesis pattern.
548 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
549 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
550 p.parse_pat_allow_top_alt(
554 CommaRecoveryMode::LikelyTuple,
558 // Here, `(pat,)` is a tuple pattern.
559 // For backward compatibility, `(..)` is a tuple pattern as well.
560 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
561 PatKind::Paren(fields.into_iter().next().unwrap())
563 PatKind::Tuple(fields)
567 /// Parse a mutable binding with the `mut` token already eaten.
568 fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
569 let mut_span = self.prev_token.span;
571 if self.eat_keyword(kw::Ref) {
572 return self.recover_mut_ref_ident(mut_span);
575 self.recover_additional_muts();
577 // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
578 if let token::Interpolated(ref nt) = self.token.kind {
579 if let token::NtPat(_) = **nt {
580 self.expected_ident_found().emit();
584 // Parse the pattern we hope to be an identifier.
585 let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
587 // If we don't have `mut $ident (@ pat)?`, error.
588 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind {
589 // Don't recurse into the subpattern.
590 // `mut` on the outer binding doesn't affect the inner bindings.
591 *m = Mutability::Mut;
593 // Add `mut` to any binding in the parsed pattern.
594 let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
595 self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
598 Ok(pat.into_inner().kind)
601 /// Recover on `mut ref? ident @ pat` and suggest
602 /// that the order of `mut` and `ref` is incorrect.
603 fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
604 let mutref_span = lo.to(self.prev_token.span);
605 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
608 "try switching the order",
610 Applicability::MachineApplicable,
614 self.parse_pat_ident(BindingMode::ByRef(Mutability::Mut))
617 /// Turn all by-value immutable bindings in a pattern into mutable bindings.
618 /// Returns `true` if any change was made.
619 fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
621 impl MutVisitor for AddMut {
622 fn visit_pat(&mut self, pat: &mut P<Pat>) {
623 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind
626 *m = Mutability::Mut;
628 noop_visit_pat(pat, self);
632 let mut add_mut = AddMut(false);
633 add_mut.visit_pat(pat);
637 /// Error on `mut $pat` where `$pat` is not an ident.
638 fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
639 let span = lo.to(pat.span);
640 let fix = pprust::pat_to_string(&pat);
641 let (problem, suggestion) = if changed_any_binding {
642 ("`mut` must be attached to each individual binding", "add `mut` to each binding")
644 ("`mut` must be followed by a named binding", "remove the `mut` prefix")
646 self.struct_span_err(span, problem)
647 .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
648 .note("`mut` may be followed by `variable` and `variable @ pattern`")
652 /// Eat any extraneous `mut`s and error + recover if we ate any.
653 fn recover_additional_muts(&mut self) {
654 let lo = self.token.span;
655 while self.eat_keyword(kw::Mut) {}
656 if lo == self.token.span {
660 let span = lo.to(self.prev_token.span);
661 self.struct_span_err(span, "`mut` on a binding may not be repeated")
664 "remove the additional `mut`s",
666 Applicability::MachineApplicable,
671 /// Parse macro invocation
672 fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
674 let args = self.parse_mac_args()?;
675 let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
676 Ok(PatKind::MacCall(mac))
679 fn fatal_unexpected_non_pat(
681 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
683 ) -> PResult<'a, P<Pat>> {
686 let expected = expected.unwrap_or("pattern");
687 let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
689 let mut err = self.struct_span_err(self.token.span, &msg);
690 err.span_label(self.token.span, format!("expected {}", expected));
692 let sp = self.sess.source_map().start_point(self.token.span);
693 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
694 self.sess.expr_parentheses_needed(&mut err, *sp);
700 /// Parses the range pattern end form `".." | "..." | "..=" ;`.
701 fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
702 let re = if self.eat(&token::DotDotDot) {
703 RangeEnd::Included(RangeSyntax::DotDotDot)
704 } else if self.eat(&token::DotDotEq) {
705 RangeEnd::Included(RangeSyntax::DotDotEq)
706 } else if self.eat(&token::DotDot) {
711 Some(respan(self.prev_token.span, re))
714 /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
715 /// `$begin $form` has already been parsed.
716 fn parse_pat_range_begin_with(
719 re: Spanned<RangeEnd>,
720 ) -> PResult<'a, PatKind> {
721 let end = if self.is_pat_range_end_start(0) {
722 // Parsing e.g. `X..=Y`.
723 Some(self.parse_pat_range_end()?)
725 // Parsing e.g. `X..`.
726 if let RangeEnd::Included(_) = re.node {
727 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
728 self.inclusive_range_with_incorrect_end(re.span);
732 Ok(PatKind::Range(Some(begin), end, re))
735 pub(super) fn inclusive_range_with_incorrect_end(&mut self, span: Span) {
736 let tok = &self.token;
738 // If the user typed "..==" instead of "..=", we want to give them
739 // a specific error message telling them to use "..=".
740 // Otherwise, we assume that they meant to type a half open exclusive
741 // range and give them an error telling them to do that instead.
742 if matches!(tok.kind, token::Eq) && tok.span.lo() == span.hi() {
743 let span_with_eq = span.to(tok.span);
745 // Ensure the user doesn't receive unhelpful unexpected token errors
747 if self.is_pat_range_end_start(0) {
748 let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
751 self.error_inclusive_range_with_extra_equals(span_with_eq);
753 self.error_inclusive_range_with_no_end(span);
757 fn error_inclusive_range_with_extra_equals(&self, span: Span) {
758 self.struct_span_err(span, "unexpected `=` after inclusive range")
759 .span_suggestion_short(
763 Applicability::MaybeIncorrect,
765 .note("inclusive ranges end with a single equals sign (`..=`)")
769 fn error_inclusive_range_with_no_end(&self, span: Span) {
770 struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
771 .span_suggestion_short(
775 Applicability::MachineApplicable,
777 .note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
781 /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
783 /// The form `...X` is prohibited to reduce confusion with the potential
784 /// expression syntax `...expr` for splatting in expressions.
785 fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
786 let end = self.parse_pat_range_end()?;
787 self.sess.gated_spans.gate(sym::half_open_range_patterns, re.span.to(self.prev_token.span));
788 if let RangeEnd::Included(ref mut syn @ RangeSyntax::DotDotDot) = &mut re.node {
789 *syn = RangeSyntax::DotDotEq;
790 self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
791 .span_suggestion_short(
795 Applicability::MachineApplicable,
799 Ok(PatKind::Range(None, Some(end), re))
802 /// Is the token `dist` away from the current suitable as the start of a range patterns end?
803 fn is_pat_range_end_start(&self, dist: usize) -> bool {
804 self.check_inline_const(dist)
805 || self.look_ahead(dist, |t| {
806 t.is_path_start() // e.g. `MY_CONST`;
807 || t.kind == token::Dot // e.g. `.5` for recovery;
808 || t.can_begin_literal_maybe_minus() // e.g. `42`.
813 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
814 if self.check_inline_const(0) {
815 self.parse_const_block(self.token.span, true)
816 } else if self.check_path() {
817 let lo = self.token.span;
818 let (qself, path) = if self.eat_lt() {
819 // Parse a qualified path
820 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
823 // Parse an unqualified path
824 (None, self.parse_path(PathStyle::Expr)?)
826 let hi = self.prev_token.span;
827 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), AttrVec::new()))
829 self.parse_literal_maybe_minus()
833 /// Is this the start of a pattern beginning with a path?
834 fn is_start_of_pat_with_path(&mut self) -> bool {
836 // Just for recovery (see `can_be_ident`).
837 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
840 /// Would `parse_pat_ident` be appropriate here?
841 fn can_be_ident_pat(&mut self) -> bool {
843 && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
844 && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
845 // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
846 && !self.token.is_keyword(kw::In)
847 // Try to do something more complex?
848 && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(token::Paren) // A tuple struct pattern.
849 | token::OpenDelim(token::Brace) // A struct pattern.
850 | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
851 | token::ModSep // A tuple / struct variant pattern.
852 | token::Not)) // A macro expanding to a pattern.
855 /// Parses `ident` or `ident @ pat`.
856 /// Used by the copy foo and ref foo patterns to give a good
857 /// error message when parsing mistakes like `ref foo(a, b)`.
858 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
859 let ident = self.parse_ident()?;
860 let sub = if self.eat(&token::At) {
861 Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
866 // Just to be friendly, if they write something like `ref Some(i)`,
867 // we end up here with `(` as the current token.
868 // This shortly leads to a parse error. Note that if there is no explicit
869 // binding mode then we do not end up here, because the lookahead
870 // will direct us over to `parse_enum_variant()`.
871 if self.token == token::OpenDelim(token::Paren) {
873 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
876 Ok(PatKind::Ident(binding_mode, ident, sub))
879 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
880 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
882 // Feature gate the use of qualified paths in patterns
883 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
886 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
887 e.span_label(path.span, "while parsing the fields for this pattern");
893 Ok(PatKind::Struct(qself, path, fields, etc))
896 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
897 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
898 let (fields, _) = self.parse_paren_comma_seq(|p| {
899 p.parse_pat_allow_top_alt(
903 CommaRecoveryMode::EitherTupleOrPipe,
907 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
909 Ok(PatKind::TupleStruct(qself, path, fields))
912 /// Parses the fields of a struct-like pattern.
913 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
914 let mut fields = Vec::new();
916 let mut ate_comma = true;
917 let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
918 let mut etc_span = None;
920 while self.token != token::CloseDelim(token::Brace) {
921 let attrs = match self.parse_outer_attributes() {
924 if let Some(mut delayed) = delayed_err {
930 let lo = self.token.span;
932 // check that a comma comes after every field
934 let err = self.struct_span_err(self.token.span, "expected `,`");
935 if let Some(mut delayed) = delayed_err {
942 if self.check(&token::DotDot) || self.token == token::DotDotDot {
944 let mut etc_sp = self.token.span;
946 self.recover_one_fewer_dotdot();
947 self.bump(); // `..` || `...`
949 if self.token == token::CloseDelim(token::Brace) {
950 etc_span = Some(etc_sp);
953 let token_str = super::token_descr(&self.token);
954 let msg = &format!("expected `}}`, found {}", token_str);
955 let mut err = self.struct_span_err(self.token.span, msg);
957 err.span_label(self.token.span, "expected `}`");
958 let mut comma_sp = None;
959 if self.token == token::Comma {
961 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
962 etc_sp = etc_sp.to(nw_span);
965 "`..` must be at the end and cannot have a trailing comma",
967 comma_sp = Some(self.token.span);
972 etc_span = Some(etc_sp.until(self.token.span));
973 if self.token == token::CloseDelim(token::Brace) {
974 // If the struct looks otherwise well formed, recover and continue.
975 if let Some(sp) = comma_sp {
976 err.span_suggestion_short(
980 Applicability::MachineApplicable,
985 } else if self.token.is_ident() && ate_comma {
986 // Accept fields coming after `..,`.
987 // This way we avoid "pattern missing fields" errors afterwards.
988 // We delay this error until the end in order to have a span for a
990 if let Some(mut delayed_err) = delayed_err {
994 delayed_err = Some(err);
997 if let Some(mut err) = delayed_err {
1005 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1006 let field = match this.parse_pat_field(lo, attrs) {
1007 Ok(field) => Ok(field),
1009 if let Some(mut delayed_err) = delayed_err.take() {
1015 ate_comma = this.eat(&token::Comma);
1016 // We just ate a comma, so there's no need to use
1017 // `TrailingToken::Comma`
1018 Ok((field, TrailingToken::None))
1024 if let Some(mut err) = delayed_err {
1025 if let Some(etc_span) = etc_span {
1026 err.multipart_suggestion(
1027 "move the `..` to the end of the field list",
1029 (etc_span, String::new()),
1030 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1032 Applicability::MachineApplicable,
1040 /// Recover on `...` as if it were `..` to avoid further errors.
1041 /// See issue #46718.
1042 fn recover_one_fewer_dotdot(&self) {
1043 if self.token != token::DotDotDot {
1047 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
1050 "to omit remaining fields, use one fewer `.`",
1052 Applicability::MachineApplicable,
1057 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, PatField> {
1058 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1060 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1061 // Parsing a pattern of the form `fieldname: pat`.
1062 let fieldname = self.parse_field_name()?;
1064 let pat = self.parse_pat_allow_top_alt(
1068 CommaRecoveryMode::EitherTupleOrPipe,
1071 (pat, fieldname, false)
1073 // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1074 let is_box = self.eat_keyword(kw::Box);
1075 let boxed_span = self.token.span;
1076 let is_ref = self.eat_keyword(kw::Ref);
1077 let is_mut = self.eat_keyword(kw::Mut);
1078 let fieldname = self.parse_field_name()?;
1079 hi = self.prev_token.span;
1081 let bind_type = match (is_ref, is_mut) {
1082 (true, true) => BindingMode::ByRef(Mutability::Mut),
1083 (true, false) => BindingMode::ByRef(Mutability::Not),
1084 (false, true) => BindingMode::ByValue(Mutability::Mut),
1085 (false, false) => BindingMode::ByValue(Mutability::Not),
1088 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
1090 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1091 (subpat, fieldname, true)
1098 attrs: attrs.into(),
1099 id: ast::DUMMY_NODE_ID,
1101 is_placeholder: false,
1105 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1106 self.mk_pat(span, PatKind::Ident(bm, ident, None))
1109 pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1110 P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })