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