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