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