]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser/pat.rs
Rollup merge of #64895 - davidtwco:issue-64130-async-error-definition, r=nikomatsakis
[rust.git] / src / libsyntax / parse / parser / pat.rs
1 use super::{Parser, PResult, PathStyle};
2
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
4 use crate::ptr::P;
5 use crate::ast::{self, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac};
6 use crate::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind};
7 use crate::mut_visit::{noop_visit_pat, MutVisitor};
8 use crate::parse::token::{self};
9 use crate::print::pprust;
10 use crate::source_map::{respan, Span, Spanned};
11 use crate::symbol::kw;
12 use crate::ThinVec;
13
14 use errors::{Applicability, DiagnosticBuilder};
15
16 type Expected = Option<&'static str>;
17
18 /// `Expected` for function and lambda parameter patterns.
19 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
20
21 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
22
23 /// Whether or not an or-pattern should be gated when occurring in the current context.
24 #[derive(PartialEq)]
25 pub enum GateOr { Yes, No }
26
27 /// Whether or not to recover a `,` when parsing or-patterns.
28 #[derive(PartialEq, Copy, Clone)]
29 enum RecoverComma { Yes, No }
30
31 impl<'a> Parser<'a> {
32     /// Parses a pattern.
33     ///
34     /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
35     /// at the top level. Used when parsing the parameters of lambda expressions,
36     /// functions, function pointers, and `pat` macro fragments.
37     pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
38         self.parse_pat_with_range_pat(true, expected)
39     }
40
41     /// Entry point to the main pattern parser.
42     /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
43     pub(super) fn parse_top_pat(&mut self, gate_or: GateOr) -> PResult<'a, P<Pat>> {
44         // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
45         let gated_leading_vert = self.eat_or_separator(None) && gate_or == GateOr::Yes;
46         let leading_vert_span = self.prev_span;
47
48         // Parse the possibly-or-pattern.
49         let pat = self.parse_pat_with_or(None, gate_or, RecoverComma::Yes)?;
50
51         // If we parsed a leading `|` which should be gated,
52         // and no other gated or-pattern has been parsed thus far,
53         // then we should really gate the leading `|`.
54         // This complicated procedure is done purely for diagnostics UX.
55         if gated_leading_vert {
56             let mut or_pattern_spans = self.sess.gated_spans.or_patterns.borrow_mut();
57             if or_pattern_spans.is_empty() {
58                 or_pattern_spans.push(leading_vert_span);
59             }
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.or_patterns.borrow_mut().push(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                 format!("{}", 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         let pat = match self.token.kind {
285             token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?,
286             token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?,
287             token::OpenDelim(token::Bracket) => {
288                 // Parse `[pat, pat,...]` as a slice pattern.
289                 let (pats, _) = self.parse_delim_comma_seq(
290                     token::Bracket,
291                     |p| p.parse_pat_with_or_inner(),
292                 )?;
293                 PatKind::Slice(pats)
294             }
295             token::DotDot => {
296                 self.bump();
297                 if self.is_pat_range_end_start() {
298                     // Parse `..42` for recovery.
299                     self.parse_pat_range_to(RangeEnd::Excluded, "..")?
300                 } else {
301                     // A rest pattern `..`.
302                     PatKind::Rest
303                 }
304             }
305             token::DotDotEq => {
306                 // Parse `..=42` for recovery.
307                 self.bump();
308                 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")?
309             }
310             token::DotDotDot => {
311                 // Parse `...42` for recovery.
312                 self.bump();
313                 self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")?
314             }
315             // At this point, token != `&`, `&&`, `(`, `[`, `..`, `..=`, or `...`.
316             _ => if self.eat_keyword(kw::Underscore) {
317                 // Parse _
318                 PatKind::Wild
319             } else if self.eat_keyword(kw::Mut) {
320                 self.parse_pat_ident_mut()?
321             } else if self.eat_keyword(kw::Ref) {
322                 // Parse ref ident @ pat / ref mut ident @ pat
323                 let mutbl = self.parse_mutability();
324                 self.parse_pat_ident(BindingMode::ByRef(mutbl))?
325             } else if self.eat_keyword(kw::Box) {
326                 // Parse `box pat`
327                 PatKind::Box(self.parse_pat_with_range_pat(false, None)?)
328             } else if self.can_be_ident_pat() {
329                 // Parse `ident @ pat`
330                 // This can give false positives and parse nullary enums,
331                 // they are dealt with later in resolve.
332                 self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))?
333             } else if self.is_start_of_pat_with_path() {
334                 // Parse pattern starting with a path
335                 let (qself, path) = if self.eat_lt() {
336                     // Parse a qualified path
337                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
338                     (Some(qself), path)
339                 } else {
340                     // Parse an unqualified path
341                     (None, self.parse_path(PathStyle::Expr)?)
342                 };
343                 match self.token.kind {
344                     token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?,
345                     token::DotDotDot | token::DotDotEq | token::DotDot => {
346                         self.parse_pat_range_starting_with_path(lo, qself, path)?
347                     }
348                     token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?,
349                     token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?,
350                     _ => PatKind::Path(qself, path),
351                 }
352             } else {
353                 // Try to parse everything else as literal with optional minus
354                 match self.parse_literal_maybe_minus() {
355                     Ok(begin)
356                         if self.check(&token::DotDot)
357                             || self.check(&token::DotDotEq)
358                             || self.check(&token::DotDotDot) =>
359                     {
360                         self.parse_pat_range_starting_with_lit(begin)?
361                     }
362                     Ok(begin) => PatKind::Lit(begin),
363                     Err(err) => return self.fatal_unexpected_non_pat(err, expected),
364                 }
365             }
366         };
367
368         let pat = self.mk_pat(lo.to(self.prev_span), pat);
369         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
370
371         if !allow_range_pat {
372             self.ban_pat_range_if_ambiguous(&pat)?
373         }
374
375         Ok(pat)
376     }
377
378     /// Ban a range pattern if it has an ambiguous interpretation.
379     fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> {
380         match pat.kind {
381             PatKind::Range(
382                 .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
383             ) => return Ok(()),
384             PatKind::Range(..) => {}
385             _ => return Ok(()),
386         }
387
388         let mut err = self.struct_span_err(
389             pat.span,
390             "the range pattern here has ambiguous interpretation",
391         );
392         err.span_suggestion(
393             pat.span,
394             "add parentheses to clarify the precedence",
395             format!("({})", pprust::pat_to_string(&pat)),
396             // "ambiguous interpretation" implies that we have to be guessing
397             Applicability::MaybeIncorrect
398         );
399         Err(err)
400     }
401
402     /// Parse `&pat` / `&mut pat`.
403     fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
404         self.expect_and()?;
405         let mutbl = self.parse_mutability();
406
407         if let token::Lifetime(name) = self.token.kind {
408             let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name));
409             err.span_label(self.token.span, "unexpected lifetime");
410             return Err(err);
411         }
412
413         let subpat = self.parse_pat_with_range_pat(false, expected)?;
414         Ok(PatKind::Ref(subpat, mutbl))
415     }
416
417     /// Parse a tuple or parenthesis pattern.
418     fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
419         let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
420
421         // Here, `(pat,)` is a tuple pattern.
422         // For backward compatibility, `(..)` is a tuple pattern as well.
423         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
424             PatKind::Paren(fields.into_iter().nth(0).unwrap())
425         } else {
426             PatKind::Tuple(fields)
427         })
428     }
429
430     /// Parse a mutable binding with the `mut` token already eaten.
431     fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
432         let mut_span = self.prev_span;
433
434         if self.eat_keyword(kw::Ref) {
435             return self.recover_mut_ref_ident(mut_span)
436         }
437
438         self.recover_additional_muts();
439
440         // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
441         if let token::Interpolated(ref nt) = self.token.kind {
442              if let token::NtPat(_) = **nt {
443                  self.expected_ident_found().emit();
444              }
445         }
446
447         // Parse the pattern we hope to be an identifier.
448         let mut pat = self.parse_pat(Some("identifier"))?;
449
450         // Add `mut` to any binding in the parsed pattern.
451         let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
452
453         // Unwrap; If we don't have `mut $ident`, error.
454         let pat = pat.into_inner();
455         match &pat.kind {
456             PatKind::Ident(..) => {}
457             _ => self.ban_mut_general_pat(mut_span, &pat, changed_any_binding),
458         }
459
460         Ok(pat.kind)
461     }
462
463     /// Recover on `mut ref? ident @ pat` and suggest
464     /// that the order of `mut` and `ref` is incorrect.
465     fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
466         let mutref_span = lo.to(self.prev_span);
467         self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
468             .span_suggestion(
469                 mutref_span,
470                 "try switching the order",
471                 "ref mut".into(),
472                 Applicability::MachineApplicable
473             )
474             .emit();
475
476         self.parse_pat_ident(BindingMode::ByRef(Mutability::Mutable))
477     }
478
479     /// Turn all by-value immutable bindings in a pattern into mutable bindings.
480     /// Returns `true` if any change was made.
481     fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
482         struct AddMut(bool);
483         impl MutVisitor for AddMut {
484             fn visit_pat(&mut self, pat: &mut P<Pat>) {
485                 if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Immutable), ..)
486                     = pat.kind
487                 {
488                     *m = Mutability::Mutable;
489                     self.0 = true;
490                 }
491                 noop_visit_pat(pat, self);
492             }
493         }
494
495         let mut add_mut = AddMut(false);
496         add_mut.visit_pat(pat);
497         add_mut.0
498     }
499
500     /// Error on `mut $pat` where `$pat` is not an ident.
501     fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
502         let span = lo.to(pat.span);
503         let fix = pprust::pat_to_string(&pat);
504         let (problem, suggestion) = if changed_any_binding {
505             ("`mut` must be attached to each individual binding", "add `mut` to each binding")
506         } else {
507             ("`mut` must be followed by a named binding", "remove the `mut` prefix")
508         };
509         self.struct_span_err(span, problem)
510             .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
511             .note("`mut` may be followed by `variable` and `variable @ pattern`")
512             .emit()
513     }
514
515     /// Eat any extraneous `mut`s and error + recover if we ate any.
516     fn recover_additional_muts(&mut self) {
517         let lo = self.token.span;
518         while self.eat_keyword(kw::Mut) {}
519         if lo == self.token.span {
520             return;
521         }
522
523         let span = lo.to(self.prev_span);
524         self.struct_span_err(span, "`mut` on a binding may not be repeated")
525             .span_suggestion(
526                 span,
527                 "remove the additional `mut`s",
528                 String::new(),
529                 Applicability::MachineApplicable,
530             )
531             .emit();
532     }
533
534     /// Parse macro invocation
535     fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> {
536         self.bump();
537         let (delim, tts) = self.expect_delimited_token_tree()?;
538         let mac = Mac {
539             path,
540             tts,
541             delim,
542             span: lo.to(self.prev_span),
543             prior_type_ascription: self.last_type_ascription,
544         };
545         Ok(PatKind::Mac(mac))
546     }
547
548     /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`.
549     /// The `$path` has already been parsed and the next token is the `$form`.
550     fn parse_pat_range_starting_with_path(
551         &mut self,
552         lo: Span,
553         qself: Option<QSelf>,
554         path: Path
555     ) -> PResult<'a, PatKind> {
556         let (end_kind, form) = match self.token.kind {
557             token::DotDot => (RangeEnd::Excluded, ".."),
558             token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."),
559             token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="),
560             _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"),
561         };
562         let op_span = self.token.span;
563         // Parse range
564         let span = lo.to(self.prev_span);
565         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
566         self.bump();
567         let end = self.parse_pat_range_end_opt(&begin, form)?;
568         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
569     }
570
571     /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`.
572     /// The `$path` has already been parsed and the next token is the `$form`.
573     fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> {
574         let op_span = self.token.span;
575         let (end_kind, form) = if self.eat(&token::DotDotDot) {
576             (RangeEnd::Included(RangeSyntax::DotDotDot), "...")
577         } else if self.eat(&token::DotDotEq) {
578             (RangeEnd::Included(RangeSyntax::DotDotEq), "..=")
579         } else if self.eat(&token::DotDot) {
580             (RangeEnd::Excluded, "..")
581         } else {
582             panic!("impossible case: we already matched on a range-operator token")
583         };
584         let end = self.parse_pat_range_end_opt(&begin, form)?;
585         Ok(PatKind::Range(begin, end, respan(op_span, end_kind)))
586     }
587
588     fn fatal_unexpected_non_pat(
589         &mut self,
590         mut err: DiagnosticBuilder<'a>,
591         expected: Expected,
592     ) -> PResult<'a, P<Pat>> {
593         err.cancel();
594
595         let expected = expected.unwrap_or("pattern");
596         let msg = format!("expected {}, found {}", expected, self.this_token_descr());
597
598         let mut err = self.fatal(&msg);
599         err.span_label(self.token.span, format!("expected {}", expected));
600
601         let sp = self.sess.source_map().start_point(self.token.span);
602         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
603             self.sess.expr_parentheses_needed(&mut err, *sp, None);
604         }
605
606         Err(err)
607     }
608
609     /// Is the current token suitable as the start of a range patterns end?
610     fn is_pat_range_end_start(&self) -> bool {
611         self.token.is_path_start() // e.g. `MY_CONST`;
612             || self.token == token::Dot // e.g. `.5` for recovery;
613             || self.token.can_begin_literal_or_bool() // e.g. `42`.
614             || self.token.is_whole_expr()
615     }
616
617     /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery.
618     fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> {
619         let lo = self.prev_span;
620         let end = self.parse_pat_range_end()?;
621         let range_span = lo.to(end.span);
622         let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new());
623
624         self.diagnostic()
625             .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form))
626             .span_suggestion(
627                 range_span,
628                 "try using the minimum value for the type",
629                 format!("MIN{}{}", form, pprust::expr_to_string(&end)),
630                 Applicability::HasPlaceholders,
631             )
632             .emit();
633
634         Ok(PatKind::Range(begin, end, respan(lo, re)))
635     }
636
637     /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern  or recover
638     /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively.
639     fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> {
640         if self.is_pat_range_end_start() {
641             // Parsing e.g. `X..=Y`.
642             self.parse_pat_range_end()
643         } else {
644             // Parsing e.g. `X..`.
645             let range_span = begin.span.to(self.prev_span);
646
647             self.diagnostic()
648                 .struct_span_err(
649                     range_span,
650                     &format!("`X{}` range patterns are not supported", form),
651                 )
652                 .span_suggestion(
653                     range_span,
654                     "try using the maximum value for the type",
655                     format!("{}{}MAX", pprust::expr_to_string(&begin), form),
656                     Applicability::HasPlaceholders,
657                 )
658                 .emit();
659
660             Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new()))
661         }
662     }
663
664     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
665         if self.token.is_path_start() {
666             let lo = self.token.span;
667             let (qself, path) = if self.eat_lt() {
668                 // Parse a qualified path
669                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
670                 (Some(qself), path)
671             } else {
672                 // Parse an unqualified path
673                 (None, self.parse_path(PathStyle::Expr)?)
674             };
675             let hi = self.prev_span;
676             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
677         } else {
678             self.parse_literal_maybe_minus()
679         }
680     }
681
682     /// Is this the start of a pattern beginning with a path?
683     fn is_start_of_pat_with_path(&mut self) -> bool {
684         self.check_path()
685         // Just for recovery (see `can_be_ident`).
686         || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
687     }
688
689     /// Would `parse_pat_ident` be appropriate here?
690     fn can_be_ident_pat(&mut self) -> bool {
691         self.check_ident()
692         && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
693         && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
694         // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
695         && !self.token.is_keyword(kw::In)
696         && self.look_ahead(1, |t| match t.kind { // Try to do something more complex?
697             token::OpenDelim(token::Paren) // A tuple struct pattern.
698             | token::OpenDelim(token::Brace) // A struct pattern.
699             | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
700             | token::ModSep // A tuple / struct variant pattern.
701             | token::Not => false, // A macro expanding to a pattern.
702             _ => true,
703         })
704     }
705
706     /// Parses `ident` or `ident @ pat`.
707     /// Used by the copy foo and ref foo patterns to give a good
708     /// error message when parsing mistakes like `ref foo(a, b)`.
709     fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> {
710         let ident = self.parse_ident()?;
711         let sub = if self.eat(&token::At) {
712             Some(self.parse_pat(Some("binding pattern"))?)
713         } else {
714             None
715         };
716
717         // Just to be friendly, if they write something like `ref Some(i)`,
718         // we end up here with `(` as the current token.
719         // This shortly leads to a parse error. Note that if there is no explicit
720         // binding mode then we do not end up here, because the lookahead
721         // will direct us over to `parse_enum_variant()`.
722         if self.token == token::OpenDelim(token::Paren) {
723             return Err(self.span_fatal(
724                 self.prev_span,
725                 "expected identifier, found enum pattern",
726             ))
727         }
728
729         Ok(PatKind::Ident(binding_mode, ident, sub))
730     }
731
732     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
733     fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
734         if qself.is_some() {
735             let msg = "unexpected `{` after qualified path";
736             let mut err = self.fatal(msg);
737             err.span_label(self.token.span, msg);
738             return Err(err);
739         }
740
741         self.bump();
742         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
743             e.emit();
744             self.recover_stmt();
745             (vec![], true)
746         });
747         self.bump();
748         Ok(PatKind::Struct(path, fields, etc))
749     }
750
751     /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
752     fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> {
753         if qself.is_some() {
754             let msg = "unexpected `(` after qualified path";
755             let mut err = self.fatal(msg);
756             err.span_label(self.token.span, msg);
757             return Err(err);
758         }
759         let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?;
760         Ok(PatKind::TupleStruct(path, fields))
761     }
762
763     /// Parses the fields of a struct-like pattern.
764     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> {
765         let mut fields = Vec::new();
766         let mut etc = false;
767         let mut ate_comma = true;
768         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
769         let mut etc_span = None;
770
771         while self.token != token::CloseDelim(token::Brace) {
772             let attrs = match self.parse_outer_attributes() {
773                 Ok(attrs) => attrs,
774                 Err(err) => {
775                     if let Some(mut delayed) = delayed_err {
776                         delayed.emit();
777                     }
778                     return Err(err);
779                 },
780             };
781             let lo = self.token.span;
782
783             // check that a comma comes after every field
784             if !ate_comma {
785                 let err = self.struct_span_err(self.prev_span, "expected `,`");
786                 if let Some(mut delayed) = delayed_err {
787                     delayed.emit();
788                 }
789                 return Err(err);
790             }
791             ate_comma = false;
792
793             if self.check(&token::DotDot) || self.token == token::DotDotDot {
794                 etc = true;
795                 let mut etc_sp = self.token.span;
796
797                 self.recover_one_fewer_dotdot();
798                 self.bump();  // `..` || `...`
799
800                 if self.token == token::CloseDelim(token::Brace) {
801                     etc_span = Some(etc_sp);
802                     break;
803                 }
804                 let token_str = self.this_token_descr();
805                 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
806
807                 err.span_label(self.token.span, "expected `}`");
808                 let mut comma_sp = None;
809                 if self.token == token::Comma { // Issue #49257
810                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
811                     etc_sp = etc_sp.to(nw_span);
812                     err.span_label(etc_sp,
813                                    "`..` must be at the end and cannot have a trailing comma");
814                     comma_sp = Some(self.token.span);
815                     self.bump();
816                     ate_comma = true;
817                 }
818
819                 etc_span = Some(etc_sp.until(self.token.span));
820                 if self.token == token::CloseDelim(token::Brace) {
821                     // If the struct looks otherwise well formed, recover and continue.
822                     if let Some(sp) = comma_sp {
823                         err.span_suggestion_short(
824                             sp,
825                             "remove this comma",
826                             String::new(),
827                             Applicability::MachineApplicable,
828                         );
829                     }
830                     err.emit();
831                     break;
832                 } else if self.token.is_ident() && ate_comma {
833                     // Accept fields coming after `..,`.
834                     // This way we avoid "pattern missing fields" errors afterwards.
835                     // We delay this error until the end in order to have a span for a
836                     // suggested fix.
837                     if let Some(mut delayed_err) = delayed_err {
838                         delayed_err.emit();
839                         return Err(err);
840                     } else {
841                         delayed_err = Some(err);
842                     }
843                 } else {
844                     if let Some(mut err) = delayed_err {
845                         err.emit();
846                     }
847                     return Err(err);
848                 }
849             }
850
851             fields.push(match self.parse_pat_field(lo, attrs) {
852                 Ok(field) => field,
853                 Err(err) => {
854                     if let Some(mut delayed_err) = delayed_err {
855                         delayed_err.emit();
856                     }
857                     return Err(err);
858                 }
859             });
860             ate_comma = self.eat(&token::Comma);
861         }
862
863         if let Some(mut err) = delayed_err {
864             if let Some(etc_span) = etc_span {
865                 err.multipart_suggestion(
866                     "move the `..` to the end of the field list",
867                     vec![
868                         (etc_span, String::new()),
869                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
870                     ],
871                     Applicability::MachineApplicable,
872                 );
873             }
874             err.emit();
875         }
876         return Ok((fields, etc));
877     }
878
879     /// Recover on `...` as if it were `..` to avoid further errors.
880     /// See issue #46718.
881     fn recover_one_fewer_dotdot(&self) {
882         if self.token != token::DotDotDot {
883             return;
884         }
885
886         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
887             .span_suggestion(
888                 self.token.span,
889                 "to omit remaining fields, use one fewer `.`",
890                 "..".to_owned(),
891                 Applicability::MachineApplicable
892             )
893             .emit();
894     }
895
896     fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> {
897         // Check if a colon exists one ahead. This means we're parsing a fieldname.
898         let hi;
899         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
900             // Parsing a pattern of the form `fieldname: pat`.
901             let fieldname = self.parse_field_name()?;
902             self.bump();
903             let pat = self.parse_pat_with_or_inner()?;
904             hi = pat.span;
905             (pat, fieldname, false)
906         } else {
907             // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
908             let is_box = self.eat_keyword(kw::Box);
909             let boxed_span = self.token.span;
910             let is_ref = self.eat_keyword(kw::Ref);
911             let is_mut = self.eat_keyword(kw::Mut);
912             let fieldname = self.parse_ident()?;
913             hi = self.prev_span;
914
915             let bind_type = match (is_ref, is_mut) {
916                 (true, true) => BindingMode::ByRef(Mutability::Mutable),
917                 (true, false) => BindingMode::ByRef(Mutability::Immutable),
918                 (false, true) => BindingMode::ByValue(Mutability::Mutable),
919                 (false, false) => BindingMode::ByValue(Mutability::Immutable),
920             };
921
922             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname);
923             let subpat = if is_box {
924                 self.mk_pat(lo.to(hi), PatKind::Box(fieldpat))
925             } else {
926                 fieldpat
927             };
928             (subpat, fieldname, true)
929         };
930
931         Ok(FieldPat {
932             ident: fieldname,
933             pat: subpat,
934             is_shorthand,
935             attrs: attrs.into(),
936             id: ast::DUMMY_NODE_ID,
937             span: lo.to(hi),
938             is_placeholder: false,
939         })
940     }
941
942     pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> {
943         self.mk_pat(span, PatKind::Ident(bm, ident, None))
944     }
945
946     fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
947         P(Pat { kind, span, id: ast::DUMMY_NODE_ID })
948     }
949 }