]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/pat.rs
117b92dc9a5746812fc000c943e4830fb6199223
[rust.git] / src / librustc_parse / parser / pat.rs
1 use super::{Parser, PathStyle};
2 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
3 use rustc_errors::{PResult, Applicability, DiagnosticBuilder};
4 use syntax::ast::{self, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac};
5 use syntax::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind};
6 use syntax::mut_visit::{noop_visit_pat, noop_visit_mac, MutVisitor};
7 use syntax::ptr::P;
8 use syntax::print::pprust;
9 use syntax::ThinVec;
10 use syntax::token;
11 use syntax_pos::source_map::{respan, Span, Spanned};
12 use syntax_pos::symbol::{kw, sym};
13
14 type Expected = Option<&'static str>;
15
16 /// `Expected` for function and lambda parameter patterns.
17 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
18
19 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
20
21 /// Whether or not an or-pattern should be gated when occurring in the current context.
22 #[derive(PartialEq)]
23 pub(super) enum GateOr { Yes, No }
24
25 /// Whether or not to recover a `,` when parsing or-patterns.
26 #[derive(PartialEq, Copy, Clone)]
27 enum RecoverComma { Yes, No }
28
29 impl<'a> Parser<'a> {
30     /// Parses a pattern.
31     ///
32     /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
33     /// at the top level. Used when parsing the parameters of lambda expressions,
34     /// functions, function pointers, and `pat` macro fragments.
35     pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
36         self.parse_pat_with_range_pat(true, expected)
37     }
38
39     /// Entry point to the main pattern parser.
40     /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
41     pub(super) fn parse_top_pat(&mut self, gate_or: GateOr) -> PResult<'a, P<Pat>> {
42         // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
43         let gated_leading_vert = self.eat_or_separator(None) && gate_or == GateOr::Yes;
44         let leading_vert_span = self.prev_span;
45
46         // Parse the possibly-or-pattern.
47         let pat = self.parse_pat_with_or(None, gate_or, RecoverComma::Yes)?;
48
49         // If we parsed a leading `|` which should be gated,
50         // and no other gated or-pattern has been parsed thus far,
51         // then we should really gate the leading `|`.
52         // This complicated procedure is done purely for diagnostics UX.
53         if gated_leading_vert && self.sess.gated_spans.is_ungated(sym::or_patterns) {
54             self.sess.gated_spans.gate(sym::or_patterns, leading_vert_span);
55         }
56
57         Ok(pat)
58     }
59
60     /// Parse the pattern for a function or function pointer parameter.
61     /// Special recovery is provided for or-patterns and leading `|`.
62     pub(super) fn parse_fn_param_pat(&mut self) -> PResult<'a, P<Pat>> {
63         self.recover_leading_vert(None, "not allowed in a parameter pattern");
64         let pat = self.parse_pat_with_or(PARAM_EXPECTED, GateOr::No, RecoverComma::No)?;
65
66         if let PatKind::Or(..) = &pat.kind {
67             self.ban_illegal_fn_param_or_pat(&pat);
68         }
69
70         Ok(pat)
71     }
72
73     /// Ban `A | B` immediately in a parameter pattern and suggest wrapping in parens.
74     fn ban_illegal_fn_param_or_pat(&self, pat: &Pat) {
75         let msg = "wrap the pattern in parenthesis";
76         let fix = format!("({})", pprust::pat_to_string(pat));
77         self.struct_span_err(pat.span, "an or-pattern parameter must be wrapped in parenthesis")
78             .span_suggestion(pat.span, msg, fix, Applicability::MachineApplicable)
79             .emit();
80     }
81
82     /// Parses a pattern, that may be a or-pattern (e.g. `Foo | Bar` in `Some(Foo | Bar)`).
83     /// Corresponds to `pat<allow_top_alt>` in RFC 2535.
84     fn parse_pat_with_or(
85         &mut self,
86         expected: Expected,
87         gate_or: GateOr,
88         rc: RecoverComma,
89     ) -> PResult<'a, P<Pat>> {
90         // Parse the first pattern (`p_0`).
91         let first_pat = self.parse_pat(expected)?;
92         self.maybe_recover_unexpected_comma(first_pat.span, rc)?;
93
94         // If the next token is not a `|`,
95         // this is not an or-pattern and we should exit here.
96         if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
97             return Ok(first_pat)
98         }
99
100         // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
101         let lo = first_pat.span;
102         let mut pats = vec![first_pat];
103         while self.eat_or_separator(Some(lo)) {
104             let pat = self.parse_pat(expected).map_err(|mut err| {
105                 err.span_label(lo, WHILE_PARSING_OR_MSG);
106                 err
107             })?;
108             self.maybe_recover_unexpected_comma(pat.span, rc)?;
109             pats.push(pat);
110         }
111         let or_pattern_span = lo.to(self.prev_span);
112
113         // Feature gate the or-pattern if instructed:
114         if gate_or == GateOr::Yes {
115             self.sess.gated_spans.gate(sym::or_patterns, or_pattern_span);
116         }
117
118         Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats)))
119     }
120
121     /// Eat the or-pattern `|` separator.
122     /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
123     fn eat_or_separator(&mut self, lo: Option<Span>) -> bool {
124         if self.recover_trailing_vert(lo) {
125             return false;
126         }
127
128         match self.token.kind {
129             token::OrOr => {
130                 // Found `||`; Recover and pretend we parsed `|`.
131                 self.ban_unexpected_or_or(lo);
132                 self.bump();
133                 true
134             }
135             _ => self.eat(&token::BinOp(token::Or)),
136         }
137     }
138
139     /// Recover if `|` or `||` is the current token and we have one of the
140     /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
141     ///
142     /// These tokens all indicate that we reached the end of the or-pattern
143     /// list and can now reliably say that the `|` was an illegal trailing vert.
144     /// Note that there are more tokens such as `@` for which we know that the `|`
145     /// is an illegal parse. However, the user's intent is less clear in that case.
146     fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
147         let is_end_ahead = self.look_ahead(1, |token| match &token.kind {
148             token::FatArrow // e.g. `a | => 0,`.
149             | token::Ident(kw::If, false) // e.g. `a | if expr`.
150             | token::Eq // e.g. `let a | = 0`.
151             | token::Semi // e.g. `let a |;`.
152             | token::Colon // e.g. `let a | :`.
153             | token::Comma // e.g. `let (a |,)`.
154             | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
155             | token::CloseDelim(token::Paren) // e.g. `let (a | )`.
156             | token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`.
157             _ => false,
158         });
159         match (is_end_ahead, &self.token.kind) {
160             (true, token::BinOp(token::Or)) | (true, token::OrOr) => {
161                 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
162                 self.bump();
163                 true
164             }
165             _ => false,
166         }
167     }
168
169     /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
170     fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
171         let mut err = self.struct_span_err(self.token.span, "unexpected token `||` after pattern");
172         err.span_suggestion(
173             self.token.span,
174             "use a single `|` to separate multiple alternative patterns",
175             "|".to_owned(),
176             Applicability::MachineApplicable
177         );
178         if let Some(lo) = lo {
179             err.span_label(lo, WHILE_PARSING_OR_MSG);
180         }
181         err.emit();
182     }
183
184     /// Some special error handling for the "top-level" patterns in a match arm,
185     /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
186     fn maybe_recover_unexpected_comma(&mut self, lo: Span, rc: RecoverComma) -> PResult<'a, ()> {
187         if rc == RecoverComma::No || self.token != token::Comma {
188             return Ok(());
189         }
190
191         // An unexpected comma after a top-level pattern is a clue that the
192         // user (perhaps more accustomed to some other language) forgot the
193         // parentheses in what should have been a tuple pattern; return a
194         // suggestion-enhanced error here rather than choking on the comma later.
195         let comma_span = self.token.span;
196         self.bump();
197         if let Err(mut err) = self.skip_pat_list() {
198             // We didn't expect this to work anyway; we just wanted to advance to the
199             // end of the comma-sequence so we know the span to suggest parenthesizing.
200             err.cancel();
201         }
202         let seq_span = lo.to(self.prev_span);
203         let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
204         if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
205             err.span_suggestion(
206                 seq_span,
207                 "try adding parentheses to match on a tuple..",
208                 format!("({})", seq_snippet),
209                 Applicability::MachineApplicable
210             )
211             .span_suggestion(
212                 seq_span,
213                 "..or a vertical bar to match on multiple alternatives",
214                 format!("{}", seq_snippet.replace(",", " |")),
215                 Applicability::MachineApplicable
216             );
217         }
218         Err(err)
219     }
220
221     /// Parse and throw away a parentesized comma separated
222     /// sequence of patterns until `)` is reached.
223     fn skip_pat_list(&mut self) -> PResult<'a, ()> {
224         while !self.check(&token::CloseDelim(token::Paren)) {
225             self.parse_pat(None)?;
226             if !self.eat(&token::Comma) {
227                 return Ok(())
228             }
229         }
230         Ok(())
231     }
232
233     /// Recursive possibly-or-pattern parser with recovery for an erroneous leading `|`.
234     /// See `parse_pat_with_or` for details on parsing or-patterns.
235     fn parse_pat_with_or_inner(&mut self) -> PResult<'a, P<Pat>> {
236         self.recover_leading_vert(None, "only allowed in a top-level pattern");
237         self.parse_pat_with_or(None, GateOr::Yes, RecoverComma::No)
238     }
239
240     /// Recover if `|` or `||` is here.
241     /// The user is thinking that a leading `|` is allowed in this position.
242     fn recover_leading_vert(&mut self, lo: Option<Span>, ctx: &str) {
243         if let token::BinOp(token::Or) | token::OrOr = self.token.kind {
244             self.ban_illegal_vert(lo, "leading", ctx);
245             self.bump();
246         }
247     }
248
249     /// A `|` or possibly `||` token shouldn't be here. Ban it.
250     fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
251         let span = self.token.span;
252         let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
253         err.span_suggestion(
254             span,
255             &format!("remove the `{}`", pprust::token_to_string(&self.token)),
256             String::new(),
257             Applicability::MachineApplicable,
258         );
259         if let Some(lo) = lo {
260             err.span_label(lo, WHILE_PARSING_OR_MSG);
261         }
262         if let token::OrOr = self.token.kind {
263             err.note("alternatives in or-patterns are separated with `|`, not `||`");
264         }
265         err.emit();
266     }
267
268     /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
269     /// allowed).
270     fn parse_pat_with_range_pat(
271         &mut self,
272         allow_range_pat: bool,
273         expected: Expected,
274     ) -> PResult<'a, P<Pat>> {
275         maybe_recover_from_interpolated_ty_qpath!(self, true);
276         maybe_whole!(self, NtPat, |x| x);
277
278         let lo = self.token.span;
279         let pat = match self.token.kind {
280             token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
281             token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
282             token::OpenDelim(token::Bracket) => {
283                 // Parse `[pat, pat,...]` as a slice pattern.
284                 let (pats, _) = self.parse_delim_comma_seq(
285                     token::Bracket,
286                     |p| p.parse_pat_with_or_inner(),
287                 )?;
288                 PatKind::Slice(pats)
289             }
290             token::DotDot => {
291                 self.bump();
292                 if self.is_pat_range_end_start() {
293                     // Parse `..42` for recovery.
294                     self.parse_pat_range_to(RangeEnd::Excluded, "..")?
295                 } else {
296                     // A rest pattern `..`.
297                     PatKind::Rest
298                 }
299             }
300             token::DotDotEq => {
301                 // Parse `..=42` for recovery.
302                 self.bump();
303                 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
304             }
305             token::DotDotDot => {
306                 // Parse `...42` for recovery.
307                 self.bump();
308                 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
309             }
310             // At this point, token != `&`, `&&`, `(`, `[`, `..`, `..=`, or `...`.
311             _ => if self.eat_keyword(kw::Underscore) {
312                 // Parse _
313                 PatKind::Wild
314             } else if self.eat_keyword(kw::Mut) {
315                 self.parse_pat_ident_mut()?
316             } else if self.eat_keyword(kw::Ref) {
317                 // Parse ref ident @ pat / ref mut ident @ pat
318                 let mutbl = self.parse_mutability();
319                 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
320             } else if self.eat_keyword(kw::Box) {
321                 // Parse `box pat`
322                 let pat = self.parse_pat_with_range_pat(false, None)?;
323                 self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_span));
324                 PatKind::Box(pat)
325             } else if self.can_be_ident_pat() {
326                 // Parse `ident @ pat`
327                 // This can give false positives and parse nullary enums,
328                 // they are dealt with later in resolve.
329                 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
330             } else if self.is_start_of_pat_with_path() {
331                 // Parse pattern starting with a path
332                 let (qself, path) = if self.eat_lt() {
333                     // Parse a qualified path
334                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
335                     (Some(qself), path)
336                 } else {
337                     // Parse an unqualified path
338                     (None, self.parse_path(PathStyle::Expr)?)
339                 };
340                 match self.token.kind {
341                     token::Not if qself.is_none() => self.parse_pat_mac_invoc(path)?,
342                     token::DotDotDot | token::DotDotEq | token::DotDot => {
343                         self.parse_pat_range_starting_with_path(lo, qself, path)?
344                     }
345                     token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
346                     token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
347                     _ => PatKind::Path(qself, path),
348                 }
349             } else {
350                 // Try to parse everything else as literal with optional minus
351                 match self.parse_literal_maybe_minus() {
352                     Ok(begin)
353                         if self.check(&token::DotDot)
354                             || self.check(&token::DotDotEq)
355                             || self.check(&token::DotDotDot) =>
356                     {
357                         self.parse_pat_range_starting_with_lit(begin)?
358                     }
359                     Ok(begin) => PatKind::Lit(begin),
360                     Err(err) => return self.fatal_unexpected_non_pat(err, expected),
361                 }
362             }
363         };
364
365         let pat = self.mk_pat(lo.to(self.prev_span), pat);
366         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
367         let pat = self.recover_intersection_pat(pat)?;
368
369         if !allow_range_pat {
370             self.ban_pat_range_if_ambiguous(&pat)?
371         }
372
373         Ok(pat)
374     }
375
376     /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
377     ///
378     /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
379     /// should already have been parsed by now  at this point,
380     /// if the next token is `@` then we can try to parse the more general form.
381     ///
382     /// Consult `parse_pat_ident` for the `binding` grammar.
383     ///
384     /// The notion of intersection patterns are found in
385     /// e.g. [F#][and] where they are called AND-patterns.
386     ///
387     /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
388     fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
389         if self.token.kind != token::At {
390             // Next token is not `@` so it's not going to be an intersection pattern.
391             return Ok(lhs);
392         }
393
394         // At this point we attempt to parse `@ $pat_rhs` and emit an error.
395         self.bump(); // `@`
396         let mut rhs = self.parse_pat(None)?;
397         let sp = lhs.span.to(rhs.span);
398
399         if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
400             // The user inverted the order, so help them fix that.
401             let mut applicability = Applicability::MachineApplicable;
402             lhs.walk(&mut |p| match p.kind {
403                 // `check_match` is unhappy if the subpattern has a binding anywhere.
404                 PatKind::Ident(..) => {
405                     applicability = Applicability::MaybeIncorrect;
406                     false // Short-circuit.
407                 },
408                 _ => true,
409             });
410
411             let lhs_span = lhs.span;
412             // Move the LHS into the RHS as a subpattern.
413             // The RHS is now the full pattern.
414             *sub = Some(lhs);
415
416             self.struct_span_err(sp, "pattern on wrong side of `@`")
417                 .span_label(lhs_span, "pattern on the left, should be on the right")
418                 .span_label(rhs.span, "binding on the right, should be on the left")
419                 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
420                 .emit();
421         } else {
422             // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
423             rhs.kind = PatKind::Wild;
424             self.struct_span_err(sp, "left-hand side of `@` must be a binding")
425                 .span_label(lhs.span, "interpreted as a pattern, not a binding")
426                 .span_label(rhs.span, "also a pattern")
427                 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
428                 .emit();
429         }
430
431         rhs.span = sp;
432         Ok(rhs)
433     }
434
435     /// Ban a range pattern if it has an ambiguous interpretation.
436     fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
437         match pat.kind {
438             PatKind::Range(
439                 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
440             ) => return Ok(()),
441             PatKind::Range(..) => {}
442             _ => return Ok(()),
443         }
444
445         let mut err = self.struct_span_err(
446             pat.span,
447             "the range pattern here has ambiguous interpretation",
448         );
449         err.span_suggestion(
450             pat.span,
451             "add parentheses to clarify the precedence",
452             format!("({})", pprust::pat_to_string(&pat)),
453             // "ambiguous interpretation" implies that we have to be guessing
454             Applicability::MaybeIncorrect
455         );
456         Err(err)
457     }
458
459     /// Parse `&pat` / `&mut pat`.
460     fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
461         self.expect_and()?;
462         self.recover_lifetime_in_deref_pat();
463         let mutbl = self.parse_mutability();
464         let subpat = self.parse_pat_with_range_pat(false, expected)?;
465         Ok(PatKind::Ref(subpat, mutbl))
466     }
467
468     fn recover_lifetime_in_deref_pat(&mut self) {
469         if let token::Lifetime(name) = self.token.kind {
470             self.bump(); // `'a`
471
472             let span = self.prev_span;
473             self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
474                 .span_suggestion(
475                     span,
476                     "remove the lifetime",
477                     String::new(),
478                     Applicability::MachineApplicable,
479                 )
480                 .emit();
481         }
482     }
483
484     /// Parse a tuple or parenthesis pattern.
485     fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
486         let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
487
488         // Here, `(pat,)` is a tuple pattern.
489         // For backward compatibility, `(..)` is a tuple pattern as well.
490         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
491             PatKind::Paren(fields.into_iter().nth(0).unwrap())
492         } else {
493             PatKind::Tuple(fields)
494         })
495     }
496
497     /// Parse a mutable binding with the `mut` token already eaten.
498     fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
499         let mut_span = self.prev_span;
500
501         if self.eat_keyword(kw::Ref) {
502             return self.recover_mut_ref_ident(mut_span)
503         }
504
505         self.recover_additional_muts();
506
507         // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
508         if let token::Interpolated(ref nt) = self.token.kind {
509              if let token::NtPat(_) = **nt {
510                  self.expected_ident_found().emit();
511              }
512         }
513
514         // Parse the pattern we hope to be an identifier.
515         let mut pat = self.parse_pat(Some("identifier"))?;
516
517         // Add `mut` to any binding in the parsed pattern.
518         let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
519
520         // Unwrap; If we don't have `mut $ident`, error.
521         let pat = pat.into_inner();
522         match &pat.kind {
523             PatKind::Ident(..) => {}
524             _ => self.ban_mut_general_pat(mut_span, &pat, changed_any_binding),
525         }
526
527         Ok(pat.kind)
528     }
529
530     /// Recover on `mut ref? ident @ pat` and suggest
531     /// that the order of `mut` and `ref` is incorrect.
532     fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
533         let mutref_span = lo.to(self.prev_span);
534         self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
535             .span_suggestion(
536                 mutref_span,
537                 "try switching the order",
538                 "ref mut".into(),
539                 Applicability::MachineApplicable
540             )
541             .emit();
542
543         self.parse_pat_ident(BindingMode::ByRef(Mutability::Mutable))
544     }
545
546     /// Turn all by-value immutable bindings in a pattern into mutable bindings.
547     /// Returns `true` if any change was made.
548     fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
549         struct AddMut(bool);
550         impl MutVisitor for AddMut {
551             fn visit_mac(&mut self, mac: &mut Mac) {
552                 noop_visit_mac(mac, self);
553             }
554
555             fn visit_pat(&mut self, pat: &mut P<Pat>) {
556                 if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Immutable), ..)
557                     = pat.kind
558                 {
559                     *m = Mutability::Mutable;
560                     self.0 = true;
561                 }
562                 noop_visit_pat(pat, self);
563             }
564         }
565
566         let mut add_mut = AddMut(false);
567         add_mut.visit_pat(pat);
568         add_mut.0
569     }
570
571     /// Error on `mut $pat` where `$pat` is not an ident.
572     fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
573         let span = lo.to(pat.span);
574         let fix = pprust::pat_to_string(&pat);
575         let (problem, suggestion) = if changed_any_binding {
576             ("`mut` must be attached to each individual binding", "add `mut` to each binding")
577         } else {
578             ("`mut` must be followed by a named binding", "remove the `mut` prefix")
579         };
580         self.struct_span_err(span, problem)
581             .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
582             .note("`mut` may be followed by `variable` and `variable @ pattern`")
583             .emit()
584     }
585
586     /// Eat any extraneous `mut`s and error + recover if we ate any.
587     fn recover_additional_muts(&mut self) {
588         let lo = self.token.span;
589         while self.eat_keyword(kw::Mut) {}
590         if lo == self.token.span {
591             return;
592         }
593
594         let span = lo.to(self.prev_span);
595         self.struct_span_err(span, "`mut` on a binding may not be repeated")
596             .span_suggestion(
597                 span,
598                 "remove the additional `mut`s",
599                 String::new(),
600                 Applicability::MachineApplicable,
601             )
602             .emit();
603     }
604
605     /// Parse macro invocation
606     fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
607         self.bump();
608         let args = self.parse_mac_args()?;
609         let mac = Mac {
610             path,
611             args,
612             prior_type_ascription: self.last_type_ascription,
613         };
614         Ok(PatKind::Mac(mac))
615     }
616
617     fn excluded_range_end(&self, span: Span) -> RangeEnd {
618         self.sess.gated_spans.gate(sym::exclusive_range_pattern, span);
619         RangeEnd::Excluded
620     }
621
622     /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
623     /// The `$path` has already been parsed and the next token is the `$form`.
624     fn parse_pat_range_starting_with_path(
625         &mut self,
626         lo: Span,
627         qself: Option<QSelf>,
628         path: Path
629     ) -> PResult<'a, PatKind> {
630         let (end_kind, form) = match self.token.kind {
631             token::DotDot => (self.excluded_range_end(self.token.span), ".."),
632             token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
633             token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
634             _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
635         };
636         let op_span = self.token.span;
637         // Parse range
638         let span = lo.to(self.prev_span);
639         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
640         self.bump();
641         let end = self.parse_pat_range_end_opt(&begin, form)?;
642         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
643     }
644
645     /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
646     /// The `$path` has already been parsed and the next token is the `$form`.
647     fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
648         let op_span = self.token.span;
649         let (end_kind, form) = if self.eat(&token::DotDotDot) {
650             (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
651         } else if self.eat(&token::DotDotEq) {
652             (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
653         } else if self.eat(&token::DotDot) {
654             (self.excluded_range_end(op_span), "..")
655         } else {
656             panic!("impossible case: we already matched on a range-operator token")
657         };
658         let end = self.parse_pat_range_end_opt(&begin, form)?;
659         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
660     }
661
662     fn fatal_unexpected_non_pat(
663         &mut self,
664         mut err: DiagnosticBuilder<'a>,
665         expected: Expected,
666     ) -> PResult<'a, P<Pat>> {
667         err.cancel();
668
669         let expected = expected.unwrap_or("pattern");
670         let msg = format!("expected {}, found {}", expected, self.this_token_descr());
671
672         let mut err = self.fatal(&msg);
673         err.span_label(self.token.span, format!("expected {}", expected));
674
675         let sp = self.sess.source_map().start_point(self.token.span);
676         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
677             self.sess.expr_parentheses_needed(&mut err, *sp, None);
678         }
679
680         Err(err)
681     }
682
683     /// Is the current token suitable as the start of a range patterns end?
684     fn is_pat_range_end_start(&self) -> bool {
685         self.token.is_path_start() // e.g. `MY_CONST`;
686             || self.token == token::Dot // e.g. `.5` for recovery;
687             || self.token.can_begin_literal_or_bool() // e.g. `42`.
688             || self.token.is_whole_expr()
689     }
690
691     /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
692     fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
693         let lo = self.prev_span;
694         let end = self.parse_pat_range_end()?;
695         let range_span = lo.to(end.span);
696         let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
697
698         self.diagnostic()
699             .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
700             .span_suggestion(
701                 range_span,
702                 "try using the minimum value for the type",
703                 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
704                 Applicability::HasPlaceholders,
705             )
706             .emit();
707
708         Ok(PatKind::Range(begin, end, respan(lo, re)))
709     }
710
711     /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern  or recover
712     /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
713     fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
714         if self.is_pat_range_end_start() {
715             // Parsing e.g. `X..=Y`.
716             self.parse_pat_range_end()
717         } else {
718             // Parsing e.g. `X..`.
719             let range_span = begin.span.to(self.prev_span);
720
721             self.diagnostic()
722                 .struct_span_err(
723                     range_span,
724                     &format!("`X{}` range patterns are not supported", form),
725                 )
726                 .span_suggestion(
727                     range_span,
728                     "try using the maximum value for the type",
729                     format!("{}{}MAX", pprust::expr_to_string(&begin), form),
730                     Applicability::HasPlaceholders,
731                 )
732                 .emit();
733
734             Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
735         }
736     }
737
738     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
739         if self.token.is_path_start() {
740             let lo = self.token.span;
741             let (qself, path) = if self.eat_lt() {
742                 // Parse a qualified path
743                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
744                 (Some(qself), path)
745             } else {
746                 // Parse an unqualified path
747                 (None, self.parse_path(PathStyle::Expr)?)
748             };
749             let hi = self.prev_span;
750             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
751         } else {
752             self.parse_literal_maybe_minus()
753         }
754     }
755
756     /// Is this the start of a pattern beginning with a path?
757     fn is_start_of_pat_with_path(&mut self) -> bool {
758         self.check_path()
759         // Just for recovery (see `can_be_ident`).
760         || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
761     }
762
763     /// Would `parse_pat_ident` be appropriate here?
764     fn can_be_ident_pat(&mut self) -> bool {
765         self.check_ident()
766         && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
767         && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
768         // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
769         && !self.token.is_keyword(kw::In)
770         && self.look_ahead(1, |t| match t.kind { // Try to do something more complex?
771             token::OpenDelim(token::Paren) // A tuple struct pattern.
772             | token::OpenDelim(token::Brace) // A struct pattern.
773             | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
774             | token::ModSep // A tuple / struct variant pattern.
775             | token::Not => false, // A macro expanding to a pattern.
776             _ => true,
777         })
778     }
779
780     /// Parses `ident` or `ident @ pat`.
781     /// Used by the copy foo and ref foo patterns to give a good
782     /// error message when parsing mistakes like `ref foo(a, b)`.
783     fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
784         let ident = self.parse_ident()?;
785         let sub = if self.eat(&token::At) {
786             Some(self.parse_pat(Some("binding pattern"))?)
787         } else {
788             None
789         };
790
791         // Just to be friendly, if they write something like `ref Some(i)`,
792         // we end up here with `(` as the current token.
793         // This shortly leads to a parse error. Note that if there is no explicit
794         // binding mode then we do not end up here, because the lookahead
795         // will direct us over to `parse_enum_variant()`.
796         if self.token == token::OpenDelim(token::Paren) {
797             return Err(self.span_fatal(
798                 self.prev_span,
799                 "expected identifier, found enum pattern",
800             ))
801         }
802
803         Ok(PatKind::Ident(binding_mode, ident, sub))
804     }
805
806     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
807     fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
808         if qself.is_some() {
809             let msg = "unexpected `{` after qualified path";
810             let mut err = self.fatal(msg);
811             err.span_label(self.token.span, msg);
812             return Err(err);
813         }
814
815         self.bump();
816         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
817             e.emit();
818             self.recover_stmt();
819             (vec![], true)
820         });
821         self.bump();
822         Ok(PatKind::Struct(path, fields, etc))
823     }
824
825     /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
826     fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
827         if qself.is_some() {
828             let msg = "unexpected `(` after qualified path";
829             let mut err = self.fatal(msg);
830             err.span_label(self.token.span, msg);
831             return Err(err);
832         }
833         let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
834         Ok(PatKind::TupleStruct(path, fields))
835     }
836
837     /// Parses the fields of a struct-like pattern.
838     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
839         let mut fields = Vec::new();
840         let mut etc = false;
841         let mut ate_comma = true;
842         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
843         let mut etc_span = None;
844
845         while self.token != token::CloseDelim(token::Brace) {
846             let attrs = match self.parse_outer_attributes() {
847                 Ok(attrs) => attrs,
848                 Err(err) => {
849                     if let Some(mut delayed) = delayed_err {
850                         delayed.emit();
851                     }
852                     return Err(err);
853                 },
854             };
855             let lo = self.token.span;
856
857             // check that a comma comes after every field
858             if !ate_comma {
859                 let err = self.struct_span_err(self.prev_span, "expected `,`");
860                 if let Some(mut delayed) = delayed_err {
861                     delayed.emit();
862                 }
863                 return Err(err);
864             }
865             ate_comma = false;
866
867             if self.check(&token::DotDot) || self.token == token::DotDotDot {
868                 etc = true;
869                 let mut etc_sp = self.token.span;
870
871                 self.recover_one_fewer_dotdot();
872                 self.bump();  // `..` || `...`
873
874                 if self.token == token::CloseDelim(token::Brace) {
875                     etc_span = Some(etc_sp);
876                     break;
877                 }
878                 let token_str = self.this_token_descr();
879                 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
880
881                 err.span_label(self.token.span, "expected `}`");
882                 let mut comma_sp = None;
883                 if self.token == token::Comma { // Issue #49257
884                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
885                     etc_sp = etc_sp.to(nw_span);
886                     err.span_label(etc_sp,
887                                    "`..` must be at the end and cannot have a trailing comma");
888                     comma_sp = Some(self.token.span);
889                     self.bump();
890                     ate_comma = true;
891                 }
892
893                 etc_span = Some(etc_sp.until(self.token.span));
894                 if self.token == token::CloseDelim(token::Brace) {
895                     // If the struct looks otherwise well formed, recover and continue.
896                     if let Some(sp) = comma_sp {
897                         err.span_suggestion_short(
898                             sp,
899                             "remove this comma",
900                             String::new(),
901                             Applicability::MachineApplicable,
902                         );
903                     }
904                     err.emit();
905                     break;
906                 } else if self.token.is_ident() && ate_comma {
907                     // Accept fields coming after `..,`.
908                     // This way we avoid "pattern missing fields" errors afterwards.
909                     // We delay this error until the end in order to have a span for a
910                     // suggested fix.
911                     if let Some(mut delayed_err) = delayed_err {
912                         delayed_err.emit();
913                         return Err(err);
914                     } else {
915                         delayed_err = Some(err);
916                     }
917                 } else {
918                     if let Some(mut err) = delayed_err {
919                         err.emit();
920                     }
921                     return Err(err);
922                 }
923             }
924
925             fields.push(match self.parse_pat_field(lo, attrs) {
926                 Ok(field) => field,
927                 Err(err) => {
928                     if let Some(mut delayed_err) = delayed_err {
929                         delayed_err.emit();
930                     }
931                     return Err(err);
932                 }
933             });
934             ate_comma = self.eat(&token::Comma);
935         }
936
937         if let Some(mut err) = delayed_err {
938             if let Some(etc_span) = etc_span {
939                 err.multipart_suggestion(
940                     "move the `..` to the end of the field list",
941                     vec![
942                         (etc_span, String::new()),
943                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
944                     ],
945                     Applicability::MachineApplicable,
946                 );
947             }
948             err.emit();
949         }
950         return Ok((fields, etc));
951     }
952
953     /// Recover on `...` as if it were `..` to avoid further errors.
954     /// See issue #46718.
955     fn recover_one_fewer_dotdot(&self) {
956         if self.token != token::DotDotDot {
957             return;
958         }
959
960         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
961             .span_suggestion(
962                 self.token.span,
963                 "to omit remaining fields, use one fewer `.`",
964                 "..".to_owned(),
965                 Applicability::MachineApplicable
966             )
967             .emit();
968     }
969
970     fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
971         // Check if a colon exists one ahead. This means we're parsing a fieldname.
972         let hi;
973         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
974             // Parsing a pattern of the form `fieldname: pat`.
975             let fieldname = self.parse_field_name()?;
976             self.bump();
977             let pat = self.parse_pat_with_or_inner()?;
978             hi = pat.span;
979             (pat, fieldname, false)
980         } else {
981             // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
982             let is_box = self.eat_keyword(kw::Box);
983             let boxed_span = self.token.span;
984             let is_ref = self.eat_keyword(kw::Ref);
985             let is_mut = self.eat_keyword(kw::Mut);
986             let fieldname = self.parse_ident()?;
987             hi = self.prev_span;
988
989             let bind_type = match (is_ref, is_mut) {
990                 (true, true) => BindingMode::ByRef(Mutability::Mutable),
991                 (true, false) => BindingMode::ByRef(Mutability::Immutable),
992                 (false, true) => BindingMode::ByValue(Mutability::Mutable),
993                 (false, false) => BindingMode::ByValue(Mutability::Immutable),
994             };
995
996             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
997             let subpat = if is_box {
998                 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
999             } else {
1000                 fieldpat
1001             };
1002             (subpat, fieldname, true)
1003         };
1004
1005         Ok(FieldPat {
1006             ident: fieldname,
1007             pat: subpat,
1008             is_shorthand,
1009             attrs: attrs.into(),
1010             id: ast::DUMMY_NODE_ID,
1011             span: lo.to(hi),
1012             is_placeholder: false,
1013         })
1014     }
1015
1016     pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1017         self.mk_pat(span, PatKind::Ident(bm, ident, None))
1018     }
1019
1020     fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1021         P(Pat { kind, span, id: ast::DUMMY_NODE_ID })
1022     }
1023 }