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