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