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