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