]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/pat.rs
Auto merge of #105421 - jacobbramley:jb/branch-prot-check, r=nagisa
[rust.git] / compiler / rustc_parse / src / parser / pat.rs
1 use super::{ForceCollect, Parser, PathStyle, TrailingToken};
2 use crate::errors::RemoveLet;
3 use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
4 use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor};
5 use rustc_ast::ptr::P;
6 use rustc_ast::token::{self, Delimiter};
7 use rustc_ast::{
8     self as ast, AttrVec, BindingAnnotation, ByRef, Expr, ExprKind, MacCall, Mutability, Pat,
9     PatField, PatKind, Path, QSelf, RangeEnd, RangeSyntax,
10 };
11 use rustc_ast_pretty::pprust;
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult};
13 use rustc_session::errors::ExprParenthesesNeeded;
14 use rustc_span::source_map::{respan, Span, Spanned};
15 use rustc_span::symbol::{kw, sym, Ident};
16
17 pub(super) type Expected = Option<&'static str>;
18
19 /// `Expected` for function and lambda parameter patterns.
20 pub(super) const PARAM_EXPECTED: Expected = Some("parameter name");
21
22 const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
23
24 /// Whether or not to recover a `,` when parsing or-patterns.
25 #[derive(PartialEq, Copy, Clone)]
26 pub enum RecoverComma {
27     Yes,
28     No,
29 }
30
31 /// Whether or not to recover a `:` when parsing patterns that were meant to be paths.
32 #[derive(PartialEq, Copy, Clone)]
33 pub enum RecoverColon {
34     Yes,
35     No,
36 }
37
38 /// Whether or not to recover a `a, b` when parsing patterns as `(a, b)` or that *and* `a | b`.
39 #[derive(PartialEq, Copy, Clone)]
40 pub enum CommaRecoveryMode {
41     LikelyTuple,
42     EitherTupleOrPipe,
43 }
44
45 /// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
46 /// emitting duplicate diagnostics.
47 #[derive(Debug, Clone, Copy)]
48 enum EatOrResult {
49     /// We recovered from a trailing vert.
50     TrailingVert,
51     /// We ate an `|` (or `||` and recovered).
52     AteOr,
53     /// We did not eat anything (i.e. the current token is not `|` or `||`).
54     None,
55 }
56
57 impl<'a> Parser<'a> {
58     /// Parses a pattern.
59     ///
60     /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns
61     /// at the top level. Used when parsing the parameters of lambda expressions,
62     /// functions, function pointers, and `pat` macro fragments.
63     pub fn parse_pat_no_top_alt(&mut self, expected: Expected) -> PResult<'a, P<Pat>> {
64         self.parse_pat_with_range_pat(true, expected)
65     }
66
67     /// Parses a pattern.
68     ///
69     /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level.
70     /// Used for parsing patterns in all cases when `pat<no_top_alt>` is not used.
71     ///
72     /// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
73     /// a leading vert is allowed in nested or-patterns, too. This allows us to
74     /// simplify the grammar somewhat.
75     pub fn parse_pat_allow_top_alt(
76         &mut self,
77         expected: Expected,
78         rc: RecoverComma,
79         ra: RecoverColon,
80         rt: CommaRecoveryMode,
81     ) -> PResult<'a, P<Pat>> {
82         self.parse_pat_allow_top_alt_inner(expected, rc, ra, rt).map(|(pat, _)| pat)
83     }
84
85     /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
86     /// recovered).
87     fn parse_pat_allow_top_alt_inner(
88         &mut self,
89         expected: Expected,
90         rc: RecoverComma,
91         ra: RecoverColon,
92         rt: CommaRecoveryMode,
93     ) -> PResult<'a, (P<Pat>, bool)> {
94         // Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
95         // suggestions (which bothers rustfix).
96         //
97         // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
98         let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
99             EatOrResult::AteOr => (Some(self.prev_token.span), false),
100             EatOrResult::TrailingVert => (None, true),
101             EatOrResult::None => (None, false),
102         };
103
104         // Parse the first pattern (`p_0`).
105         let mut first_pat = self.parse_pat_no_top_alt(expected)?;
106         if rc == RecoverComma::Yes {
107             self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
108         }
109
110         // If the next token is not a `|`,
111         // this is not an or-pattern and we should exit here.
112         if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr {
113             // If we parsed a leading `|` which should be gated,
114             // then we should really gate the leading `|`.
115             // This complicated procedure is done purely for diagnostics UX.
116
117             // Check if the user wrote `foo:bar` instead of `foo::bar`.
118             if ra == RecoverColon::Yes {
119                 first_pat = self.maybe_recover_colon_colon_in_pat_typo(first_pat, expected);
120             }
121
122             if let Some(leading_vert_span) = leading_vert_span {
123                 // If there was a leading vert, treat this as an or-pattern. This improves
124                 // diagnostics.
125                 let span = leading_vert_span.to(self.prev_token.span);
126                 return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert));
127             }
128
129             return Ok((first_pat, trailing_vert));
130         }
131
132         // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
133         let lo = leading_vert_span.unwrap_or(first_pat.span);
134         let mut pats = vec![first_pat];
135         loop {
136             match self.eat_or_separator(Some(lo)) {
137                 EatOrResult::AteOr => {}
138                 EatOrResult::None => break,
139                 EatOrResult::TrailingVert => {
140                     trailing_vert = true;
141                     break;
142                 }
143             }
144             let pat = self.parse_pat_no_top_alt(expected).map_err(|mut err| {
145                 err.span_label(lo, WHILE_PARSING_OR_MSG);
146                 err
147             })?;
148             if rc == RecoverComma::Yes {
149                 self.maybe_recover_unexpected_comma(pat.span, rt)?;
150             }
151             pats.push(pat);
152         }
153         let or_pattern_span = lo.to(self.prev_token.span);
154
155         Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
156     }
157
158     /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
159     /// type annotation (e.g. for `let` bindings or `fn` params).
160     ///
161     /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
162     /// eat the `Colon` token if one is present.
163     ///
164     /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
165     /// otherwise).
166     pub(super) fn parse_pat_before_ty(
167         &mut self,
168         expected: Expected,
169         rc: RecoverComma,
170         syntax_loc: &str,
171     ) -> PResult<'a, (P<Pat>, bool)> {
172         // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
173         // or-patterns so that we can detect when a user tries to use it. This allows us to print a
174         // better error message.
175         let (pat, trailing_vert) = self.parse_pat_allow_top_alt_inner(
176             expected,
177             rc,
178             RecoverColon::No,
179             CommaRecoveryMode::LikelyTuple,
180         )?;
181         let colon = self.eat(&token::Colon);
182
183         if let PatKind::Or(pats) = &pat.kind {
184             let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc);
185             let (help, fix) = if pats.len() == 1 {
186                 // If all we have is a leading vert, then print a special message. This is the case
187                 // if `parse_pat_allow_top_alt` returns an or-pattern with one variant.
188                 let msg = "remove the `|`";
189                 let fix = pprust::pat_to_string(&pat);
190                 (msg, fix)
191             } else {
192                 let msg = "wrap the pattern in parentheses";
193                 let fix = format!("({})", pprust::pat_to_string(&pat));
194                 (msg, fix)
195             };
196
197             if trailing_vert {
198                 // We already emitted an error and suggestion to remove the trailing vert. Don't
199                 // emit again.
200                 self.sess.span_diagnostic.delay_span_bug(pat.span, &msg);
201             } else {
202                 self.struct_span_err(pat.span, &msg)
203                     .span_suggestion(pat.span, help, fix, Applicability::MachineApplicable)
204                     .emit();
205             }
206         }
207
208         Ok((pat, colon))
209     }
210
211     /// Parse the pattern for a function or function pointer parameter, followed by a colon.
212     ///
213     /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
214     /// otherwise).
215     pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (P<Pat>, bool)> {
216         // In order to get good UX, we first recover in the case of a leading vert for an illegal
217         // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
218         // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
219         // separately.
220         if let token::OrOr = self.token.kind {
221             let span = self.token.span;
222             let mut err = self.struct_span_err(span, "unexpected `||` before function parameter");
223             err.span_suggestion(span, "remove the `||`", "", Applicability::MachineApplicable);
224             err.note("alternatives in or-patterns are separated with `|`, not `||`");
225             err.emit();
226             self.bump();
227         }
228
229         self.parse_pat_before_ty(PARAM_EXPECTED, RecoverComma::No, "function parameters")
230     }
231
232     /// Eat the or-pattern `|` separator.
233     /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
234     fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
235         if self.recover_trailing_vert(lo) {
236             EatOrResult::TrailingVert
237         } else if matches!(self.token.kind, token::OrOr) {
238             // Found `||`; Recover and pretend we parsed `|`.
239             self.ban_unexpected_or_or(lo);
240             self.bump();
241             EatOrResult::AteOr
242         } else if self.eat(&token::BinOp(token::Or)) {
243             EatOrResult::AteOr
244         } else {
245             EatOrResult::None
246         }
247     }
248
249     /// Recover if `|` or `||` is the current token and we have one of the
250     /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
251     ///
252     /// These tokens all indicate that we reached the end of the or-pattern
253     /// list and can now reliably say that the `|` was an illegal trailing vert.
254     /// Note that there are more tokens such as `@` for which we know that the `|`
255     /// is an illegal parse. However, the user's intent is less clear in that case.
256     fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
257         let is_end_ahead = self.look_ahead(1, |token| {
258             matches!(
259                 &token.uninterpolate().kind,
260                 token::FatArrow // e.g. `a | => 0,`.
261                 | token::Ident(kw::If, false) // e.g. `a | if expr`.
262                 | token::Eq // e.g. `let a | = 0`.
263                 | token::Semi // e.g. `let a |;`.
264                 | token::Colon // e.g. `let a | :`.
265                 | token::Comma // e.g. `let (a |,)`.
266                 | token::CloseDelim(Delimiter::Bracket) // e.g. `let [a | ]`.
267                 | token::CloseDelim(Delimiter::Parenthesis) // e.g. `let (a | )`.
268                 | token::CloseDelim(Delimiter::Brace) // e.g. `let A { f: a | }`.
269             )
270         });
271         match (is_end_ahead, &self.token.kind) {
272             (true, token::BinOp(token::Or) | token::OrOr) => {
273                 self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern");
274                 self.bump();
275                 true
276             }
277             _ => false,
278         }
279     }
280
281     /// We have parsed `||` instead of `|`. Error and suggest `|` instead.
282     fn ban_unexpected_or_or(&mut self, lo: Option<Span>) {
283         let mut err = self.struct_span_err(self.token.span, "unexpected token `||` in pattern");
284         err.span_suggestion(
285             self.token.span,
286             "use a single `|` to separate multiple alternative patterns",
287             "|",
288             Applicability::MachineApplicable,
289         );
290         if let Some(lo) = lo {
291             err.span_label(lo, WHILE_PARSING_OR_MSG);
292         }
293         err.emit();
294     }
295
296     /// A `|` or possibly `||` token shouldn't be here. Ban it.
297     fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) {
298         let span = self.token.span;
299         let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx));
300         err.span_suggestion(
301             span,
302             &format!("remove the `{}`", pprust::token_to_string(&self.token)),
303             "",
304             Applicability::MachineApplicable,
305         );
306         if let Some(lo) = lo {
307             err.span_label(lo, WHILE_PARSING_OR_MSG);
308         }
309         if let token::OrOr = self.token.kind {
310             err.note("alternatives in or-patterns are separated with `|`, not `||`");
311         }
312         err.emit();
313     }
314
315     /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
316     /// allowed).
317     fn parse_pat_with_range_pat(
318         &mut self,
319         allow_range_pat: bool,
320         expected: Expected,
321     ) -> PResult<'a, P<Pat>> {
322         maybe_recover_from_interpolated_ty_qpath!(self, true);
323         maybe_whole!(self, NtPat, |x| x);
324
325         let mut lo = self.token.span;
326
327         if self.token.is_keyword(kw::Let) && self.look_ahead(1, |tok| tok.can_begin_pattern()) {
328             self.bump();
329             self.sess.emit_err(RemoveLet { span: lo });
330             lo = self.token.span;
331         }
332
333         let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
334             self.parse_pat_deref(expected)?
335         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
336             self.parse_pat_tuple_or_parens()?
337         } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
338             // Parse `[pat, pat,...]` as a slice pattern.
339             let (pats, _) = self.parse_delim_comma_seq(Delimiter::Bracket, |p| {
340                 p.parse_pat_allow_top_alt(
341                     None,
342                     RecoverComma::No,
343                     RecoverColon::No,
344                     CommaRecoveryMode::EitherTupleOrPipe,
345                 )
346             })?;
347             PatKind::Slice(pats)
348         } else if self.check(&token::DotDot) && !self.is_pat_range_end_start(1) {
349             // A rest pattern `..`.
350             self.bump(); // `..`
351             PatKind::Rest
352         } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) {
353             self.recover_dotdotdot_rest_pat(lo)
354         } else if let Some(form) = self.parse_range_end() {
355             self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
356         } else if self.eat_keyword(kw::Underscore) {
357             // Parse _
358             PatKind::Wild
359         } else if self.eat_keyword(kw::Mut) {
360             self.parse_pat_ident_mut()?
361         } else if self.eat_keyword(kw::Ref) {
362             // Parse ref ident @ pat / ref mut ident @ pat
363             let mutbl = self.parse_mutability();
364             self.parse_pat_ident(BindingAnnotation(ByRef::Yes, mutbl))?
365         } else if self.eat_keyword(kw::Box) {
366             self.parse_pat_box()?
367         } else if self.check_inline_const(0) {
368             // Parse `const pat`
369             let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
370
371             if let Some(re) = self.parse_range_end() {
372                 self.parse_pat_range_begin_with(const_expr, re)?
373             } else {
374                 PatKind::Lit(const_expr)
375             }
376         } else if self.can_be_ident_pat() {
377             // Parse `ident @ pat`
378             // This can give false positives and parse nullary enums,
379             // they are dealt with later in resolve.
380             self.parse_pat_ident(BindingAnnotation::NONE)?
381         } else if self.is_start_of_pat_with_path() {
382             // Parse pattern starting with a path
383             let (qself, path) = if self.eat_lt() {
384                 // Parse a qualified path
385                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
386                 (Some(qself), path)
387             } else {
388                 // Parse an unqualified path
389                 (None, self.parse_path(PathStyle::Expr)?)
390             };
391             let span = lo.to(self.prev_token.span);
392
393             if qself.is_none() && self.check(&token::Not) {
394                 self.parse_pat_mac_invoc(path)?
395             } else if let Some(form) = self.parse_range_end() {
396                 let begin = self.mk_expr(span, ExprKind::Path(qself, path));
397                 self.parse_pat_range_begin_with(begin, form)?
398             } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
399                 self.parse_pat_struct(qself, path)?
400             } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
401                 self.parse_pat_tuple_struct(qself, path)?
402             } else {
403                 PatKind::Path(qself, path)
404             }
405         } else if matches!(self.token.kind, token::Lifetime(_))
406             // In pattern position, we're totally fine with using "next token isn't colon"
407             // as a heuristic. We could probably just always try to recover if it's a lifetime,
408             // because we never have `'a: label {}` in a pattern position anyways, but it does
409             // keep us from suggesting something like `let 'a: Ty = ..` => `let 'a': Ty = ..`
410             && !self.look_ahead(1, |token| matches!(token.kind, token::Colon))
411         {
412             // Recover a `'a` as a `'a'` literal
413             let lt = self.expect_lifetime();
414             let (lit, _) =
415                 self.recover_unclosed_char(lt.ident, Parser::mk_token_lit_char, |self_| {
416                     let expected = expected.unwrap_or("pattern");
417                     let msg = format!(
418                         "expected {}, found {}",
419                         expected,
420                         super::token_descr(&self_.token)
421                     );
422
423                     let mut err = self_.struct_span_err(self_.token.span, &msg);
424                     err.span_label(self_.token.span, format!("expected {}", expected));
425                     err
426                 });
427             PatKind::Lit(self.mk_expr(lo, ExprKind::Lit(lit)))
428         } else {
429             // Try to parse everything else as literal with optional minus
430             match self.parse_literal_maybe_minus() {
431                 Ok(begin) => match self.parse_range_end() {
432                     Some(form) => self.parse_pat_range_begin_with(begin, form)?,
433                     None => PatKind::Lit(begin),
434                 },
435                 Err(err) => return self.fatal_unexpected_non_pat(err, expected),
436             }
437         };
438
439         let pat = self.mk_pat(lo.to(self.prev_token.span), pat);
440         let pat = self.maybe_recover_from_bad_qpath(pat)?;
441         let pat = self.recover_intersection_pat(pat)?;
442
443         if !allow_range_pat {
444             self.ban_pat_range_if_ambiguous(&pat)
445         }
446
447         Ok(pat)
448     }
449
450     /// Recover from a typoed `...` pattern that was encountered
451     /// Ref: Issue #70388
452     fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind {
453         // A typoed rest pattern `...`.
454         self.bump(); // `...`
455
456         // The user probably mistook `...` for a rest pattern `..`.
457         self.struct_span_err(lo, "unexpected `...`")
458             .span_label(lo, "not a valid pattern")
459             .span_suggestion_short(
460                 lo,
461                 "for a rest pattern, use `..` instead of `...`",
462                 "..",
463                 Applicability::MachineApplicable,
464             )
465             .emit();
466         PatKind::Rest
467     }
468
469     /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
470     ///
471     /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
472     /// should already have been parsed by now  at this point,
473     /// if the next token is `@` then we can try to parse the more general form.
474     ///
475     /// Consult `parse_pat_ident` for the `binding` grammar.
476     ///
477     /// The notion of intersection patterns are found in
478     /// e.g. [F#][and] where they are called AND-patterns.
479     ///
480     /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
481     fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> {
482         if self.token.kind != token::At {
483             // Next token is not `@` so it's not going to be an intersection pattern.
484             return Ok(lhs);
485         }
486
487         // At this point we attempt to parse `@ $pat_rhs` and emit an error.
488         self.bump(); // `@`
489         let mut rhs = self.parse_pat_no_top_alt(None)?;
490         let sp = lhs.span.to(rhs.span);
491
492         if let PatKind::Ident(_, _, sub @ None) = &mut rhs.kind {
493             // The user inverted the order, so help them fix that.
494             let mut applicability = Applicability::MachineApplicable;
495             // FIXME(bindings_after_at): Remove this code when stabilizing the feature.
496             lhs.walk(&mut |p| match p.kind {
497                 // `check_match` is unhappy if the subpattern has a binding anywhere.
498                 PatKind::Ident(..) => {
499                     applicability = Applicability::MaybeIncorrect;
500                     false // Short-circuit.
501                 }
502                 _ => true,
503             });
504
505             let lhs_span = lhs.span;
506             // Move the LHS into the RHS as a subpattern.
507             // The RHS is now the full pattern.
508             *sub = Some(lhs);
509
510             self.struct_span_err(sp, "pattern on wrong side of `@`")
511                 .span_label(lhs_span, "pattern on the left, should be on the right")
512                 .span_label(rhs.span, "binding on the right, should be on the left")
513                 .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability)
514                 .emit();
515         } else {
516             // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
517             rhs.kind = PatKind::Wild;
518             self.struct_span_err(sp, "left-hand side of `@` must be a binding")
519                 .span_label(lhs.span, "interpreted as a pattern, not a binding")
520                 .span_label(rhs.span, "also a pattern")
521                 .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`")
522                 .emit();
523         }
524
525         rhs.span = sp;
526         Ok(rhs)
527     }
528
529     /// Ban a range pattern if it has an ambiguous interpretation.
530     fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
531         match pat.kind {
532             PatKind::Range(
533                 ..,
534                 Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
535             ) => return,
536             PatKind::Range(..) => {}
537             _ => return,
538         }
539
540         self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation")
541             .span_suggestion(
542                 pat.span,
543                 "add parentheses to clarify the precedence",
544                 format!("({})", pprust::pat_to_string(&pat)),
545                 // "ambiguous interpretation" implies that we have to be guessing
546                 Applicability::MaybeIncorrect,
547             )
548             .emit();
549     }
550
551     /// Parse `&pat` / `&mut pat`.
552     fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> {
553         self.expect_and()?;
554         self.recover_lifetime_in_deref_pat();
555         let mutbl = self.parse_mutability();
556         let subpat = self.parse_pat_with_range_pat(false, expected)?;
557         Ok(PatKind::Ref(subpat, mutbl))
558     }
559
560     fn recover_lifetime_in_deref_pat(&mut self) {
561         if let token::Lifetime(name) = self.token.kind {
562             self.bump(); // `'a`
563
564             let span = self.prev_token.span;
565             self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name))
566                 .span_suggestion(span, "remove the lifetime", "", Applicability::MachineApplicable)
567                 .emit();
568         }
569     }
570
571     /// Parse a tuple or parenthesis pattern.
572     fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> {
573         let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
574             p.parse_pat_allow_top_alt(
575                 None,
576                 RecoverComma::No,
577                 RecoverColon::No,
578                 CommaRecoveryMode::LikelyTuple,
579             )
580         })?;
581
582         // Here, `(pat,)` is a tuple pattern.
583         // For backward compatibility, `(..)` is a tuple pattern as well.
584         Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) {
585             PatKind::Paren(fields.into_iter().next().unwrap())
586         } else {
587             PatKind::Tuple(fields)
588         })
589     }
590
591     /// Parse a mutable binding with the `mut` token already eaten.
592     fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
593         let mut_span = self.prev_token.span;
594
595         if self.eat_keyword(kw::Ref) {
596             return self.recover_mut_ref_ident(mut_span);
597         }
598
599         self.recover_additional_muts();
600
601         // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
602         if let token::Interpolated(nt) = &self.token.kind {
603             if let token::NtPat(_) = **nt {
604                 self.expected_ident_found().emit();
605             }
606         }
607
608         // Parse the pattern we hope to be an identifier.
609         let mut pat = self.parse_pat_no_top_alt(Some("identifier"))?;
610
611         // If we don't have `mut $ident (@ pat)?`, error.
612         if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) = &mut pat.kind
613         {
614             // Don't recurse into the subpattern.
615             // `mut` on the outer binding doesn't affect the inner bindings.
616             *m = Mutability::Mut;
617         } else {
618             // Add `mut` to any binding in the parsed pattern.
619             let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
620             self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
621         }
622
623         Ok(pat.into_inner().kind)
624     }
625
626     /// Recover on `mut ref? ident @ pat` and suggest
627     /// that the order of `mut` and `ref` is incorrect.
628     fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> {
629         let mutref_span = lo.to(self.prev_token.span);
630         self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
631             .span_suggestion(
632                 mutref_span,
633                 "try switching the order",
634                 "ref mut",
635                 Applicability::MachineApplicable,
636             )
637             .emit();
638
639         self.parse_pat_ident(BindingAnnotation::REF_MUT)
640     }
641
642     /// Turn all by-value immutable bindings in a pattern into mutable bindings.
643     /// Returns `true` if any change was made.
644     fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool {
645         struct AddMut(bool);
646         impl MutVisitor for AddMut {
647             fn visit_pat(&mut self, pat: &mut P<Pat>) {
648                 if let PatKind::Ident(BindingAnnotation(ByRef::No, m @ Mutability::Not), ..) =
649                     &mut pat.kind
650                 {
651                     self.0 = true;
652                     *m = Mutability::Mut;
653                 }
654                 noop_visit_pat(pat, self);
655             }
656         }
657
658         let mut add_mut = AddMut(false);
659         add_mut.visit_pat(pat);
660         add_mut.0
661     }
662
663     /// Error on `mut $pat` where `$pat` is not an ident.
664     fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
665         let span = lo.to(pat.span);
666         let fix = pprust::pat_to_string(&pat);
667         let (problem, suggestion) = if changed_any_binding {
668             ("`mut` must be attached to each individual binding", "add `mut` to each binding")
669         } else {
670             ("`mut` must be followed by a named binding", "remove the `mut` prefix")
671         };
672         self.struct_span_err(span, problem)
673             .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable)
674             .note("`mut` may be followed by `variable` and `variable @ pattern`")
675             .emit();
676     }
677
678     /// Eat any extraneous `mut`s and error + recover if we ate any.
679     fn recover_additional_muts(&mut self) {
680         let lo = self.token.span;
681         while self.eat_keyword(kw::Mut) {}
682         if lo == self.token.span {
683             return;
684         }
685
686         let span = lo.to(self.prev_token.span);
687         self.struct_span_err(span, "`mut` on a binding may not be repeated")
688             .span_suggestion(
689                 span,
690                 "remove the additional `mut`s",
691                 "",
692                 Applicability::MachineApplicable,
693             )
694             .emit();
695     }
696
697     /// Parse macro invocation
698     fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
699         self.bump();
700         let args = self.parse_delim_args()?;
701         let mac = P(MacCall { path, args, prior_type_ascription: self.last_type_ascription });
702         Ok(PatKind::MacCall(mac))
703     }
704
705     fn fatal_unexpected_non_pat(
706         &mut self,
707         err: DiagnosticBuilder<'a, ErrorGuaranteed>,
708         expected: Expected,
709     ) -> PResult<'a, P<Pat>> {
710         err.cancel();
711
712         let expected = expected.unwrap_or("pattern");
713         let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token));
714
715         let mut err = self.struct_span_err(self.token.span, &msg);
716         err.span_label(self.token.span, format!("expected {}", expected));
717
718         let sp = self.sess.source_map().start_point(self.token.span);
719         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
720             err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
721         }
722
723         Err(err)
724     }
725
726     /// Parses the range pattern end form `".." | "..." | "..=" ;`.
727     fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
728         let re = if self.eat(&token::DotDotDot) {
729             RangeEnd::Included(RangeSyntax::DotDotDot)
730         } else if self.eat(&token::DotDotEq) {
731             RangeEnd::Included(RangeSyntax::DotDotEq)
732         } else if self.eat(&token::DotDot) {
733             RangeEnd::Excluded
734         } else {
735             return None;
736         };
737         Some(respan(self.prev_token.span, re))
738     }
739
740     /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
741     /// `$begin $form` has already been parsed.
742     fn parse_pat_range_begin_with(
743         &mut self,
744         begin: P<Expr>,
745         re: Spanned<RangeEnd>,
746     ) -> PResult<'a, PatKind> {
747         let end = if self.is_pat_range_end_start(0) {
748             // Parsing e.g. `X..=Y`.
749             Some(self.parse_pat_range_end()?)
750         } else {
751             // Parsing e.g. `X..`.
752             if let RangeEnd::Included(_) = re.node {
753                 // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
754                 self.inclusive_range_with_incorrect_end(re.span);
755             }
756             None
757         };
758         Ok(PatKind::Range(Some(begin), end, re))
759     }
760
761     pub(super) fn inclusive_range_with_incorrect_end(&mut self, span: Span) {
762         let tok = &self.token;
763
764         // If the user typed "..==" instead of "..=", we want to give them
765         // a specific error message telling them to use "..=".
766         // Otherwise, we assume that they meant to type a half open exclusive
767         // range and give them an error telling them to do that instead.
768         if matches!(tok.kind, token::Eq) && tok.span.lo() == span.hi() {
769             let span_with_eq = span.to(tok.span);
770
771             // Ensure the user doesn't receive unhelpful unexpected token errors
772             self.bump();
773             if self.is_pat_range_end_start(0) {
774                 let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
775             }
776
777             self.error_inclusive_range_with_extra_equals(span_with_eq);
778         } else {
779             self.error_inclusive_range_with_no_end(span);
780         }
781     }
782
783     fn error_inclusive_range_with_extra_equals(&self, span: Span) {
784         self.struct_span_err(span, "unexpected `=` after inclusive range")
785             .span_suggestion_short(span, "use `..=` instead", "..=", Applicability::MaybeIncorrect)
786             .note("inclusive ranges end with a single equals sign (`..=`)")
787             .emit();
788     }
789
790     fn error_inclusive_range_with_no_end(&self, span: Span) {
791         struct_span_err!(self.sess.span_diagnostic, span, E0586, "inclusive range with no end")
792             .span_suggestion_short(span, "use `..` instead", "..", Applicability::MachineApplicable)
793             .note("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)")
794             .emit();
795     }
796
797     /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
798     ///
799     /// The form `...X` is prohibited to reduce confusion with the potential
800     /// expression syntax `...expr` for splatting in expressions.
801     fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
802         let end = self.parse_pat_range_end()?;
803         if let RangeEnd::Included(syn @ RangeSyntax::DotDotDot) = &mut re.node {
804             *syn = RangeSyntax::DotDotEq;
805             self.struct_span_err(re.span, "range-to patterns with `...` are not allowed")
806                 .span_suggestion_short(
807                     re.span,
808                     "use `..=` instead",
809                     "..=",
810                     Applicability::MachineApplicable,
811                 )
812                 .emit();
813         }
814         Ok(PatKind::Range(None, Some(end), re))
815     }
816
817     /// Is the token `dist` away from the current suitable as the start of a range patterns end?
818     fn is_pat_range_end_start(&self, dist: usize) -> bool {
819         self.check_inline_const(dist)
820             || self.look_ahead(dist, |t| {
821                 t.is_path_start() // e.g. `MY_CONST`;
822                 || t.kind == token::Dot // e.g. `.5` for recovery;
823                 || t.can_begin_literal_maybe_minus() // e.g. `42`.
824                 || t.is_whole_expr()
825                 || t.is_lifetime() // recover `'a` instead of `'a'`
826             })
827     }
828
829     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
830         if self.check_inline_const(0) {
831             self.parse_const_block(self.token.span, true)
832         } else if self.check_path() {
833             let lo = self.token.span;
834             let (qself, path) = if self.eat_lt() {
835                 // Parse a qualified path
836                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
837                 (Some(qself), path)
838             } else {
839                 // Parse an unqualified path
840                 (None, self.parse_path(PathStyle::Expr)?)
841             };
842             let hi = self.prev_token.span;
843             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
844         } else {
845             self.parse_literal_maybe_minus()
846         }
847     }
848
849     /// Is this the start of a pattern beginning with a path?
850     fn is_start_of_pat_with_path(&mut self) -> bool {
851         self.check_path()
852         // Just for recovery (see `can_be_ident`).
853         || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
854     }
855
856     /// Would `parse_pat_ident` be appropriate here?
857     fn can_be_ident_pat(&mut self) -> bool {
858         self.check_ident()
859         && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
860         && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
861         // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
862         && !self.token.is_keyword(kw::In)
863         // Try to do something more complex?
864         && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(Delimiter::Parenthesis) // A tuple struct pattern.
865             | token::OpenDelim(Delimiter::Brace) // A struct pattern.
866             | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
867             | token::ModSep // A tuple / struct variant pattern.
868             | token::Not)) // A macro expanding to a pattern.
869     }
870
871     /// Parses `ident` or `ident @ pat`.
872     /// Used by the copy foo and ref foo patterns to give a good
873     /// error message when parsing mistakes like `ref foo(a, b)`.
874     fn parse_pat_ident(&mut self, binding_annotation: BindingAnnotation) -> PResult<'a, PatKind> {
875         let ident = self.parse_ident()?;
876         let sub = if self.eat(&token::At) {
877             Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
878         } else {
879             None
880         };
881
882         // Just to be friendly, if they write something like `ref Some(i)`,
883         // we end up here with `(` as the current token.
884         // This shortly leads to a parse error. Note that if there is no explicit
885         // binding mode then we do not end up here, because the lookahead
886         // will direct us over to `parse_enum_variant()`.
887         if self.token == token::OpenDelim(Delimiter::Parenthesis) {
888             return Err(self
889                 .struct_span_err(self.prev_token.span, "expected identifier, found enum pattern"));
890         }
891
892         Ok(PatKind::Ident(binding_annotation, ident, sub))
893     }
894
895     /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
896     fn parse_pat_struct(&mut self, qself: Option<P<QSelf>>, path: Path) -> PResult<'a, PatKind> {
897         if qself.is_some() {
898             // Feature gate the use of qualified paths in patterns
899             self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
900         }
901         self.bump();
902         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
903             e.span_label(path.span, "while parsing the fields for this pattern");
904             e.emit();
905             self.recover_stmt();
906             (vec![], true)
907         });
908         self.bump();
909         Ok(PatKind::Struct(qself, path, fields, etc))
910     }
911
912     /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
913     fn parse_pat_tuple_struct(
914         &mut self,
915         qself: Option<P<QSelf>>,
916         path: Path,
917     ) -> PResult<'a, PatKind> {
918         let (fields, _) = self.parse_paren_comma_seq(|p| {
919             p.parse_pat_allow_top_alt(
920                 None,
921                 RecoverComma::No,
922                 RecoverColon::No,
923                 CommaRecoveryMode::EitherTupleOrPipe,
924             )
925         })?;
926         if qself.is_some() {
927             self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
928         }
929         Ok(PatKind::TupleStruct(qself, path, fields))
930     }
931
932     /// Are we sure this could not possibly be the start of a pattern?
933     ///
934     /// Currently, this only accounts for tokens that can follow identifiers
935     /// in patterns, but this can be extended as necessary.
936     fn isnt_pattern_start(&self) -> bool {
937         [
938             token::Eq,
939             token::Colon,
940             token::Comma,
941             token::Semi,
942             token::At,
943             token::OpenDelim(Delimiter::Brace),
944             token::CloseDelim(Delimiter::Brace),
945             token::CloseDelim(Delimiter::Parenthesis),
946         ]
947         .contains(&self.token.kind)
948     }
949
950     /// Parses `box pat`
951     fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
952         let box_span = self.prev_token.span;
953
954         if self.isnt_pattern_start() {
955             self.struct_span_err(
956                 self.token.span,
957                 format!("expected pattern, found {}", super::token_descr(&self.token)),
958             )
959             .span_note(box_span, "`box` is a reserved keyword")
960             .span_suggestion_verbose(
961                 box_span.shrink_to_lo(),
962                 "escape `box` to use it as an identifier",
963                 "r#",
964                 Applicability::MaybeIncorrect,
965             )
966             .emit();
967
968             // We cannot use `parse_pat_ident()` since it will complain `box`
969             // is not an identifier.
970             let sub = if self.eat(&token::At) {
971                 Some(self.parse_pat_no_top_alt(Some("binding pattern"))?)
972             } else {
973                 None
974             };
975
976             Ok(PatKind::Ident(BindingAnnotation::NONE, Ident::new(kw::Box, box_span), sub))
977         } else {
978             let pat = self.parse_pat_with_range_pat(false, None)?;
979             self.sess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span));
980             Ok(PatKind::Box(pat))
981         }
982     }
983
984     /// Parses the fields of a struct-like pattern.
985     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<PatField>, bool)> {
986         let mut fields = Vec::new();
987         let mut etc = false;
988         let mut ate_comma = true;
989         let mut delayed_err: Option<DiagnosticBuilder<'a, ErrorGuaranteed>> = None;
990         let mut etc_span = None;
991
992         while self.token != token::CloseDelim(Delimiter::Brace) {
993             let attrs = match self.parse_outer_attributes() {
994                 Ok(attrs) => attrs,
995                 Err(err) => {
996                     if let Some(mut delayed) = delayed_err {
997                         delayed.emit();
998                     }
999                     return Err(err);
1000                 }
1001             };
1002             let lo = self.token.span;
1003
1004             // check that a comma comes after every field
1005             if !ate_comma {
1006                 let err = self.struct_span_err(self.token.span, "expected `,`");
1007                 if let Some(mut delayed) = delayed_err {
1008                     delayed.emit();
1009                 }
1010                 return Err(err);
1011             }
1012             ate_comma = false;
1013
1014             if self.check(&token::DotDot) || self.token == token::DotDotDot {
1015                 etc = true;
1016                 let mut etc_sp = self.token.span;
1017
1018                 self.recover_one_fewer_dotdot();
1019                 self.bump(); // `..` || `...`
1020
1021                 if self.token == token::CloseDelim(Delimiter::Brace) {
1022                     etc_span = Some(etc_sp);
1023                     break;
1024                 }
1025                 let token_str = super::token_descr(&self.token);
1026                 let msg = &format!("expected `}}`, found {}", token_str);
1027                 let mut err = self.struct_span_err(self.token.span, msg);
1028
1029                 err.span_label(self.token.span, "expected `}`");
1030                 let mut comma_sp = None;
1031                 if self.token == token::Comma {
1032                     // Issue #49257
1033                     let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span);
1034                     etc_sp = etc_sp.to(nw_span);
1035                     err.span_label(
1036                         etc_sp,
1037                         "`..` must be at the end and cannot have a trailing comma",
1038                     );
1039                     comma_sp = Some(self.token.span);
1040                     self.bump();
1041                     ate_comma = true;
1042                 }
1043
1044                 etc_span = Some(etc_sp.until(self.token.span));
1045                 if self.token == token::CloseDelim(Delimiter::Brace) {
1046                     // If the struct looks otherwise well formed, recover and continue.
1047                     if let Some(sp) = comma_sp {
1048                         err.span_suggestion_short(
1049                             sp,
1050                             "remove this comma",
1051                             "",
1052                             Applicability::MachineApplicable,
1053                         );
1054                     }
1055                     err.emit();
1056                     break;
1057                 } else if self.token.is_ident() && ate_comma {
1058                     // Accept fields coming after `..,`.
1059                     // This way we avoid "pattern missing fields" errors afterwards.
1060                     // We delay this error until the end in order to have a span for a
1061                     // suggested fix.
1062                     if let Some(mut delayed_err) = delayed_err {
1063                         delayed_err.emit();
1064                         return Err(err);
1065                     } else {
1066                         delayed_err = Some(err);
1067                     }
1068                 } else {
1069                     if let Some(mut err) = delayed_err {
1070                         err.emit();
1071                     }
1072                     return Err(err);
1073                 }
1074             }
1075
1076             let field =
1077                 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1078                     let field = match this.parse_pat_field(lo, attrs) {
1079                         Ok(field) => Ok(field),
1080                         Err(err) => {
1081                             if let Some(mut delayed_err) = delayed_err.take() {
1082                                 delayed_err.emit();
1083                             }
1084                             return Err(err);
1085                         }
1086                     }?;
1087                     ate_comma = this.eat(&token::Comma);
1088                     // We just ate a comma, so there's no need to use
1089                     // `TrailingToken::Comma`
1090                     Ok((field, TrailingToken::None))
1091                 })?;
1092
1093             fields.push(field)
1094         }
1095
1096         if let Some(mut err) = delayed_err {
1097             if let Some(etc_span) = etc_span {
1098                 err.multipart_suggestion(
1099                     "move the `..` to the end of the field list",
1100                     vec![
1101                         (etc_span, String::new()),
1102                         (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
1103                     ],
1104                     Applicability::MachineApplicable,
1105                 );
1106             }
1107             err.emit();
1108         }
1109         Ok((fields, etc))
1110     }
1111
1112     /// Recover on `...` as if it were `..` to avoid further errors.
1113     /// See issue #46718.
1114     fn recover_one_fewer_dotdot(&self) {
1115         if self.token != token::DotDotDot {
1116             return;
1117         }
1118
1119         self.struct_span_err(self.token.span, "expected field pattern, found `...`")
1120             .span_suggestion(
1121                 self.token.span,
1122                 "to omit remaining fields, use one fewer `.`",
1123                 "..",
1124                 Applicability::MachineApplicable,
1125             )
1126             .emit();
1127     }
1128
1129     fn parse_pat_field(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, PatField> {
1130         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1131         let hi;
1132         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1133             // Parsing a pattern of the form `fieldname: pat`.
1134             let fieldname = self.parse_field_name()?;
1135             self.bump();
1136             let pat = self.parse_pat_allow_top_alt(
1137                 None,
1138                 RecoverComma::No,
1139                 RecoverColon::No,
1140                 CommaRecoveryMode::EitherTupleOrPipe,
1141             )?;
1142             hi = pat.span;
1143             (pat, fieldname, false)
1144         } else {
1145             // Parsing a pattern of the form `(box) (ref) (mut) fieldname`.
1146             let is_box = self.eat_keyword(kw::Box);
1147             let boxed_span = self.token.span;
1148             let is_ref = self.eat_keyword(kw::Ref);
1149             let is_mut = self.eat_keyword(kw::Mut);
1150             let fieldname = self.parse_field_name()?;
1151             hi = self.prev_token.span;
1152
1153             let mutability = match is_mut {
1154                 false => Mutability::Not,
1155                 true => Mutability::Mut,
1156             };
1157             let ann = BindingAnnotation(ByRef::from(is_ref), mutability);
1158             let fieldpat = self.mk_pat_ident(boxed_span.to(hi), ann, fieldname);
1159             let subpat =
1160                 if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat };
1161             (subpat, fieldname, true)
1162         };
1163
1164         Ok(PatField {
1165             ident: fieldname,
1166             pat: subpat,
1167             is_shorthand,
1168             attrs,
1169             id: ast::DUMMY_NODE_ID,
1170             span: lo.to(hi),
1171             is_placeholder: false,
1172         })
1173     }
1174
1175     pub(super) fn mk_pat_ident(&self, span: Span, ann: BindingAnnotation, ident: Ident) -> P<Pat> {
1176         self.mk_pat(span, PatKind::Ident(ann, ident, None))
1177     }
1178
1179     pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> {
1180         P(Pat { kind, span, id: ast::DUMMY_NODE_ID, tokens: None })
1181     }
1182 }