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