]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/pat.rs
Auto merge of #77616 - jyn514:no-normalize, r=lcnr
[rust.git] / compiler / rustc_parse / src / parser / pat.rs
1 use super::{Parser, PathStyle};
2 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
3 use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor};
4 use rustc_ast::ptr::P;
5 use rustc_ast::token;
6 use rustc_ast::{self as ast, AttrVec, Attribute, FieldPat, MacCall, Pat, PatKind, RangeEnd};
7 use rustc_ast::{BindingMode, Expr, ExprKind, Mutability, Path, QSelf, RangeSyntax};
8 use rustc_ast_pretty::pprust;
9 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult};
10 use rustc_span::source_map::{respan, Span, Spanned};
11 use rustc_span::symbol::{kw, sym, Ident};
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_token.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_token.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| {
153             matches!(
154                 &token.uninterpolate().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) // e.g. `let A { f: a | }`.
164             )
165         });
166         match (is_end_ahead, &self.token.kind) {
167             (true, token::BinOp(token::Or) | 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_token.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 self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
301             self.recover_dotdotdot_rest_pat(lo)
302         } else if let Some(form) = self.parse_range_end() {
303             self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
304         } else if self.eat_keyword(kw::Underscore) {
305             // Parse _
306             PatKind::Wild
307         } else if self.eat_keyword(kw::Mut) {
308             self.parse_pat_ident_mut()?
309         } else if self.eat_keyword(kw::Ref) {
310             // Parse ref ident @ pat / ref mut ident @ pat
311             let mutbl = self.parse_mutability();
312             self.parse_pat_ident(BindingMode::ByRef(mutbl))?
313         } else if self.eat_keyword(kw::Box) {
314             // Parse `box pat`
315             let pat = self.parse_pat_with_range_pat(false, None)?;
316             self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_token.span));
317             PatKind::Box(pat)
318         } else if self.check_inline_const(0) {
319             // Parse `const pat`
320             let const_expr = self.parse_const_block(lo.to(self.token.span))?;
321
322             if let Some(re) = self.parse_range_end() {
323                 self.parse_pat_range_begin_with(const_expr, re)?
324             } else {
325                 PatKind::Lit(const_expr)
326             }
327         } else if self.can_be_ident_pat() {
328             // Parse `ident @ pat`
329             // This can give false positives and parse nullary enums,
330             // they are dealt with later in resolve.
331             self.parse_pat_ident(BindingMode::ByValue(Mutability::Not))?
332         } else if self.is_start_of_pat_with_path() {
333             // Parse pattern starting with a path
334             let (qself, path) = if self.eat_lt() {
335                 // Parse a qualified path
336                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
337                 (Some(qself), path)
338             } else {
339                 // Parse an unqualified path
340                 (None, self.parse_path(PathStyle::Expr)?)
341             };
342             let span = lo.to(self.prev_token.span);
343
344             if qself.is_none() && self.check(&token::Not) {
345                 self.parse_pat_mac_invoc(path)?
346             } else if let Some(form) = self.parse_range_end() {
347                 let begin = self.mk_expr(span, ExprKind::Path(qself, path), AttrVec::new());
348                 self.parse_pat_range_begin_with(begin, form)?
349             } else if self.check(&token::OpenDelim(token::Brace)) {
350                 self.parse_pat_struct(qself, path)?
351             } else if self.check(&token::OpenDelim(token::Paren)) {
352                 self.parse_pat_tuple_struct(qself, path)?
353             } else {
354                 PatKind::Path(qself, path)
355             }
356         } else {
357             // Try to parse everything else as literal with optional minus
358             match self.parse_literal_maybe_minus() {
359                 Ok(begin) => match self.parse_range_end() {
360                     Some(form) => self.parse_pat_range_begin_with(begin, form)?,
361                     None => PatKind::Lit(begin),
362                 },
363                 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
364             }
365         };
366
367         let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
368         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
369         let pat = self.recover_intersection_pat(pat)?;
370
371         if !allow_range_pat {
372             self.ban_pat_range_if_ambiguous(&pat)
373         }
374
375         Ok(pat)
376     }
377
378     /// Recover from a typoed `...` pattern that was encountered
379     /// Ref: Issue #70388
380     fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
381         // A typoed rest pattern `...`.
382         self.bump(); // `...`
383
384         // The user probably mistook `...` for a rest pattern `..`.
385         self.struct_span_err(lo, "unexpected `...`")
386             .span_label(lo, "not a valid pattern")
387             .span_suggestion_short(
388                 lo,
389                 "for a rest pattern, use `..` instead of `...`",
390                 "..".to_owned(),
391                 Applicability::MachineApplicable,
392             )
393             .emit();
394         PatKind::Rest
395     }
396
397     /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
398     ///
399     /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
400     /// should already have been parsed by now  at this point,
401     /// if the next token is `@` then we can try to parse the more general form.
402     ///
403     /// Consult `parse_pat_ident` for the `binding` grammar.
404     ///
405     /// The notion of intersection patterns are found in
406     /// e.g. [F#][and] where they are called AND-patterns.
407     ///
408     /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
409     fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
410         if self.token.kind != token::At {
411             // Next token is not `@` so it's not going to be an intersection pattern.
412             return Ok(lhs);
413         }
414
415         // At this point we attempt to parse `@ $pat_rhs` and emit an error.
416         self.bump(); // `@`
417         let mut rhs = self.parse_pat(None)?;
418         let sp = lhs.span.to(rhs.span);
419
420         if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind {
421             // The user inverted the order, so help them fix that.
422             let mut applicability = Applicability::MachineApplicable;
423             // FIXME(bindings_after_at): Remove this code when stabilizing the feature.
424             lhs.walk(&mut |p| match p.kind {
425                 // `check_match` is unhappy if the subpattern has a binding anywhere.
426                 PatKind::Ident(..) => {
427                     applicability = Applicability::MaybeIncorrect;
428                     false // Short-circuit.
429                 }
430                 _ => true,
431             });
432
433             let lhs_span = lhs.span;
434             // Move the LHS into the RHS as a subpattern.
435             // The RHS is now the full pattern.
436             *sub = Some(lhs);
437
438             self.struct_span_err(sp, "pattern on wrong side of `@`")
439                 .span_label(lhs_span, "pattern on the left, should be on the right")
440                 .span_label(rhs.span, "binding on the right, should be on the left")
441                 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
442                 .emit();
443         } else {
444             // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
445             rhs.kind = PatKind::Wild;
446             self.struct_span_err(sp, "left-hand side of `@` must be a binding")
447                 .span_label(lhs.span, "interpreted as a pattern, not a binding")
448                 .span_label(rhs.span, "also a pattern")
449                 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
450                 .emit();
451         }
452
453         rhs.span = sp;
454         Ok(rhs)
455     }
456
457     /// Ban a range pattern if it has an ambiguous interpretation.
458     fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
459         match pat.kind {
460             PatKind::Range(
461                 ..,
462                 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
463             ) => return,
464             PatKind::Range(..) => {}
465             _ => return,
466         }
467
468         self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
469             .span_suggestion(
470                 pat.span,
471                 "add parentheses to clarify the precedence",
472                 format!("({})", pprust::pat_to_string(&pat)),
473                 // "ambiguous interpretation" implies that we have to be guessing
474                 Applicability::MaybeIncorrect,
475             )
476             .emit();
477     }
478
479     /// Parse `&pat` / `&mut pat`.
480     fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
481         self.expect_and()?;
482         self.recover_lifetime_in_deref_pat();
483         let mutbl = self.parse_mutability();
484         let subpat = self.parse_pat_with_range_pat(false, expected)?;
485         Ok(PatKind::Ref(subpat, mutbl))
486     }
487
488     fn recover_lifetime_in_deref_pat(&mut self) {
489         if let token::Lifetime(name) = self.token.kind {
490             self.bump(); // `'a`
491
492             let span = self.prev_token.span;
493             self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
494                 .span_suggestion(
495                     span,
496                     "remove the lifetime",
497                     String::new(),
498                     Applicability::MachineApplicable,
499                 )
500                 .emit();
501         }
502     }
503
504     /// Parse a tuple or parenthesis pattern.
505     fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
506         let (fields, trailing_comma) =
507             self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
508
509         // Here, `(pat,)` is a tuple pattern.
510         // For backward compatibility, `(..)` is a tuple pattern as well.
511         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
512             PatKind::Paren(fields.into_iter().next().unwrap())
513         } else {
514             PatKind::Tuple(fields)
515         })
516     }
517
518     /// Parse a mutable binding with the `mut` token already eaten.
519     fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
520         let mut_span = self.prev_token.span;
521
522         if self.eat_keyword(kw::Ref) {
523             return self.recover_mut_ref_ident(mut_span);
524         }
525
526         self.recover_additional_muts();
527
528         // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
529         if let token::Interpolated(ref nt) = self.token.kind {
530             if let token::NtPat(_) = **nt {
531                 self.expected_ident_found().emit();
532             }
533         }
534
535         // Parse the pattern we hope to be an identifier.
536         let mut pat = self.parse_pat(Some("identifier"))?;
537
538         // If we don't have `mut $ident (@ pat)?`, error.
539         if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind {
540             // Don't recurse into the subpattern.
541             // `mut` on the outer binding doesn't affect the inner bindings.
542             *m = Mutability::Mut;
543         } else {
544             // Add `mut` to any binding in the parsed pattern.
545             let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
546             self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
547         }
548
549         Ok(pat.into_inner().kind)
550     }
551
552     /// Recover on `mut ref? ident @ pat` and suggest
553     /// that the order of `mut` and `ref` is incorrect.
554     fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
555         let mutref_span = lo.to(self.prev_token.span);
556         self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
557             .span_suggestion(
558                 mutref_span,
559                 "try switching the order",
560                 "ref mut".into(),
561                 Applicability::MachineApplicable,
562             )
563             .emit();
564
565         self.parse_pat_ident(BindingMode::ByRef(Mutability::Mut))
566     }
567
568     /// Turn all by-value immutable bindings in a pattern into mutable bindings.
569     /// Returns `true` if any change was made.
570     fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
571         struct AddMut(bool);
572         impl MutVisitor for AddMut {
573             fn visit_pat(&mut self, pat: &mut P<Pat>) {
574                 if let PatKind::Ident(BindingMode::ByValue(m @ Mutability::Not), ..) = &mut pat.kind
575                 {
576                     self.0 = true;
577                     *m = Mutability::Mut;
578                 }
579                 noop_visit_pat(pat, self);
580             }
581         }
582
583         let mut add_mut = AddMut(false);
584         add_mut.visit_pat(pat);
585         add_mut.0
586     }
587
588     /// Error on `mut $pat` where `$pat` is not an ident.
589     fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
590         let span = lo.to(pat.span);
591         let fix = pprust::pat_to_string(&pat);
592         let (problem, suggestion) = if changed_any_binding {
593             ("`mut` must be attached to each individual binding", "add `mut` to each binding")
594         } else {
595             ("`mut` must be followed by a named binding", "remove the `mut` prefix")
596         };
597         self.struct_span_err(span, problem)
598             .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
599             .note("`mut` may be followed by `variable` and `variable @ pattern`")
600             .emit();
601     }
602
603     /// Eat any extraneous `mut`s and error + recover if we ate any.
604     fn recover_additional_muts(&mut self) {
605         let lo = self.token.span;
606         while self.eat_keyword(kw::Mut) {}
607         if lo == self.token.span {
608             return;
609         }
610
611         let span = lo.to(self.prev_token.span);
612         self.struct_span_err(span, "`mut` on a binding may not be repeated")
613             .span_suggestion(
614                 span,
615                 "remove the additional `mut`s",
616                 String::new(),
617                 Applicability::MachineApplicable,
618             )
619             .emit();
620     }
621
622     /// Parse macro invocation
623     fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
624         self.bump();
625         let args = self.parse_mac_args()?;
626         let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription };
627         Ok(PatKind::MacCall(mac))
628     }
629
630     fn fatal_unexpected_non_pat(
631         &mut self,
632         mut err: DiagnosticBuilder<'a>,
633         expected: Expected,
634     ) -> PResult<'a, P<Pat>> {
635         err.cancel();
636
637         let expected = expected.unwrap_or("pattern");
638         let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
639
640         let mut err = self.struct_span_err(self.token.span, &msg);
641         err.span_label(self.token.span, format!("expected {}", expected));
642
643         let sp = self.sess.source_map().start_point(self.token.span);
644         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
645             self.sess.expr_parentheses_needed(&mut err, *sp, None);
646         }
647
648         Err(err)
649     }
650
651     /// Parses the range pattern end form `".." | "..." | "..=" ;`.
652     fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
653         let re = if self.eat(&token::DotDotDot) {
654             RangeEnd::Included(RangeSyntax::DotDotDot)
655         } else if self.eat(&token::DotDotEq) {
656             RangeEnd::Included(RangeSyntax::DotDotEq)
657         } else if self.eat(&token::DotDot) {
658             self.sess.gated_spans.gate(sym::exclusive_range_pattern, self.prev_token.span);
659             RangeEnd::Excluded
660         } else {
661             return None;
662         };
663         Some(respan(self.prev_token.span, re))
664     }
665
666     /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
667     /// `$begin $form` has already been parsed.
668     fn parse_pat_range_begin_with(
669         &mut self,
670         begin: P<Expr>,
671         re: Spanned<RangeEnd>,
672     ) -> PResult<'a, PatKind> {
673         let end = if self.is_pat_range_end_start(0) {
674             // Parsing e.g. `X..=Y`.
675             Some(self.parse_pat_range_end()?)
676         } else {
677             // Parsing e.g. `X..`.
678             self.sess.gated_spans.gate(sym::half_open_range_patterns, begin.span.to(re.span));
679             if let RangeEnd::Included(_) = re.node {
680                 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
681                 // Possibly also do this for `X..=` in *expression* contexts.
682                 self.error_inclusive_range_with_no_end(re.span);
683             }
684             None
685         };
686         Ok(PatKind::Range(Some(begin), end, re))
687     }
688
689     pub(super) fn error_inclusive_range_with_no_end(&self, span: Span) {
690         struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
691             .span_suggestion_short(
692                 span,
693                 "use `..` instead",
694                 "..".to_string(),
695                 Applicability::MachineApplicable,
696             )
697             .note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
698             .emit();
699     }
700
701     /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
702     ///
703     /// The form `...X` is prohibited to reduce confusion with the potential
704     /// expression syntax `...expr` for splatting in expressions.
705     fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
706         let end = self.parse_pat_range_end()?;
707         self.sess.gated_spans.gate(sym::half_open_range_patterns, re.span.to(self.prev_token.span));
708         if let RangeEnd::Included(ref mut syn @ RangeSyntax::DotDotDot) = &mut re.node {
709             *syn = RangeSyntax::DotDotEq;
710             self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
711                 .span_suggestion_short(
712                     re.span,
713                     "use `..=` instead",
714                     "..=".to_string(),
715                     Applicability::MachineApplicable,
716                 )
717                 .emit();
718         }
719         Ok(PatKind::Range(None, Some(end), re))
720     }
721
722     /// Is the token `dist` away from the current suitable as the start of a range patterns end?
723     fn is_pat_range_end_start(&self, dist: usize) -> bool {
724         self.check_inline_const(dist)
725             || self.look_ahead(dist, |t| {
726                 t.is_path_start() // e.g. `MY_CONST`;
727                 || t.kind == token::Dot // e.g. `.5` for recovery;
728                 || t.can_begin_literal_maybe_minus() // e.g. `42`.
729                 || t.is_whole_expr()
730             })
731     }
732
733     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
734         if self.check_inline_const(0) {
735             self.parse_const_block(self.token.span)
736         } else if self.check_path() {
737             let lo = self.token.span;
738             let (qself, path) = if self.eat_lt() {
739                 // Parse a qualified path
740                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
741                 (Some(qself), path)
742             } else {
743                 // Parse an unqualified path
744                 (None, self.parse_path(PathStyle::Expr)?)
745             };
746             let hi = self.prev_token.span;
747             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), AttrVec::new()))
748         } else {
749             self.parse_literal_maybe_minus()
750         }
751     }
752
753     /// Is this the start of a pattern beginning with a path?
754     fn is_start_of_pat_with_path(&mut self) -> bool {
755         self.check_path()
756         // Just for recovery (see `can_be_ident`).
757         || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
758     }
759
760     /// Would `parse_pat_ident` be appropriate here?
761     fn can_be_ident_pat(&mut self) -> bool {
762         self.check_ident()
763         && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
764         && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
765         // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
766         && !self.token.is_keyword(kw::In)
767         // Try to do something more complex?
768         && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(token::Paren) // A tuple struct pattern.
769             | token::OpenDelim(token::Brace) // A struct pattern.
770             | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
771             | token::ModSep // A tuple / struct variant pattern.
772             | token::Not)) // A macro expanding to a pattern.
773     }
774
775     /// Parses `ident` or `ident @ pat`.
776     /// Used by the copy foo and ref foo patterns to give a good
777     /// error message when parsing mistakes like `ref foo(a, b)`.
778     fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
779         let ident = self.parse_ident()?;
780         let sub = if self.eat(&token::At) {
781             Some(self.parse_pat(Some("binding pattern"))?)
782         } else {
783             None
784         };
785
786         // Just to be friendly, if they write something like `ref Some(i)`,
787         // we end up here with `(` as the current token.
788         // This shortly leads to a parse error. Note that if there is no explicit
789         // binding mode then we do not end up here, because the lookahead
790         // will direct us over to `parse_enum_variant()`.
791         if self.token == token::OpenDelim(token::Paren) {
792             return Err(self
793                 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
794         }
795
796         Ok(PatKind::Ident(binding_mode, ident, sub))
797     }
798
799     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
800     fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
801         if qself.is_some() {
802             return self.error_qpath_before_pat(&path, "{");
803         }
804         self.bump();
805         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
806             e.span_label(path.span, "while parsing the fields for this pattern");
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             return self.error_qpath_before_pat(&path, "(");
819         }
820         let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
821         Ok(PatKind::TupleStruct(path, fields))
822     }
823
824     /// Error when there's a qualified path, e.g. `<Foo as Bar>::Baz`
825     /// as the path of e.g., a tuple or record struct pattern.
826     fn error_qpath_before_pat(&mut self, path: &Path, token: &str) -> PResult<'a, PatKind> {
827         let msg = &format!("unexpected `{}` after qualified path", token);
828         let mut err = self.struct_span_err(self.token.span, msg);
829         err.span_label(self.token.span, msg);
830         err.span_label(path.span, "the qualified path");
831         Err(err)
832     }
833
834     /// Parses the fields of a struct-like pattern.
835     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
836         let mut fields = Vec::new();
837         let mut etc = false;
838         let mut ate_comma = true;
839         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
840         let mut etc_span = None;
841
842         while self.token != token::CloseDelim(token::Brace) {
843             let attrs = match self.parse_outer_attributes() {
844                 Ok(attrs) => attrs,
845                 Err(err) => {
846                     if let Some(mut delayed) = delayed_err {
847                         delayed.emit();
848                     }
849                     return Err(err);
850                 }
851             };
852             let lo = self.token.span;
853
854             // check that a comma comes after every field
855             if !ate_comma {
856                 let err = self.struct_span_err(self.token.span, "expected `,`");
857                 if let Some(mut delayed) = delayed_err {
858                     delayed.emit();
859                 }
860                 return Err(err);
861             }
862             ate_comma = false;
863
864             if self.check(&token::DotDot) || self.token == token::DotDotDot {
865                 etc = true;
866                 let mut etc_sp = self.token.span;
867
868                 self.recover_one_fewer_dotdot();
869                 self.bump(); // `..` || `...`
870
871                 if self.token == token::CloseDelim(token::Brace) {
872                     etc_span = Some(etc_sp);
873                     break;
874                 }
875                 let token_str = super::token_descr(&self.token);
876                 let msg = &format!("expected `}}`, found {}", token_str);
877                 let mut err = self.struct_span_err(self.token.span, msg);
878
879                 err.span_label(self.token.span, "expected `}`");
880                 let mut comma_sp = None;
881                 if self.token == token::Comma {
882                     // Issue #49257
883                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
884                     etc_sp = etc_sp.to(nw_span);
885                     err.span_label(
886                         etc_sp,
887                         "`..` must be at the end and cannot have a trailing comma",
888                     );
889                     comma_sp = Some(self.token.span);
890                     self.bump();
891                     ate_comma = true;
892                 }
893
894                 etc_span = Some(etc_sp.until(self.token.span));
895                 if self.token == token::CloseDelim(token::Brace) {
896                     // If the struct looks otherwise well formed, recover and continue.
897                     if let Some(sp) = comma_sp {
898                         err.span_suggestion_short(
899                             sp,
900                             "remove this comma",
901                             String::new(),
902                             Applicability::MachineApplicable,
903                         );
904                     }
905                     err.emit();
906                     break;
907                 } else if self.token.is_ident() && ate_comma {
908                     // Accept fields coming after `..,`.
909                     // This way we avoid "pattern missing fields" errors afterwards.
910                     // We delay this error until the end in order to have a span for a
911                     // suggested fix.
912                     if let Some(mut delayed_err) = delayed_err {
913                         delayed_err.emit();
914                         return Err(err);
915                     } else {
916                         delayed_err = Some(err);
917                     }
918                 } else {
919                     if let Some(mut err) = delayed_err {
920                         err.emit();
921                     }
922                     return Err(err);
923                 }
924             }
925
926             fields.push(match self.parse_pat_field(lo, attrs) {
927                 Ok(field) => field,
928                 Err(err) => {
929                     if let Some(mut delayed_err) = delayed_err {
930                         delayed_err.emit();
931                     }
932                     return Err(err);
933                 }
934             });
935             ate_comma = self.eat(&token::Comma);
936         }
937
938         if let Some(mut err) = delayed_err {
939             if let Some(etc_span) = etc_span {
940                 err.multipart_suggestion(
941                     "move the `..` to the end of the field list",
942                     vec![
943                         (etc_span, String::new()),
944                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
945                     ],
946                     Applicability::MachineApplicable,
947                 );
948             }
949             err.emit();
950         }
951         Ok((fields, etc))
952     }
953
954     /// Recover on `...` as if it were `..` to avoid further errors.
955     /// See issue #46718.
956     fn recover_one_fewer_dotdot(&self) {
957         if self.token != token::DotDotDot {
958             return;
959         }
960
961         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
962             .span_suggestion(
963                 self.token.span,
964                 "to omit remaining fields, use one fewer `.`",
965                 "..".to_owned(),
966                 Applicability::MachineApplicable,
967             )
968             .emit();
969     }
970
971     fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
972         // Check if a colon exists one ahead. This means we're parsing a fieldname.
973         let hi;
974         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
975             // Parsing a pattern of the form `fieldname: pat`.
976             let fieldname = self.parse_field_name()?;
977             self.bump();
978             let pat = self.parse_pat_with_or_inner()?;
979             hi = pat.span;
980             (pat, fieldname, false)
981         } else {
982             // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
983             let is_box = self.eat_keyword(kw::Box);
984             let boxed_span = self.token.span;
985             let is_ref = self.eat_keyword(kw::Ref);
986             let is_mut = self.eat_keyword(kw::Mut);
987             let fieldname = self.parse_ident()?;
988             hi = self.prev_token.span;
989
990             let bind_type = match (is_ref, is_mut) {
991                 (true, true) => BindingMode::ByRef(Mutability::Mut),
992                 (true, false) => BindingMode::ByRef(Mutability::Not),
993                 (false, true) => BindingMode::ByValue(Mutability::Mut),
994                 (false, false) => BindingMode::ByValue(Mutability::Not),
995             };
996
997             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
998             let subpat =
999                 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1000             (subpat, fieldname, true)
1001         };
1002
1003         Ok(FieldPat {
1004             ident: fieldname,
1005             pat: subpat,
1006             is_shorthand,
1007             attrs: attrs.into(),
1008             id: ast::DUMMY_NODE_ID,
1009             span: lo.to(hi),
1010             is_placeholder: false,
1011         })
1012     }
1013
1014     pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
1015         self.mk_pat(span, PatKind::Ident(bm, ident, None))
1016     }
1017
1018     fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1019         P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
1020     }
1021 }