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};
6 use rustc_ast::{self as ast, AttrVec, Attribute, MacCall, Pat, PatField, PatKind, RangeEnd};
7 use rustc_ast::{BindingMode, Expr, ExprKind, Mutability, Path, QSelf, RangeSyntax};
8 use rustc_ast_pretty::pprust;
9 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult};
10 use rustc_span::source_map::{respan, Span, Spanned};
11 use rustc_span::symbol::{kw, sym, Ident};
13 type Expected = Option<&'static str>;
15 /// `Expected` for function and lambda parameter patterns.
16 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
18 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
20 /// Whether or not to recover a `,` when parsing or-patterns.
21 #[derive(PartialEq, Copy, Clone)]
22 pub enum RecoverComma {
27 /// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
28 /// emitting duplicate diagnostics.
29 #[derive(Debug, Clone, Copy)]
31 /// We recovered from a trailing vert.
33 /// We ate an `|` (or `||` and recovered).
35 /// We did not eat anything (i.e. the current token is not `|` or `||`).
42 /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
43 /// at the top level. Used when parsing the parameters of lambda expressions,
44 /// functions, function pointers, and `pat` macro fragments.
45 pub fn parse_pat_no_top_alt(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
46 self.parse_pat_with_range_pat(true, expected)
51 /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
52 /// Used for parsing patterns in all cases when `pat<no_top_alt>` is not used.
54 /// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
55 /// a leading vert is allowed in nested or-patterns, too. This allows us to
56 /// simplify the grammar somewhat.
57 pub fn parse_pat_allow_top_alt(
61 ) -> PResult<'a, P<Pat>> {
62 self.parse_pat_allow_top_alt_inner(expected, rc).map(|(pat, _)| pat)
65 /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
67 fn parse_pat_allow_top_alt_inner(
71 ) -> PResult<'a, (P<Pat>, bool)> {
72 // Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
73 // suggestions (which bothers rustfix).
75 // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
76 let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
77 EatOrResult::AteOr => (Some(self.prev_token.span), false),
78 EatOrResult::TrailingVert => (None, true),
79 EatOrResult::None => (None, false),
82 // Parse the first pattern (`p_0`).
83 let first_pat = self.parse_pat_no_top_alt(expected)?;
84 self.maybe_recover_unexpected_comma(first_pat.span, rc)?;
86 // If the next token is not a `|`,
87 // this is not an or-pattern and we should exit here.
88 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
89 // If we parsed a leading `|` which should be gated,
90 // then we should really gate the leading `|`.
91 // This complicated procedure is done purely for diagnostics UX.
92 if let Some(leading_vert_span) = leading_vert_span {
93 // If there was a leading vert, treat this as an or-pattern. This improves
95 let span = leading_vert_span.to(self.prev_token.span);
96 return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
99 return Ok((first_pat, trailing_vert));
102 // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
103 let lo = leading_vert_span.unwrap_or(first_pat.span);
104 let mut pats = vec![first_pat];
106 match self.eat_or_separator(Some(lo)) {
107 EatOrResult::AteOr => {}
108 EatOrResult::None => break,
109 EatOrResult::TrailingVert => {
110 trailing_vert = true;
114 let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
115 err.span_label(lo, WHILE_PARSING_OR_MSG);
118 self.maybe_recover_unexpected_comma(pat.span, rc)?;
121 let or_pattern_span = lo.to(self.prev_token.span);
123 Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
126 /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
127 /// type annotation (e.g. for `let` bindings or `fn` params).
129 /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
130 /// eat the `Colon` token if one is present.
132 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
134 pub(super) fn parse_pat_before_ty(
139 ) -> PResult<'a, (P<Pat>, bool)> {
140 // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
141 // or-patterns so that we can detect when a user tries to use it. This allows us to print a
142 // better error message.
143 let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(expected, rc)?;
144 let colon = self.eat(&token::Colon);
146 if let PatKind::Or(pats) = &pat.kind {
147 let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc);
148 let (help, fix) = if pats.len() == 1 {
149 // If all we have is a leading vert, then print a special message. This is the case
150 // if `parse_pat_allow_top_alt` returns an or-pattern with one variant.
151 let msg = "remove the `|`";
152 let fix = pprust::pat_to_string(&pat);
155 let msg = "wrap the pattern in parentheses";
156 let fix = format!("({})", pprust::pat_to_string(&pat));
161 // We already emitted an error and suggestion to remove the trailing vert. Don't
163 self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
165 self.struct_span_err(pat.span, &msg)
166 .span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
174 /// Parse the pattern for a function or function pointer parameter, followed by a colon.
176 /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
178 pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
179 // In order to get good UX, we first recover in the case of a leading vert for an illegal
180 // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
181 // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
183 if let token::OrOr = self.token.kind {
184 let span = self.token.span;
185 let mut err = self.struct_span_err(span, "unexpected `||` before function parameter");
190 Applicability::MachineApplicable,
192 err.note("alternatives in or-patterns are separated with `|`, not `||`");
197 self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
200 /// Eat the or-pattern `|` separator.
201 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
202 fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
203 if self.recover_trailing_vert(lo) {
204 EatOrResult::TrailingVert
205 } else if matches!(self.token.kind, token::OrOr) {
206 // Found `||`; Recover and pretend we parsed `|`.
207 self.ban_unexpected_or_or(lo);
210 } else if self.eat(&token::BinOp(token::Or)) {
217 /// Recover if `|` or `||` is the current token and we have one of the
218 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
220 /// These tokens all indicate that we reached the end of the or-pattern
221 /// list and can now reliably say that the `|` was an illegal trailing vert.
222 /// Note that there are more tokens such as `@` for which we know that the `|`
223 /// is an illegal parse. However, the user's intent is less clear in that case.
224 fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
225 let is_end_ahead = self.look_ahead(1, |token| {
227 &token.uninterpolate().kind,
228 token::FatArrow // e.g. `a | => 0,`.
229 | token::Ident(kw::If, false) // e.g. `a | if expr`.
230 | token::Eq // e.g. `let a | = 0`.
231 | token::Semi // e.g. `let a |;`.
232 | token::Colon // e.g. `let a | :`.
233 | token::Comma // e.g. `let (a |,)`.
234 | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
235 | token::CloseDelim(token::Paren) // e.g. `let (a | )`.
236 | token::CloseDelim(token::Brace) // e.g. `let A { f: a | }`.
239 match (is_end_ahead, &self.token.kind) {
240 (true, token::BinOp(token::Or) | token::OrOr) => {
241 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
249 /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
250 fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
251 let mut err = self.struct_span_err(self.token.span, "unexpected token `||` in pattern");
254 "use a single `|` to separate multiple alternative patterns",
256 Applicability::MachineApplicable,
258 if let Some(lo) = lo {
259 err.span_label(lo, WHILE_PARSING_OR_MSG);
264 /// Some special error handling for the "top-level" patterns in a match arm,
265 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
266 fn maybe_recover_unexpected_comma(&mut self, lo: Span, rc: RecoverComma) -> PResult<'a, ()> {
267 if rc == RecoverComma::No || self.token != token::Comma {
271 // An unexpected comma after a top-level pattern is a clue that the
272 // user (perhaps more accustomed to some other language) forgot the
273 // parentheses in what should have been a tuple pattern; return a
274 // suggestion-enhanced error here rather than choking on the comma later.
275 let comma_span = self.token.span;
277 if let Err(mut err) = self.skip_pat_list() {
278 // We didn't expect this to work anyway; we just wanted to advance to the
279 // end of the comma-sequence so we know the span to suggest parenthesizing.
282 let seq_span = lo.to(self.prev_token.span);
283 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
284 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
285 const MSG: &str = "try adding parentheses to match on a tuple...";
290 format!("({})", seq_snippet),
291 Applicability::MachineApplicable,
295 "...or a vertical bar to match on multiple alternatives",
296 seq_snippet.replace(",", " |"),
297 Applicability::MachineApplicable,
303 /// Parse and throw away a parenthesized comma separated
304 /// sequence of patterns until `)` is reached.
305 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
306 while !self.check(&token::CloseDelim(token::Paren)) {
307 self.parse_pat_no_top_alt(None)?;
308 if !self.eat(&token::Comma) {
315 /// A `|` or possibly `||` token shouldn't be here. Ban it.
316 fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
317 let span = self.token.span;
318 let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
321 &format!("remove the `{}`", pprust::token_to_string(&self.token)),
323 Applicability::MachineApplicable,
325 if let Some(lo) = lo {
326 err.span_label(lo, WHILE_PARSING_OR_MSG);
328 if let token::OrOr = self.token.kind {
329 err.note("alternatives in or-patterns are separated with `|`, not `||`");
334 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
336 fn parse_pat_with_range_pat(
338 allow_range_pat: bool,
340 ) -> PResult<'a, P<Pat>> {
341 maybe_recover_from_interpolated_ty_qpath!(self, true);
342 maybe_whole!(self, NtPat, |x| x);
344 let lo = self.token.span;
346 let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
347 self.parse_pat_deref(expected)?
348 } else if self.check(&token::OpenDelim(token::Paren)) {
349 self.parse_pat_tuple_or_parens()?
350 } else if self.check(&token::OpenDelim(token::Bracket)) {
351 // Parse `[pat, pat,...]` as a slice pattern.
352 let (pats, _) = self.parse_delim_comma_seq(token::Bracket, |p| {
353 p.parse_pat_allow_top_alt(None, RecoverComma::No)
356 } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
357 // A rest pattern `..`.
360 } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
361 self.recover_dotdotdot_rest_pat(lo)
362 } else if let Some(form) = self.parse_range_end() {
363 self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
364 } else if self.eat_keyword(kw::Underscore) {
367 } else if self.eat_keyword(kw::Mut) {
368 self.parse_pat_ident_mut()?
369 } else if self.eat_keyword(kw::Ref) {
370 // Parse ref ident @ pat / ref mut ident @ pat
371 let mutbl = self.parse_mutability();
372 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
373 } else if self.eat_keyword(kw::Box) {
375 let pat = self.parse_pat_with_range_pat(false, None)?;
376 self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_token.span));
378 } else if self.check_inline_const(0) {
380 let const_expr = self.parse_const_block(lo.to(self.token.span))?;
382 if let Some(re) = self.parse_range_end() {
383 self.parse_pat_range_begin_with(const_expr, re)?
385 PatKind::Lit(const_expr)
387 } else if self.can_be_ident_pat() {
388 // Parse `ident @ pat`
389 // This can give false positives and parse nullary enums,
390 // they are dealt with later in resolve.
391 self.parse_pat_ident(BindingMode::ByValue(Mutability::Not))?
392 } else if self.is_start_of_pat_with_path() {
393 // Parse pattern starting with a path
394 let (qself, path) = if self.eat_lt() {
395 // Parse a qualified path
396 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
399 // Parse an unqualified path
400 (None, self.parse_path(PathStyle::Expr)?)
402 let span = lo.to(self.prev_token.span);
404 if qself.is_none() && self.check(&token::Not) {
405 self.parse_pat_mac_invoc(path)?
406 } else if let Some(form) = self.parse_range_end() {
407 let begin = self.mk_expr(span, ExprKind::Path(qself, path), AttrVec::new());
408 self.parse_pat_range_begin_with(begin, form)?
409 } else if self.check(&token::OpenDelim(token::Brace)) {
410 self.parse_pat_struct(qself, path)?
411 } else if self.check(&token::OpenDelim(token::Paren)) {
412 self.parse_pat_tuple_struct(qself, path)?
414 PatKind::Path(qself, path)
417 // Try to parse everything else as literal with optional minus
418 match self.parse_literal_maybe_minus() {
419 Ok(begin) => match self.parse_range_end() {
420 Some(form) => self.parse_pat_range_begin_with(begin, form)?,
421 None => PatKind::Lit(begin),
423 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
427 let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
428 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
429 let pat = self.recover_intersection_pat(pat)?;
431 if !allow_range_pat {
432 self.ban_pat_range_if_ambiguous(&pat)
438 /// Recover from a typoed `...` pattern that was encountered
439 /// Ref: Issue #70388
440 fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
441 // A typoed rest pattern `...`.
442 self.bump(); // `...`
444 // The user probably mistook `...` for a rest pattern `..`.
445 self.struct_span_err(lo, "unexpected `...`")
446 .span_label(lo, "not a valid pattern")
447 .span_suggestion_short(
449 "for a rest pattern, use `..` instead of `...`",
451 Applicability::MachineApplicable,
457 /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
459 /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
460 /// should already have been parsed by now at this point,
461 /// if the next token is `@` then we can try to parse the more general form.
463 /// Consult `parse_pat_ident` for the `binding` grammar.
465 /// The notion of intersection patterns are found in
466 /// e.g. [F#][and] where they are called AND-patterns.
468 /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
469 fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
470 if self.token.kind != token::At {
471 // Next token is not `@` so it's not going to be an intersection pattern.
475 // At this point we attempt to parse `@ $pat_rhs` and emit an error.
477 let mut rhs = self.parse_pat_no_top_alt(None)?;
478 let sp = lhs.span.to(rhs.span);
480 if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
481 // The user inverted the order, so help them fix that.
482 let mut applicability = Applicability::MachineApplicable;
483 // FIXME(bindings_after_at): Remove this code when stabilizing the feature.
484 lhs.walk(&mut |p| match p.kind {
485 // `check_match` is unhappy if the subpattern has a binding anywhere.
486 PatKind::Ident(..) => {
487 applicability = Applicability::MaybeIncorrect;
488 false // Short-circuit.
493 let lhs_span = lhs.span;
494 // Move the LHS into the RHS as a subpattern.
495 // The RHS is now the full pattern.
498 self.struct_span_err(sp, "pattern on wrong side of `@`")
499 .span_label(lhs_span, "pattern on the left, should be on the right")
500 .span_label(rhs.span, "binding on the right, should be on the left")
501 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
504 // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
505 rhs.kind = PatKind::Wild;
506 self.struct_span_err(sp, "left-hand side of `@` must be a binding")
507 .span_label(lhs.span, "interpreted as a pattern, not a binding")
508 .span_label(rhs.span, "also a pattern")
509 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
517 /// Ban a range pattern if it has an ambiguous interpretation.
518 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
522 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
524 PatKind::Range(..) => {}
528 self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
531 "add parentheses to clarify the precedence",
532 format!("({})", pprust::pat_to_string(&pat)),
533 // "ambiguous interpretation" implies that we have to be guessing
534 Applicability::MaybeIncorrect,
539 /// Parse `&pat` / `&mut pat`.
540 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
542 self.recover_lifetime_in_deref_pat();
543 let mutbl = self.parse_mutability();
544 let subpat = self.parse_pat_with_range_pat(false, expected)?;
545 Ok(PatKind::Ref(subpat, mutbl))
548 fn recover_lifetime_in_deref_pat(&mut self) {
549 if let token::Lifetime(name) = self.token.kind {
552 let span = self.prev_token.span;
553 self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
556 "remove the lifetime",
558 Applicability::MachineApplicable,
564 /// Parse a tuple or parenthesis pattern.
565 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
566 let (fields, trailing_comma) =
567 self.parse_paren_comma_seq(|p| p.parse_pat_allow_top_alt(None, RecoverComma::No))?;
569 // Here, `(pat,)` is a tuple pattern.
570 // For backward compatibility, `(..)` is a tuple pattern as well.
571 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
572 PatKind::Paren(fields.into_iter().next().unwrap())
574 PatKind::Tuple(fields)
578 /// Parse a mutable binding with the `mut` token already eaten.
579 fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
580 let mut_span = self.prev_token.span;
582 if self.eat_keyword(kw::Ref) {
583 return self.recover_mut_ref_ident(mut_span);
586 self.recover_additional_muts();
588 // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
589 if let token::Interpolated(ref nt) = self.token.kind {
590 if let token::NtPat(_) = **nt {
591 self.expected_ident_found().emit();
595 // Parse the pattern we hope to be an identifier.
596 let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
598 // If we don't have `mut $ident (@ pat)?`, error.
599 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind {
600 // Don't recurse into the subpattern.
601 // `mut` on the outer binding doesn't affect the inner bindings.
602 *m = Mutability::Mut;
604 // Add `mut` to any binding in the parsed pattern.
605 let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
606 self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
609 Ok(pat.into_inner().kind)
612 /// Recover on `mut ref? ident @ pat` and suggest
613 /// that the order of `mut` and `ref` is incorrect.
614 fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
615 let mutref_span = lo.to(self.prev_token.span);
616 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
619 "try switching the order",
621 Applicability::MachineApplicable,
625 self.parse_pat_ident(BindingMode::ByRef(Mutability::Mut))
628 /// Turn all by-value immutable bindings in a pattern into mutable bindings.
629 /// Returns `true` if any change was made.
630 fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
632 impl MutVisitor for AddMut {
633 fn visit_pat(&mut self, pat: &mut P<Pat>) {
634 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind
637 *m = Mutability::Mut;
639 noop_visit_pat(pat, self);
643 let mut add_mut = AddMut(false);
644 add_mut.visit_pat(pat);
648 /// Error on `mut $pat` where `$pat` is not an ident.
649 fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
650 let span = lo.to(pat.span);
651 let fix = pprust::pat_to_string(&pat);
652 let (problem, suggestion) = if changed_any_binding {
653 ("`mut` must be attached to each individual binding", "add `mut` to each binding")
655 ("`mut` must be followed by a named binding", "remove the `mut` prefix")
657 self.struct_span_err(span, problem)
658 .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
659 .note("`mut` may be followed by `variable` and `variable @ pattern`")
663 /// Eat any extraneous `mut`s and error + recover if we ate any.
664 fn recover_additional_muts(&mut self) {
665 let lo = self.token.span;
666 while self.eat_keyword(kw::Mut) {}
667 if lo == self.token.span {
671 let span = lo.to(self.prev_token.span);
672 self.struct_span_err(span, "`mut` on a binding may not be repeated")
675 "remove the additional `mut`s",
677 Applicability::MachineApplicable,
682 /// Parse macro invocation
683 fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
685 let args = self.parse_mac_args()?;
686 let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
687 Ok(PatKind::MacCall(mac))
690 fn fatal_unexpected_non_pat(
692 mut err: DiagnosticBuilder<'a>,
694 ) -> PResult<'a, P<Pat>> {
697 let expected = expected.unwrap_or("pattern");
698 let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
700 let mut err = self.struct_span_err(self.token.span, &msg);
701 err.span_label(self.token.span, format!("expected {}", expected));
703 let sp = self.sess.source_map().start_point(self.token.span);
704 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
705 self.sess.expr_parentheses_needed(&mut err, *sp, None);
711 /// Parses the range pattern end form `".." | "..." | "..=" ;`.
712 fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
713 let re = if self.eat(&token::DotDotDot) {
714 RangeEnd::Included(RangeSyntax::DotDotDot)
715 } else if self.eat(&token::DotDotEq) {
716 RangeEnd::Included(RangeSyntax::DotDotEq)
717 } else if self.eat(&token::DotDot) {
718 self.sess.gated_spans.gate(sym::exclusive_range_pattern, self.prev_token.span);
723 Some(respan(self.prev_token.span, re))
726 /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
727 /// `$begin $form` has already been parsed.
728 fn parse_pat_range_begin_with(
731 re: Spanned<RangeEnd>,
732 ) -> PResult<'a, PatKind> {
733 let end = if self.is_pat_range_end_start(0) {
734 // Parsing e.g. `X..=Y`.
735 Some(self.parse_pat_range_end()?)
737 // Parsing e.g. `X..`.
738 self.sess.gated_spans.gate(sym::half_open_range_patterns, begin.span.to(re.span));
739 if let RangeEnd::Included(_) = re.node {
740 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
741 // Possibly also do this for `X..=` in *expression* contexts.
742 self.error_inclusive_range_with_no_end(re.span);
746 Ok(PatKind::Range(Some(begin), end, re))
749 pub(super) fn error_inclusive_range_with_no_end(&self, span: Span) {
750 struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
751 .span_suggestion_short(
755 Applicability::MachineApplicable,
757 .note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
761 /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
763 /// The form `...X` is prohibited to reduce confusion with the potential
764 /// expression syntax `...expr` for splatting in expressions.
765 fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
766 let end = self.parse_pat_range_end()?;
767 self.sess.gated_spans.gate(sym::half_open_range_patterns, re.span.to(self.prev_token.span));
768 if let RangeEnd::Included(ref mut syn @ RangeSyntax::DotDotDot) = &mut re.node {
769 *syn = RangeSyntax::DotDotEq;
770 self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
771 .span_suggestion_short(
775 Applicability::MachineApplicable,
779 Ok(PatKind::Range(None, Some(end), re))
782 /// Is the token `dist` away from the current suitable as the start of a range patterns end?
783 fn is_pat_range_end_start(&self, dist: usize) -> bool {
784 self.check_inline_const(dist)
785 || self.look_ahead(dist, |t| {
786 t.is_path_start() // e.g. `MY_CONST`;
787 || t.kind == token::Dot // e.g. `.5` for recovery;
788 || t.can_begin_literal_maybe_minus() // e.g. `42`.
793 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
794 if self.check_inline_const(0) {
795 self.parse_const_block(self.token.span)
796 } else if self.check_path() {
797 let lo = self.token.span;
798 let (qself, path) = if self.eat_lt() {
799 // Parse a qualified path
800 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
803 // Parse an unqualified path
804 (None, self.parse_path(PathStyle::Expr)?)
806 let hi = self.prev_token.span;
807 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), AttrVec::new()))
809 self.parse_literal_maybe_minus()
813 /// Is this the start of a pattern beginning with a path?
814 fn is_start_of_pat_with_path(&mut self) -> bool {
816 // Just for recovery (see `can_be_ident`).
817 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
820 /// Would `parse_pat_ident` be appropriate here?
821 fn can_be_ident_pat(&mut self) -> bool {
823 && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
824 && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
825 // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
826 && !self.token.is_keyword(kw::In)
827 // Try to do something more complex?
828 && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(token::Paren) // A tuple struct pattern.
829 | token::OpenDelim(token::Brace) // A struct pattern.
830 | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
831 | token::ModSep // A tuple / struct variant pattern.
832 | token::Not)) // A macro expanding to a pattern.
835 /// Parses `ident` or `ident @ pat`.
836 /// Used by the copy foo and ref foo patterns to give a good
837 /// error message when parsing mistakes like `ref foo(a, b)`.
838 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
839 let ident = self.parse_ident()?;
840 let sub = if self.eat(&token::At) {
841 Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
846 // Just to be friendly, if they write something like `ref Some(i)`,
847 // we end up here with `(` as the current token.
848 // This shortly leads to a parse error. Note that if there is no explicit
849 // binding mode then we do not end up here, because the lookahead
850 // will direct us over to `parse_enum_variant()`.
851 if self.token == token::OpenDelim(token::Paren) {
853 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
856 Ok(PatKind::Ident(binding_mode, ident, sub))
859 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
860 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
862 // Feature gate the use of qualified paths in patterns
863 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
866 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
867 e.span_label(path.span, "while parsing the fields for this pattern");
873 Ok(PatKind::Struct(qself, path, fields, etc))
876 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
877 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
879 self.parse_paren_comma_seq(|p| p.parse_pat_allow_top_alt(None, RecoverComma::No))?;
881 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
883 Ok(PatKind::TupleStruct(qself, path, fields))
886 /// Parses the fields of a struct-like pattern.
887 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
888 let mut fields = Vec::new();
890 let mut ate_comma = true;
891 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
892 let mut etc_span = None;
894 while self.token != token::CloseDelim(token::Brace) {
895 let attrs = match self.parse_outer_attributes() {
898 if let Some(mut delayed) = delayed_err {
904 let lo = self.token.span;
906 // check that a comma comes after every field
908 let err = self.struct_span_err(self.token.span, "expected `,`");
909 if let Some(mut delayed) = delayed_err {
916 if self.check(&token::DotDot) || self.token == token::DotDotDot {
918 let mut etc_sp = self.token.span;
920 self.recover_one_fewer_dotdot();
921 self.bump(); // `..` || `...`
923 if self.token == token::CloseDelim(token::Brace) {
924 etc_span = Some(etc_sp);
927 let token_str = super::token_descr(&self.token);
928 let msg = &format!("expected `}}`, found {}", token_str);
929 let mut err = self.struct_span_err(self.token.span, msg);
931 err.span_label(self.token.span, "expected `}`");
932 let mut comma_sp = None;
933 if self.token == token::Comma {
935 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
936 etc_sp = etc_sp.to(nw_span);
939 "`..` must be at the end and cannot have a trailing comma",
941 comma_sp = Some(self.token.span);
946 etc_span = Some(etc_sp.until(self.token.span));
947 if self.token == token::CloseDelim(token::Brace) {
948 // If the struct looks otherwise well formed, recover and continue.
949 if let Some(sp) = comma_sp {
950 err.span_suggestion_short(
954 Applicability::MachineApplicable,
959 } else if self.token.is_ident() && ate_comma {
960 // Accept fields coming after `..,`.
961 // This way we avoid "pattern missing fields" errors afterwards.
962 // We delay this error until the end in order to have a span for a
964 if let Some(mut delayed_err) = delayed_err {
968 delayed_err = Some(err);
971 if let Some(mut err) = delayed_err {
979 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
980 let field = match this.parse_pat_field(lo, attrs) {
981 Ok(field) => Ok(field),
983 if let Some(mut delayed_err) = delayed_err.take() {
989 ate_comma = this.eat(&token::Comma);
990 // We just ate a comma, so there's no need to use
991 // `TrailingToken::Comma`
992 Ok((field, TrailingToken::None))
998 if let Some(mut err) = delayed_err {
999 if let Some(etc_span) = etc_span {
1000 err.multipart_suggestion(
1001 "move the `..` to the end of the field list",
1003 (etc_span, String::new()),
1004 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1006 Applicability::MachineApplicable,
1014 /// Recover on `...` as if it were `..` to avoid further errors.
1015 /// See issue #46718.
1016 fn recover_one_fewer_dotdot(&self) {
1017 if self.token != token::DotDotDot {
1021 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
1024 "to omit remaining fields, use one fewer `.`",
1026 Applicability::MachineApplicable,
1031 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, PatField> {
1032 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1034 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1035 // Parsing a pattern of the form `fieldname: pat`.
1036 let fieldname = self.parse_field_name()?;
1038 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::No)?;
1040 (pat, fieldname, false)
1042 // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1043 let is_box = self.eat_keyword(kw::Box);
1044 let boxed_span = self.token.span;
1045 let is_ref = self.eat_keyword(kw::Ref);
1046 let is_mut = self.eat_keyword(kw::Mut);
1047 let fieldname = self.parse_field_name()?;
1048 hi = self.prev_token.span;
1050 let bind_type = match (is_ref, is_mut) {
1051 (true, true) => BindingMode::ByRef(Mutability::Mut),
1052 (true, false) => BindingMode::ByRef(Mutability::Not),
1053 (false, true) => BindingMode::ByValue(Mutability::Mut),
1054 (false, false) => BindingMode::ByValue(Mutability::Not),
1057 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
1059 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1060 (subpat, fieldname, true)
1067 attrs: attrs.into(),
1068 id: ast::DUMMY_NODE_ID,
1070 is_placeholder: false,
1074 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1075 self.mk_pat(span, PatKind::Ident(bm, ident, None))
1078 fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1079 P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })