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};
17 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
18 self.parse_pat_with_range_pat(true, expected)
21 /// Parses patterns, separated by '|' s.
22 pub(super) fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
23 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
24 self.eat(&token::BinOp(token::Or));
26 let mut pats = Vec::new();
28 pats.push(self.parse_top_level_pat()?);
30 if self.token == token::OrOr {
31 self.struct_span_err(self.token.span, "unexpected token `||` after pattern")
34 "use a single `|` to specify multiple patterns",
36 Applicability::MachineApplicable
40 } else if self.eat(&token::BinOp(token::Or)) {
41 // This is a No-op. Continue the loop to parse the next
49 /// A wrapper around `parse_pat` with some special error handling for the
50 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
51 /// to subpatterns within such).
52 pub(super) fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
53 let pat = self.parse_pat(None)?;
54 if self.token == token::Comma {
55 // An unexpected comma after a top-level pattern is a clue that the
56 // user (perhaps more accustomed to some other language) forgot the
57 // parentheses in what should have been a tuple pattern; return a
58 // suggestion-enhanced error here rather than choking on the comma
60 let comma_span = self.token.span;
62 if let Err(mut err) = self.skip_pat_list() {
63 // We didn't expect this to work anyway; we just wanted
64 // to advance to the end of the comma-sequence so we know
65 // the span to suggest parenthesizing
68 let seq_span = pat.span.to(self.prev_span);
69 let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
70 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
73 "try adding parentheses to match on a tuple..",
74 format!("({})", seq_snippet),
75 Applicability::MachineApplicable
78 "..or a vertical bar to match on multiple alternatives",
79 format!("{}", seq_snippet.replace(",", " |")),
80 Applicability::MachineApplicable
88 /// Parse and throw away a parentesized comma separated
89 /// sequence of patterns until `)` is reached.
90 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
91 while !self.check(&token::CloseDelim(token::Paren)) {
92 self.parse_pat(None)?;
93 if !self.eat(&token::Comma) {
100 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
102 fn parse_pat_with_range_pat(
104 allow_range_pat: bool,
105 expected: Option<&'static str>,
106 ) -> PResult<'a, P<Pat>> {
107 maybe_recover_from_interpolated_ty_qpath!(self, true);
108 maybe_whole!(self, NtPat, |x| x);
110 let lo = self.token.span;
111 let pat = match self.token.kind {
112 token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
113 token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
114 token::OpenDelim(token::Bracket) => {
115 // Parse `[pat, pat,...]` as a slice pattern.
116 PatKind::Slice(self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat(None))?.0)
120 if self.is_pat_range_end_start() {
121 // Parse `..42` for recovery.
122 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
124 // A rest pattern `..`.
129 // Parse `..=42` for recovery.
131 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
133 token::DotDotDot => {
134 // Parse `...42` for recovery.
136 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
138 // At this point, token != &, &&, (, [
139 _ => if self.eat_keyword(kw::Underscore) {
142 } else if self.eat_keyword(kw::Mut) {
143 self.recover_pat_ident_mut_first()?
144 } else if self.eat_keyword(kw::Ref) {
145 // Parse ref ident @ pat / ref mut ident @ pat
146 let mutbl = self.parse_mutability();
147 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
148 } else if self.eat_keyword(kw::Box) {
150 PatKind::Box(self.parse_pat_with_range_pat(false, None)?)
151 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
152 self.parse_as_ident() {
153 // Parse `ident @ pat`
154 // This can give false positives and parse nullary enums,
155 // they are dealt with later in resolve.
156 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
157 } else if self.token.is_path_start() {
158 // Parse pattern starting with a path
159 let (qself, path) = if self.eat_lt() {
160 // Parse a qualified path
161 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
164 // Parse an unqualified path
165 (None, self.parse_path(PathStyle::Expr)?)
167 match self.token.kind {
168 token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?,
169 token::DotDotDot | token::DotDotEq | token::DotDot => {
170 self.parse_pat_range_starting_with_path(lo, qself, path)?
172 token::OpenDelim(token::Brace) => {
174 let msg = "unexpected `{` after qualified path";
175 let mut err = self.fatal(msg);
176 err.span_label(self.token.span, msg);
179 // Parse struct pattern
181 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
187 PatKind::Struct(path, fields, etc)
189 token::OpenDelim(token::Paren) => {
191 let msg = "unexpected `(` after qualified path";
192 let mut err = self.fatal(msg);
193 err.span_label(self.token.span, msg);
196 // Parse tuple struct or enum pattern
197 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
198 PatKind::TupleStruct(path, fields)
200 _ => PatKind::Path(qself, path),
203 // Try to parse everything else as literal with optional minus
204 match self.parse_literal_maybe_minus() {
206 if self.check(&token::DotDot)
207 || self.check(&token::DotDotEq)
208 || self.check(&token::DotDotDot) =>
210 self.parse_pat_range_starting_with_lit(begin)?
212 Ok(begin) => PatKind::Lit(begin),
214 self.cancel(&mut err);
215 let expected = expected.unwrap_or("pattern");
217 "expected {}, found {}",
219 self.this_token_descr(),
221 let mut err = self.fatal(&msg);
222 err.span_label(self.token.span, format!("expected {}", expected));
223 let sp = self.sess.source_map().start_point(self.token.span);
224 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
225 self.sess.expr_parentheses_needed(&mut err, *sp, None);
233 let pat = self.mk_pat(lo.to(self.prev_span), pat);
234 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
236 if !allow_range_pat {
237 self.ban_pat_range_if_ambiguous(&pat)?
243 /// Ban a range pattern if it has an ambiguous interpretation.
244 fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
247 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
249 PatKind::Range(..) => {}
253 let mut err = self.struct_span_err(
255 "the range pattern here has ambiguous interpretation",
259 "add parentheses to clarify the precedence",
260 format!("({})", pprust::pat_to_string(&pat)),
261 // "ambiguous interpretation" implies that we have to be guessing
262 Applicability::MaybeIncorrect
267 /// Parse `&pat` / `&mut pat`.
268 fn parse_pat_deref(&mut self, expected: Option<&'static str>) -> PResult<'a, PatKind> {
270 let mutbl = self.parse_mutability();
272 if let token::Lifetime(name) = self.token.kind {
273 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
274 err.span_label(self.token.span, "unexpected lifetime");
278 let subpat = self.parse_pat_with_range_pat(false, expected)?;
279 Ok(PatKind::Ref(subpat, mutbl))
282 /// Parse a tuple or parenthesis pattern.
283 fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
284 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
286 // Here, `(pat,)` is a tuple pattern.
287 // For backward compatibility, `(..)` is a tuple pattern as well.
288 Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
289 PatKind::Paren(fields.into_iter().nth(0).unwrap())
291 PatKind::Tuple(fields)
295 /// Recover on `mut ref? ident @ pat` and suggest
296 /// that the order of `mut` and `ref` is incorrect.
297 fn recover_pat_ident_mut_first(&mut self) -> PResult<'a, PatKind> {
298 let mutref_span = self.prev_span.to(self.token.span);
299 let binding_mode = if self.eat_keyword(kw::Ref) {
300 self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
303 "try switching the order",
305 Applicability::MachineApplicable
308 BindingMode::ByRef(Mutability::Mutable)
310 BindingMode::ByValue(Mutability::Mutable)
312 self.parse_pat_ident(binding_mode)
315 /// Parse macro invocation
316 fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> {
318 let (delim, tts) = self.expect_delimited_token_tree()?;
319 let mac = respan(lo.to(self.prev_span), Mac_ {
323 prior_type_ascription: self.last_type_ascription,
325 Ok(PatKind::Mac(mac))
328 /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
329 /// The `$path` has already been parsed and the next token is the `$form`.
330 fn parse_pat_range_starting_with_path(
333 qself: Option<QSelf>,
335 ) -> PResult<'a, PatKind> {
336 let (end_kind, form) = match self.token.kind {
337 token::DotDot => (RangeEnd::Excluded, ".."),
338 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
339 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
340 _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
342 let op_span = self.token.span;
344 let span = lo.to(self.prev_span);
345 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
347 let end = self.parse_pat_range_end_opt(&begin, form)?;
348 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
351 /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
352 /// The `$path` has already been parsed and the next token is the `$form`.
353 fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
354 let op_span = self.token.span;
355 let (end_kind, form) = if self.eat(&token::DotDotDot) {
356 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
357 } else if self.eat(&token::DotDotEq) {
358 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
359 } else if self.eat(&token::DotDot) {
360 (RangeEnd::Excluded, "..")
362 panic!("impossible case: we already matched on a range-operator token")
364 let end = self.parse_pat_range_end_opt(&begin, form)?;
365 Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
368 // Helper function to decide whether to parse as ident binding
369 // or to try to do something more complex like range patterns.
370 fn parse_as_ident(&mut self) -> bool {
371 self.look_ahead(1, |t| match t.kind {
372 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
373 token::DotDotDot | token::DotDotEq | token::DotDot |
374 token::ModSep | token::Not => false,
379 /// Is the current token suitable as the start of a range patterns end?
380 fn is_pat_range_end_start(&self) -> bool {
381 self.token.is_path_start() // e.g. `MY_CONST`;
382 || self.token == token::Dot // e.g. `.5` for recovery;
383 || self.token.can_begin_literal_or_bool() // e.g. `42`.
384 || self.token.is_whole_expr()
387 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
388 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
389 let lo = self.prev_span;
390 let end = self.parse_pat_range_end()?;
391 let range_span = lo.to(end.span);
392 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
395 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
398 "try using the minimum value for the type",
399 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
400 Applicability::HasPlaceholders,
404 Ok(PatKind::Range(begin, end, respan(lo, re)))
407 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
408 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
409 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
410 if self.is_pat_range_end_start() {
411 // Parsing e.g. `X..=Y`.
412 self.parse_pat_range_end()
414 // Parsing e.g. `X..`.
415 let range_span = begin.span.to(self.prev_span);
420 &format!("`X{}` range patterns are not supported", form),
424 "try using the maximum value for the type",
425 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
426 Applicability::HasPlaceholders,
430 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
434 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
435 if self.token.is_path_start() {
436 let lo = self.token.span;
437 let (qself, path) = if self.eat_lt() {
438 // Parse a qualified path
439 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
442 // Parse an unqualified path
443 (None, self.parse_path(PathStyle::Expr)?)
445 let hi = self.prev_span;
446 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
448 self.parse_literal_maybe_minus()
452 /// Parses `ident` or `ident @ pat`.
453 /// Used by the copy foo and ref foo patterns to give a good
454 /// error message when parsing mistakes like `ref foo(a, b)`.
455 fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
456 let ident = self.parse_ident()?;
457 let sub = if self.eat(&token::At) {
458 Some(self.parse_pat(Some("binding pattern"))?)
463 // Just to be friendly, if they write something like `ref Some(i)`,
464 // we end up here with `(` as the current token.
465 // This shortly leads to a parse error. Note that if there is no explicit
466 // binding mode then we do not end up here, because the lookahead
467 // will direct us over to `parse_enum_variant()`.
468 if self.token == token::OpenDelim(token::Paren) {
469 return Err(self.span_fatal(
471 "expected identifier, found enum pattern",
475 Ok(PatKind::Ident(binding_mode, ident, sub))
478 /// Parses the fields of a struct-like pattern.
479 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<Spanned<FieldPat>>, bool)> {
480 let mut fields = Vec::new();
482 let mut ate_comma = true;
483 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
484 let mut etc_span = None;
486 while self.token != token::CloseDelim(token::Brace) {
487 let attrs = match self.parse_outer_attributes() {
490 if let Some(mut delayed) = delayed_err {
496 let lo = self.token.span;
498 // check that a comma comes after every field
500 let err = self.struct_span_err(self.prev_span, "expected `,`");
501 if let Some(mut delayed) = delayed_err {
508 if self.check(&token::DotDot) || self.token == token::DotDotDot {
510 let mut etc_sp = self.token.span;
512 if self.token == token::DotDotDot { // Issue #46718
513 // Accept `...` as if it were `..` to avoid further errors
514 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
517 "to omit remaining fields, use one fewer `.`",
519 Applicability::MachineApplicable
523 self.bump(); // `..` || `...`
525 if self.token == token::CloseDelim(token::Brace) {
526 etc_span = Some(etc_sp);
529 let token_str = self.this_token_descr();
530 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
532 err.span_label(self.token.span, "expected `}`");
533 let mut comma_sp = None;
534 if self.token == token::Comma { // Issue #49257
535 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
536 etc_sp = etc_sp.to(nw_span);
537 err.span_label(etc_sp,
538 "`..` must be at the end and cannot have a trailing comma");
539 comma_sp = Some(self.token.span);
544 etc_span = Some(etc_sp.until(self.token.span));
545 if self.token == token::CloseDelim(token::Brace) {
546 // If the struct looks otherwise well formed, recover and continue.
547 if let Some(sp) = comma_sp {
548 err.span_suggestion_short(
552 Applicability::MachineApplicable,
557 } else if self.token.is_ident() && ate_comma {
558 // Accept fields coming after `..,`.
559 // This way we avoid "pattern missing fields" errors afterwards.
560 // We delay this error until the end in order to have a span for a
562 if let Some(mut delayed_err) = delayed_err {
566 delayed_err = Some(err);
569 if let Some(mut err) = delayed_err {
576 fields.push(match self.parse_pat_field(lo, attrs) {
579 if let Some(mut delayed_err) = delayed_err {
585 ate_comma = self.eat(&token::Comma);
588 if let Some(mut err) = delayed_err {
589 if let Some(etc_span) = etc_span {
590 err.multipart_suggestion(
591 "move the `..` to the end of the field list",
593 (etc_span, String::new()),
594 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
596 Applicability::MachineApplicable,
601 return Ok((fields, etc));
607 attrs: Vec<Attribute>
608 ) -> PResult<'a, Spanned<FieldPat>> {
609 // Check if a colon exists one ahead. This means we're parsing a fieldname.
611 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
612 // Parsing a pattern of the form "fieldname: pat"
613 let fieldname = self.parse_field_name()?;
615 let pat = self.parse_pat(None)?;
617 (pat, fieldname, false)
619 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
620 let is_box = self.eat_keyword(kw::Box);
621 let boxed_span = self.token.span;
622 let is_ref = self.eat_keyword(kw::Ref);
623 let is_mut = self.eat_keyword(kw::Mut);
624 let fieldname = self.parse_ident()?;
627 let bind_type = match (is_ref, is_mut) {
628 (true, true) => BindingMode::ByRef(Mutability::Mutable),
629 (true, false) => BindingMode::ByRef(Mutability::Immutable),
630 (false, true) => BindingMode::ByValue(Mutability::Mutable),
631 (false, false) => BindingMode::ByValue(Mutability::Immutable),
634 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
635 let subpat = if is_box {
636 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
640 (subpat, fieldname, true)
654 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
655 self.mk_pat(span, PatKind::Ident(bm, ident, None))
658 fn mk_pat(&self, span: Span, node: PatKind) -> P<Pat> {
659 P(Pat { node, span, id: ast::DUMMY_NODE_ID })