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