]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser/pat.rs
parser: type alias `type Expected = Option<&'static str>;`.
[rust.git] / src / libsyntax / parse / parser / pat.rs
1 use super::{Parser, PResult, PathStyle};
2
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
4 use crate::ptr::P;
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;
11 use crate::ThinVec;
12
13 use errors::{Applicability, DiagnosticBuilder};
14
15 type Expected = Option<&'static str>;
16
17 impl<'a> Parser<'a> {
18     /// Parses a pattern.
19     pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
20         self.parse_pat_with_range_pat(true, expected)
21     }
22
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 (RFC 1925 + RFC 2530)
26         self.eat(&token::BinOp(token::Or));
27
28         let mut pats = Vec::new();
29         loop {
30             pats.push(self.parse_top_level_pat()?);
31
32             if self.token == token::OrOr {
33                 self.ban_unexpected_or_or();
34                 self.bump();
35             } else if self.eat(&token::BinOp(token::Or)) {
36                 // This is a No-op. Continue the loop to parse the next
37                 // pattern.
38             } else {
39                 return Ok(pats);
40             }
41         };
42     }
43
44     fn ban_unexpected_or_or(&mut self) {
45         self.struct_span_err(self.token.span, "unexpected token `||` after pattern")
46             .span_suggestion(
47                 self.token.span,
48                 "use a single `|` to specify multiple patterns",
49                 "|".to_owned(),
50                 Applicability::MachineApplicable
51             )
52             .emit();
53     }
54
55     /// A wrapper around `parse_pat` with some special error handling for the
56     /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
57     /// to subpatterns within such).
58     pub(super) fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
59         let pat = self.parse_pat(None)?;
60         if self.token == token::Comma {
61             // An unexpected comma after a top-level pattern is a clue that the
62             // user (perhaps more accustomed to some other language) forgot the
63             // parentheses in what should have been a tuple pattern; return a
64             // suggestion-enhanced error here rather than choking on the comma
65             // later.
66             let comma_span = self.token.span;
67             self.bump();
68             if let Err(mut err) = self.skip_pat_list() {
69                 // We didn't expect this to work anyway; we just wanted
70                 // to advance to the end of the comma-sequence so we know
71                 // the span to suggest parenthesizing
72                 err.cancel();
73             }
74             let seq_span = pat.span.to(self.prev_span);
75             let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
76             if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
77                 err.span_suggestion(
78                     seq_span,
79                     "try adding parentheses to match on a tuple..",
80                     format!("({})", seq_snippet),
81                     Applicability::MachineApplicable
82                 ).span_suggestion(
83                     seq_span,
84                     "..or a vertical bar to match on multiple alternatives",
85                     format!("{}", seq_snippet.replace(",", " |")),
86                     Applicability::MachineApplicable
87                 );
88             }
89             return Err(err);
90         }
91         Ok(pat)
92     }
93
94     /// Parse and throw away a parentesized comma separated
95     /// sequence of patterns until `)` is reached.
96     fn skip_pat_list(&mut self) -> PResult<'a, ()> {
97         while !self.check(&token::CloseDelim(token::Paren)) {
98             self.parse_pat(None)?;
99             if !self.eat(&token::Comma) {
100                 return Ok(())
101             }
102         }
103         Ok(())
104     }
105
106     /// Parses a pattern, that may be a or-pattern (e.g. `Some(Foo | Bar)`).
107     fn parse_pat_with_or(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
108         // Parse the first pattern.
109         let first_pat = self.parse_pat(expected)?;
110
111         // If the next token is not a `|`, this is not an or-pattern and
112         // we should exit here.
113         if !self.check(&token::BinOp(token::Or)) {
114             return Ok(first_pat)
115         }
116
117         let lo = first_pat.span;
118
119         let mut pats = vec![first_pat];
120
121         while self.eat(&token::BinOp(token::Or)) {
122             pats.push(self.parse_pat_with_range_pat(true, expected)?);
123         }
124
125         let or_pattern_span = lo.to(self.prev_span);
126
127         self.sess.gated_spans.or_patterns.borrow_mut().push(or_pattern_span);
128
129         Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats)))
130     }
131
132     /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
133     /// allowed).
134     fn parse_pat_with_range_pat(
135         &mut self,
136         allow_range_pat: bool,
137         expected: Expected,
138     ) -> PResult<'a, P<Pat>> {
139         maybe_recover_from_interpolated_ty_qpath!(self, true);
140         maybe_whole!(self, NtPat, |x| x);
141
142         let lo = self.token.span;
143         let pat = match self.token.kind {
144             token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
145             token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
146             token::OpenDelim(token::Bracket) => {
147                 // Parse `[pat, pat,...]` as a slice pattern.
148                 PatKind::Slice(self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat(None))?.0)
149             }
150             token::DotDot => {
151                 self.bump();
152                 if self.is_pat_range_end_start() {
153                     // Parse `..42` for recovery.
154                     self.parse_pat_range_to(RangeEnd::Excluded, "..")?
155                 } else {
156                     // A rest pattern `..`.
157                     PatKind::Rest
158                 }
159             }
160             token::DotDotEq => {
161                 // Parse `..=42` for recovery.
162                 self.bump();
163                 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
164             }
165             token::DotDotDot => {
166                 // Parse `...42` for recovery.
167                 self.bump();
168                 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
169             }
170             // At this point, token != &, &&, (, [
171             _ => if self.eat_keyword(kw::Underscore) {
172                 // Parse _
173                 PatKind::Wild
174             } else if self.eat_keyword(kw::Mut) {
175                 self.recover_pat_ident_mut_first()?
176             } else if self.eat_keyword(kw::Ref) {
177                 // Parse ref ident @ pat / ref mut ident @ pat
178                 let mutbl = self.parse_mutability();
179                 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
180             } else if self.eat_keyword(kw::Box) {
181                 // Parse `box pat`
182                 PatKind::Box(self.parse_pat_with_range_pat(false, None)?)
183             } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
184                       self.parse_as_ident() {
185                 // Parse `ident @ pat`
186                 // This can give false positives and parse nullary enums,
187                 // they are dealt with later in resolve.
188                 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
189             } else if self.token.is_path_start() {
190                 // Parse pattern starting with a path
191                 let (qself, path) = if self.eat_lt() {
192                     // Parse a qualified path
193                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
194                     (Some(qself), path)
195                 } else {
196                     // Parse an unqualified path
197                     (None, self.parse_path(PathStyle::Expr)?)
198                 };
199                 match self.token.kind {
200                     token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?,
201                     token::DotDotDot | token::DotDotEq | token::DotDot => {
202                         self.parse_pat_range_starting_with_path(lo, qself, path)?
203                     }
204                     token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
205                     token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
206                     _ => PatKind::Path(qself, path),
207                 }
208             } else {
209                 // Try to parse everything else as literal with optional minus
210                 match self.parse_literal_maybe_minus() {
211                     Ok(begin)
212                         if self.check(&token::DotDot)
213                             || self.check(&token::DotDotEq)
214                             || self.check(&token::DotDotDot) =>
215                     {
216                         self.parse_pat_range_starting_with_lit(begin)?
217                     }
218                     Ok(begin) => PatKind::Lit(begin),
219                     Err(err) => return self.fatal_unexpected_non_pat(err, expected),
220                 }
221             }
222         };
223
224         let pat = self.mk_pat(lo.to(self.prev_span), pat);
225         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
226
227         if !allow_range_pat {
228             self.ban_pat_range_if_ambiguous(&pat)?
229         }
230
231         Ok(pat)
232     }
233
234     /// Ban a range pattern if it has an ambiguous interpretation.
235     fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
236         match pat.node {
237             PatKind::Range(
238                 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
239             ) => return Ok(()),
240             PatKind::Range(..) => {}
241             _ => return Ok(()),
242         }
243
244         let mut err = self.struct_span_err(
245             pat.span,
246             "the range pattern here has ambiguous interpretation",
247         );
248         err.span_suggestion(
249             pat.span,
250             "add parentheses to clarify the precedence",
251             format!("({})", pprust::pat_to_string(&pat)),
252             // "ambiguous interpretation" implies that we have to be guessing
253             Applicability::MaybeIncorrect
254         );
255         Err(err)
256     }
257
258     /// Parse `&pat` / `&mut pat`.
259     fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
260         self.expect_and()?;
261         let mutbl = self.parse_mutability();
262
263         if let token::Lifetime(name) = self.token.kind {
264             let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
265             err.span_label(self.token.span, "unexpected lifetime");
266             return Err(err);
267         }
268
269         let subpat = self.parse_pat_with_range_pat(false, expected)?;
270         Ok(PatKind::Ref(subpat, mutbl))
271     }
272
273     /// Parse a tuple or parenthesis pattern.
274     fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
275         let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
276             p.parse_pat_with_or(None)
277         })?;
278
279         // Here, `(pat,)` is a tuple pattern.
280         // For backward compatibility, `(..)` is a tuple pattern as well.
281         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
282             PatKind::Paren(fields.into_iter().nth(0).unwrap())
283         } else {
284             PatKind::Tuple(fields)
285         })
286     }
287
288     /// Recover on `mut ref? ident @ pat` and suggest
289     /// that the order of `mut` and `ref` is incorrect.
290     fn recover_pat_ident_mut_first(&mut self) -> PResult<'a, PatKind> {
291         let mutref_span = self.prev_span.to(self.token.span);
292         let binding_mode = if self.eat_keyword(kw::Ref) {
293             self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
294                 .span_suggestion(
295                     mutref_span,
296                     "try switching the order",
297                     "ref mut".into(),
298                     Applicability::MachineApplicable
299                 )
300                 .emit();
301             BindingMode::ByRef(Mutability::Mutable)
302         } else {
303             BindingMode::ByValue(Mutability::Mutable)
304         };
305         self.parse_pat_ident(binding_mode)
306     }
307
308     /// Parse macro invocation
309     fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> {
310         self.bump();
311         let (delim, tts) = self.expect_delimited_token_tree()?;
312         let mac = Mac {
313             path,
314             tts,
315             delim,
316             span: lo.to(self.prev_span),
317             prior_type_ascription: self.last_type_ascription,
318         };
319         Ok(PatKind::Mac(mac))
320     }
321
322     /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
323     /// The `$path` has already been parsed and the next token is the `$form`.
324     fn parse_pat_range_starting_with_path(
325         &mut self,
326         lo: Span,
327         qself: Option<QSelf>,
328         path: Path
329     ) -> PResult<'a, PatKind> {
330         let (end_kind, form) = match self.token.kind {
331             token::DotDot => (RangeEnd::Excluded, ".."),
332             token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
333             token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
334             _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
335         };
336         let op_span = self.token.span;
337         // Parse range
338         let span = lo.to(self.prev_span);
339         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
340         self.bump();
341         let end = self.parse_pat_range_end_opt(&begin, form)?;
342         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
343     }
344
345     /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
346     /// The `$path` has already been parsed and the next token is the `$form`.
347     fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
348         let op_span = self.token.span;
349         let (end_kind, form) = if self.eat(&token::DotDotDot) {
350             (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
351         } else if self.eat(&token::DotDotEq) {
352             (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
353         } else if self.eat(&token::DotDot) {
354             (RangeEnd::Excluded, "..")
355         } else {
356             panic!("impossible case: we already matched on a range-operator token")
357         };
358         let end = self.parse_pat_range_end_opt(&begin, form)?;
359         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
360     }
361
362     fn fatal_unexpected_non_pat(
363         &mut self,
364         mut err: DiagnosticBuilder<'a>,
365         expected: Expected,
366     ) -> PResult<'a, P<Pat>> {
367         self.cancel(&mut err);
368
369         let expected = expected.unwrap_or("pattern");
370         let msg = format!("expected {}, found {}", expected, self.this_token_descr());
371
372         let mut err = self.fatal(&msg);
373         err.span_label(self.token.span, format!("expected {}", expected));
374
375         let sp = self.sess.source_map().start_point(self.token.span);
376         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
377             self.sess.expr_parentheses_needed(&mut err, *sp, None);
378         }
379
380         Err(err)
381     }
382
383     // Helper function to decide whether to parse as ident binding
384     // or to try to do something more complex like range patterns.
385     fn parse_as_ident(&mut self) -> bool {
386         self.look_ahead(1, |t| match t.kind {
387             token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
388             token::DotDotDot | token::DotDotEq | token::DotDot |
389             token::ModSep | token::Not => false,
390             _ => true,
391         })
392     }
393
394     /// Is the current token suitable as the start of a range patterns end?
395     fn is_pat_range_end_start(&self) -> bool {
396         self.token.is_path_start() // e.g. `MY_CONST`;
397             || self.token == token::Dot // e.g. `.5` for recovery;
398             || self.token.can_begin_literal_or_bool() // e.g. `42`.
399             || self.token.is_whole_expr()
400     }
401
402     /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
403     fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
404         let lo = self.prev_span;
405         let end = self.parse_pat_range_end()?;
406         let range_span = lo.to(end.span);
407         let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
408
409         self.diagnostic()
410             .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
411             .span_suggestion(
412                 range_span,
413                 "try using the minimum value for the type",
414                 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
415                 Applicability::HasPlaceholders,
416             )
417             .emit();
418
419         Ok(PatKind::Range(begin, end, respan(lo, re)))
420     }
421
422     /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern  or recover
423     /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
424     fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
425         if self.is_pat_range_end_start() {
426             // Parsing e.g. `X..=Y`.
427             self.parse_pat_range_end()
428         } else {
429             // Parsing e.g. `X..`.
430             let range_span = begin.span.to(self.prev_span);
431
432             self.diagnostic()
433                 .struct_span_err(
434                     range_span,
435                     &format!("`X{}` range patterns are not supported", form),
436                 )
437                 .span_suggestion(
438                     range_span,
439                     "try using the maximum value for the type",
440                     format!("{}{}MAX", pprust::expr_to_string(&begin), form),
441                     Applicability::HasPlaceholders,
442                 )
443                 .emit();
444
445             Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
446         }
447     }
448
449     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
450         if self.token.is_path_start() {
451             let lo = self.token.span;
452             let (qself, path) = if self.eat_lt() {
453                 // Parse a qualified path
454                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
455                 (Some(qself), path)
456             } else {
457                 // Parse an unqualified path
458                 (None, self.parse_path(PathStyle::Expr)?)
459             };
460             let hi = self.prev_span;
461             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
462         } else {
463             self.parse_literal_maybe_minus()
464         }
465     }
466
467     /// Parses `ident` or `ident @ pat`.
468     /// Used by the copy foo and ref foo patterns to give a good
469     /// error message when parsing mistakes like `ref foo(a, b)`.
470     fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
471         let ident = self.parse_ident()?;
472         let sub = if self.eat(&token::At) {
473             Some(self.parse_pat(Some("binding pattern"))?)
474         } else {
475             None
476         };
477
478         // Just to be friendly, if they write something like `ref Some(i)`,
479         // we end up here with `(` as the current token.
480         // This shortly leads to a parse error. Note that if there is no explicit
481         // binding mode then we do not end up here, because the lookahead
482         // will direct us over to `parse_enum_variant()`.
483         if self.token == token::OpenDelim(token::Paren) {
484             return Err(self.span_fatal(
485                 self.prev_span,
486                 "expected identifier, found enum pattern",
487             ))
488         }
489
490         Ok(PatKind::Ident(binding_mode, ident, sub))
491     }
492
493     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
494     fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
495         if qself.is_some() {
496             let msg = "unexpected `{` after qualified path";
497             let mut err = self.fatal(msg);
498             err.span_label(self.token.span, msg);
499             return Err(err);
500         }
501
502         self.bump();
503         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
504             e.emit();
505             self.recover_stmt();
506             (vec![], true)
507         });
508         self.bump();
509         Ok(PatKind::Struct(path, fields, etc))
510     }
511
512     /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
513     fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
514         if qself.is_some() {
515             let msg = "unexpected `(` after qualified path";
516             let mut err = self.fatal(msg);
517             err.span_label(self.token.span, msg);
518             return Err(err);
519         }
520         let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or(None))?;
521         Ok(PatKind::TupleStruct(path, fields))
522     }
523
524     /// Parses the fields of a struct-like pattern.
525     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
526         let mut fields = Vec::new();
527         let mut etc = false;
528         let mut ate_comma = true;
529         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
530         let mut etc_span = None;
531
532         while self.token != token::CloseDelim(token::Brace) {
533             let attrs = match self.parse_outer_attributes() {
534                 Ok(attrs) => attrs,
535                 Err(err) => {
536                     if let Some(mut delayed) = delayed_err {
537                         delayed.emit();
538                     }
539                     return Err(err);
540                 },
541             };
542             let lo = self.token.span;
543
544             // check that a comma comes after every field
545             if !ate_comma {
546                 let err = self.struct_span_err(self.prev_span, "expected `,`");
547                 if let Some(mut delayed) = delayed_err {
548                     delayed.emit();
549                 }
550                 return Err(err);
551             }
552             ate_comma = false;
553
554             if self.check(&token::DotDot) || self.token == token::DotDotDot {
555                 etc = true;
556                 let mut etc_sp = self.token.span;
557
558                 self.recover_one_fewer_dotdot();
559                 self.bump();  // `..` || `...`
560
561                 if self.token == token::CloseDelim(token::Brace) {
562                     etc_span = Some(etc_sp);
563                     break;
564                 }
565                 let token_str = self.this_token_descr();
566                 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
567
568                 err.span_label(self.token.span, "expected `}`");
569                 let mut comma_sp = None;
570                 if self.token == token::Comma { // Issue #49257
571                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
572                     etc_sp = etc_sp.to(nw_span);
573                     err.span_label(etc_sp,
574                                    "`..` must be at the end and cannot have a trailing comma");
575                     comma_sp = Some(self.token.span);
576                     self.bump();
577                     ate_comma = true;
578                 }
579
580                 etc_span = Some(etc_sp.until(self.token.span));
581                 if self.token == token::CloseDelim(token::Brace) {
582                     // If the struct looks otherwise well formed, recover and continue.
583                     if let Some(sp) = comma_sp {
584                         err.span_suggestion_short(
585                             sp,
586                             "remove this comma",
587                             String::new(),
588                             Applicability::MachineApplicable,
589                         );
590                     }
591                     err.emit();
592                     break;
593                 } else if self.token.is_ident() && ate_comma {
594                     // Accept fields coming after `..,`.
595                     // This way we avoid "pattern missing fields" errors afterwards.
596                     // We delay this error until the end in order to have a span for a
597                     // suggested fix.
598                     if let Some(mut delayed_err) = delayed_err {
599                         delayed_err.emit();
600                         return Err(err);
601                     } else {
602                         delayed_err = Some(err);
603                     }
604                 } else {
605                     if let Some(mut err) = delayed_err {
606                         err.emit();
607                     }
608                     return Err(err);
609                 }
610             }
611
612             fields.push(match self.parse_pat_field(lo, attrs) {
613                 Ok(field) => field,
614                 Err(err) => {
615                     if let Some(mut delayed_err) = delayed_err {
616                         delayed_err.emit();
617                     }
618                     return Err(err);
619                 }
620             });
621             ate_comma = self.eat(&token::Comma);
622         }
623
624         if let Some(mut err) = delayed_err {
625             if let Some(etc_span) = etc_span {
626                 err.multipart_suggestion(
627                     "move the `..` to the end of the field list",
628                     vec![
629                         (etc_span, String::new()),
630                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
631                     ],
632                     Applicability::MachineApplicable,
633                 );
634             }
635             err.emit();
636         }
637         return Ok((fields, etc));
638     }
639
640     /// Recover on `...` as if it were `..` to avoid further errors.
641     /// See issue #46718.
642     fn recover_one_fewer_dotdot(&self) {
643         if self.token != token::DotDotDot {
644             return;
645         }
646
647         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
648             .span_suggestion(
649                 self.token.span,
650                 "to omit remaining fields, use one fewer `.`",
651                 "..".to_owned(),
652                 Applicability::MachineApplicable
653             )
654             .emit();
655     }
656
657     fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
658         // Check if a colon exists one ahead. This means we're parsing a fieldname.
659         let hi;
660         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
661             // Parsing a pattern of the form "fieldname: pat"
662             let fieldname = self.parse_field_name()?;
663             self.bump();
664             let pat = self.parse_pat_with_or(None)?;
665             hi = pat.span;
666             (pat, fieldname, false)
667         } else {
668             // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
669             let is_box = self.eat_keyword(kw::Box);
670             let boxed_span = self.token.span;
671             let is_ref = self.eat_keyword(kw::Ref);
672             let is_mut = self.eat_keyword(kw::Mut);
673             let fieldname = self.parse_ident()?;
674             hi = self.prev_span;
675
676             let bind_type = match (is_ref, is_mut) {
677                 (true, true) => BindingMode::ByRef(Mutability::Mutable),
678                 (true, false) => BindingMode::ByRef(Mutability::Immutable),
679                 (false, true) => BindingMode::ByValue(Mutability::Mutable),
680                 (false, false) => BindingMode::ByValue(Mutability::Immutable),
681             };
682
683             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
684             let subpat = if is_box {
685                 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
686             } else {
687                 fieldpat
688             };
689             (subpat, fieldname, true)
690         };
691
692         Ok(FieldPat {
693             ident: fieldname,
694             pat: subpat,
695             is_shorthand,
696             attrs: attrs.into(),
697             id: ast::DUMMY_NODE_ID,
698             span: lo.to(hi),
699         })
700     }
701
702     pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
703         self.mk_pat(span, PatKind::Ident(bm, ident, None))
704     }
705
706     fn mk_pat(&self, span: Span, node: PatKind) -> P<Pat> {
707         P(Pat { node, span, id: ast::DUMMY_NODE_ID })
708     }
709 }