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};
19 expected: Option<&'static str>
20 ) -> PResult<'a, P<Pat>> {
21 self.parse_pat_with_range_pat(true, expected)
24 /// Parses patterns, separated by '|' s.
25 pub(super) fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
26 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
27 self.eat(&token::BinOp(token::Or));
29 let mut pats = Vec::new();
31 pats.push(self.parse_top_level_pat()?);
33 if self.token == token::OrOr {
34 self.ban_unexpected_or_or();
36 } else if self.eat(&token::BinOp(token::Or)) {
37 // This is a No-op. Continue the loop to parse the next
45 fn ban_unexpected_or_or(&mut self) {
46 self.struct_span_err(self.token.span, "unexpected token `||` after pattern")
49 "use a single `|` to specify multiple patterns",
51 Applicability::MachineApplicable
56 /// A wrapper around `parse_pat` with some special error handling for the
57 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
58 /// to subpatterns within such).
59 pub(super) fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
60 let pat = self.parse_pat(None)?;
61 if self.token == token::Comma {
62 // An unexpected comma after a top-level pattern is a clue that the
63 // user (perhaps more accustomed to some other language) forgot the
64 // parentheses in what should have been a tuple pattern; return a
65 // suggestion-enhanced error here rather than choking on the comma
67 let comma_span = self.token.span;
69 if let Err(mut err) = self.skip_pat_list() {
70 // We didn't expect this to work anyway; we just wanted
71 // to advance to the end of the comma-sequence so we know
72 // the span to suggest parenthesizing
75 let seq_span = pat.span.to(self.prev_span);
76 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
77 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
80 "try adding parentheses to match on a tuple..",
81 format!("({})", seq_snippet),
82 Applicability::MachineApplicable
85 "..or a vertical bar to match on multiple alternatives",
86 format!("{}", seq_snippet.replace(",", " |")),
87 Applicability::MachineApplicable
95 /// Parse and throw away a parentesized comma separated
96 /// sequence of patterns until `)` is reached.
97 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
98 while !self.check(&token::CloseDelim(token::Paren)) {
99 self.parse_pat(None)?;
100 if !self.eat(&token::Comma) {
107 /// Parses a pattern, that may be a or-pattern (e.g. `Some(Foo | Bar)`).
108 fn parse_pat_with_or(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
109 // Parse the first pattern.
110 let first_pat = self.parse_pat(expected)?;
112 // If the next token is not a `|`, this is not an or-pattern and
113 // we should exit here.
114 if !self.check(&token::BinOp(token::Or)) {
118 let lo = first_pat.span;
120 let mut pats = vec![first_pat];
122 while self.eat(&token::BinOp(token::Or)) {
123 pats.push(self.parse_pat_with_range_pat(true, expected)?);
126 let or_pattern_span = lo.to(self.prev_span);
128 self.sess.gated_spans.or_patterns.borrow_mut().push(or_pattern_span);
130 Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats)))
133 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
135 fn parse_pat_with_range_pat(
137 allow_range_pat: bool,
138 expected: Option<&'static str>,
139 ) -> PResult<'a, P<Pat>> {
140 maybe_recover_from_interpolated_ty_qpath!(self, true);
141 maybe_whole!(self, NtPat, |x| x);
143 let lo = self.token.span;
144 let pat = match self.token.kind {
145 token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
146 token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
147 token::OpenDelim(token::Bracket) => {
148 // Parse `[pat, pat,...]` as a slice pattern.
149 PatKind::Slice(self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat(None))?.0)
153 if self.is_pat_range_end_start() {
154 // Parse `..42` for recovery.
155 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
157 // A rest pattern `..`.
162 // Parse `..=42` for recovery.
164 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
166 token::DotDotDot => {
167 // Parse `...42` for recovery.
169 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
171 // At this point, token != &, &&, (, [
172 _ => if self.eat_keyword(kw::Underscore) {
175 } else if self.eat_keyword(kw::Mut) {
176 self.recover_pat_ident_mut_first()?
177 } else if self.eat_keyword(kw::Ref) {
178 // Parse ref ident @ pat / ref mut ident @ pat
179 let mutbl = self.parse_mutability();
180 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
181 } else if self.eat_keyword(kw::Box) {
183 PatKind::Box(self.parse_pat_with_range_pat(false, None)?)
184 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
185 self.parse_as_ident() {
186 // Parse `ident @ pat`
187 // This can give false positives and parse nullary enums,
188 // they are dealt with later in resolve.
189 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
190 } else if self.token.is_path_start() {
191 // Parse pattern starting with a path
192 let (qself, path) = if self.eat_lt() {
193 // Parse a qualified path
194 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
197 // Parse an unqualified path
198 (None, self.parse_path(PathStyle::Expr)?)
200 match self.token.kind {
201 token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?,
202 token::DotDotDot | token::DotDotEq | token::DotDot => {
203 self.parse_pat_range_starting_with_path(lo, qself, path)?
205 token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
206 token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
207 _ => PatKind::Path(qself, path),
210 // Try to parse everything else as literal with optional minus
211 match self.parse_literal_maybe_minus() {
213 if self.check(&token::DotDot)
214 || self.check(&token::DotDotEq)
215 || self.check(&token::DotDotDot) =>
217 self.parse_pat_range_starting_with_lit(begin)?
219 Ok(begin) => PatKind::Lit(begin),
220 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
225 let pat = self.mk_pat(lo.to(self.prev_span), pat);
226 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
228 if !allow_range_pat {
229 self.ban_pat_range_if_ambiguous(&pat)?
235 /// Ban a range pattern if it has an ambiguous interpretation.
236 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
239 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
241 PatKind::Range(..) => {}
245 let mut err = self.struct_span_err(
247 "the range pattern here has ambiguous interpretation",
251 "add parentheses to clarify the precedence",
252 format!("({})", pprust::pat_to_string(&pat)),
253 // "ambiguous interpretation" implies that we have to be guessing
254 Applicability::MaybeIncorrect
259 /// Parse `&pat` / `&mut pat`.
260 fn parse_pat_deref(&mut self, expected: Option<&'static str>) -> PResult<'a, PatKind> {
262 let mutbl = self.parse_mutability();
264 if let token::Lifetime(name) = self.token.kind {
265 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
266 err.span_label(self.token.span, "unexpected lifetime");
270 let subpat = self.parse_pat_with_range_pat(false, expected)?;
271 Ok(PatKind::Ref(subpat, mutbl))
274 /// Parse a tuple or parenthesis pattern.
275 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
276 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
277 p.parse_pat_with_or(None)
280 // Here, `(pat,)` is a tuple pattern.
281 // For backward compatibility, `(..)` is a tuple pattern as well.
282 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
283 PatKind::Paren(fields.into_iter().nth(0).unwrap())
285 PatKind::Tuple(fields)
289 /// Recover on `mut ref? ident @ pat` and suggest
290 /// that the order of `mut` and `ref` is incorrect.
291 fn recover_pat_ident_mut_first(&mut self) -> PResult<'a, PatKind> {
292 let mutref_span = self.prev_span.to(self.token.span);
293 let binding_mode = if self.eat_keyword(kw::Ref) {
294 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
297 "try switching the order",
299 Applicability::MachineApplicable
302 BindingMode::ByRef(Mutability::Mutable)
304 BindingMode::ByValue(Mutability::Mutable)
306 self.parse_pat_ident(binding_mode)
309 /// Parse macro invocation
310 fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> {
312 let (delim, tts) = self.expect_delimited_token_tree()?;
317 span: lo.to(self.prev_span),
318 prior_type_ascription: self.last_type_ascription,
320 Ok(PatKind::Mac(mac))
323 /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
324 /// The `$path` has already been parsed and the next token is the `$form`.
325 fn parse_pat_range_starting_with_path(
328 qself: Option<QSelf>,
330 ) -> PResult<'a, PatKind> {
331 let (end_kind, form) = match self.token.kind {
332 token::DotDot => (RangeEnd::Excluded, ".."),
333 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
334 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
335 _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
337 let op_span = self.token.span;
339 let span = lo.to(self.prev_span);
340 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
342 let end = self.parse_pat_range_end_opt(&begin, form)?;
343 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
346 /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
347 /// The `$path` has already been parsed and the next token is the `$form`.
348 fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
349 let op_span = self.token.span;
350 let (end_kind, form) = if self.eat(&token::DotDotDot) {
351 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
352 } else if self.eat(&token::DotDotEq) {
353 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
354 } else if self.eat(&token::DotDot) {
355 (RangeEnd::Excluded, "..")
357 panic!("impossible case: we already matched on a range-operator token")
359 let end = self.parse_pat_range_end_opt(&begin, form)?;
360 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
363 fn fatal_unexpected_non_pat(
365 mut err: DiagnosticBuilder<'a>,
366 expected: Option<&'static str>,
367 ) -> PResult<'a, P<Pat>> {
368 self.cancel(&mut err);
370 let expected = expected.unwrap_or("pattern");
371 let msg = format!("expected {}, found {}", expected, self.this_token_descr());
373 let mut err = self.fatal(&msg);
374 err.span_label(self.token.span, format!("expected {}", expected));
376 let sp = self.sess.source_map().start_point(self.token.span);
377 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
378 self.sess.expr_parentheses_needed(&mut err, *sp, None);
384 // Helper function to decide whether to parse as ident binding
385 // or to try to do something more complex like range patterns.
386 fn parse_as_ident(&mut self) -> bool {
387 self.look_ahead(1, |t| match t.kind {
388 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
389 token::DotDotDot | token::DotDotEq | token::DotDot |
390 token::ModSep | token::Not => false,
395 /// Is the current token suitable as the start of a range patterns end?
396 fn is_pat_range_end_start(&self) -> bool {
397 self.token.is_path_start() // e.g. `MY_CONST`;
398 || self.token == token::Dot // e.g. `.5` for recovery;
399 || self.token.can_begin_literal_or_bool() // e.g. `42`.
400 || self.token.is_whole_expr()
403 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
404 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
405 let lo = self.prev_span;
406 let end = self.parse_pat_range_end()?;
407 let range_span = lo.to(end.span);
408 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
411 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
414 "try using the minimum value for the type",
415 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
416 Applicability::HasPlaceholders,
420 Ok(PatKind::Range(begin, end, respan(lo, re)))
423 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
424 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
425 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
426 if self.is_pat_range_end_start() {
427 // Parsing e.g. `X..=Y`.
428 self.parse_pat_range_end()
430 // Parsing e.g. `X..`.
431 let range_span = begin.span.to(self.prev_span);
436 &format!("`X{}` range patterns are not supported", form),
440 "try using the maximum value for the type",
441 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
442 Applicability::HasPlaceholders,
446 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
450 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
451 if self.token.is_path_start() {
452 let lo = self.token.span;
453 let (qself, path) = if self.eat_lt() {
454 // Parse a qualified path
455 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
458 // Parse an unqualified path
459 (None, self.parse_path(PathStyle::Expr)?)
461 let hi = self.prev_span;
462 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
464 self.parse_literal_maybe_minus()
468 /// Parses `ident` or `ident @ pat`.
469 /// Used by the copy foo and ref foo patterns to give a good
470 /// error message when parsing mistakes like `ref foo(a, b)`.
471 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
472 let ident = self.parse_ident()?;
473 let sub = if self.eat(&token::At) {
474 Some(self.parse_pat(Some("binding pattern"))?)
479 // Just to be friendly, if they write something like `ref Some(i)`,
480 // we end up here with `(` as the current token.
481 // This shortly leads to a parse error. Note that if there is no explicit
482 // binding mode then we do not end up here, because the lookahead
483 // will direct us over to `parse_enum_variant()`.
484 if self.token == token::OpenDelim(token::Paren) {
485 return Err(self.span_fatal(
487 "expected identifier, found enum pattern",
491 Ok(PatKind::Ident(binding_mode, ident, sub))
494 /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
495 fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
497 let msg = "unexpected `{` after qualified path";
498 let mut err = self.fatal(msg);
499 err.span_label(self.token.span, msg);
504 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
510 Ok(PatKind::Struct(path, fields, etc))
513 /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
514 fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
516 let msg = "unexpected `(` after qualified path";
517 let mut err = self.fatal(msg);
518 err.span_label(self.token.span, msg);
521 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or(None))?;
522 Ok(PatKind::TupleStruct(path, fields))
525 /// Parses the fields of a struct-like pattern.
526 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
527 let mut fields = Vec::new();
529 let mut ate_comma = true;
530 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
531 let mut etc_span = None;
533 while self.token != token::CloseDelim(token::Brace) {
534 let attrs = match self.parse_outer_attributes() {
537 if let Some(mut delayed) = delayed_err {
543 let lo = self.token.span;
545 // check that a comma comes after every field
547 let err = self.struct_span_err(self.prev_span, "expected `,`");
548 if let Some(mut delayed) = delayed_err {
555 if self.check(&token::DotDot) || self.token == token::DotDotDot {
557 let mut etc_sp = self.token.span;
559 self.recover_one_fewer_dotdot();
560 self.bump(); // `..` || `...`
562 if self.token == token::CloseDelim(token::Brace) {
563 etc_span = Some(etc_sp);
566 let token_str = self.this_token_descr();
567 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
569 err.span_label(self.token.span, "expected `}`");
570 let mut comma_sp = None;
571 if self.token == token::Comma { // Issue #49257
572 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
573 etc_sp = etc_sp.to(nw_span);
574 err.span_label(etc_sp,
575 "`..` must be at the end and cannot have a trailing comma");
576 comma_sp = Some(self.token.span);
581 etc_span = Some(etc_sp.until(self.token.span));
582 if self.token == token::CloseDelim(token::Brace) {
583 // If the struct looks otherwise well formed, recover and continue.
584 if let Some(sp) = comma_sp {
585 err.span_suggestion_short(
589 Applicability::MachineApplicable,
594 } else if self.token.is_ident() && ate_comma {
595 // Accept fields coming after `..,`.
596 // This way we avoid "pattern missing fields" errors afterwards.
597 // We delay this error until the end in order to have a span for a
599 if let Some(mut delayed_err) = delayed_err {
603 delayed_err = Some(err);
606 if let Some(mut err) = delayed_err {
613 fields.push(match self.parse_pat_field(lo, attrs) {
616 if let Some(mut delayed_err) = delayed_err {
622 ate_comma = self.eat(&token::Comma);
625 if let Some(mut err) = delayed_err {
626 if let Some(etc_span) = etc_span {
627 err.multipart_suggestion(
628 "move the `..` to the end of the field list",
630 (etc_span, String::new()),
631 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
633 Applicability::MachineApplicable,
638 return Ok((fields, etc));
641 /// Recover on `...` as if it were `..` to avoid further errors.
642 /// See issue #46718.
643 fn recover_one_fewer_dotdot(&self) {
644 if self.token != token::DotDotDot {
648 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
651 "to omit remaining fields, use one fewer `.`",
653 Applicability::MachineApplicable
658 fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
659 // Check if a colon exists one ahead. This means we're parsing a fieldname.
661 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
662 // Parsing a pattern of the form "fieldname: pat"
663 let fieldname = self.parse_field_name()?;
665 let pat = self.parse_pat_with_or(None)?;
667 (pat, fieldname, false)
669 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
670 let is_box = self.eat_keyword(kw::Box);
671 let boxed_span = self.token.span;
672 let is_ref = self.eat_keyword(kw::Ref);
673 let is_mut = self.eat_keyword(kw::Mut);
674 let fieldname = self.parse_ident()?;
677 let bind_type = match (is_ref, is_mut) {
678 (true, true) => BindingMode::ByRef(Mutability::Mutable),
679 (true, false) => BindingMode::ByRef(Mutability::Immutable),
680 (false, true) => BindingMode::ByValue(Mutability::Mutable),
681 (false, false) => BindingMode::ByValue(Mutability::Immutable),
684 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
685 let subpat = if is_box {
686 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
690 (subpat, fieldname, true)
698 id: ast::DUMMY_NODE_ID,
703 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
704 self.mk_pat(span, PatKind::Ident(bm, ident, None))
707 fn mk_pat(&self, span: Span, node: PatKind) -> P<Pat> {
708 P(Pat { node, span, id: ast::DUMMY_NODE_ID })