1 use super::{Parser, PResult, PathStyle};
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
5 use crate::ast::{self, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac};
6 use crate::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind};
7 use crate::mut_visit::{noop_visit_pat, MutVisitor};
8 use crate::parse::token::{self};
9 use crate::print::pprust;
10 use crate::source_map::{respan, Span, Spanned};
11 use crate::symbol::kw;
14 use errors::{Applicability, DiagnosticBuilder};
16 type Expected = Option<&'static str>;
18 /// `Expected` for function and lambda parameter patterns.
19 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
21 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
23 /// Whether or not an or-pattern should be gated when occurring in the current context.
25 pub enum GateOr { Yes, No }
27 /// Whether or not to recover a `,` when parsing or-patterns.
28 #[derive(PartialEq, Copy, Clone)]
29 enum RecoverComma { Yes, No }
34 /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
35 /// at the top level. Used when parsing the parameters of lambda expressions,
36 /// functions, function pointers, and `pat` macro fragments.
37 pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
38 self.parse_pat_with_range_pat(true, expected)
41 /// Entry point to the main pattern parser.
42 /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
43 pub(super) fn parse_top_pat(&mut self, gate_or: GateOr) -> PResult<'a, P<Pat>> {
44 // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
45 let gated_leading_vert = self.eat_or_separator(None) && gate_or == GateOr::Yes;
46 let leading_vert_span = self.prev_span;
48 // Parse the possibly-or-pattern.
49 let pat = self.parse_pat_with_or(None, gate_or, RecoverComma::Yes)?;
51 // If we parsed a leading `|` which should be gated,
52 // and no other gated or-pattern has been parsed thus far,
53 // then we should really gate the leading `|`.
54 // This complicated procedure is done purely for diagnostics UX.
55 if gated_leading_vert {
56 let mut or_pattern_spans = self.sess.gated_spans.or_patterns.borrow_mut();
57 if or_pattern_spans.is_empty() {
58 or_pattern_spans.push(leading_vert_span);
65 /// Parse the pattern for a function or function pointer parameter.
66 /// Special recovery is provided for or-patterns and leading `|`.
67 pub(super) fn parse_fn_param_pat(&mut self) -> PResult<'a, P<Pat>> {
68 self.recover_leading_vert(None, "not allowed in a parameter pattern");
69 let pat = self.parse_pat_with_or(PARAM_EXPECTED, GateOr::No, RecoverComma::No)?;
71 if let PatKind::Or(..) = &pat.kind {
72 self.ban_illegal_fn_param_or_pat(&pat);
78 /// Ban `A | B` immediately in a parameter pattern and suggest wrapping in parens.
79 fn ban_illegal_fn_param_or_pat(&self, pat: &Pat) {
80 let msg = "wrap the pattern in parenthesis";
81 let fix = format!("({})", pprust::pat_to_string(pat));
82 self.struct_span_err(pat.span, "an or-pattern parameter must be wrapped in parenthesis")
83 .span_suggestion(pat.span, msg, fix, Applicability::MachineApplicable)
87 /// Parses a pattern, that may be a or-pattern (e.g. `Foo | Bar` in `Some(Foo | Bar)`).
88 /// Corresponds to `pat<allow_top_alt>` in RFC 2535.
94 ) -> PResult<'a, P<Pat>> {
95 // Parse the first pattern (`p_0`).
96 let first_pat = self.parse_pat(expected)?;
97 self.maybe_recover_unexpected_comma(first_pat.span, rc)?;
99 // If the next token is not a `|`,
100 // this is not an or-pattern and we should exit here.
101 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
105 // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
106 let lo = first_pat.span;
107 let mut pats = vec![first_pat];
108 while self.eat_or_separator(Some(lo)) {
109 let pat = self.parse_pat(expected).map_err(|mut err| {
110 err.span_label(lo, WHILE_PARSING_OR_MSG);
113 self.maybe_recover_unexpected_comma(pat.span, rc)?;
116 let or_pattern_span = lo.to(self.prev_span);
118 // Feature gate the or-pattern if instructed:
119 if gate_or == GateOr::Yes {
120 self.sess.gated_spans.or_patterns.borrow_mut().push(or_pattern_span);
123 Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats)))
126 /// Eat the or-pattern `|` separator.
127 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
128 fn eat_or_separator(&mut self, lo: Option<Span>) -> bool {
129 if self.recover_trailing_vert(lo) {
133 match self.token.kind {
135 // Found `||`; Recover and pretend we parsed `|`.
136 self.ban_unexpected_or_or(lo);
140 _ => self.eat(&token::BinOp(token::Or)),
144 /// Recover if `|` or `||` is the current token and we have one of the
145 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
147 /// These tokens all indicate that we reached the end of the or-pattern
148 /// list and can now reliably say that the `|` was an illegal trailing vert.
149 /// Note that there are more tokens such as `@` for which we know that the `|`
150 /// is an illegal parse. However, the user's intent is less clear in that case.
151 fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
152 let is_end_ahead = self.look_ahead(1, |token| match &token.kind {
153 token::FatArrow // e.g. `a | => 0,`.
154 | token::Ident(kw::If, false) // e.g. `a | if expr`.
155 | token::Eq // e.g. `let a | = 0`.
156 | token::Semi // e.g. `let a |;`.
157 | token::Colon // e.g. `let a | :`.
158 | token::Comma // e.g. `let (a |,)`.
159 | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
160 | token::CloseDelim(token::Paren) // e.g. `let (a | )`.
161 | token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`.
164 match (is_end_ahead, &self.token.kind) {
165 (true, token::BinOp(token::Or)) | (true, token::OrOr) => {
166 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
174 /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
175 fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
176 let mut err = self.struct_span_err(self.token.span, "unexpected token `||` after pattern");
179 "use a single `|` to separate multiple alternative patterns",
181 Applicability::MachineApplicable
183 if let Some(lo) = lo {
184 err.span_label(lo, WHILE_PARSING_OR_MSG);
189 /// Some special error handling for the "top-level" patterns in a match arm,
190 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
191 fn maybe_recover_unexpected_comma(&mut self, lo: Span, rc: RecoverComma) -> PResult<'a, ()> {
192 if rc == RecoverComma::No || self.token != token::Comma {
196 // An unexpected comma after a top-level pattern is a clue that the
197 // user (perhaps more accustomed to some other language) forgot the
198 // parentheses in what should have been a tuple pattern; return a
199 // suggestion-enhanced error here rather than choking on the comma later.
200 let comma_span = self.token.span;
202 if let Err(mut err) = self.skip_pat_list() {
203 // We didn't expect this to work anyway; we just wanted to advance to the
204 // end of the comma-sequence so we know the span to suggest parenthesizing.
207 let seq_span = lo.to(self.prev_span);
208 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
209 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
212 "try adding parentheses to match on a tuple..",
213 format!("({})", seq_snippet),
214 Applicability::MachineApplicable
218 "..or a vertical bar to match on multiple alternatives",
219 format!("{}", seq_snippet.replace(",", " |")),
220 Applicability::MachineApplicable
226 /// Parse and throw away a parentesized comma separated
227 /// sequence of patterns until `)` is reached.
228 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
229 while !self.check(&token::CloseDelim(token::Paren)) {
230 self.parse_pat(None)?;
231 if !self.eat(&token::Comma) {
238 /// Recursive possibly-or-pattern parser with recovery for an erroneous leading `|`.
239 /// See `parse_pat_with_or` for details on parsing or-patterns.
240 fn parse_pat_with_or_inner(&mut self) -> PResult<'a, P<Pat>> {
241 self.recover_leading_vert(None, "only allowed in a top-level pattern");
242 self.parse_pat_with_or(None, GateOr::Yes, RecoverComma::No)
245 /// Recover if `|` or `||` is here.
246 /// The user is thinking that a leading `|` is allowed in this position.
247 fn recover_leading_vert(&mut self, lo: Option<Span>, ctx: &str) {
248 if let token::BinOp(token::Or) | token::OrOr = self.token.kind {
249 self.ban_illegal_vert(lo, "leading", ctx);
254 /// A `|` or possibly `||` token shouldn't be here. Ban it.
255 fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
256 let span = self.token.span;
257 let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
260 &format!("remove the `{}`", pprust::token_to_string(&self.token)),
262 Applicability::MachineApplicable,
264 if let Some(lo) = lo {
265 err.span_label(lo, WHILE_PARSING_OR_MSG);
267 if let token::OrOr = self.token.kind {
268 err.note("alternatives in or-patterns are separated with `|`, not `||`");
273 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
275 fn parse_pat_with_range_pat(
277 allow_range_pat: bool,
279 ) -> PResult<'a, P<Pat>> {
280 maybe_recover_from_interpolated_ty_qpath!(self, true);
281 maybe_whole!(self, NtPat, |x| x);
283 let lo = self.token.span;
284 let pat = match self.token.kind {
285 token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
286 token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
287 token::OpenDelim(token::Bracket) => {
288 // Parse `[pat, pat,...]` as a slice pattern.
289 let (pats, _) = self.parse_delim_comma_seq(
291 |p| p.parse_pat_with_or_inner(),
297 if self.is_pat_range_end_start() {
298 // Parse `..42` for recovery.
299 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
301 // A rest pattern `..`.
306 // Parse `..=42` for recovery.
308 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
310 token::DotDotDot => {
311 // Parse `...42` for recovery.
313 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
315 // At this point, token != `&`, `&&`, `(`, `[`, `..`, `..=`, or `...`.
316 _ => if self.eat_keyword(kw::Underscore) {
319 } else if self.eat_keyword(kw::Mut) {
320 self.parse_pat_ident_mut()?
321 } else if self.eat_keyword(kw::Ref) {
322 // Parse ref ident @ pat / ref mut ident @ pat
323 let mutbl = self.parse_mutability();
324 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
325 } else if self.eat_keyword(kw::Box) {
327 PatKind::Box(self.parse_pat_with_range_pat(false, None)?)
328 } else if self.can_be_ident_pat() {
329 // Parse `ident @ pat`
330 // This can give false positives and parse nullary enums,
331 // they are dealt with later in resolve.
332 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
333 } else if self.is_start_of_pat_with_path() {
334 // Parse pattern starting with a path
335 let (qself, path) = if self.eat_lt() {
336 // Parse a qualified path
337 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
340 // Parse an unqualified path
341 (None, self.parse_path(PathStyle::Expr)?)
343 match self.token.kind {
344 token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?,
345 token::DotDotDot | token::DotDotEq | token::DotDot => {
346 self.parse_pat_range_starting_with_path(lo, qself, path)?
348 token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
349 token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
350 _ => PatKind::Path(qself, path),
353 // Try to parse everything else as literal with optional minus
354 match self.parse_literal_maybe_minus() {
356 if self.check(&token::DotDot)
357 || self.check(&token::DotDotEq)
358 || self.check(&token::DotDotDot) =>
360 self.parse_pat_range_starting_with_lit(begin)?
362 Ok(begin) => PatKind::Lit(begin),
363 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
368 let pat = self.mk_pat(lo.to(self.prev_span), pat);
369 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
371 if !allow_range_pat {
372 self.ban_pat_range_if_ambiguous(&pat)?
378 /// Ban a range pattern if it has an ambiguous interpretation.
379 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
382 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
384 PatKind::Range(..) => {}
388 let mut err = self.struct_span_err(
390 "the range pattern here has ambiguous interpretation",
394 "add parentheses to clarify the precedence",
395 format!("({})", pprust::pat_to_string(&pat)),
396 // "ambiguous interpretation" implies that we have to be guessing
397 Applicability::MaybeIncorrect
402 /// Parse `&pat` / `&mut pat`.
403 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
405 let mutbl = self.parse_mutability();
407 if let token::Lifetime(name) = self.token.kind {
408 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
409 err.span_label(self.token.span, "unexpected lifetime");
413 let subpat = self.parse_pat_with_range_pat(false, expected)?;
414 Ok(PatKind::Ref(subpat, mutbl))
417 /// Parse a tuple or parenthesis pattern.
418 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
419 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
421 // Here, `(pat,)` is a tuple pattern.
422 // For backward compatibility, `(..)` is a tuple pattern as well.
423 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
424 PatKind::Paren(fields.into_iter().nth(0).unwrap())
426 PatKind::Tuple(fields)
430 /// Parse a mutable binding with the `mut` token already eaten.
431 fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
432 let mut_span = self.prev_span;
434 if self.eat_keyword(kw::Ref) {
435 return self.recover_mut_ref_ident(mut_span)
438 self.recover_additional_muts();
440 // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
441 if let token::Interpolated(ref nt) = self.token.kind {
442 if let token::NtPat(_) = **nt {
443 self.expected_ident_found().emit();
447 // Parse the pattern we hope to be an identifier.
448 let mut pat = self.parse_pat(Some("identifier"))?;
450 // Add `mut` to any binding in the parsed pattern.
451 let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
453 // Unwrap; If we don't have `mut $ident`, error.
454 let pat = pat.into_inner();
456 PatKind::Ident(..) => {}
457 _ => self.ban_mut_general_pat(mut_span, &pat, changed_any_binding),
463 /// Recover on `mut ref? ident @ pat` and suggest
464 /// that the order of `mut` and `ref` is incorrect.
465 fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
466 let mutref_span = lo.to(self.prev_span);
467 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
470 "try switching the order",
472 Applicability::MachineApplicable
476 self.parse_pat_ident(BindingMode::ByRef(Mutability::Mutable))
479 /// Turn all by-value immutable bindings in a pattern into mutable bindings.
480 /// Returns `true` if any change was made.
481 fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
483 impl MutVisitor for AddMut {
484 fn visit_pat(&mut self, pat: &mut P<Pat>) {
485 if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Immutable), ..)
488 *m = Mutability::Mutable;
491 noop_visit_pat(pat, self);
495 let mut add_mut = AddMut(false);
496 add_mut.visit_pat(pat);
500 /// Error on `mut $pat` where `$pat` is not an ident.
501 fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
502 let span = lo.to(pat.span);
503 let fix = pprust::pat_to_string(&pat);
504 let (problem, suggestion) = if changed_any_binding {
505 ("`mut` must be attached to each individual binding", "add `mut` to each binding")
507 ("`mut` must be followed by a named binding", "remove the `mut` prefix")
509 self.struct_span_err(span, problem)
510 .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
511 .note("`mut` may be followed by `variable` and `variable @ pattern`")
515 /// Eat any extraneous `mut`s and error + recover if we ate any.
516 fn recover_additional_muts(&mut self) {
517 let lo = self.token.span;
518 while self.eat_keyword(kw::Mut) {}
519 if lo == self.token.span {
523 let span = lo.to(self.prev_span);
524 self.struct_span_err(span, "`mut` on a binding may not be repeated")
527 "remove the additional `mut`s",
529 Applicability::MachineApplicable,
534 /// Parse macro invocation
535 fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> {
537 let (delim, tts) = self.expect_delimited_token_tree()?;
542 span: lo.to(self.prev_span),
543 prior_type_ascription: self.last_type_ascription,
545 Ok(PatKind::Mac(mac))
548 /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
549 /// The `$path` has already been parsed and the next token is the `$form`.
550 fn parse_pat_range_starting_with_path(
553 qself: Option<QSelf>,
555 ) -> PResult<'a, PatKind> {
556 let (end_kind, form) = match self.token.kind {
557 token::DotDot => (RangeEnd::Excluded, ".."),
558 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
559 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
560 _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
562 let op_span = self.token.span;
564 let span = lo.to(self.prev_span);
565 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
567 let end = self.parse_pat_range_end_opt(&begin, form)?;
568 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
571 /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
572 /// The `$path` has already been parsed and the next token is the `$form`.
573 fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
574 let op_span = self.token.span;
575 let (end_kind, form) = if self.eat(&token::DotDotDot) {
576 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
577 } else if self.eat(&token::DotDotEq) {
578 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
579 } else if self.eat(&token::DotDot) {
580 (RangeEnd::Excluded, "..")
582 panic!("impossible case: we already matched on a range-operator token")
584 let end = self.parse_pat_range_end_opt(&begin, form)?;
585 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
588 fn fatal_unexpected_non_pat(
590 mut err: DiagnosticBuilder<'a>,
592 ) -> PResult<'a, P<Pat>> {
595 let expected = expected.unwrap_or("pattern");
596 let msg = format!("expected {}, found {}", expected, self.this_token_descr());
598 let mut err = self.fatal(&msg);
599 err.span_label(self.token.span, format!("expected {}", expected));
601 let sp = self.sess.source_map().start_point(self.token.span);
602 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
603 self.sess.expr_parentheses_needed(&mut err, *sp, None);
609 /// Is the current token suitable as the start of a range patterns end?
610 fn is_pat_range_end_start(&self) -> bool {
611 self.token.is_path_start() // e.g. `MY_CONST`;
612 || self.token == token::Dot // e.g. `.5` for recovery;
613 || self.token.can_begin_literal_or_bool() // e.g. `42`.
614 || self.token.is_whole_expr()
617 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
618 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
619 let lo = self.prev_span;
620 let end = self.parse_pat_range_end()?;
621 let range_span = lo.to(end.span);
622 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
625 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
628 "try using the minimum value for the type",
629 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
630 Applicability::HasPlaceholders,
634 Ok(PatKind::Range(begin, end, respan(lo, re)))
637 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
638 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
639 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
640 if self.is_pat_range_end_start() {
641 // Parsing e.g. `X..=Y`.
642 self.parse_pat_range_end()
644 // Parsing e.g. `X..`.
645 let range_span = begin.span.to(self.prev_span);
650 &format!("`X{}` range patterns are not supported", form),
654 "try using the maximum value for the type",
655 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
656 Applicability::HasPlaceholders,
660 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
664 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
665 if self.token.is_path_start() {
666 let lo = self.token.span;
667 let (qself, path) = if self.eat_lt() {
668 // Parse a qualified path
669 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
672 // Parse an unqualified path
673 (None, self.parse_path(PathStyle::Expr)?)
675 let hi = self.prev_span;
676 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
678 self.parse_literal_maybe_minus()
682 /// Is this the start of a pattern beginning with a path?
683 fn is_start_of_pat_with_path(&mut self) -> bool {
685 // Just for recovery (see `can_be_ident`).
686 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
689 /// Would `parse_pat_ident` be appropriate here?
690 fn can_be_ident_pat(&mut self) -> bool {
692 && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
693 && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
694 // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
695 && !self.token.is_keyword(kw::In)
696 && self.look_ahead(1, |t| match t.kind { // Try to do something more complex?
697 token::OpenDelim(token::Paren) // A tuple struct pattern.
698 | token::OpenDelim(token::Brace) // A struct pattern.
699 | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
700 | token::ModSep // A tuple / struct variant pattern.
701 | token::Not => false, // A macro expanding to a pattern.
706 /// Parses `ident` or `ident @ pat`.
707 /// Used by the copy foo and ref foo patterns to give a good
708 /// error message when parsing mistakes like `ref foo(a, b)`.
709 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
710 let ident = self.parse_ident()?;
711 let sub = if self.eat(&token::At) {
712 Some(self.parse_pat(Some("binding pattern"))?)
717 // Just to be friendly, if they write something like `ref Some(i)`,
718 // we end up here with `(` as the current token.
719 // This shortly leads to a parse error. Note that if there is no explicit
720 // binding mode then we do not end up here, because the lookahead
721 // will direct us over to `parse_enum_variant()`.
722 if self.token == token::OpenDelim(token::Paren) {
723 return Err(self.span_fatal(
725 "expected identifier, found enum pattern",
729 Ok(PatKind::Ident(binding_mode, ident, sub))
732 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
733 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
735 let msg = "unexpected `{` after qualified path";
736 let mut err = self.fatal(msg);
737 err.span_label(self.token.span, msg);
742 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
748 Ok(PatKind::Struct(path, fields, etc))
751 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
752 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
754 let msg = "unexpected `(` after qualified path";
755 let mut err = self.fatal(msg);
756 err.span_label(self.token.span, msg);
759 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
760 Ok(PatKind::TupleStruct(path, fields))
763 /// Parses the fields of a struct-like pattern.
764 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
765 let mut fields = Vec::new();
767 let mut ate_comma = true;
768 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
769 let mut etc_span = None;
771 while self.token != token::CloseDelim(token::Brace) {
772 let attrs = match self.parse_outer_attributes() {
775 if let Some(mut delayed) = delayed_err {
781 let lo = self.token.span;
783 // check that a comma comes after every field
785 let err = self.struct_span_err(self.prev_span, "expected `,`");
786 if let Some(mut delayed) = delayed_err {
793 if self.check(&token::DotDot) || self.token == token::DotDotDot {
795 let mut etc_sp = self.token.span;
797 self.recover_one_fewer_dotdot();
798 self.bump(); // `..` || `...`
800 if self.token == token::CloseDelim(token::Brace) {
801 etc_span = Some(etc_sp);
804 let token_str = self.this_token_descr();
805 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
807 err.span_label(self.token.span, "expected `}`");
808 let mut comma_sp = None;
809 if self.token == token::Comma { // Issue #49257
810 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
811 etc_sp = etc_sp.to(nw_span);
812 err.span_label(etc_sp,
813 "`..` must be at the end and cannot have a trailing comma");
814 comma_sp = Some(self.token.span);
819 etc_span = Some(etc_sp.until(self.token.span));
820 if self.token == token::CloseDelim(token::Brace) {
821 // If the struct looks otherwise well formed, recover and continue.
822 if let Some(sp) = comma_sp {
823 err.span_suggestion_short(
827 Applicability::MachineApplicable,
832 } else if self.token.is_ident() && ate_comma {
833 // Accept fields coming after `..,`.
834 // This way we avoid "pattern missing fields" errors afterwards.
835 // We delay this error until the end in order to have a span for a
837 if let Some(mut delayed_err) = delayed_err {
841 delayed_err = Some(err);
844 if let Some(mut err) = delayed_err {
851 fields.push(match self.parse_pat_field(lo, attrs) {
854 if let Some(mut delayed_err) = delayed_err {
860 ate_comma = self.eat(&token::Comma);
863 if let Some(mut err) = delayed_err {
864 if let Some(etc_span) = etc_span {
865 err.multipart_suggestion(
866 "move the `..` to the end of the field list",
868 (etc_span, String::new()),
869 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
871 Applicability::MachineApplicable,
876 return Ok((fields, etc));
879 /// Recover on `...` as if it were `..` to avoid further errors.
880 /// See issue #46718.
881 fn recover_one_fewer_dotdot(&self) {
882 if self.token != token::DotDotDot {
886 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
889 "to omit remaining fields, use one fewer `.`",
891 Applicability::MachineApplicable
896 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
897 // Check if a colon exists one ahead. This means we're parsing a fieldname.
899 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
900 // Parsing a pattern of the form `fieldname: pat`.
901 let fieldname = self.parse_field_name()?;
903 let pat = self.parse_pat_with_or_inner()?;
905 (pat, fieldname, false)
907 // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
908 let is_box = self.eat_keyword(kw::Box);
909 let boxed_span = self.token.span;
910 let is_ref = self.eat_keyword(kw::Ref);
911 let is_mut = self.eat_keyword(kw::Mut);
912 let fieldname = self.parse_ident()?;
915 let bind_type = match (is_ref, is_mut) {
916 (true, true) => BindingMode::ByRef(Mutability::Mutable),
917 (true, false) => BindingMode::ByRef(Mutability::Immutable),
918 (false, true) => BindingMode::ByValue(Mutability::Mutable),
919 (false, false) => BindingMode::ByValue(Mutability::Immutable),
922 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
923 let subpat = if is_box {
924 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
928 (subpat, fieldname, true)
936 id: ast::DUMMY_NODE_ID,
938 is_placeholder: false,
942 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
943 self.mk_pat(span, PatKind::Ident(bm, ident, None))
946 fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
947 P(Pat { kind, span, id: ast::DUMMY_NODE_ID })