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::parse::token::{self};
8 use crate::print::pprust;
9 use crate::source_map::{respan, Span, Spanned};
10 use crate::symbol::kw;
13 use errors::{Applicability, DiagnosticBuilder};
15 type Expected = Option<&'static str>;
19 pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
20 self.parse_pat_with_range_pat(true, expected)
23 /// Parses patterns, separated by '|' s.
24 pub(super) fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
25 // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
26 self.eat_or_separator();
28 let mut pats = Vec::new();
30 pats.push(self.parse_top_level_pat()?);
32 if !self.eat_or_separator() {
38 pub(super) fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
39 let pat = self.parse_pat(None)?;
40 self.maybe_recover_unexpected_comma(pat.span, true)?;
44 /// Parses a pattern, that may be a or-pattern (e.g. `Foo | Bar` in `Some(Foo | Bar)`).
45 /// Corresponds to `pat<allow_top_alt>` in RFC 2535.
51 ) -> PResult<'a, P<Pat>> {
52 // Parse the first pattern.
53 let first_pat = self.parse_pat(expected)?;
54 self.maybe_recover_unexpected_comma(first_pat.span, top_level)?;
56 // If the next token is not a `|`,
57 // this is not an or-pattern and we should exit here.
58 if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
62 let lo = first_pat.span;
63 let mut pats = vec![first_pat];
64 while self.eat_or_separator() {
65 let pat = self.parse_pat(expected)?;
66 self.maybe_recover_unexpected_comma(pat.span, top_level)?;
69 let or_pattern_span = lo.to(self.prev_span);
71 // Feature gate the or-pattern if instructed:
73 self.sess.gated_spans.or_patterns.borrow_mut().push(or_pattern_span);
76 Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats)))
79 /// Eat the or-pattern `|` separator.
80 /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
81 fn eat_or_separator(&mut self) -> bool {
82 match self.token.kind {
84 // Found `||`; Recover and pretend we parsed `|`.
85 self.ban_unexpected_or_or();
89 _ => self.eat(&token::BinOp(token::Or)),
93 /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
94 fn ban_unexpected_or_or(&mut self) {
95 self.struct_span_err(self.token.span, "unexpected token `||` after pattern")
98 "use a single `|` to specify multiple patterns",
100 Applicability::MachineApplicable
105 /// Some special error handling for the "top-level" patterns in a match arm,
106 /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
107 fn maybe_recover_unexpected_comma(&mut self, lo: Span, top_level: bool) -> PResult<'a, ()> {
108 if !top_level || self.token != token::Comma {
112 // An unexpected comma after a top-level pattern is a clue that the
113 // user (perhaps more accustomed to some other language) forgot the
114 // parentheses in what should have been a tuple pattern; return a
115 // suggestion-enhanced error here rather than choking on the comma later.
116 let comma_span = self.token.span;
118 if let Err(mut err) = self.skip_pat_list() {
119 // We didn't expect this to work anyway; we just wanted to advance to the
120 // end of the comma-sequence so we know the span to suggest parenthesizing.
123 let seq_span = lo.to(self.prev_span);
124 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
125 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
128 "try adding parentheses to match on a tuple..",
129 format!("({})", seq_snippet),
130 Applicability::MachineApplicable
134 "..or a vertical bar to match on multiple alternatives",
135 format!("{}", seq_snippet.replace(",", " |")),
136 Applicability::MachineApplicable
142 /// Parse and throw away a parentesized comma separated
143 /// sequence of patterns until `)` is reached.
144 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
145 while !self.check(&token::CloseDelim(token::Paren)) {
146 self.parse_pat(None)?;
147 if !self.eat(&token::Comma) {
154 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
156 fn parse_pat_with_range_pat(
158 allow_range_pat: bool,
160 ) -> PResult<'a, P<Pat>> {
161 maybe_recover_from_interpolated_ty_qpath!(self, true);
162 maybe_whole!(self, NtPat, |x| x);
164 let lo = self.token.span;
165 let pat = match self.token.kind {
166 token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
167 token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
168 token::OpenDelim(token::Bracket) => {
169 // Parse `[pat, pat,...]` as a slice pattern.
170 let (pats, _) = self.parse_delim_comma_seq(
172 |p| p.parse_pat_with_or(None, true, false),
178 if self.is_pat_range_end_start() {
179 // Parse `..42` for recovery.
180 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
182 // A rest pattern `..`.
187 // Parse `..=42` for recovery.
189 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
191 token::DotDotDot => {
192 // Parse `...42` for recovery.
194 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
196 // At this point, token != &, &&, (, [
197 _ => if self.eat_keyword(kw::Underscore) {
200 } else if self.eat_keyword(kw::Mut) {
201 self.recover_pat_ident_mut_first()?
202 } else if self.eat_keyword(kw::Ref) {
203 // Parse ref ident @ pat / ref mut ident @ pat
204 let mutbl = self.parse_mutability();
205 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
206 } else if self.eat_keyword(kw::Box) {
208 PatKind::Box(self.parse_pat_with_range_pat(false, None)?)
209 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
210 self.parse_as_ident() {
211 // Parse `ident @ pat`
212 // This can give false positives and parse nullary enums,
213 // they are dealt with later in resolve.
214 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
215 } else if self.token.is_path_start() {
216 // Parse pattern starting with a path
217 let (qself, path) = if self.eat_lt() {
218 // Parse a qualified path
219 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
222 // Parse an unqualified path
223 (None, self.parse_path(PathStyle::Expr)?)
225 match self.token.kind {
226 token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?,
227 token::DotDotDot | token::DotDotEq | token::DotDot => {
228 self.parse_pat_range_starting_with_path(lo, qself, path)?
230 token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
231 token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
232 _ => PatKind::Path(qself, path),
235 // Try to parse everything else as literal with optional minus
236 match self.parse_literal_maybe_minus() {
238 if self.check(&token::DotDot)
239 || self.check(&token::DotDotEq)
240 || self.check(&token::DotDotDot) =>
242 self.parse_pat_range_starting_with_lit(begin)?
244 Ok(begin) => PatKind::Lit(begin),
245 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
250 let pat = self.mk_pat(lo.to(self.prev_span), pat);
251 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
253 if !allow_range_pat {
254 self.ban_pat_range_if_ambiguous(&pat)?
260 /// Ban a range pattern if it has an ambiguous interpretation.
261 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
264 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
266 PatKind::Range(..) => {}
270 let mut err = self.struct_span_err(
272 "the range pattern here has ambiguous interpretation",
276 "add parentheses to clarify the precedence",
277 format!("({})", pprust::pat_to_string(&pat)),
278 // "ambiguous interpretation" implies that we have to be guessing
279 Applicability::MaybeIncorrect
284 /// Parse `&pat` / `&mut pat`.
285 fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
287 let mutbl = self.parse_mutability();
289 if let token::Lifetime(name) = self.token.kind {
290 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
291 err.span_label(self.token.span, "unexpected lifetime");
295 let subpat = self.parse_pat_with_range_pat(false, expected)?;
296 Ok(PatKind::Ref(subpat, mutbl))
299 /// Parse a tuple or parenthesis pattern.
300 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
301 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
302 p.parse_pat_with_or(None, true, false)
305 // Here, `(pat,)` is a tuple pattern.
306 // For backward compatibility, `(..)` is a tuple pattern as well.
307 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
308 PatKind::Paren(fields.into_iter().nth(0).unwrap())
310 PatKind::Tuple(fields)
314 /// Recover on `mut ref? ident @ pat` and suggest
315 /// that the order of `mut` and `ref` is incorrect.
316 fn recover_pat_ident_mut_first(&mut self) -> PResult<'a, PatKind> {
317 let mutref_span = self.prev_span.to(self.token.span);
318 let binding_mode = if self.eat_keyword(kw::Ref) {
319 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
322 "try switching the order",
324 Applicability::MachineApplicable
327 BindingMode::ByRef(Mutability::Mutable)
329 BindingMode::ByValue(Mutability::Mutable)
331 self.parse_pat_ident(binding_mode)
334 /// Parse macro invocation
335 fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> {
337 let (delim, tts) = self.expect_delimited_token_tree()?;
342 span: lo.to(self.prev_span),
343 prior_type_ascription: self.last_type_ascription,
345 Ok(PatKind::Mac(mac))
348 /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
349 /// The `$path` has already been parsed and the next token is the `$form`.
350 fn parse_pat_range_starting_with_path(
353 qself: Option<QSelf>,
355 ) -> PResult<'a, PatKind> {
356 let (end_kind, form) = match self.token.kind {
357 token::DotDot => (RangeEnd::Excluded, ".."),
358 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
359 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
360 _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
362 let op_span = self.token.span;
364 let span = lo.to(self.prev_span);
365 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
367 let end = self.parse_pat_range_end_opt(&begin, form)?;
368 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
371 /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
372 /// The `$path` has already been parsed and the next token is the `$form`.
373 fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
374 let op_span = self.token.span;
375 let (end_kind, form) = if self.eat(&token::DotDotDot) {
376 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
377 } else if self.eat(&token::DotDotEq) {
378 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
379 } else if self.eat(&token::DotDot) {
380 (RangeEnd::Excluded, "..")
382 panic!("impossible case: we already matched on a range-operator token")
384 let end = self.parse_pat_range_end_opt(&begin, form)?;
385 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
388 fn fatal_unexpected_non_pat(
390 mut err: DiagnosticBuilder<'a>,
392 ) -> PResult<'a, P<Pat>> {
393 self.cancel(&mut err);
395 let expected = expected.unwrap_or("pattern");
396 let msg = format!("expected {}, found {}", expected, self.this_token_descr());
398 let mut err = self.fatal(&msg);
399 err.span_label(self.token.span, format!("expected {}", expected));
401 let sp = self.sess.source_map().start_point(self.token.span);
402 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
403 self.sess.expr_parentheses_needed(&mut err, *sp, None);
409 // Helper function to decide whether to parse as ident binding
410 // or to try to do something more complex like range patterns.
411 fn parse_as_ident(&mut self) -> bool {
412 self.look_ahead(1, |t| match t.kind {
413 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
414 token::DotDotDot | token::DotDotEq | token::DotDot |
415 token::ModSep | token::Not => false,
420 /// Is the current token suitable as the start of a range patterns end?
421 fn is_pat_range_end_start(&self) -> bool {
422 self.token.is_path_start() // e.g. `MY_CONST`;
423 || self.token == token::Dot // e.g. `.5` for recovery;
424 || self.token.can_begin_literal_or_bool() // e.g. `42`.
425 || self.token.is_whole_expr()
428 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
429 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
430 let lo = self.prev_span;
431 let end = self.parse_pat_range_end()?;
432 let range_span = lo.to(end.span);
433 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
436 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
439 "try using the minimum value for the type",
440 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
441 Applicability::HasPlaceholders,
445 Ok(PatKind::Range(begin, end, respan(lo, re)))
448 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
449 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
450 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
451 if self.is_pat_range_end_start() {
452 // Parsing e.g. `X..=Y`.
453 self.parse_pat_range_end()
455 // Parsing e.g. `X..`.
456 let range_span = begin.span.to(self.prev_span);
461 &format!("`X{}` range patterns are not supported", form),
465 "try using the maximum value for the type",
466 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
467 Applicability::HasPlaceholders,
471 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
475 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
476 if self.token.is_path_start() {
477 let lo = self.token.span;
478 let (qself, path) = if self.eat_lt() {
479 // Parse a qualified path
480 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
483 // Parse an unqualified path
484 (None, self.parse_path(PathStyle::Expr)?)
486 let hi = self.prev_span;
487 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
489 self.parse_literal_maybe_minus()
493 /// Parses `ident` or `ident @ pat`.
494 /// Used by the copy foo and ref foo patterns to give a good
495 /// error message when parsing mistakes like `ref foo(a, b)`.
496 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
497 let ident = self.parse_ident()?;
498 let sub = if self.eat(&token::At) {
499 Some(self.parse_pat(Some("binding pattern"))?)
504 // Just to be friendly, if they write something like `ref Some(i)`,
505 // we end up here with `(` as the current token.
506 // This shortly leads to a parse error. Note that if there is no explicit
507 // binding mode then we do not end up here, because the lookahead
508 // will direct us over to `parse_enum_variant()`.
509 if self.token == token::OpenDelim(token::Paren) {
510 return Err(self.span_fatal(
512 "expected identifier, found enum pattern",
516 Ok(PatKind::Ident(binding_mode, ident, sub))
519 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
520 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
522 let msg = "unexpected `{` after qualified path";
523 let mut err = self.fatal(msg);
524 err.span_label(self.token.span, msg);
529 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
535 Ok(PatKind::Struct(path, fields, etc))
538 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
539 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
541 let msg = "unexpected `(` after qualified path";
542 let mut err = self.fatal(msg);
543 err.span_label(self.token.span, msg);
546 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or(None, true, false))?;
547 Ok(PatKind::TupleStruct(path, fields))
550 /// Parses the fields of a struct-like pattern.
551 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
552 let mut fields = Vec::new();
554 let mut ate_comma = true;
555 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
556 let mut etc_span = None;
558 while self.token != token::CloseDelim(token::Brace) {
559 let attrs = match self.parse_outer_attributes() {
562 if let Some(mut delayed) = delayed_err {
568 let lo = self.token.span;
570 // check that a comma comes after every field
572 let err = self.struct_span_err(self.prev_span, "expected `,`");
573 if let Some(mut delayed) = delayed_err {
580 if self.check(&token::DotDot) || self.token == token::DotDotDot {
582 let mut etc_sp = self.token.span;
584 self.recover_one_fewer_dotdot();
585 self.bump(); // `..` || `...`
587 if self.token == token::CloseDelim(token::Brace) {
588 etc_span = Some(etc_sp);
591 let token_str = self.this_token_descr();
592 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
594 err.span_label(self.token.span, "expected `}`");
595 let mut comma_sp = None;
596 if self.token == token::Comma { // Issue #49257
597 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
598 etc_sp = etc_sp.to(nw_span);
599 err.span_label(etc_sp,
600 "`..` must be at the end and cannot have a trailing comma");
601 comma_sp = Some(self.token.span);
606 etc_span = Some(etc_sp.until(self.token.span));
607 if self.token == token::CloseDelim(token::Brace) {
608 // If the struct looks otherwise well formed, recover and continue.
609 if let Some(sp) = comma_sp {
610 err.span_suggestion_short(
614 Applicability::MachineApplicable,
619 } else if self.token.is_ident() && ate_comma {
620 // Accept fields coming after `..,`.
621 // This way we avoid "pattern missing fields" errors afterwards.
622 // We delay this error until the end in order to have a span for a
624 if let Some(mut delayed_err) = delayed_err {
628 delayed_err = Some(err);
631 if let Some(mut err) = delayed_err {
638 fields.push(match self.parse_pat_field(lo, attrs) {
641 if let Some(mut delayed_err) = delayed_err {
647 ate_comma = self.eat(&token::Comma);
650 if let Some(mut err) = delayed_err {
651 if let Some(etc_span) = etc_span {
652 err.multipart_suggestion(
653 "move the `..` to the end of the field list",
655 (etc_span, String::new()),
656 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
658 Applicability::MachineApplicable,
663 return Ok((fields, etc));
666 /// Recover on `...` as if it were `..` to avoid further errors.
667 /// See issue #46718.
668 fn recover_one_fewer_dotdot(&self) {
669 if self.token != token::DotDotDot {
673 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
676 "to omit remaining fields, use one fewer `.`",
678 Applicability::MachineApplicable
683 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
684 // Check if a colon exists one ahead. This means we're parsing a fieldname.
686 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
687 // Parsing a pattern of the form "fieldname: pat"
688 let fieldname = self.parse_field_name()?;
690 let pat = self.parse_pat_with_or(None, true, false)?;
692 (pat, fieldname, false)
694 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
695 let is_box = self.eat_keyword(kw::Box);
696 let boxed_span = self.token.span;
697 let is_ref = self.eat_keyword(kw::Ref);
698 let is_mut = self.eat_keyword(kw::Mut);
699 let fieldname = self.parse_ident()?;
702 let bind_type = match (is_ref, is_mut) {
703 (true, true) => BindingMode::ByRef(Mutability::Mutable),
704 (true, false) => BindingMode::ByRef(Mutability::Immutable),
705 (false, true) => BindingMode::ByValue(Mutability::Mutable),
706 (false, false) => BindingMode::ByValue(Mutability::Immutable),
709 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
710 let subpat = if is_box {
711 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
715 (subpat, fieldname, true)
723 id: ast::DUMMY_NODE_ID,
728 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
729 self.mk_pat(span, PatKind::Ident(bm, ident, None))
732 fn mk_pat(&self, span: Span, node: PatKind) -> P<Pat> {
733 P(Pat { node, span, id: ast::DUMMY_NODE_ID })