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