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, 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;
112 match self.token.kind {
113 token::BinOp(token::And) | token::AndAnd => {
114 // Parse &pat / &mut pat
116 let mutbl = self.parse_mutability();
117 if let token::Lifetime(name) = self.token.kind {
118 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
119 err.span_label(self.token.span, "unexpected lifetime");
122 let subpat = self.parse_pat_with_range_pat(false, expected)?;
123 pat = PatKind::Ref(subpat, mutbl);
125 token::OpenDelim(token::Paren) => {
126 // Parse a tuple or parenthesis pattern.
127 let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
129 // Here, `(pat,)` is a tuple pattern.
130 // For backward compatibility, `(..)` is a tuple pattern as well.
131 pat = if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
132 PatKind::Paren(fields.into_iter().nth(0).unwrap())
134 PatKind::Tuple(fields)
137 token::OpenDelim(token::Bracket) => {
138 // Parse `[pat, pat,...]` as a slice pattern.
139 let (slice, _) = self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat(None))?;
140 pat = PatKind::Slice(slice);
144 pat = if self.is_pat_range_end_start() {
145 // Parse `..42` for recovery.
146 self.parse_pat_range_to(RangeEnd::Excluded, "..")?
148 // A rest pattern `..`.
153 // Parse `..=42` for recovery.
155 pat = self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?;
157 token::DotDotDot => {
158 // Parse `...42` for recovery.
160 pat = self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?;
162 // At this point, token != &, &&, (, [
163 _ => if self.eat_keyword(kw::Underscore) {
166 } else if self.eat_keyword(kw::Mut) {
167 // Parse mut ident @ pat / mut ref ident @ pat
168 let mutref_span = self.prev_span.to(self.token.span);
169 let binding_mode = if self.eat_keyword(kw::Ref) {
171 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
174 "try switching the order",
176 Applicability::MachineApplicable
178 BindingMode::ByRef(Mutability::Mutable)
180 BindingMode::ByValue(Mutability::Mutable)
182 pat = self.parse_pat_ident(binding_mode)?;
183 } else if self.eat_keyword(kw::Ref) {
184 // Parse ref ident @ pat / ref mut ident @ pat
185 let mutbl = self.parse_mutability();
186 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
187 } else if self.eat_keyword(kw::Box) {
189 let subpat = self.parse_pat_with_range_pat(false, None)?;
190 pat = PatKind::Box(subpat);
191 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
192 self.parse_as_ident() {
194 // This can give false positives and parse nullary enums,
195 // they are dealt with later in resolve
196 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
197 pat = self.parse_pat_ident(binding_mode)?;
198 } else if self.token.is_path_start() {
199 // Parse pattern starting with a path
200 let (qself, path) = if self.eat_lt() {
201 // Parse a qualified path
202 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
205 // Parse an unqualified path
206 (None, self.parse_path(PathStyle::Expr)?)
208 match self.token.kind {
209 token::Not if qself.is_none() => {
210 // Parse macro invocation
212 let (delim, tts) = self.expect_delimited_token_tree()?;
213 let mac = respan(lo.to(self.prev_span), Mac_ {
217 prior_type_ascription: self.last_type_ascription,
219 pat = PatKind::Mac(mac);
221 token::DotDotDot | token::DotDotEq | token::DotDot => {
222 let (end_kind, form) = match self.token.kind {
223 token::DotDot => (RangeEnd::Excluded, ".."),
224 token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
225 token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
226 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
229 let op_span = self.token.span;
231 let span = lo.to(self.prev_span);
232 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
234 let end = self.parse_pat_range_end_opt(&begin, form)?;
235 pat = PatKind::Range(begin, end, respan(op_span, end_kind));
237 token::OpenDelim(token::Brace) => {
239 let msg = "unexpected `{` after qualified path";
240 let mut err = self.fatal(msg);
241 err.span_label(self.token.span, msg);
244 // Parse struct pattern
246 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
252 pat = PatKind::Struct(path, fields, etc);
254 token::OpenDelim(token::Paren) => {
256 let msg = "unexpected `(` after qualified path";
257 let mut err = self.fatal(msg);
258 err.span_label(self.token.span, msg);
261 // Parse tuple struct or enum pattern
262 let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat(None))?;
263 pat = PatKind::TupleStruct(path, fields)
265 _ => pat = PatKind::Path(qself, path),
268 // Try to parse everything else as literal with optional minus
269 match self.parse_literal_maybe_minus() {
271 let op_span = self.token.span;
272 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
273 self.check(&token::DotDotDot) {
274 let (end_kind, form) = if self.eat(&token::DotDotDot) {
275 (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
276 } else if self.eat(&token::DotDotEq) {
277 (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
278 } else if self.eat(&token::DotDot) {
279 (RangeEnd::Excluded, "..")
281 panic!("impossible case: we already matched \
282 on a range-operator token")
284 let end = self.parse_pat_range_end_opt(&begin, form)?;
285 pat = PatKind::Range(begin, end, respan(op_span, end_kind))
287 pat = PatKind::Lit(begin);
291 self.cancel(&mut err);
292 let expected = expected.unwrap_or("pattern");
294 "expected {}, found {}",
296 self.this_token_descr(),
298 let mut err = self.fatal(&msg);
299 err.span_label(self.token.span, format!("expected {}", expected));
300 let sp = self.sess.source_map().start_point(self.token.span);
301 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
302 self.sess.expr_parentheses_needed(&mut err, *sp, None);
310 let pat = self.mk_pat(lo.to(self.prev_span), pat);
311 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
313 if !allow_range_pat {
316 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
318 PatKind::Range(..) => {
319 let mut err = self.struct_span_err(
321 "the range pattern here has ambiguous interpretation",
325 "add parentheses to clarify the precedence",
326 format!("({})", pprust::pat_to_string(&pat)),
327 // "ambiguous interpretation" implies that we have to be guessing
328 Applicability::MaybeIncorrect
339 // Helper function to decide whether to parse as ident binding
340 // or to try to do something more complex like range patterns.
341 fn parse_as_ident(&mut self) -> bool {
342 self.look_ahead(1, |t| match t.kind {
343 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
344 token::DotDotDot | token::DotDotEq | token::DotDot |
345 token::ModSep | token::Not => false,
350 /// Is the current token suitable as the start of a range patterns end?
351 fn is_pat_range_end_start(&self) -> bool {
352 self.token.is_path_start() // e.g. `MY_CONST`;
353 || self.token == token::Dot // e.g. `.5` for recovery;
354 || self.token.can_begin_literal_or_bool() // e.g. `42`.
355 || self.token.is_whole_expr()
358 /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
359 fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
360 let lo = self.prev_span;
361 let end = self.parse_pat_range_end()?;
362 let range_span = lo.to(end.span);
363 let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
366 .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
369 "try using the minimum value for the type",
370 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
371 Applicability::HasPlaceholders,
375 Ok(PatKind::Range(begin, end, respan(lo, re)))
378 /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover
379 /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
380 fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
381 if self.is_pat_range_end_start() {
382 // Parsing e.g. `X..=Y`.
383 self.parse_pat_range_end()
385 // Parsing e.g. `X..`.
386 let range_span = begin.span.to(self.prev_span);
391 &format!("`X{}` range patterns are not supported", form),
395 "try using the maximum value for the type",
396 format!("{}{}MAX", pprust::expr_to_string(&begin), form),
397 Applicability::HasPlaceholders,
401 Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
405 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
406 if self.token.is_path_start() {
407 let lo = self.token.span;
408 let (qself, path) = if self.eat_lt() {
409 // Parse a qualified path
410 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
413 // Parse an unqualified path
414 (None, self.parse_path(PathStyle::Expr)?)
416 let hi = self.prev_span;
417 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
419 self.parse_literal_maybe_minus()
423 /// Parses `ident` or `ident @ pat`.
424 /// used by the copy foo and ref foo patterns to give a good
425 /// error message when parsing mistakes like `ref foo(a, b)`.
426 fn parse_pat_ident(&mut self,
427 binding_mode: ast::BindingMode)
428 -> PResult<'a, PatKind> {
429 let ident = self.parse_ident()?;
430 let sub = if self.eat(&token::At) {
431 Some(self.parse_pat(Some("binding pattern"))?)
436 // just to be friendly, if they write something like
438 // we end up here with ( as the current token. This shortly
439 // leads to a parse error. Note that if there is no explicit
440 // binding mode then we do not end up here, because the lookahead
441 // will direct us over to parse_enum_variant()
442 if self.token == token::OpenDelim(token::Paren) {
443 return Err(self.span_fatal(
445 "expected identifier, found enum pattern"))
448 Ok(PatKind::Ident(binding_mode, ident, sub))
451 /// Parses the fields of a struct-like pattern.
452 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<Spanned<FieldPat>>, bool)> {
453 let mut fields = Vec::new();
455 let mut ate_comma = true;
456 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
457 let mut etc_span = None;
459 while self.token != token::CloseDelim(token::Brace) {
460 let attrs = match self.parse_outer_attributes() {
463 if let Some(mut delayed) = delayed_err {
469 let lo = self.token.span;
471 // check that a comma comes after every field
473 let err = self.struct_span_err(self.prev_span, "expected `,`");
474 if let Some(mut delayed) = delayed_err {
481 if self.check(&token::DotDot) || self.token == token::DotDotDot {
483 let mut etc_sp = self.token.span;
485 if self.token == token::DotDotDot { // Issue #46718
486 // Accept `...` as if it were `..` to avoid further errors
487 self.struct_span_err(self.token.span, "expected field pattern, found `...`")
490 "to omit remaining fields, use one fewer `.`",
492 Applicability::MachineApplicable
496 self.bump(); // `..` || `...`
498 if self.token == token::CloseDelim(token::Brace) {
499 etc_span = Some(etc_sp);
502 let token_str = self.this_token_descr();
503 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
505 err.span_label(self.token.span, "expected `}`");
506 let mut comma_sp = None;
507 if self.token == token::Comma { // Issue #49257
508 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
509 etc_sp = etc_sp.to(nw_span);
510 err.span_label(etc_sp,
511 "`..` must be at the end and cannot have a trailing comma");
512 comma_sp = Some(self.token.span);
517 etc_span = Some(etc_sp.until(self.token.span));
518 if self.token == token::CloseDelim(token::Brace) {
519 // If the struct looks otherwise well formed, recover and continue.
520 if let Some(sp) = comma_sp {
521 err.span_suggestion_short(
525 Applicability::MachineApplicable,
530 } else if self.token.is_ident() && ate_comma {
531 // Accept fields coming after `..,`.
532 // This way we avoid "pattern missing fields" errors afterwards.
533 // We delay this error until the end in order to have a span for a
535 if let Some(mut delayed_err) = delayed_err {
539 delayed_err = Some(err);
542 if let Some(mut err) = delayed_err {
549 fields.push(match self.parse_pat_field(lo, attrs) {
552 if let Some(mut delayed_err) = delayed_err {
558 ate_comma = self.eat(&token::Comma);
561 if let Some(mut err) = delayed_err {
562 if let Some(etc_span) = etc_span {
563 err.multipart_suggestion(
564 "move the `..` to the end of the field list",
566 (etc_span, String::new()),
567 (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
569 Applicability::MachineApplicable,
574 return Ok((fields, etc));
580 attrs: Vec<Attribute>
581 ) -> PResult<'a, Spanned<FieldPat>> {
582 // Check if a colon exists one ahead. This means we're parsing a fieldname.
584 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
585 // Parsing a pattern of the form "fieldname: pat"
586 let fieldname = self.parse_field_name()?;
588 let pat = self.parse_pat(None)?;
590 (pat, fieldname, false)
592 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
593 let is_box = self.eat_keyword(kw::Box);
594 let boxed_span = self.token.span;
595 let is_ref = self.eat_keyword(kw::Ref);
596 let is_mut = self.eat_keyword(kw::Mut);
597 let fieldname = self.parse_ident()?;
600 let bind_type = match (is_ref, is_mut) {
601 (true, true) => BindingMode::ByRef(Mutability::Mutable),
602 (true, false) => BindingMode::ByRef(Mutability::Immutable),
603 (false, true) => BindingMode::ByValue(Mutability::Mutable),
604 (false, false) => BindingMode::ByValue(Mutability::Immutable),
607 let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
608 let subpat = if is_box {
609 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
613 (subpat, fieldname, true)
627 pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
628 self.mk_pat(span, PatKind::Ident(bm, ident, None))
631 fn mk_pat(&self, span: Span, node: PatKind) -> P<Pat> {
632 P(Pat { node, span, id: ast::DUMMY_NODE_ID })