1 use super::{Parser, PathStyle};
2 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
3 use syntax::ast::{self, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac};
4 use syntax::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind};
5 use syntax::mut_visit::{noop_visit_pat, noop_visit_mac, MutVisitor};
7 use syntax::print::pprust;
10 use syntax::source_map::{respan, Span, Spanned};
11 use syntax_pos::symbol::{kw, sym};
12 use errors::{PResult, Applicability, DiagnosticBuilder};
14 type Expected = Option<&'static str>;
16 /// `Expected` for function and lambda parameter patterns.
17 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
19 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
21 /// Whether or not an or-pattern should be gated when occurring in the current context.
23 pub(super) enum GateOr { Yes, No }
25 /// Whether or not to recover a `,` when parsing or-patterns.
26 #[derive(PartialEq, Copy, Clone)]
27 enum RecoverComma { Yes, No }
32 /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
33 /// at the top level. Used when parsing the parameters of lambda expressions,
34 /// functions, function pointers, and `pat` macro fragments.
35 pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
36 self.parse_pat_with_range_pat(true, expected)
39 /// Entry point to the main pattern parser.
40 /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
41 pub(super) fn parse_top_pat(&mut self, gate_or: GateOr) -> PResult<'a, P<Pat>> {
42 // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
43 let gated_leading_vert = self.eat_or_separator(None) && gate_or == GateOr::Yes;
44 let leading_vert_span = self.prev_span;
46 // Parse the possibly-or-pattern.
47 let pat = self.parse_pat_with_or(None, gate_or, RecoverComma::Yes)?;
49 // If we parsed a leading `|` which should be gated,
50 // and no other gated or-pattern has been parsed thus far,
51 // then we should really gate the leading `|`.
52 // This complicated procedure is done purely for diagnostics UX.
53 if gated_leading_vert && self.sess.gated_spans.is_ungated(sym::or_patterns) {
54 self.sess.gated_spans.gate(sym::or_patterns, leading_vert_span);
60 /// Parse the pattern for a function or function pointer parameter.
61 /// Special recovery is provided for or-patterns and leading `|`.
62 pub(super) fn parse_fn_param_pat(&mut self) -> PResult<'a, P<Pat>> {
63 self.recover_leading_vert(None, "not allowed in a parameter pattern");
64 let pat = self.parse_pat_with_or(PARAM_EXPECTED, GateOr::No, RecoverComma::No)?;
66 if let PatKind::Or(..) = &pat.kind {
67 self.ban_illegal_fn_param_or_pat(&pat);
73 /// Ban `A | B` immediately in a parameter pattern and suggest wrapping in parens.
74 fn ban_illegal_fn_param_or_pat(&self, pat: &Pat) {
75 let msg = "wrap the pattern in parenthesis";
76 let fix = format!("({})", pprust::pat_to_string(pat));
77 self.struct_span_err(pat.span, "an or-pattern parameter must be wrapped in parenthesis")
78 .span_suggestion(pat.span, msg, fix, Applicability::MachineApplicable)
82 /// Parses a pattern, that may be a or-pattern (e.g. `Foo | Bar` in `Some(Foo | Bar)`).
83 /// Corresponds to `pat<allow_top_alt>` in RFC 2535.
89 ) -> PResult<'a, P<Pat>> {
90 // Parse the first pattern (`p_0`).
91 let first_pat = self.parse_pat(expected)?;
92 self.maybe_recover_unexpected_comma(first_pat.span, rc)?;
94 // If the next token is not a `|`,
95 // this is not an or-pattern and we should exit here.
96 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
100 // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
101 let lo = first_pat.span;
102 let mut pats = vec![first_pat];
103 while self.eat_or_separator(Some(lo)) {
104 let pat = self.parse_pat(expected).map_err(|mut err| {
105 err.span_label(lo, WHILE_PARSING_OR_MSG);
108 self.maybe_recover_unexpected_comma(pat.span, rc)?;
111 let or_pattern_span = lo.to(self.prev_span);
113 // Feature gate the or-pattern if instructed:
114 if gate_or == GateOr::Yes {
115 self.sess.gated_spans.gate(sym::or_patterns, or_pattern_span);
118 Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats)))
121 /// Eat the or-pattern `|` separator.
122 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
123 fn eat_or_separator(&mut self, lo: Option<Span>) -> bool {
124 if self.recover_trailing_vert(lo) {
128 match self.token.kind {
130 // Found `||`; Recover and pretend we parsed `|`.
131 self.ban_unexpected_or_or(lo);
135 _ => self.eat(&token::BinOp(token::Or)),
139 /// Recover if `|` or `||` is the current token and we have one of the
140 /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
142 /// These tokens all indicate that we reached the end of the or-pattern
143 /// list and can now reliably say that the `|` was an illegal trailing vert.
144 /// Note that there are more tokens such as `@` for which we know that the `|`
145 /// is an illegal parse. However, the user's intent is less clear in that case.
146 fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
147 let is_end_ahead = self.look_ahead(1, |token| match &token.kind {
148 token::FatArrow // e.g. `a | => 0,`.
149 | token::Ident(kw::If, false) // e.g. `a | if expr`.
150 | token::Eq // e.g. `let a | = 0`.
151 | token::Semi // e.g. `let a |;`.
152 | token::Colon // e.g. `let a | :`.
153 | token::Comma // e.g. `let (a |,)`.
154 | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
155 | token::CloseDelim(token::Paren) // e.g. `let (a | )`.
156 | token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`.
159 match (is_end_ahead, &self.token.kind) {
160 (true, token::BinOp(token::Or)) | (true, token::OrOr) => {
161 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
169 /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
170 fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
171 let mut err = self.struct_span_err(self.token.span, "unexpected token `||` after pattern");
174 "use a single `|` to separate multiple alternative patterns",
176 Applicability::MachineApplicable
178 if let Some(lo) = lo {
179 err.span_label(lo, WHILE_PARSING_OR_MSG);
184 /// Some special error handling for the "top-level" patterns in a match arm,
185 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
186 fn maybe_recover_unexpected_comma(&mut self, lo: Span, rc: RecoverComma) -> PResult<'a, ()> {
187 if rc == RecoverComma::No || self.token != token::Comma {
191 // An unexpected comma after a top-level pattern is a clue that the
192 // user (perhaps more accustomed to some other language) forgot the
193 // parentheses in what should have been a tuple pattern; return a
194 // suggestion-enhanced error here rather than choking on the comma later.
195 let comma_span = self.token.span;
197 if let Err(mut err) = self.skip_pat_list() {
198 // We didn't expect this to work anyway; we just wanted to advance to the
199 // end of the comma-sequence so we know the span to suggest parenthesizing.
202 let seq_span = lo.to(self.prev_span);
203 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
204 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
207 "try adding parentheses to match on a tuple..",
208 format!("({})", seq_snippet),
209 Applicability::MachineApplicable
213 "..or a vertical bar to match on multiple alternatives",
214 format!("{}", seq_snippet.replace(",", " |")),
215 Applicability::MachineApplicable
221 /// Parse and throw away a parentesized comma separated
222 /// sequence of patterns until `)` is reached.
223 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
224 while !self.check(&token::CloseDelim(token::Paren)) {
225 self.parse_pat(None)?;
226 if !self.eat(&token::Comma) {
233 /// Recursive possibly-or-pattern parser with recovery for an erroneous leading `|`.
234 /// See `parse_pat_with_or` for details on parsing or-patterns.
235 fn parse_pat_with_or_inner(&mut self) -> PResult<'a, P<Pat>> {
236 self.recover_leading_vert(None, "only allowed in a top-level pattern");
237 self.parse_pat_with_or(None, GateOr::Yes, RecoverComma::No)
240 /// Recover if `|` or `||` is here.
241 /// The user is thinking that a leading `|` is allowed in this position.
242 fn recover_leading_vert(&mut self, lo: Option<Span>, ctx: &str) {
243 if let token::BinOp(token::Or) | token::OrOr = self.token.kind {
244 self.ban_illegal_vert(lo, "leading", ctx);
249 /// A `|` or possibly `||` token shouldn't be here. Ban it.
250 fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
251 let span = self.token.span;
252 let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
255 &format!("remove the `{}`", pprust::token_to_string(&self.token)),
257 Applicability::MachineApplicable,
259 if let Some(lo) = lo {
260 err.span_label(lo, WHILE_PARSING_OR_MSG);
262 if let token::OrOr = self.token.kind {
263 err.note("alternatives in or-patterns are separated with `|`, not `||`");
268 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
270 fn parse_pat_with_range_pat(
272 allow_range_pat: bool,
274 ) -> PResult<'a, P<Pat>> {
275 maybe_recover_from_interpolated_ty_qpath!(self, true);
276 maybe_whole!(self, NtPat, |x| x);
278 let lo = self.token.span;
279 let pat = match self.token.kind {
280 token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
281 token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
282 token::OpenDelim(token::Bracket) => {
283 // Parse `[pat, pat,...]` as a slice pattern.
284 let (pats, _) = self.parse_delim_comma_seq(
286 |p| p.parse_pat_with_or_inner(),
292 if self.is_pat_range_end_start() {
293 // Parse `..42` for recovery.
294 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
296 // A rest pattern `..`.
301 // Parse `..=42` for recovery.
303 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
305 token::DotDotDot => {
306 // Parse `...42` for recovery.
308 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
310 // At this point, token != `&`, `&&`, `(`, `[`, `..`, `..=`, or `...`.
311 _ => if self.eat_keyword(kw::Underscore) {
314 } else if self.eat_keyword(kw::Mut) {
315 self.parse_pat_ident_mut()?
316 } else if self.eat_keyword(kw::Ref) {
317 // Parse ref ident @ pat / ref mut ident @ pat
318 let mutbl = self.parse_mutability();
319 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
320 } else if self.eat_keyword(kw::Box) {
322 let pat = self.parse_pat_with_range_pat(false, None)?;
323 self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_span));
325 } else if self.can_be_ident_pat() {
326 // Parse `ident @ pat`
327 // This can give false positives and parse nullary enums,
328 // they are dealt with later in resolve.
329 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
330 } else if self.is_start_of_pat_with_path() {
331 // Parse pattern starting with a path
332 let (qself, path) = if self.eat_lt() {
333 // Parse a qualified path
334 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
337 // Parse an unqualified path
338 (None, self.parse_path(PathStyle::Expr)?)
340 match self.token.kind {
341 token::Not if qself.is_none() => self.parse_pat_mac_invoc(path)?,
342 token::DotDotDot | token::DotDotEq | token::DotDot => {
343 self.parse_pat_range_starting_with_path(lo, qself, path)?
345 token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
346 token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
347 _ => PatKind::Path(qself, path),
350 // Try to parse everything else as literal with optional minus
351 match self.parse_literal_maybe_minus() {
353 if self.check(&token::DotDot)
354 || self.check(&token::DotDotEq)
355 || self.check(&token::DotDotDot) =>
357 self.parse_pat_range_starting_with_lit(begin)?
359 Ok(begin) => PatKind::Lit(begin),
360 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
365 let pat = self.mk_pat(lo.to(self.prev_span), pat);
366 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
367 let pat = self.recover_intersection_pat(pat)?;
369 if !allow_range_pat {
370 self.ban_pat_range_if_ambiguous(&pat)?
376 /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
378 /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
379 /// should already have been parsed by now at this point,
380 /// if the next token is `@` then we can try to parse the more general form.
382 /// Consult `parse_pat_ident` for the `binding` grammar.
384 /// The notion of intersection patterns are found in
385 /// e.g. [F#][and] where they are called AND-patterns.
387 /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
388 fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
389 if self.token.kind != token::At {
390 // Next token is not `@` so it's not going to be an intersection pattern.
394 // At this point we attempt to parse `@ $pat_rhs` and emit an error.
396 let mut rhs = self.parse_pat(None)?;
397 let sp = lhs.span.to(rhs.span);
399 if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
400 // The user inverted the order, so help them fix that.
401 let mut applicability = Applicability::MachineApplicable;
402 lhs.walk(&mut |p| match p.kind {
403 // `check_match` is unhappy if the subpattern has a binding anywhere.
404 PatKind::Ident(..) => {
405 applicability = Applicability::MaybeIncorrect;
406 false // Short-circuit.
411 let lhs_span = lhs.span;
412 // Move the LHS into the RHS as a subpattern.
413 // The RHS is now the full pattern.
416 self.struct_span_err(sp, "pattern on wrong side of `@`")
417 .span_label(lhs_span, "pattern on the left, should be on the right")
418 .span_label(rhs.span, "binding on the right, should be on the left")
419 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
422 // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
423 rhs.kind = PatKind::Wild;
424 self.struct_span_err(sp, "left-hand side of `@` must be a binding")
425 .span_label(lhs.span, "interpreted as a pattern, not a binding")
426 .span_label(rhs.span, "also a pattern")
427 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
435 /// Ban a range pattern if it has an ambiguous interpretation.
436 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
439 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
441 PatKind::Range(..) => {}
445 let mut err = self.struct_span_err(
447 "the range pattern here has ambiguous interpretation",
451 "add parentheses to clarify the precedence",
452 format!("({})", pprust::pat_to_string(&pat)),
453 // "ambiguous interpretation" implies that we have to be guessing
454 Applicability::MaybeIncorrect
459 /// Parse `&pat` / `&mut pat`.
460 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
462 let mutbl = self.parse_mutability();
464 if let token::Lifetime(name) = self.token.kind {
465 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
466 err.span_label(self.token.span, "unexpected lifetime");
470 let subpat = self.parse_pat_with_range_pat(false, expected)?;
471 Ok(PatKind::Ref(subpat, mutbl))
474 /// Parse a tuple or parenthesis pattern.
475 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
476 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
478 // Here, `(pat,)` is a tuple pattern.
479 // For backward compatibility, `(..)` is a tuple pattern as well.
480 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
481 PatKind::Paren(fields.into_iter().nth(0).unwrap())
483 PatKind::Tuple(fields)
487 /// Parse a mutable binding with the `mut` token already eaten.
488 fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
489 let mut_span = self.prev_span;
491 if self.eat_keyword(kw::Ref) {
492 return self.recover_mut_ref_ident(mut_span)
495 self.recover_additional_muts();
497 // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
498 if let token::Interpolated(ref nt) = self.token.kind {
499 if let token::NtPat(_) = **nt {
500 self.expected_ident_found().emit();
504 // Parse the pattern we hope to be an identifier.
505 let mut pat = self.parse_pat(Some("identifier"))?;
507 // Add `mut` to any binding in the parsed pattern.
508 let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
510 // Unwrap; If we don't have `mut $ident`, error.
511 let pat = pat.into_inner();
513 PatKind::Ident(..) => {}
514 _ => self.ban_mut_general_pat(mut_span, &pat, changed_any_binding),
520 /// Recover on `mut ref? ident @ pat` and suggest
521 /// that the order of `mut` and `ref` is incorrect.
522 fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
523 let mutref_span = lo.to(self.prev_span);
524 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
527 "try switching the order",
529 Applicability::MachineApplicable
533 self.parse_pat_ident(BindingMode::ByRef(Mutability::Mutable))
536 /// Turn all by-value immutable bindings in a pattern into mutable bindings.
537 /// Returns `true` if any change was made.
538 fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
540 impl MutVisitor for AddMut {
541 fn visit_mac(&mut self, mac: &mut Mac) {
542 noop_visit_mac(mac, self);
545 fn visit_pat(&mut self, pat: &mut P<Pat>) {
546 if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Immutable), ..)
549 *m = Mutability::Mutable;
552 noop_visit_pat(pat, self);
556 let mut add_mut = AddMut(false);
557 add_mut.visit_pat(pat);
561 /// Error on `mut $pat` where `$pat` is not an ident.
562 fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
563 let span = lo.to(pat.span);
564 let fix = pprust::pat_to_string(&pat);
565 let (problem, suggestion) = if changed_any_binding {
566 ("`mut` must be attached to each individual binding", "add `mut` to each binding")
568 ("`mut` must be followed by a named binding", "remove the `mut` prefix")
570 self.struct_span_err(span, problem)
571 .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
572 .note("`mut` may be followed by `variable` and `variable @ pattern`")
576 /// Eat any extraneous `mut`s and error + recover if we ate any.
577 fn recover_additional_muts(&mut self) {
578 let lo = self.token.span;
579 while self.eat_keyword(kw::Mut) {}
580 if lo == self.token.span {
584 let span = lo.to(self.prev_span);
585 self.struct_span_err(span, "`mut` on a binding may not be repeated")
588 "remove the additional `mut`s",
590 Applicability::MachineApplicable,
595 /// Parse macro invocation
596 fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
598 let args = self.parse_mac_args()?;
602 prior_type_ascription: self.last_type_ascription,
604 Ok(PatKind::Mac(mac))
607 fn excluded_range_end(&self, span: Span) -> RangeEnd {
608 self.sess.gated_spans.gate(sym::exclusive_range_pattern, span);
612 /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
613 /// The `$path` has already been parsed and the next token is the `$form`.
614 fn parse_pat_range_starting_with_path(
617 qself: Option<QSelf>,
619 ) -> PResult<'a, PatKind> {
620 let (end_kind, form) = match self.token.kind {
621 token::DotDot => (self.excluded_range_end(self.token.span), ".."),
622 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
623 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
624 _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
626 let op_span = self.token.span;
628 let span = lo.to(self.prev_span);
629 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
631 let end = self.parse_pat_range_end_opt(&begin, form)?;
632 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
635 /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
636 /// The `$path` has already been parsed and the next token is the `$form`.
637 fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
638 let op_span = self.token.span;
639 let (end_kind, form) = if self.eat(&token::DotDotDot) {
640 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
641 } else if self.eat(&token::DotDotEq) {
642 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
643 } else if self.eat(&token::DotDot) {
644 (self.excluded_range_end(op_span), "..")
646 panic!("impossible case: we already matched on a range-operator token")
648 let end = self.parse_pat_range_end_opt(&begin, form)?;
649 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
652 fn fatal_unexpected_non_pat(
654 mut err: DiagnosticBuilder<'a>,
656 ) -> PResult<'a, P<Pat>> {
659 let expected = expected.unwrap_or("pattern");
660 let msg = format!("expected {}, found {}", expected, self.this_token_descr());
662 let mut err = self.fatal(&msg);
663 err.span_label(self.token.span, format!("expected {}", expected));
665 let sp = self.sess.source_map().start_point(self.token.span);
666 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
667 self.sess.expr_parentheses_needed(&mut err, *sp, None);
673 /// Is the current token suitable as the start of a range patterns end?
674 fn is_pat_range_end_start(&self) -> bool {
675 self.token.is_path_start() // e.g. `MY_CONST`;
676 || self.token == token::Dot // e.g. `.5` for recovery;
677 || self.token.can_begin_literal_or_bool() // e.g. `42`.
678 || self.token.is_whole_expr()
681 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
682 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
683 let lo = self.prev_span;
684 let end = self.parse_pat_range_end()?;
685 let range_span = lo.to(end.span);
686 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
689 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
692 "try using the minimum value for the type",
693 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
694 Applicability::HasPlaceholders,
698 Ok(PatKind::Range(begin, end, respan(lo, re)))
701 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
702 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
703 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
704 if self.is_pat_range_end_start() {
705 // Parsing e.g. `X..=Y`.
706 self.parse_pat_range_end()
708 // Parsing e.g. `X..`.
709 let range_span = begin.span.to(self.prev_span);
714 &format!("`X{}` range patterns are not supported", form),
718 "try using the maximum value for the type",
719 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
720 Applicability::HasPlaceholders,
724 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
728 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
729 if self.token.is_path_start() {
730 let lo = self.token.span;
731 let (qself, path) = if self.eat_lt() {
732 // Parse a qualified path
733 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
736 // Parse an unqualified path
737 (None, self.parse_path(PathStyle::Expr)?)
739 let hi = self.prev_span;
740 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
742 self.parse_literal_maybe_minus()
746 /// Is this the start of a pattern beginning with a path?
747 fn is_start_of_pat_with_path(&mut self) -> bool {
749 // Just for recovery (see `can_be_ident`).
750 || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
753 /// Would `parse_pat_ident` be appropriate here?
754 fn can_be_ident_pat(&mut self) -> bool {
756 && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
757 && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
758 // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
759 && !self.token.is_keyword(kw::In)
760 && self.look_ahead(1, |t| match t.kind { // Try to do something more complex?
761 token::OpenDelim(token::Paren) // A tuple struct pattern.
762 | token::OpenDelim(token::Brace) // A struct pattern.
763 | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
764 | token::ModSep // A tuple / struct variant pattern.
765 | token::Not => false, // A macro expanding to a pattern.
770 /// Parses `ident` or `ident @ pat`.
771 /// Used by the copy foo and ref foo patterns to give a good
772 /// error message when parsing mistakes like `ref foo(a, b)`.
773 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
774 let ident = self.parse_ident()?;
775 let sub = if self.eat(&token::At) {
776 Some(self.parse_pat(Some("binding pattern"))?)
781 // Just to be friendly, if they write something like `ref Some(i)`,
782 // we end up here with `(` as the current token.
783 // This shortly leads to a parse error. Note that if there is no explicit
784 // binding mode then we do not end up here, because the lookahead
785 // will direct us over to `parse_enum_variant()`.
786 if self.token == token::OpenDelim(token::Paren) {
787 return Err(self.span_fatal(
789 "expected identifier, found enum pattern",
793 Ok(PatKind::Ident(binding_mode, ident, sub))
796 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
797 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
799 let msg = "unexpected `{` after qualified path";
800 let mut err = self.fatal(msg);
801 err.span_label(self.token.span, msg);
806 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
812 Ok(PatKind::Struct(path, fields, etc))
815 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
816 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
818 let msg = "unexpected `(` after qualified path";
819 let mut err = self.fatal(msg);
820 err.span_label(self.token.span, msg);
823 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
824 Ok(PatKind::TupleStruct(path, fields))
827 /// Parses the fields of a struct-like pattern.
828 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
829 let mut fields = Vec::new();
831 let mut ate_comma = true;
832 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
833 let mut etc_span = None;
835 while self.token != token::CloseDelim(token::Brace) {
836 let attrs = match self.parse_outer_attributes() {
839 if let Some(mut delayed) = delayed_err {
845 let lo = self.token.span;
847 // check that a comma comes after every field
849 let err = self.struct_span_err(self.prev_span, "expected `,`");
850 if let Some(mut delayed) = delayed_err {
857 if self.check(&token::DotDot) || self.token == token::DotDotDot {
859 let mut etc_sp = self.token.span;
861 self.recover_one_fewer_dotdot();
862 self.bump(); // `..` || `...`
864 if self.token == token::CloseDelim(token::Brace) {
865 etc_span = Some(etc_sp);
868 let token_str = self.this_token_descr();
869 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
871 err.span_label(self.token.span, "expected `}`");
872 let mut comma_sp = None;
873 if self.token == token::Comma { // Issue #49257
874 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
875 etc_sp = etc_sp.to(nw_span);
876 err.span_label(etc_sp,
877 "`..` must be at the end and cannot have a trailing comma");
878 comma_sp = Some(self.token.span);
883 etc_span = Some(etc_sp.until(self.token.span));
884 if self.token == token::CloseDelim(token::Brace) {
885 // If the struct looks otherwise well formed, recover and continue.
886 if let Some(sp) = comma_sp {
887 err.span_suggestion_short(
891 Applicability::MachineApplicable,
896 } else if self.token.is_ident() && ate_comma {
897 // Accept fields coming after `..,`.
898 // This way we avoid "pattern missing fields" errors afterwards.
899 // We delay this error until the end in order to have a span for a
901 if let Some(mut delayed_err) = delayed_err {
905 delayed_err = Some(err);
908 if let Some(mut err) = delayed_err {
915 fields.push(match self.parse_pat_field(lo, attrs) {
918 if let Some(mut delayed_err) = delayed_err {
924 ate_comma = self.eat(&token::Comma);
927 if let Some(mut err) = delayed_err {
928 if let Some(etc_span) = etc_span {
929 err.multipart_suggestion(
930 "move the `..` to the end of the field list",
932 (etc_span, String::new()),
933 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
935 Applicability::MachineApplicable,
940 return Ok((fields, etc));
943 /// Recover on `...` as if it were `..` to avoid further errors.
944 /// See issue #46718.
945 fn recover_one_fewer_dotdot(&self) {
946 if self.token != token::DotDotDot {
950 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
953 "to omit remaining fields, use one fewer `.`",
955 Applicability::MachineApplicable
960 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
961 // Check if a colon exists one ahead. This means we're parsing a fieldname.
963 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
964 // Parsing a pattern of the form `fieldname: pat`.
965 let fieldname = self.parse_field_name()?;
967 let pat = self.parse_pat_with_or_inner()?;
969 (pat, fieldname, false)
971 // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
972 let is_box = self.eat_keyword(kw::Box);
973 let boxed_span = self.token.span;
974 let is_ref = self.eat_keyword(kw::Ref);
975 let is_mut = self.eat_keyword(kw::Mut);
976 let fieldname = self.parse_ident()?;
979 let bind_type = match (is_ref, is_mut) {
980 (true, true) => BindingMode::ByRef(Mutability::Mutable),
981 (true, false) => BindingMode::ByRef(Mutability::Immutable),
982 (false, true) => BindingMode::ByValue(Mutability::Mutable),
983 (false, false) => BindingMode::ByValue(Mutability::Immutable),
986 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
987 let subpat = if is_box {
988 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
992 (subpat, fieldname, true)
1000 id: ast::DUMMY_NODE_ID,
1002 is_placeholder: false,
1006 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1007 self.mk_pat(span, PatKind::Ident(bm, ident, None))
1010 fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1011 P(Pat { kind, span, id: ast::DUMMY_NODE_ID })