]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/pat.rs
update comment to explain the importance of this check more clearly
[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 syntax::ast::{self, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac};
4 use syntax::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind};
5 use syntax::mut_visit::{noop_visit_pat, noop_visit_mac, MutVisitor};
6 use syntax::ptr::P;
7 use syntax::print::pprust;
8 use syntax::ThinVec;
9 use syntax::token;
10 use syntax::source_map::{respan, Span, Spanned};
11 use syntax_pos::symbol::{kw, sym};
12 use errors::{PResult, Applicability, DiagnosticBuilder};
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         let mutbl = self.parse_mutability();
463
464         if let token::Lifetime(name) = self.token.kind {
465             let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
466             err.span_label(self.token.span, "unexpected lifetime");
467             return Err(err);
468         }
469
470         let subpat = self.parse_pat_with_range_pat(false, expected)?;
471         Ok(PatKind::Ref(subpat, mutbl))
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) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
477
478         // Here, `(pat,)` is a tuple pattern.
479         // For backward compatibility, `(..)` is a tuple pattern as well.
480         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
481             PatKind::Paren(fields.into_iter().nth(0).unwrap())
482         } else {
483             PatKind::Tuple(fields)
484         })
485     }
486
487     /// Parse a mutable binding with the `mut` token already eaten.
488     fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
489         let mut_span = self.prev_span;
490
491         if self.eat_keyword(kw::Ref) {
492             return self.recover_mut_ref_ident(mut_span)
493         }
494
495         self.recover_additional_muts();
496
497         // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
498         if let token::Interpolated(ref nt) = self.token.kind {
499              if let token::NtPat(_) = **nt {
500                  self.expected_ident_found().emit();
501              }
502         }
503
504         // Parse the pattern we hope to be an identifier.
505         let mut pat = self.parse_pat(Some("identifier"))?;
506
507         // Add `mut` to any binding in the parsed pattern.
508         let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
509
510         // Unwrap; If we don't have `mut $ident`, error.
511         let pat = pat.into_inner();
512         match &pat.kind {
513             PatKind::Ident(..) => {}
514             _ => self.ban_mut_general_pat(mut_span, &pat, changed_any_binding),
515         }
516
517         Ok(pat.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::Mutable))
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(ref mut m @ Mutability::Immutable), ..)
547                     = pat.kind
548                 {
549                     *m = Mutability::Mutable;
550                     self.0 = true;
551                 }
552                 noop_visit_pat(pat, self);
553             }
554         }
555
556         let mut add_mut = AddMut(false);
557         add_mut.visit_pat(pat);
558         add_mut.0
559     }
560
561     /// Error on `mut $pat` where `$pat` is not an ident.
562     fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
563         let span = lo.to(pat.span);
564         let fix = pprust::pat_to_string(&pat);
565         let (problem, suggestion) = if changed_any_binding {
566             ("`mut` must be attached to each individual binding", "add `mut` to each binding")
567         } else {
568             ("`mut` must be followed by a named binding", "remove the `mut` prefix")
569         };
570         self.struct_span_err(span, problem)
571             .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
572             .note("`mut` may be followed by `variable` and `variable @ pattern`")
573             .emit()
574     }
575
576     /// Eat any extraneous `mut`s and error + recover if we ate any.
577     fn recover_additional_muts(&mut self) {
578         let lo = self.token.span;
579         while self.eat_keyword(kw::Mut) {}
580         if lo == self.token.span {
581             return;
582         }
583
584         let span = lo.to(self.prev_span);
585         self.struct_span_err(span, "`mut` on a binding may not be repeated")
586             .span_suggestion(
587                 span,
588                 "remove the additional `mut`s",
589                 String::new(),
590                 Applicability::MachineApplicable,
591             )
592             .emit();
593     }
594
595     /// Parse macro invocation
596     fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
597         self.bump();
598         let args = self.parse_mac_args()?;
599         let mac = Mac {
600             path,
601             args,
602             prior_type_ascription: self.last_type_ascription,
603         };
604         Ok(PatKind::Mac(mac))
605     }
606
607     fn excluded_range_end(&self, span: Span) -> RangeEnd {
608         self.sess.gated_spans.gate(sym::exclusive_range_pattern, span);
609         RangeEnd::Excluded
610     }
611
612     /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
613     /// The `$path` has already been parsed and the next token is the `$form`.
614     fn parse_pat_range_starting_with_path(
615         &mut self,
616         lo: Span,
617         qself: Option<QSelf>,
618         path: Path
619     ) -> PResult<'a, PatKind> {
620         let (end_kind, form) = match self.token.kind {
621             token::DotDot => (self.excluded_range_end(self.token.span), ".."),
622             token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
623             token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
624             _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
625         };
626         let op_span = self.token.span;
627         // Parse range
628         let span = lo.to(self.prev_span);
629         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
630         self.bump();
631         let end = self.parse_pat_range_end_opt(&begin, form)?;
632         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
633     }
634
635     /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
636     /// The `$path` has already been parsed and the next token is the `$form`.
637     fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
638         let op_span = self.token.span;
639         let (end_kind, form) = if self.eat(&token::DotDotDot) {
640             (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
641         } else if self.eat(&token::DotDotEq) {
642             (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
643         } else if self.eat(&token::DotDot) {
644             (self.excluded_range_end(op_span), "..")
645         } else {
646             panic!("impossible case: we already matched on a range-operator token")
647         };
648         let end = self.parse_pat_range_end_opt(&begin, form)?;
649         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
650     }
651
652     fn fatal_unexpected_non_pat(
653         &mut self,
654         mut err: DiagnosticBuilder<'a>,
655         expected: Expected,
656     ) -> PResult<'a, P<Pat>> {
657         err.cancel();
658
659         let expected = expected.unwrap_or("pattern");
660         let msg = format!("expected {}, found {}", expected, self.this_token_descr());
661
662         let mut err = self.fatal(&msg);
663         err.span_label(self.token.span, format!("expected {}", expected));
664
665         let sp = self.sess.source_map().start_point(self.token.span);
666         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
667             self.sess.expr_parentheses_needed(&mut err, *sp, None);
668         }
669
670         Err(err)
671     }
672
673     /// Is the current token suitable as the start of a range patterns end?
674     fn is_pat_range_end_start(&self) -> bool {
675         self.token.is_path_start() // e.g. `MY_CONST`;
676             || self.token == token::Dot // e.g. `.5` for recovery;
677             || self.token.can_begin_literal_or_bool() // e.g. `42`.
678             || self.token.is_whole_expr()
679     }
680
681     /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
682     fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
683         let lo = self.prev_span;
684         let end = self.parse_pat_range_end()?;
685         let range_span = lo.to(end.span);
686         let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
687
688         self.diagnostic()
689             .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
690             .span_suggestion(
691                 range_span,
692                 "try using the minimum value for the type",
693                 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
694                 Applicability::HasPlaceholders,
695             )
696             .emit();
697
698         Ok(PatKind::Range(begin, end, respan(lo, re)))
699     }
700
701     /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern  or recover
702     /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
703     fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
704         if self.is_pat_range_end_start() {
705             // Parsing e.g. `X..=Y`.
706             self.parse_pat_range_end()
707         } else {
708             // Parsing e.g. `X..`.
709             let range_span = begin.span.to(self.prev_span);
710
711             self.diagnostic()
712                 .struct_span_err(
713                     range_span,
714                     &format!("`X{}` range patterns are not supported", form),
715                 )
716                 .span_suggestion(
717                     range_span,
718                     "try using the maximum value for the type",
719                     format!("{}{}MAX", pprust::expr_to_string(&begin), form),
720                     Applicability::HasPlaceholders,
721                 )
722                 .emit();
723
724             Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
725         }
726     }
727
728     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
729         if self.token.is_path_start() {
730             let lo = self.token.span;
731             let (qself, path) = if self.eat_lt() {
732                 // Parse a qualified path
733                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
734                 (Some(qself), path)
735             } else {
736                 // Parse an unqualified path
737                 (None, self.parse_path(PathStyle::Expr)?)
738             };
739             let hi = self.prev_span;
740             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
741         } else {
742             self.parse_literal_maybe_minus()
743         }
744     }
745
746     /// Is this the start of a pattern beginning with a path?
747     fn is_start_of_pat_with_path(&mut self) -> bool {
748         self.check_path()
749         // Just for recovery (see `can_be_ident`).
750         || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
751     }
752
753     /// Would `parse_pat_ident` be appropriate here?
754     fn can_be_ident_pat(&mut self) -> bool {
755         self.check_ident()
756         && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
757         && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
758         // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
759         && !self.token.is_keyword(kw::In)
760         && self.look_ahead(1, |t| match t.kind { // Try to do something more complex?
761             token::OpenDelim(token::Paren) // A tuple struct pattern.
762             | token::OpenDelim(token::Brace) // A struct pattern.
763             | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
764             | token::ModSep // A tuple / struct variant pattern.
765             | token::Not => false, // A macro expanding to a pattern.
766             _ => true,
767         })
768     }
769
770     /// Parses `ident` or `ident @ pat`.
771     /// Used by the copy foo and ref foo patterns to give a good
772     /// error message when parsing mistakes like `ref foo(a, b)`.
773     fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
774         let ident = self.parse_ident()?;
775         let sub = if self.eat(&token::At) {
776             Some(self.parse_pat(Some("binding pattern"))?)
777         } else {
778             None
779         };
780
781         // Just to be friendly, if they write something like `ref Some(i)`,
782         // we end up here with `(` as the current token.
783         // This shortly leads to a parse error. Note that if there is no explicit
784         // binding mode then we do not end up here, because the lookahead
785         // will direct us over to `parse_enum_variant()`.
786         if self.token == token::OpenDelim(token::Paren) {
787             return Err(self.span_fatal(
788                 self.prev_span,
789                 "expected identifier, found enum pattern",
790             ))
791         }
792
793         Ok(PatKind::Ident(binding_mode, ident, sub))
794     }
795
796     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
797     fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
798         if qself.is_some() {
799             let msg = "unexpected `{` after qualified path";
800             let mut err = self.fatal(msg);
801             err.span_label(self.token.span, msg);
802             return Err(err);
803         }
804
805         self.bump();
806         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
807             e.emit();
808             self.recover_stmt();
809             (vec![], true)
810         });
811         self.bump();
812         Ok(PatKind::Struct(path, fields, etc))
813     }
814
815     /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
816     fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
817         if qself.is_some() {
818             let msg = "unexpected `(` after qualified path";
819             let mut err = self.fatal(msg);
820             err.span_label(self.token.span, msg);
821             return Err(err);
822         }
823         let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
824         Ok(PatKind::TupleStruct(path, fields))
825     }
826
827     /// Parses the fields of a struct-like pattern.
828     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
829         let mut fields = Vec::new();
830         let mut etc = false;
831         let mut ate_comma = true;
832         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
833         let mut etc_span = None;
834
835         while self.token != token::CloseDelim(token::Brace) {
836             let attrs = match self.parse_outer_attributes() {
837                 Ok(attrs) => attrs,
838                 Err(err) => {
839                     if let Some(mut delayed) = delayed_err {
840                         delayed.emit();
841                     }
842                     return Err(err);
843                 },
844             };
845             let lo = self.token.span;
846
847             // check that a comma comes after every field
848             if !ate_comma {
849                 let err = self.struct_span_err(self.prev_span, "expected `,`");
850                 if let Some(mut delayed) = delayed_err {
851                     delayed.emit();
852                 }
853                 return Err(err);
854             }
855             ate_comma = false;
856
857             if self.check(&token::DotDot) || self.token == token::DotDotDot {
858                 etc = true;
859                 let mut etc_sp = self.token.span;
860
861                 self.recover_one_fewer_dotdot();
862                 self.bump();  // `..` || `...`
863
864                 if self.token == token::CloseDelim(token::Brace) {
865                     etc_span = Some(etc_sp);
866                     break;
867                 }
868                 let token_str = self.this_token_descr();
869                 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
870
871                 err.span_label(self.token.span, "expected `}`");
872                 let mut comma_sp = None;
873                 if self.token == token::Comma { // Issue #49257
874                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
875                     etc_sp = etc_sp.to(nw_span);
876                     err.span_label(etc_sp,
877                                    "`..` must be at the end and cannot have a trailing comma");
878                     comma_sp = Some(self.token.span);
879                     self.bump();
880                     ate_comma = true;
881                 }
882
883                 etc_span = Some(etc_sp.until(self.token.span));
884                 if self.token == token::CloseDelim(token::Brace) {
885                     // If the struct looks otherwise well formed, recover and continue.
886                     if let Some(sp) = comma_sp {
887                         err.span_suggestion_short(
888                             sp,
889                             "remove this comma",
890                             String::new(),
891                             Applicability::MachineApplicable,
892                         );
893                     }
894                     err.emit();
895                     break;
896                 } else if self.token.is_ident() && ate_comma {
897                     // Accept fields coming after `..,`.
898                     // This way we avoid "pattern missing fields" errors afterwards.
899                     // We delay this error until the end in order to have a span for a
900                     // suggested fix.
901                     if let Some(mut delayed_err) = delayed_err {
902                         delayed_err.emit();
903                         return Err(err);
904                     } else {
905                         delayed_err = Some(err);
906                     }
907                 } else {
908                     if let Some(mut err) = delayed_err {
909                         err.emit();
910                     }
911                     return Err(err);
912                 }
913             }
914
915             fields.push(match self.parse_pat_field(lo, attrs) {
916                 Ok(field) => field,
917                 Err(err) => {
918                     if let Some(mut delayed_err) = delayed_err {
919                         delayed_err.emit();
920                     }
921                     return Err(err);
922                 }
923             });
924             ate_comma = self.eat(&token::Comma);
925         }
926
927         if let Some(mut err) = delayed_err {
928             if let Some(etc_span) = etc_span {
929                 err.multipart_suggestion(
930                     "move the `..` to the end of the field list",
931                     vec![
932                         (etc_span, String::new()),
933                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
934                     ],
935                     Applicability::MachineApplicable,
936                 );
937             }
938             err.emit();
939         }
940         return Ok((fields, etc));
941     }
942
943     /// Recover on `...` as if it were `..` to avoid further errors.
944     /// See issue #46718.
945     fn recover_one_fewer_dotdot(&self) {
946         if self.token != token::DotDotDot {
947             return;
948         }
949
950         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
951             .span_suggestion(
952                 self.token.span,
953                 "to omit remaining fields, use one fewer `.`",
954                 "..".to_owned(),
955                 Applicability::MachineApplicable
956             )
957             .emit();
958     }
959
960     fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
961         // Check if a colon exists one ahead. This means we're parsing a fieldname.
962         let hi;
963         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
964             // Parsing a pattern of the form `fieldname: pat`.
965             let fieldname = self.parse_field_name()?;
966             self.bump();
967             let pat = self.parse_pat_with_or_inner()?;
968             hi = pat.span;
969             (pat, fieldname, false)
970         } else {
971             // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
972             let is_box = self.eat_keyword(kw::Box);
973             let boxed_span = self.token.span;
974             let is_ref = self.eat_keyword(kw::Ref);
975             let is_mut = self.eat_keyword(kw::Mut);
976             let fieldname = self.parse_ident()?;
977             hi = self.prev_span;
978
979             let bind_type = match (is_ref, is_mut) {
980                 (true, true) => BindingMode::ByRef(Mutability::Mutable),
981                 (true, false) => BindingMode::ByRef(Mutability::Immutable),
982                 (false, true) => BindingMode::ByValue(Mutability::Mutable),
983                 (false, false) => BindingMode::ByValue(Mutability::Immutable),
984             };
985
986             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
987             let subpat = if is_box {
988                 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
989             } else {
990                 fieldpat
991             };
992             (subpat, fieldname, true)
993         };
994
995         Ok(FieldPat {
996             ident: fieldname,
997             pat: subpat,
998             is_shorthand,
999             attrs: attrs.into(),
1000             id: ast::DUMMY_NODE_ID,
1001             span: lo.to(hi),
1002             is_placeholder: false,
1003         })
1004     }
1005
1006     pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1007         self.mk_pat(span, PatKind::Ident(bm, ident, None))
1008     }
1009
1010     fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1011         P(Pat { kind, span, id: ast::DUMMY_NODE_ID })
1012     }
1013 }