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