]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/diagnostics.rs
Rollup merge of #105497 - albertlarsan68:doc-panic-hook-and-catch-unwind, r=m-ou-se
[rust.git] / compiler / rustc_parse / src / parser / diagnostics.rs
1 use super::pat::Expected;
2 use super::{
3     BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep,
4     TokenExpectType, TokenType,
5 };
6 use crate::errors::{
7     AmbiguousPlus, AttributeOnParamType, BadQPathStage2, BadTypePlus, BadTypePlusSub,
8     ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
9     ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
10     DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11     GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12     IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13     ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14     QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
15     StructLiteralBodyWithoutPathSugg, SuggEscapeToUseAsIdentifier, SuggRemoveComma,
16     UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
17     UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
18 };
19
20 use crate::lexer::UnmatchedBrace;
21 use crate::parser;
22 use rustc_ast as ast;
23 use rustc_ast::ptr::P;
24 use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};
25 use rustc_ast::util::parser::AssocOp;
26 use rustc_ast::{
27     AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingAnnotation, Block,
28     BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
29     Path, PathSegment, QSelf, Ty, TyKind,
30 };
31 use rustc_ast_pretty::pprust;
32 use rustc_data_structures::fx::FxHashSet;
33 use rustc_errors::{
34     fluent, Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult,
35 };
36 use rustc_errors::{pluralize, Diagnostic, ErrorGuaranteed, IntoDiagnostic};
37 use rustc_session::errors::ExprParenthesesNeeded;
38 use rustc_span::source_map::Spanned;
39 use rustc_span::symbol::{kw, sym, Ident};
40 use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
41 use std::mem::take;
42 use std::ops::{Deref, DerefMut};
43 use thin_vec::{thin_vec, ThinVec};
44
45 /// Creates a placeholder argument.
46 pub(super) fn dummy_arg(ident: Ident) -> Param {
47     let pat = P(Pat {
48         id: ast::DUMMY_NODE_ID,
49         kind: PatKind::Ident(BindingAnnotation::NONE, ident, None),
50         span: ident.span,
51         tokens: None,
52     });
53     let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
54     Param {
55         attrs: AttrVec::default(),
56         id: ast::DUMMY_NODE_ID,
57         pat,
58         span: ident.span,
59         ty: P(ty),
60         is_placeholder: false,
61     }
62 }
63
64 pub(super) trait RecoverQPath: Sized + 'static {
65     const PATH_STYLE: PathStyle = PathStyle::Expr;
66     fn to_ty(&self) -> Option<P<Ty>>;
67     fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
68 }
69
70 impl RecoverQPath for Ty {
71     const PATH_STYLE: PathStyle = PathStyle::Type;
72     fn to_ty(&self) -> Option<P<Ty>> {
73         Some(P(self.clone()))
74     }
75     fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
76         Self {
77             span: path.span,
78             kind: TyKind::Path(qself, path),
79             id: ast::DUMMY_NODE_ID,
80             tokens: None,
81         }
82     }
83 }
84
85 impl RecoverQPath for Pat {
86     fn to_ty(&self) -> Option<P<Ty>> {
87         self.to_ty()
88     }
89     fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
90         Self {
91             span: path.span,
92             kind: PatKind::Path(qself, path),
93             id: ast::DUMMY_NODE_ID,
94             tokens: None,
95         }
96     }
97 }
98
99 impl RecoverQPath for Expr {
100     fn to_ty(&self) -> Option<P<Ty>> {
101         self.to_ty()
102     }
103     fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
104         Self {
105             span: path.span,
106             kind: ExprKind::Path(qself, path),
107             attrs: AttrVec::new(),
108             id: ast::DUMMY_NODE_ID,
109             tokens: None,
110         }
111     }
112 }
113
114 /// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`.
115 pub(crate) enum ConsumeClosingDelim {
116     Yes,
117     No,
118 }
119
120 #[derive(Clone, Copy)]
121 pub enum AttemptLocalParseRecovery {
122     Yes,
123     No,
124 }
125
126 impl AttemptLocalParseRecovery {
127     pub fn yes(&self) -> bool {
128         match self {
129             AttemptLocalParseRecovery::Yes => true,
130             AttemptLocalParseRecovery::No => false,
131         }
132     }
133
134     pub fn no(&self) -> bool {
135         match self {
136             AttemptLocalParseRecovery::Yes => false,
137             AttemptLocalParseRecovery::No => true,
138         }
139     }
140 }
141
142 /// Information for emitting suggestions and recovering from
143 /// C-style `i++`, `--i`, etc.
144 #[derive(Debug, Copy, Clone)]
145 struct IncDecRecovery {
146     /// Is this increment/decrement its own statement?
147     standalone: IsStandalone,
148     /// Is this an increment or decrement?
149     op: IncOrDec,
150     /// Is this pre- or postfix?
151     fixity: UnaryFixity,
152 }
153
154 /// Is an increment or decrement expression its own statement?
155 #[derive(Debug, Copy, Clone)]
156 enum IsStandalone {
157     /// It's standalone, i.e., its own statement.
158     Standalone,
159     /// It's a subexpression, i.e., *not* standalone.
160     Subexpr,
161 }
162
163 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
164 enum IncOrDec {
165     Inc,
166     // FIXME: `i--` recovery isn't implemented yet
167     #[allow(dead_code)]
168     Dec,
169 }
170
171 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
172 enum UnaryFixity {
173     Pre,
174     Post,
175 }
176
177 impl IncOrDec {
178     fn chr(&self) -> char {
179         match self {
180             Self::Inc => '+',
181             Self::Dec => '-',
182         }
183     }
184
185     fn name(&self) -> &'static str {
186         match self {
187             Self::Inc => "increment",
188             Self::Dec => "decrement",
189         }
190     }
191 }
192
193 impl std::fmt::Display for UnaryFixity {
194     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195         match self {
196             Self::Pre => write!(f, "prefix"),
197             Self::Post => write!(f, "postfix"),
198         }
199     }
200 }
201
202 struct MultiSugg {
203     msg: String,
204     patches: Vec<(Span, String)>,
205     applicability: Applicability,
206 }
207
208 impl MultiSugg {
209     fn emit(self, err: &mut Diagnostic) {
210         err.multipart_suggestion(&self.msg, self.patches, self.applicability);
211     }
212
213     fn emit_verbose(self, err: &mut Diagnostic) {
214         err.multipart_suggestion_verbose(&self.msg, self.patches, self.applicability);
215     }
216 }
217
218 /// SnapshotParser is used to create a snapshot of the parser
219 /// without causing duplicate errors being emitted when the `Parser`
220 /// is dropped.
221 pub struct SnapshotParser<'a> {
222     parser: Parser<'a>,
223     unclosed_delims: Vec<UnmatchedBrace>,
224 }
225
226 impl<'a> Deref for SnapshotParser<'a> {
227     type Target = Parser<'a>;
228
229     fn deref(&self) -> &Self::Target {
230         &self.parser
231     }
232 }
233
234 impl<'a> DerefMut for SnapshotParser<'a> {
235     fn deref_mut(&mut self) -> &mut Self::Target {
236         &mut self.parser
237     }
238 }
239
240 impl<'a> Parser<'a> {
241     #[rustc_lint_diagnostics]
242     pub fn struct_span_err<S: Into<MultiSpan>>(
243         &self,
244         sp: S,
245         m: impl Into<DiagnosticMessage>,
246     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
247         self.sess.span_diagnostic.struct_span_err(sp, m)
248     }
249
250     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<DiagnosticMessage>) -> ! {
251         self.sess.span_diagnostic.span_bug(sp, m)
252     }
253
254     pub(super) fn diagnostic(&self) -> &'a Handler {
255         &self.sess.span_diagnostic
256     }
257
258     /// Replace `self` with `snapshot.parser` and extend `unclosed_delims` with `snapshot.unclosed_delims`.
259     /// This is to avoid losing unclosed delims errors `create_snapshot_for_diagnostic` clears.
260     pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
261         *self = snapshot.parser;
262         self.unclosed_delims.extend(snapshot.unclosed_delims);
263     }
264
265     pub fn unclosed_delims(&self) -> &[UnmatchedBrace] {
266         &self.unclosed_delims
267     }
268
269     /// Create a snapshot of the `Parser`.
270     pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
271         let mut snapshot = self.clone();
272         let unclosed_delims = self.unclosed_delims.clone();
273         // Clear `unclosed_delims` in snapshot to avoid
274         // duplicate errors being emitted when the `Parser`
275         // is dropped (which may or may not happen, depending
276         // if the parsing the snapshot is created for is successful)
277         snapshot.unclosed_delims.clear();
278         SnapshotParser { parser: snapshot, unclosed_delims }
279     }
280
281     pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
282         self.sess.source_map().span_to_snippet(span)
283     }
284
285     pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
286         let valid_follow = &[
287             TokenKind::Eq,
288             TokenKind::Colon,
289             TokenKind::Comma,
290             TokenKind::Semi,
291             TokenKind::ModSep,
292             TokenKind::OpenDelim(Delimiter::Brace),
293             TokenKind::OpenDelim(Delimiter::Parenthesis),
294             TokenKind::CloseDelim(Delimiter::Brace),
295             TokenKind::CloseDelim(Delimiter::Parenthesis),
296         ];
297         let suggest_raw = match self.token.ident() {
298             Some((ident, false))
299                 if ident.is_raw_guess()
300                     && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) =>
301             {
302                 Some(SuggEscapeToUseAsIdentifier {
303                     span: ident.span.shrink_to_lo(),
304                     // `Symbol::to_string()` is different from `Symbol::into_diagnostic_arg()`,
305                     // which uses `Symbol::to_ident_string()` and "helpfully" adds an implicit `r#`
306                     ident_name: ident.name.to_string(),
307                 })
308             }
309             _ => None,
310         };
311
312         let suggest_remove_comma =
313             if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
314                 Some(SuggRemoveComma { span: self.token.span })
315             } else {
316                 None
317             };
318
319         let err = ExpectedIdentifier {
320             span: self.token.span,
321             token: self.token.clone(),
322             suggest_raw,
323             suggest_remove_comma,
324         };
325         err.into_diagnostic(&self.sess.span_diagnostic)
326     }
327
328     pub(super) fn expected_one_of_not_found(
329         &mut self,
330         edible: &[TokenKind],
331         inedible: &[TokenKind],
332     ) -> PResult<'a, bool /* recovered */> {
333         debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
334         fn tokens_to_string(tokens: &[TokenType]) -> String {
335             let mut i = tokens.iter();
336             // This might be a sign we need a connect method on `Iterator`.
337             let b = i.next().map_or_else(String::new, |t| t.to_string());
338             i.enumerate().fold(b, |mut b, (i, a)| {
339                 if tokens.len() > 2 && i == tokens.len() - 2 {
340                     b.push_str(", or ");
341                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
342                     b.push_str(" or ");
343                 } else {
344                     b.push_str(", ");
345                 }
346                 b.push_str(&a.to_string());
347                 b
348             })
349         }
350
351         let mut expected = edible
352             .iter()
353             .map(|x| TokenType::Token(x.clone()))
354             .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
355             .chain(self.expected_tokens.iter().cloned())
356             .filter_map(|token| {
357                 // filter out suggestions which suggest the same token which was found and deemed incorrect
358                 fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool {
359                     if let TokenKind::Ident(current_sym, _) = found {
360                         if let TokenType::Keyword(suggested_sym) = expected {
361                             return current_sym == suggested_sym;
362                         }
363                     }
364                     false
365                 }
366                 if token != parser::TokenType::Token(self.token.kind.clone()) {
367                     let eq = is_ident_eq_keyword(&self.token.kind, &token);
368                     // if the suggestion is a keyword and the found token is an ident,
369                     // the content of which are equal to the suggestion's content,
370                     // we can remove that suggestion (see the return None statement below)
371
372                     // if this isn't the case however, and the suggestion is a token the
373                     // content of which is the same as the found token's, we remove it as well
374                     if !eq {
375                         if let TokenType::Token(kind) = &token {
376                             if kind == &self.token.kind {
377                                 return None;
378                             }
379                         }
380                         return Some(token);
381                     }
382                 }
383                 return None;
384             })
385             .collect::<Vec<_>>();
386         expected.sort_by_cached_key(|x| x.to_string());
387         expected.dedup();
388
389         let sm = self.sess.source_map();
390
391         // Special-case "expected `;`" errors
392         if expected.contains(&TokenType::Token(token::Semi)) {
393             if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
394                 // Likely inside a macro, can't provide meaningful suggestions.
395             } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
396                 // The current token is in the same line as the prior token, not recoverable.
397             } else if [token::Comma, token::Colon].contains(&self.token.kind)
398                 && self.prev_token.kind == token::CloseDelim(Delimiter::Parenthesis)
399             {
400                 // Likely typo: The current token is on a new line and is expected to be
401                 // `.`, `;`, `?`, or an operator after a close delimiter token.
402                 //
403                 // let a = std::process::Command::new("echo")
404                 //         .arg("1")
405                 //         ,arg("2")
406                 //         ^
407                 // https://github.com/rust-lang/rust/issues/72253
408             } else if self.look_ahead(1, |t| {
409                 t == &token::CloseDelim(Delimiter::Brace)
410                     || t.can_begin_expr() && t.kind != token::Colon
411             }) && [token::Comma, token::Colon].contains(&self.token.kind)
412             {
413                 // Likely typo: `,` â†’ `;` or `:` â†’ `;`. This is triggered if the current token is
414                 // either `,` or `:`, and the next token could either start a new statement or is a
415                 // block close. For example:
416                 //
417                 //   let x = 32:
418                 //   let y = 42;
419                 self.sess.emit_err(ExpectedSemi {
420                     span: self.token.span,
421                     token: self.token.clone(),
422                     unexpected_token_label: None,
423                     sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
424                 });
425                 self.bump();
426                 return Ok(true);
427             } else if self.look_ahead(0, |t| {
428                 t == &token::CloseDelim(Delimiter::Brace)
429                     || ((t.can_begin_expr() || t.can_begin_item())
430                         && t != &token::Semi
431                         && t != &token::Pound)
432                     // Avoid triggering with too many trailing `#` in raw string.
433                     || (sm.is_multiline(
434                         self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
435                     ) && t == &token::Pound)
436             }) && !expected.contains(&TokenType::Token(token::Comma))
437             {
438                 // Missing semicolon typo. This is triggered if the next token could either start a
439                 // new statement or is a block close. For example:
440                 //
441                 //   let x = 32
442                 //   let y = 42;
443                 let span = self.prev_token.span.shrink_to_hi();
444                 self.sess.emit_err(ExpectedSemi {
445                     span,
446                     token: self.token.clone(),
447                     unexpected_token_label: Some(self.token.span),
448                     sugg: ExpectedSemiSugg::AddSemi(span),
449                 });
450                 return Ok(true);
451             }
452         }
453
454         if self.token.kind == TokenKind::EqEq
455             && self.prev_token.is_ident()
456             && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq)))
457         {
458             // Likely typo: `=` â†’ `==` in let expr or enum item
459             return Err(self.sess.create_err(UseEqInstead { span: self.token.span }));
460         }
461
462         let expect = tokens_to_string(&expected);
463         let actual = super::token_descr(&self.token);
464         let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
465             let short_expect = if expected.len() > 6 {
466                 format!("{} possible tokens", expected.len())
467             } else {
468                 expect.clone()
469             };
470             (
471                 format!("expected one of {expect}, found {actual}"),
472                 (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")),
473             )
474         } else if expected.is_empty() {
475             (
476                 format!("unexpected token: {actual}"),
477                 (self.prev_token.span, "unexpected token after this".to_string()),
478             )
479         } else {
480             (
481                 format!("expected {expect}, found {actual}"),
482                 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
483             )
484         };
485         self.last_unexpected_token_span = Some(self.token.span);
486         // FIXME: translation requires list formatting (for `expect`)
487         let mut err = self.struct_span_err(self.token.span, &msg_exp);
488
489         if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
490             if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
491                 err.span_suggestion_short(
492                     self.prev_token.span,
493                     &format!("write `fn` instead of `{symbol}` to declare a function"),
494                     "fn",
495                     Applicability::MachineApplicable,
496                 );
497             }
498         }
499
500         // `pub` may be used for an item or `pub(crate)`
501         if self.prev_token.is_ident_named(sym::public)
502             && (self.token.can_begin_item()
503                 || self.token.kind == TokenKind::OpenDelim(Delimiter::Parenthesis))
504         {
505             err.span_suggestion_short(
506                 self.prev_token.span,
507                 "write `pub` instead of `public` to make the item public",
508                 "pub",
509                 Applicability::MachineApplicable,
510             );
511         }
512
513         // Add suggestion for a missing closing angle bracket if '>' is included in expected_tokens
514         // there are unclosed angle brackets
515         if self.unmatched_angle_bracket_count > 0
516             && self.token.kind == TokenKind::Eq
517             && expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Gt)))
518         {
519             err.span_label(self.prev_token.span, "maybe try to close unmatched angle bracket");
520         }
521
522         let sp = if self.token == token::Eof {
523             // This is EOF; don't want to point at the following char, but rather the last token.
524             self.prev_token.span
525         } else {
526             label_sp
527         };
528         match self.recover_closing_delimiter(
529             &expected
530                 .iter()
531                 .filter_map(|tt| match tt {
532                     TokenType::Token(t) => Some(t.clone()),
533                     _ => None,
534                 })
535                 .collect::<Vec<_>>(),
536             err,
537         ) {
538             Err(e) => err = e,
539             Ok(recovered) => {
540                 return Ok(recovered);
541             }
542         }
543
544         if self.check_too_many_raw_str_terminators(&mut err) {
545             if expected.contains(&TokenType::Token(token::Semi)) && self.eat(&token::Semi) {
546                 err.emit();
547                 return Ok(true);
548             } else {
549                 return Err(err);
550             }
551         }
552
553         if self.prev_token.span == DUMMY_SP {
554             // Account for macro context where the previous span might not be
555             // available to avoid incorrect output (#54841).
556             err.span_label(self.token.span, label_exp);
557         } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
558             // When the spans are in the same line, it means that the only content between
559             // them is whitespace, point at the found token in that case:
560             //
561             // X |     () => { syntax error };
562             //   |                    ^^^^^ expected one of 8 possible tokens here
563             //
564             // instead of having:
565             //
566             // X |     () => { syntax error };
567             //   |                   -^^^^^ unexpected token
568             //   |                   |
569             //   |                   expected one of 8 possible tokens here
570             err.span_label(self.token.span, label_exp);
571         } else {
572             err.span_label(sp, label_exp);
573             err.span_label(self.token.span, "unexpected token");
574         }
575         self.maybe_annotate_with_ascription(&mut err, false);
576         Err(err)
577     }
578
579     fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
580         let sm = self.sess.source_map();
581         match (&self.prev_token.kind, &self.token.kind) {
582             (
583                 TokenKind::Literal(Lit {
584                     kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
585                     ..
586                 }),
587                 TokenKind::Pound,
588             ) if !sm.is_multiline(
589                 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
590             ) =>
591             {
592                 let n_hashes: u8 = *n_hashes;
593                 err.set_primary_message("too many `#` when terminating raw string");
594                 let str_span = self.prev_token.span;
595                 let mut span = self.token.span;
596                 let mut count = 0;
597                 while self.token.kind == TokenKind::Pound
598                     && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
599                 {
600                     span = span.with_hi(self.token.span.hi());
601                     self.bump();
602                     count += 1;
603                 }
604                 err.set_span(span);
605                 err.span_suggestion(
606                     span,
607                     &format!("remove the extra `#`{}", pluralize!(count)),
608                     "",
609                     Applicability::MachineApplicable,
610                 );
611                 err.span_label(
612                     str_span,
613                     &format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
614                 );
615                 true
616             }
617             _ => false,
618         }
619     }
620
621     pub fn maybe_suggest_struct_literal(
622         &mut self,
623         lo: Span,
624         s: BlockCheckMode,
625     ) -> Option<PResult<'a, P<Block>>> {
626         if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
627             // We might be having a struct literal where people forgot to include the path:
628             // fn foo() -> Foo {
629             //     field: value,
630             // }
631             let mut snapshot = self.create_snapshot_for_diagnostic();
632             let path = Path {
633                 segments: ThinVec::new(),
634                 span: self.prev_token.span.shrink_to_lo(),
635                 tokens: None,
636             };
637             let struct_expr = snapshot.parse_struct_expr(None, path, false);
638             let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
639             return Some(match (struct_expr, block_tail) {
640                 (Ok(expr), Err(mut err)) => {
641                     // We have encountered the following:
642                     // fn foo() -> Foo {
643                     //     field: value,
644                     // }
645                     // Suggest:
646                     // fn foo() -> Foo { Path {
647                     //     field: value,
648                     // } }
649                     err.delay_as_bug();
650                     self.sess.emit_err(StructLiteralBodyWithoutPath {
651                         span: expr.span,
652                         sugg: StructLiteralBodyWithoutPathSugg {
653                             before: expr.span.shrink_to_lo(),
654                             after: expr.span.shrink_to_hi(),
655                         },
656                     });
657                     self.restore_snapshot(snapshot);
658                     let mut tail = self.mk_block(
659                         vec![self.mk_stmt_err(expr.span)],
660                         s,
661                         lo.to(self.prev_token.span),
662                     );
663                     tail.could_be_bare_literal = true;
664                     Ok(tail)
665                 }
666                 (Err(err), Ok(tail)) => {
667                     // We have a block tail that contains a somehow valid type ascription expr.
668                     err.cancel();
669                     Ok(tail)
670                 }
671                 (Err(snapshot_err), Err(err)) => {
672                     // We don't know what went wrong, emit the normal error.
673                     snapshot_err.cancel();
674                     self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
675                     Err(err)
676                 }
677                 (Ok(_), Ok(mut tail)) => {
678                     tail.could_be_bare_literal = true;
679                     Ok(tail)
680                 }
681             });
682         }
683         None
684     }
685
686     pub fn maybe_annotate_with_ascription(
687         &mut self,
688         err: &mut Diagnostic,
689         maybe_expected_semicolon: bool,
690     ) {
691         if let Some((sp, likely_path)) = self.last_type_ascription.take() {
692             let sm = self.sess.source_map();
693             let next_pos = sm.lookup_char_pos(self.token.span.lo());
694             let op_pos = sm.lookup_char_pos(sp.hi());
695
696             let allow_unstable = self.sess.unstable_features.is_nightly_build();
697
698             if likely_path {
699                 err.span_suggestion(
700                     sp,
701                     "maybe write a path separator here",
702                     "::",
703                     if allow_unstable {
704                         Applicability::MaybeIncorrect
705                     } else {
706                         Applicability::MachineApplicable
707                     },
708                 );
709                 self.sess.type_ascription_path_suggestions.borrow_mut().insert(sp);
710             } else if op_pos.line != next_pos.line && maybe_expected_semicolon {
711                 err.span_suggestion(
712                     sp,
713                     "try using a semicolon",
714                     ";",
715                     Applicability::MaybeIncorrect,
716                 );
717             } else if allow_unstable {
718                 err.span_label(sp, "tried to parse a type due to this type ascription");
719             } else {
720                 err.span_label(sp, "tried to parse a type due to this");
721             }
722             if allow_unstable {
723                 // Give extra information about type ascription only if it's a nightly compiler.
724                 err.note(
725                     "`#![feature(type_ascription)]` lets you annotate an expression with a type: \
726                      `<expr>: <type>`",
727                 );
728                 if !likely_path {
729                     // Avoid giving too much info when it was likely an unrelated typo.
730                     err.note(
731                         "see issue #23416 <https://github.com/rust-lang/rust/issues/23416> \
732                         for more information",
733                     );
734                 }
735             }
736         }
737     }
738
739     /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
740     /// passes through any errors encountered. Used for error recovery.
741     pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) {
742         if let Err(err) =
743             self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| {
744                 Ok(p.parse_token_tree())
745             })
746         {
747             err.cancel();
748         }
749     }
750
751     /// This function checks if there are trailing angle brackets and produces
752     /// a diagnostic to suggest removing them.
753     ///
754     /// ```ignore (diagnostic)
755     /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>();
756     ///                                                    ^^ help: remove extra angle brackets
757     /// ```
758     ///
759     /// If `true` is returned, then trailing brackets were recovered, tokens were consumed
760     /// up until one of the tokens in 'end' was encountered, and an error was emitted.
761     pub(super) fn check_trailing_angle_brackets(
762         &mut self,
763         segment: &PathSegment,
764         end: &[&TokenKind],
765     ) -> bool {
766         if !self.may_recover() {
767             return false;
768         }
769
770         // This function is intended to be invoked after parsing a path segment where there are two
771         // cases:
772         //
773         // 1. A specific token is expected after the path segment.
774         //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
775         //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
776         // 2. No specific token is expected after the path segment.
777         //    eg. `x.foo` (field access)
778         //
779         // This function is called after parsing `.foo` and before parsing the token `end` (if
780         // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
781         // `Foo::<Bar>`.
782
783         // We only care about trailing angle brackets if we previously parsed angle bracket
784         // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
785         // removed in this case:
786         //
787         // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
788         //
789         // This case is particularly tricky as we won't notice it just looking at the tokens -
790         // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
791         // have already been parsed):
792         //
793         // `x.foo::<u32>>>(3)`
794         let parsed_angle_bracket_args =
795             segment.args.as_ref().map_or(false, |args| args.is_angle_bracketed());
796
797         debug!(
798             "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
799             parsed_angle_bracket_args,
800         );
801         if !parsed_angle_bracket_args {
802             return false;
803         }
804
805         // Keep the span at the start so we can highlight the sequence of `>` characters to be
806         // removed.
807         let lo = self.token.span;
808
809         // We need to look-ahead to see if we have `>` characters without moving the cursor forward
810         // (since we might have the field access case and the characters we're eating are
811         // actual operators and not trailing characters - ie `x.foo >> 3`).
812         let mut position = 0;
813
814         // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
815         // many of each (so we can correctly pluralize our error messages) and continue to
816         // advance.
817         let mut number_of_shr = 0;
818         let mut number_of_gt = 0;
819         while self.look_ahead(position, |t| {
820             trace!("check_trailing_angle_brackets: t={:?}", t);
821             if *t == token::BinOp(token::BinOpToken::Shr) {
822                 number_of_shr += 1;
823                 true
824             } else if *t == token::Gt {
825                 number_of_gt += 1;
826                 true
827             } else {
828                 false
829             }
830         }) {
831             position += 1;
832         }
833
834         // If we didn't find any trailing `>` characters, then we have nothing to error about.
835         debug!(
836             "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
837             number_of_gt, number_of_shr,
838         );
839         if number_of_gt < 1 && number_of_shr < 1 {
840             return false;
841         }
842
843         // Finally, double check that we have our end token as otherwise this is the
844         // second case.
845         if self.look_ahead(position, |t| {
846             trace!("check_trailing_angle_brackets: t={:?}", t);
847             end.contains(&&t.kind)
848         }) {
849             // Eat from where we started until the end token so that parsing can continue
850             // as if we didn't have those extra angle brackets.
851             self.eat_to_tokens(end);
852             let span = lo.until(self.token.span);
853
854             let num_extra_brackets = number_of_gt + number_of_shr * 2;
855             self.sess.emit_err(UnmatchedAngleBrackets { span, num_extra_brackets });
856             return true;
857         }
858         false
859     }
860
861     /// Check if a method call with an intended turbofish has been written without surrounding
862     /// angle brackets.
863     pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
864         if !self.may_recover() {
865             return;
866         }
867
868         if token::ModSep == self.token.kind && segment.args.is_none() {
869             let snapshot = self.create_snapshot_for_diagnostic();
870             self.bump();
871             let lo = self.token.span;
872             match self.parse_angle_args(None) {
873                 Ok(args) => {
874                     let span = lo.to(self.prev_token.span);
875                     // Detect trailing `>` like in `x.collect::Vec<_>>()`.
876                     let mut trailing_span = self.prev_token.span.shrink_to_hi();
877                     while self.token.kind == token::BinOp(token::Shr)
878                         || self.token.kind == token::Gt
879                     {
880                         trailing_span = trailing_span.to(self.token.span);
881                         self.bump();
882                     }
883                     if self.token.kind == token::OpenDelim(Delimiter::Parenthesis) {
884                         // Recover from bad turbofish: `foo.collect::Vec<_>()`.
885                         let args = AngleBracketedArgs { args, span }.into();
886                         segment.args = args;
887
888                         self.sess.emit_err(GenericParamsWithoutAngleBrackets {
889                             span,
890                             sugg: GenericParamsWithoutAngleBracketsSugg {
891                                 left: span.shrink_to_lo(),
892                                 right: trailing_span,
893                             },
894                         });
895                     } else {
896                         // This doesn't look like an invalid turbofish, can't recover parse state.
897                         self.restore_snapshot(snapshot);
898                     }
899                 }
900                 Err(err) => {
901                     // We couldn't parse generic parameters, unlikely to be a turbofish. Rely on
902                     // generic parse error instead.
903                     err.cancel();
904                     self.restore_snapshot(snapshot);
905                 }
906             }
907         }
908     }
909
910     /// When writing a turbofish with multiple type parameters missing the leading `::`, we will
911     /// encounter a parse error when encountering the first `,`.
912     pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
913         &mut self,
914         mut e: DiagnosticBuilder<'a, ErrorGuaranteed>,
915         expr: &mut P<Expr>,
916     ) -> PResult<'a, ()> {
917         if let ExprKind::Binary(binop, _, _) = &expr.kind
918             && let ast::BinOpKind::Lt = binop.node
919             && self.eat(&token::Comma)
920         {
921             let x = self.parse_seq_to_before_end(
922                 &token::Gt,
923                 SeqSep::trailing_allowed(token::Comma),
924                 |p| p.parse_generic_arg(None),
925             );
926             match x {
927                 Ok((_, _, false)) => {
928                     if self.eat(&token::Gt) {
929                         e.span_suggestion_verbose(
930                             binop.span.shrink_to_lo(),
931                             fluent::parse_sugg_turbofish_syntax,
932                             "::",
933                             Applicability::MaybeIncorrect,
934                         )
935                         .emit();
936                         match self.parse_expr() {
937                             Ok(_) => {
938                                 *expr =
939                                     self.mk_expr_err(expr.span.to(self.prev_token.span));
940                                 return Ok(());
941                             }
942                             Err(err) => {
943                                 *expr = self.mk_expr_err(expr.span);
944                                 err.cancel();
945                             }
946                         }
947                     }
948                 }
949                 Err(err) => {
950                     err.cancel();
951                 }
952                 _ => {}
953             }
954         }
955         Err(e)
956     }
957
958     /// Check to see if a pair of chained operators looks like an attempt at chained comparison,
959     /// e.g. `1 < x <= 3`. If so, suggest either splitting the comparison into two, or
960     /// parenthesising the leftmost comparison.
961     fn attempt_chained_comparison_suggestion(
962         &mut self,
963         err: &mut ComparisonOperatorsCannotBeChained,
964         inner_op: &Expr,
965         outer_op: &Spanned<AssocOp>,
966     ) -> bool /* advanced the cursor */ {
967         if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
968             if let ExprKind::Field(_, ident) = l1.kind
969                 && ident.as_str().parse::<i32>().is_err()
970                 && !matches!(r1.kind, ExprKind::Lit(_))
971             {
972                 // The parser has encountered `foo.bar<baz`, the likelihood of the turbofish
973                 // suggestion being the only one to apply is high.
974                 return false;
975             }
976             return match (op.node, &outer_op.node) {
977                 // `x == y == z`
978                 (BinOpKind::Eq, AssocOp::Equal) |
979                 // `x < y < z` and friends.
980                 (BinOpKind::Lt, AssocOp::Less | AssocOp::LessEqual) |
981                 (BinOpKind::Le, AssocOp::LessEqual | AssocOp::Less) |
982                 // `x > y > z` and friends.
983                 (BinOpKind::Gt, AssocOp::Greater | AssocOp::GreaterEqual) |
984                 (BinOpKind::Ge, AssocOp::GreaterEqual | AssocOp::Greater) => {
985                     let expr_to_str = |e: &Expr| {
986                         self.span_to_snippet(e.span)
987                             .unwrap_or_else(|_| pprust::expr_to_string(&e))
988                     };
989                     err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
990                         span: inner_op.span.shrink_to_hi(),
991                         middle_term: expr_to_str(&r1),
992                     });
993                     false // Keep the current parse behavior, where the AST is `(x < y) < z`.
994                 }
995                 // `x == y < z`
996                 (BinOpKind::Eq, AssocOp::Less | AssocOp::LessEqual | AssocOp::Greater | AssocOp::GreaterEqual) => {
997                     // Consume `z`/outer-op-rhs.
998                     let snapshot = self.create_snapshot_for_diagnostic();
999                     match self.parse_expr() {
1000                         Ok(r2) => {
1001                             // We are sure that outer-op-rhs could be consumed, the suggestion is
1002                             // likely correct.
1003                             err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1004                                 left: r1.span.shrink_to_lo(),
1005                                 right: r2.span.shrink_to_hi(),
1006                             });
1007                             true
1008                         }
1009                         Err(expr_err) => {
1010                             expr_err.cancel();
1011                             self.restore_snapshot(snapshot);
1012                             false
1013                         }
1014                     }
1015                 }
1016                 // `x > y == z`
1017                 (BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge, AssocOp::Equal) => {
1018                     let snapshot = self.create_snapshot_for_diagnostic();
1019                     // At this point it is always valid to enclose the lhs in parentheses, no
1020                     // further checks are necessary.
1021                     match self.parse_expr() {
1022                         Ok(_) => {
1023                             err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1024                                 left: l1.span.shrink_to_lo(),
1025                                 right: r1.span.shrink_to_hi(),
1026                             });
1027                             true
1028                         }
1029                         Err(expr_err) => {
1030                             expr_err.cancel();
1031                             self.restore_snapshot(snapshot);
1032                             false
1033                         }
1034                     }
1035                 }
1036                 _ => false,
1037             };
1038         }
1039         false
1040     }
1041
1042     /// Produces an error if comparison operators are chained (RFC #558).
1043     /// We only need to check the LHS, not the RHS, because all comparison ops have same
1044     /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`).
1045     ///
1046     /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used
1047     /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the
1048     /// case.
1049     ///
1050     /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left
1051     /// associative we can infer that we have:
1052     ///
1053     /// ```text
1054     ///           outer_op
1055     ///           /   \
1056     ///     inner_op   r2
1057     ///        /  \
1058     ///      l1    r1
1059     /// ```
1060     pub(super) fn check_no_chained_comparison(
1061         &mut self,
1062         inner_op: &Expr,
1063         outer_op: &Spanned<AssocOp>,
1064     ) -> PResult<'a, Option<P<Expr>>> {
1065         debug_assert!(
1066             outer_op.node.is_comparison(),
1067             "check_no_chained_comparison: {:?} is not comparison",
1068             outer_op.node,
1069         );
1070
1071         let mk_err_expr = |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err)));
1072
1073         match &inner_op.kind {
1074             ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1075                 let mut err = ComparisonOperatorsCannotBeChained {
1076                     span: vec![op.span, self.prev_token.span],
1077                     suggest_turbofish: None,
1078                     help_turbofish: None,
1079                     chaining_sugg: None,
1080                 };
1081
1082                 // Include `<` to provide this recommendation even in a case like
1083                 // `Foo<Bar<Baz<Qux, ()>>>`
1084                 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Less
1085                     || outer_op.node == AssocOp::Greater
1086                 {
1087                     if outer_op.node == AssocOp::Less {
1088                         let snapshot = self.create_snapshot_for_diagnostic();
1089                         self.bump();
1090                         // So far we have parsed `foo<bar<`, consume the rest of the type args.
1091                         let modifiers =
1092                             [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)];
1093                         self.consume_tts(1, &modifiers);
1094
1095                         if !&[token::OpenDelim(Delimiter::Parenthesis), token::ModSep]
1096                             .contains(&self.token.kind)
1097                         {
1098                             // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the
1099                             // parser and bail out.
1100                             self.restore_snapshot(snapshot);
1101                         }
1102                     }
1103                     return if token::ModSep == self.token.kind {
1104                         // We have some certainty that this was a bad turbofish at this point.
1105                         // `foo< bar >::`
1106                         err.suggest_turbofish = Some(op.span.shrink_to_lo());
1107
1108                         let snapshot = self.create_snapshot_for_diagnostic();
1109                         self.bump(); // `::`
1110
1111                         // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`.
1112                         match self.parse_expr() {
1113                             Ok(_) => {
1114                                 // 99% certain that the suggestion is correct, continue parsing.
1115                                 self.sess.emit_err(err);
1116                                 // FIXME: actually check that the two expressions in the binop are
1117                                 // paths and resynthesize new fn call expression instead of using
1118                                 // `ExprKind::Err` placeholder.
1119                                 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1120                             }
1121                             Err(expr_err) => {
1122                                 expr_err.cancel();
1123                                 // Not entirely sure now, but we bubble the error up with the
1124                                 // suggestion.
1125                                 self.restore_snapshot(snapshot);
1126                                 Err(err.into_diagnostic(&self.sess.span_diagnostic))
1127                             }
1128                         }
1129                     } else if token::OpenDelim(Delimiter::Parenthesis) == self.token.kind {
1130                         // We have high certainty that this was a bad turbofish at this point.
1131                         // `foo< bar >(`
1132                         err.suggest_turbofish = Some(op.span.shrink_to_lo());
1133                         // Consume the fn call arguments.
1134                         match self.consume_fn_args() {
1135                             Err(()) => Err(err.into_diagnostic(&self.sess.span_diagnostic)),
1136                             Ok(()) => {
1137                                 self.sess.emit_err(err);
1138                                 // FIXME: actually check that the two expressions in the binop are
1139                                 // paths and resynthesize new fn call expression instead of using
1140                                 // `ExprKind::Err` placeholder.
1141                                 mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1142                             }
1143                         }
1144                     } else {
1145                         if !matches!(l1.kind, ExprKind::Lit(_))
1146                             && !matches!(r1.kind, ExprKind::Lit(_))
1147                         {
1148                             // All we know is that this is `foo < bar >` and *nothing* else. Try to
1149                             // be helpful, but don't attempt to recover.
1150                             err.help_turbofish = Some(());
1151                         }
1152
1153                         // If it looks like a genuine attempt to chain operators (as opposed to a
1154                         // misformatted turbofish, for instance), suggest a correct form.
1155                         if self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op)
1156                         {
1157                             self.sess.emit_err(err);
1158                             mk_err_expr(self, inner_op.span.to(self.prev_token.span))
1159                         } else {
1160                             // These cases cause too many knock-down errors, bail out (#61329).
1161                             Err(err.into_diagnostic(&self.sess.span_diagnostic))
1162                         }
1163                     };
1164                 }
1165                 let recover =
1166                     self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1167                 self.sess.emit_err(err);
1168                 if recover {
1169                     return mk_err_expr(self, inner_op.span.to(self.prev_token.span));
1170                 }
1171             }
1172             _ => {}
1173         }
1174         Ok(None)
1175     }
1176
1177     fn consume_fn_args(&mut self) -> Result<(), ()> {
1178         let snapshot = self.create_snapshot_for_diagnostic();
1179         self.bump(); // `(`
1180
1181         // Consume the fn call arguments.
1182         let modifiers = [
1183             (token::OpenDelim(Delimiter::Parenthesis), 1),
1184             (token::CloseDelim(Delimiter::Parenthesis), -1),
1185         ];
1186         self.consume_tts(1, &modifiers);
1187
1188         if self.token.kind == token::Eof {
1189             // Not entirely sure that what we consumed were fn arguments, rollback.
1190             self.restore_snapshot(snapshot);
1191             Err(())
1192         } else {
1193             // 99% certain that the suggestion is correct, continue parsing.
1194             Ok(())
1195         }
1196     }
1197
1198     pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1199         if impl_dyn_multi {
1200             self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
1201         }
1202     }
1203
1204     /// Swift lets users write `Ty?` to mean `Option<Ty>`. Parse the construct and recover from it.
1205     pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1206         if self.token == token::Question {
1207             self.bump();
1208             self.sess.emit_err(QuestionMarkInType {
1209                 span: self.prev_token.span,
1210                 sugg: QuestionMarkInTypeSugg {
1211                     left: ty.span.shrink_to_lo(),
1212                     right: self.prev_token.span,
1213                 },
1214             });
1215             self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err)
1216         } else {
1217             ty
1218         }
1219     }
1220
1221     pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1222         // Do not add `+` to expected tokens.
1223         if !self.token.is_like_plus() {
1224             return Ok(());
1225         }
1226
1227         self.bump(); // `+`
1228         let bounds = self.parse_generic_bounds(None)?;
1229         let sum_span = ty.span.to(self.prev_token.span);
1230
1231         let sub = match &ty.kind {
1232             TyKind::Rptr(lifetime, mut_ty) => {
1233                 let sum_with_parens = pprust::to_string(|s| {
1234                     s.s.word("&");
1235                     s.print_opt_lifetime(lifetime);
1236                     s.print_mutability(mut_ty.mutbl, false);
1237                     s.popen();
1238                     s.print_type(&mut_ty.ty);
1239                     if !bounds.is_empty() {
1240                         s.word(" + ");
1241                         s.print_type_bounds(&bounds);
1242                     }
1243                     s.pclose()
1244                 });
1245
1246                 BadTypePlusSub::AddParen { sum_with_parens, span: sum_span }
1247             }
1248             TyKind::Ptr(..) | TyKind::BareFn(..) => BadTypePlusSub::ForgotParen { span: sum_span },
1249             _ => BadTypePlusSub::ExpectPath { span: sum_span },
1250         };
1251
1252         self.sess.emit_err(BadTypePlus { ty: pprust::ty_to_string(ty), span: sum_span, sub });
1253
1254         Ok(())
1255     }
1256
1257     pub(super) fn recover_from_prefix_increment(
1258         &mut self,
1259         operand_expr: P<Expr>,
1260         op_span: Span,
1261         start_stmt: bool,
1262     ) -> PResult<'a, P<Expr>> {
1263         let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1264         let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1265         self.recover_from_inc_dec(operand_expr, kind, op_span)
1266     }
1267
1268     pub(super) fn recover_from_postfix_increment(
1269         &mut self,
1270         operand_expr: P<Expr>,
1271         op_span: Span,
1272         start_stmt: bool,
1273     ) -> PResult<'a, P<Expr>> {
1274         let kind = IncDecRecovery {
1275             standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1276             op: IncOrDec::Inc,
1277             fixity: UnaryFixity::Post,
1278         };
1279         self.recover_from_inc_dec(operand_expr, kind, op_span)
1280     }
1281
1282     fn recover_from_inc_dec(
1283         &mut self,
1284         base: P<Expr>,
1285         kind: IncDecRecovery,
1286         op_span: Span,
1287     ) -> PResult<'a, P<Expr>> {
1288         let mut err = self.struct_span_err(
1289             op_span,
1290             &format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1291         );
1292         err.span_label(op_span, &format!("not a valid {} operator", kind.fixity));
1293
1294         let help_base_case = |mut err: DiagnosticBuilder<'_, _>, base| {
1295             err.help(&format!("use `{}= 1` instead", kind.op.chr()));
1296             err.emit();
1297             Ok(base)
1298         };
1299
1300         // (pre, post)
1301         let spans = match kind.fixity {
1302             UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1303             UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1304         };
1305
1306         match kind.standalone {
1307             IsStandalone::Standalone => {
1308                 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1309             }
1310             IsStandalone::Subexpr => {
1311                 let Ok(base_src) = self.span_to_snippet(base.span)
1312                 else { return help_base_case(err, base) };
1313                 match kind.fixity {
1314                     UnaryFixity::Pre => {
1315                         self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1316                     }
1317                     UnaryFixity::Post => {
1318                         // won't suggest since we can not handle the precedences
1319                         // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
1320                         if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1321                             self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1322                         }
1323                     }
1324                 }
1325             }
1326         }
1327         Err(err)
1328     }
1329
1330     fn prefix_inc_dec_suggest(
1331         &mut self,
1332         base_src: String,
1333         kind: IncDecRecovery,
1334         (pre_span, post_span): (Span, Span),
1335     ) -> MultiSugg {
1336         MultiSugg {
1337             msg: format!("use `{}= 1` instead", kind.op.chr()),
1338             patches: vec![
1339                 (pre_span, "{ ".to_string()),
1340                 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1341             ],
1342             applicability: Applicability::MachineApplicable,
1343         }
1344     }
1345
1346     fn postfix_inc_dec_suggest(
1347         &mut self,
1348         base_src: String,
1349         kind: IncDecRecovery,
1350         (pre_span, post_span): (Span, Span),
1351     ) -> MultiSugg {
1352         let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1353         MultiSugg {
1354             msg: format!("use `{}= 1` instead", kind.op.chr()),
1355             patches: vec![
1356                 (pre_span, format!("{{ let {tmp_var} = ")),
1357                 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1358             ],
1359             applicability: Applicability::HasPlaceholders,
1360         }
1361     }
1362
1363     fn inc_dec_standalone_suggest(
1364         &mut self,
1365         kind: IncDecRecovery,
1366         (pre_span, post_span): (Span, Span),
1367     ) -> MultiSugg {
1368         let mut patches = Vec::new();
1369
1370         if !pre_span.is_empty() {
1371             patches.push((pre_span, String::new()));
1372         }
1373
1374         patches.push((post_span, format!(" {}= 1", kind.op.chr())));
1375         MultiSugg {
1376             msg: format!("use `{}= 1` instead", kind.op.chr()),
1377             patches,
1378             applicability: Applicability::MachineApplicable,
1379         }
1380     }
1381
1382     /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`.
1383     /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem`
1384     /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type.
1385     pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1386         &mut self,
1387         base: P<T>,
1388     ) -> PResult<'a, P<T>> {
1389         if !self.may_recover() {
1390             return Ok(base);
1391         }
1392
1393         // Do not add `::` to expected tokens.
1394         if self.token == token::ModSep {
1395             if let Some(ty) = base.to_ty() {
1396                 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1397             }
1398         }
1399         Ok(base)
1400     }
1401
1402     /// Given an already parsed `Ty`, parses the `::AssocItem` tail and
1403     /// combines them into a `<Ty>::AssocItem` expression/pattern/type.
1404     pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1405         &mut self,
1406         ty_span: Span,
1407         ty: P<Ty>,
1408     ) -> PResult<'a, P<T>> {
1409         self.expect(&token::ModSep)?;
1410
1411         let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None };
1412         self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1413         path.span = ty_span.to(self.prev_token.span);
1414
1415         let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty));
1416         self.sess.emit_err(BadQPathStage2 {
1417             span: path.span,
1418             ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)),
1419         });
1420
1421         let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`.
1422         Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
1423     }
1424
1425     pub fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
1426         if self.token.kind == TokenKind::Semi {
1427             self.bump();
1428
1429             let mut err =
1430                 IncorrectSemicolon { span: self.prev_token.span, opt_help: None, name: "" };
1431
1432             if !items.is_empty() {
1433                 let previous_item = &items[items.len() - 1];
1434                 let previous_item_kind_name = match previous_item.kind {
1435                     // Say "braced struct" because tuple-structs and
1436                     // braceless-empty-struct declarations do take a semicolon.
1437                     ItemKind::Struct(..) => Some("braced struct"),
1438                     ItemKind::Enum(..) => Some("enum"),
1439                     ItemKind::Trait(..) => Some("trait"),
1440                     ItemKind::Union(..) => Some("union"),
1441                     _ => None,
1442                 };
1443                 if let Some(name) = previous_item_kind_name {
1444                     err.opt_help = Some(());
1445                     err.name = name;
1446                 }
1447             }
1448             self.sess.emit_err(err);
1449             true
1450         } else {
1451             false
1452         }
1453     }
1454
1455     /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a
1456     /// closing delimiter.
1457     pub(super) fn unexpected_try_recover(
1458         &mut self,
1459         t: &TokenKind,
1460     ) -> PResult<'a, bool /* recovered */> {
1461         let token_str = pprust::token_kind_to_string(t);
1462         let this_token_str = super::token_descr(&self.token);
1463         let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1464             // Point at the end of the macro call when reaching end of macro arguments.
1465             (token::Eof, Some(_)) => {
1466                 let sp = self.prev_token.span.shrink_to_hi();
1467                 (sp, sp)
1468             }
1469             // We don't want to point at the following span after DUMMY_SP.
1470             // This happens when the parser finds an empty TokenStream.
1471             _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1472             // EOF, don't want to point at the following char, but rather the last token.
1473             (token::Eof, None) => (self.prev_token.span, self.token.span),
1474             _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1475         };
1476         let msg = format!(
1477             "expected `{}`, found {}",
1478             token_str,
1479             match (&self.token.kind, self.subparser_name) {
1480                 (token::Eof, Some(origin)) => format!("end of {origin}"),
1481                 _ => this_token_str,
1482             },
1483         );
1484         let mut err = self.struct_span_err(sp, &msg);
1485         let label_exp = format!("expected `{token_str}`");
1486         match self.recover_closing_delimiter(&[t.clone()], err) {
1487             Err(e) => err = e,
1488             Ok(recovered) => {
1489                 return Ok(recovered);
1490             }
1491         }
1492         let sm = self.sess.source_map();
1493         if !sm.is_multiline(prev_sp.until(sp)) {
1494             // When the spans are in the same line, it means that the only content
1495             // between them is whitespace, point only at the found token.
1496             err.span_label(sp, label_exp);
1497         } else {
1498             err.span_label(prev_sp, label_exp);
1499             err.span_label(sp, "unexpected token");
1500         }
1501         Err(err)
1502     }
1503
1504     pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1505         if self.eat(&token::Semi) {
1506             return Ok(());
1507         }
1508         self.expect(&token::Semi).map(drop) // Error unconditionally
1509     }
1510
1511     /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`,
1512     /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`.
1513     pub(super) fn recover_incorrect_await_syntax(
1514         &mut self,
1515         lo: Span,
1516         await_sp: Span,
1517     ) -> PResult<'a, P<Expr>> {
1518         let (hi, expr, is_question) = if self.token == token::Not {
1519             // Handle `await!(<expr>)`.
1520             self.recover_await_macro()?
1521         } else {
1522             self.recover_await_prefix(await_sp)?
1523         };
1524         let sp = self.error_on_incorrect_await(lo, hi, &expr, is_question);
1525         let kind = match expr.kind {
1526             // Avoid knock-down errors as we don't know whether to interpret this as `foo().await?`
1527             // or `foo()?.await` (the very reason we went with postfix syntax ðŸ˜…).
1528             ExprKind::Try(_) => ExprKind::Err,
1529             _ => ExprKind::Await(expr),
1530         };
1531         let expr = self.mk_expr(lo.to(sp), kind);
1532         self.maybe_recover_from_bad_qpath(expr)
1533     }
1534
1535     fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1536         self.expect(&token::Not)?;
1537         self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1538         let expr = self.parse_expr()?;
1539         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?;
1540         Ok((self.prev_token.span, expr, false))
1541     }
1542
1543     fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1544         let is_question = self.eat(&token::Question); // Handle `await? <expr>`.
1545         let expr = if self.token == token::OpenDelim(Delimiter::Brace) {
1546             // Handle `await { <expr> }`.
1547             // This needs to be handled separately from the next arm to avoid
1548             // interpreting `await { <expr> }?` as `<expr>?.await`.
1549             self.parse_block_expr(None, self.token.span, BlockCheckMode::Default)
1550         } else {
1551             self.parse_expr()
1552         }
1553         .map_err(|mut err| {
1554             err.span_label(await_sp, "while parsing this incorrect await expression");
1555             err
1556         })?;
1557         Ok((expr.span, expr, is_question))
1558     }
1559
1560     fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span {
1561         let span = lo.to(hi);
1562         let applicability = match expr.kind {
1563             ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?`
1564             _ => Applicability::MachineApplicable,
1565         };
1566
1567         self.sess.emit_err(IncorrectAwait {
1568             span,
1569             sugg_span: (span, applicability),
1570             expr: self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)),
1571             question_mark: if is_question { "?" } else { "" },
1572         });
1573
1574         span
1575     }
1576
1577     /// If encountering `future.await()`, consumes and emits an error.
1578     pub(super) fn recover_from_await_method_call(&mut self) {
1579         if self.token == token::OpenDelim(Delimiter::Parenthesis)
1580             && self.look_ahead(1, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1581         {
1582             // future.await()
1583             let lo = self.token.span;
1584             self.bump(); // (
1585             let span = lo.to(self.token.span);
1586             self.bump(); // )
1587
1588             self.sess.emit_err(IncorrectUseOfAwait { span });
1589         }
1590     }
1591
1592     pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
1593         let is_try = self.token.is_keyword(kw::Try);
1594         let is_questionmark = self.look_ahead(1, |t| t == &token::Not); //check for !
1595         let is_open = self.look_ahead(2, |t| t == &token::OpenDelim(Delimiter::Parenthesis)); //check for (
1596
1597         if is_try && is_questionmark && is_open {
1598             let lo = self.token.span;
1599             self.bump(); //remove try
1600             self.bump(); //remove !
1601             let try_span = lo.to(self.token.span); //we take the try!( span
1602             self.bump(); //remove (
1603             let is_empty = self.token == token::CloseDelim(Delimiter::Parenthesis); //check if the block is empty
1604             self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::No); //eat the block
1605             let hi = self.token.span;
1606             self.bump(); //remove )
1607             let mut err = self.struct_span_err(lo.to(hi), "use of deprecated `try` macro");
1608             err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
1609             let prefix = if is_empty { "" } else { "alternatively, " };
1610             if !is_empty {
1611                 err.multipart_suggestion(
1612                     "you can use the `?` operator instead",
1613                     vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
1614                     Applicability::MachineApplicable,
1615                 );
1616             }
1617             err.span_suggestion(lo.shrink_to_lo(), &format!("{prefix}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax"), "r#", Applicability::MachineApplicable);
1618             err.emit();
1619             Ok(self.mk_expr_err(lo.to(hi)))
1620         } else {
1621             Err(self.expected_expression_found()) // The user isn't trying to invoke the try! macro
1622         }
1623     }
1624
1625     /// Recovers a situation like `for ( $pat in $expr )`
1626     /// and suggest writing `for $pat in $expr` instead.
1627     ///
1628     /// This should be called before parsing the `$block`.
1629     pub(super) fn recover_parens_around_for_head(
1630         &mut self,
1631         pat: P<Pat>,
1632         begin_paren: Option<Span>,
1633     ) -> P<Pat> {
1634         match (&self.token.kind, begin_paren) {
1635             (token::CloseDelim(Delimiter::Parenthesis), Some(begin_par_sp)) => {
1636                 self.bump();
1637
1638                 let sm = self.sess.source_map();
1639                 let left = begin_par_sp;
1640                 let right = self.prev_token.span;
1641                 let left_snippet = if let Ok(snip) = sm.span_to_prev_source(left) &&
1642                         !snip.ends_with(' ') {
1643                                 " ".to_string()
1644                             } else {
1645                                 "".to_string()
1646                             };
1647
1648                 let right_snippet = if let Ok(snip) = sm.span_to_next_source(right) &&
1649                         !snip.starts_with(' ') {
1650                                 " ".to_string()
1651                             } else {
1652                                 "".to_string()
1653                         };
1654
1655                 self.sess.emit_err(ParenthesesInForHead {
1656                     span: vec![left, right],
1657                     // With e.g. `for (x) in y)` this would replace `(x) in y)`
1658                     // with `x) in y)` which is syntactically invalid.
1659                     // However, this is prevented before we get here.
1660                     sugg: ParenthesesInForHeadSugg { left, right, left_snippet, right_snippet },
1661                 });
1662
1663                 // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint.
1664                 pat.and_then(|pat| match pat.kind {
1665                     PatKind::Paren(pat) => pat,
1666                     _ => P(pat),
1667                 })
1668             }
1669             _ => pat,
1670         }
1671     }
1672
1673     pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
1674         (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
1675             self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
1676             || self.token.is_ident() &&
1677             matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
1678             !self.token.is_reserved_ident() &&           // v `foo:bar(baz)`
1679             self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Parenthesis))
1680             || self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) // `foo:bar {`
1681             || self.look_ahead(1, |t| t == &token::Colon) &&     // `foo:bar::<baz`
1682             self.look_ahead(2, |t| t == &token::Lt) &&
1683             self.look_ahead(3, |t| t.is_ident())
1684             || self.look_ahead(1, |t| t == &token::Colon) &&  // `foo:bar:baz`
1685             self.look_ahead(2, |t| t.is_ident())
1686             || self.look_ahead(1, |t| t == &token::ModSep)
1687                 && (self.look_ahead(2, |t| t.is_ident()) ||   // `foo:bar::baz`
1688             self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>`
1689     }
1690
1691     pub(super) fn recover_seq_parse_error(
1692         &mut self,
1693         delim: Delimiter,
1694         lo: Span,
1695         result: PResult<'a, P<Expr>>,
1696     ) -> P<Expr> {
1697         match result {
1698             Ok(x) => x,
1699             Err(mut err) => {
1700                 err.emit();
1701                 // Recover from parse error, callers expect the closing delim to be consumed.
1702                 self.consume_block(delim, ConsumeClosingDelim::Yes);
1703                 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err)
1704             }
1705         }
1706     }
1707
1708     pub(super) fn recover_closing_delimiter(
1709         &mut self,
1710         tokens: &[TokenKind],
1711         mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
1712     ) -> PResult<'a, bool> {
1713         let mut pos = None;
1714         // We want to use the last closing delim that would apply.
1715         for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
1716             if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
1717                 && Some(self.token.span) > unmatched.unclosed_span
1718             {
1719                 pos = Some(i);
1720             }
1721         }
1722         match pos {
1723             Some(pos) => {
1724                 // Recover and assume that the detected unclosed delimiter was meant for
1725                 // this location. Emit the diagnostic and act as if the delimiter was
1726                 // present for the parser's sake.
1727
1728                 // Don't attempt to recover from this unclosed delimiter more than once.
1729                 let unmatched = self.unclosed_delims.remove(pos);
1730                 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
1731                 if unmatched.found_delim.is_none() {
1732                     // We encountered `Eof`, set this fact here to avoid complaining about missing
1733                     // `fn main()` when we found place to suggest the closing brace.
1734                     *self.sess.reached_eof.borrow_mut() = true;
1735                 }
1736
1737                 // We want to suggest the inclusion of the closing delimiter where it makes
1738                 // the most sense, which is immediately after the last token:
1739                 //
1740                 //  {foo(bar {}}
1741                 //      ^      ^
1742                 //      |      |
1743                 //      |      help: `)` may belong here
1744                 //      |
1745                 //      unclosed delimiter
1746                 if let Some(sp) = unmatched.unclosed_span {
1747                     let mut primary_span: Vec<Span> =
1748                         err.span.primary_spans().iter().cloned().collect();
1749                     primary_span.push(sp);
1750                     let mut primary_span: MultiSpan = primary_span.into();
1751                     for span_label in err.span.span_labels() {
1752                         if let Some(label) = span_label.label {
1753                             primary_span.push_span_label(span_label.span, label);
1754                         }
1755                     }
1756                     err.set_span(primary_span);
1757                     err.span_label(sp, "unclosed delimiter");
1758                 }
1759                 // Backticks should be removed to apply suggestions.
1760                 let mut delim = delim.to_string();
1761                 delim.retain(|c| c != '`');
1762                 err.span_suggestion_short(
1763                     self.prev_token.span.shrink_to_hi(),
1764                     &format!("`{delim}` may belong here"),
1765                     delim,
1766                     Applicability::MaybeIncorrect,
1767                 );
1768                 if unmatched.found_delim.is_none() {
1769                     // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown
1770                     // errors which would be emitted elsewhere in the parser and let other error
1771                     // recovery consume the rest of the file.
1772                     Err(err)
1773                 } else {
1774                     err.emit();
1775                     self.expected_tokens.clear(); // Reduce the number of errors.
1776                     Ok(true)
1777                 }
1778             }
1779             _ => Err(err),
1780         }
1781     }
1782
1783     /// Eats tokens until we can be relatively sure we reached the end of the
1784     /// statement. This is something of a best-effort heuristic.
1785     ///
1786     /// We terminate when we find an unmatched `}` (without consuming it).
1787     pub(super) fn recover_stmt(&mut self) {
1788         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
1789     }
1790
1791     /// If `break_on_semi` is `Break`, then we will stop consuming tokens after
1792     /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
1793     /// approximate -- it can mean we break too early due to macros, but that
1794     /// should only lead to sub-optimal recovery, not inaccurate parsing).
1795     ///
1796     /// If `break_on_block` is `Break`, then we will stop consuming tokens
1797     /// after finding (and consuming) a brace-delimited block.
1798     pub(super) fn recover_stmt_(
1799         &mut self,
1800         break_on_semi: SemiColonMode,
1801         break_on_block: BlockMode,
1802     ) {
1803         let mut brace_depth = 0;
1804         let mut bracket_depth = 0;
1805         let mut in_block = false;
1806         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
1807         loop {
1808             debug!("recover_stmt_ loop {:?}", self.token);
1809             match self.token.kind {
1810                 token::OpenDelim(Delimiter::Brace) => {
1811                     brace_depth += 1;
1812                     self.bump();
1813                     if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
1814                     {
1815                         in_block = true;
1816                     }
1817                 }
1818                 token::OpenDelim(Delimiter::Bracket) => {
1819                     bracket_depth += 1;
1820                     self.bump();
1821                 }
1822                 token::CloseDelim(Delimiter::Brace) => {
1823                     if brace_depth == 0 {
1824                         debug!("recover_stmt_ return - close delim {:?}", self.token);
1825                         break;
1826                     }
1827                     brace_depth -= 1;
1828                     self.bump();
1829                     if in_block && bracket_depth == 0 && brace_depth == 0 {
1830                         debug!("recover_stmt_ return - block end {:?}", self.token);
1831                         break;
1832                     }
1833                 }
1834                 token::CloseDelim(Delimiter::Bracket) => {
1835                     bracket_depth -= 1;
1836                     if bracket_depth < 0 {
1837                         bracket_depth = 0;
1838                     }
1839                     self.bump();
1840                 }
1841                 token::Eof => {
1842                     debug!("recover_stmt_ return - Eof");
1843                     break;
1844                 }
1845                 token::Semi => {
1846                     self.bump();
1847                     if break_on_semi == SemiColonMode::Break
1848                         && brace_depth == 0
1849                         && bracket_depth == 0
1850                     {
1851                         debug!("recover_stmt_ return - Semi");
1852                         break;
1853                     }
1854                 }
1855                 token::Comma
1856                     if break_on_semi == SemiColonMode::Comma
1857                         && brace_depth == 0
1858                         && bracket_depth == 0 =>
1859                 {
1860                     debug!("recover_stmt_ return - Semi");
1861                     break;
1862                 }
1863                 _ => self.bump(),
1864             }
1865         }
1866     }
1867
1868     pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
1869         if self.eat_keyword(kw::In) {
1870             // a common typo: `for _ in in bar {}`
1871             self.sess.emit_err(InInTypo {
1872                 span: self.prev_token.span,
1873                 sugg_span: in_span.until(self.prev_token.span),
1874             });
1875         }
1876     }
1877
1878     pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
1879         if let token::DocComment(..) = self.token.kind {
1880             self.sess.emit_err(DocCommentOnParamType { span: self.token.span });
1881             self.bump();
1882         } else if self.token == token::Pound
1883             && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Bracket))
1884         {
1885             let lo = self.token.span;
1886             // Skip every token until next possible arg.
1887             while self.token != token::CloseDelim(Delimiter::Bracket) {
1888                 self.bump();
1889             }
1890             let sp = lo.to(self.token.span);
1891             self.bump();
1892             self.sess.emit_err(AttributeOnParamType { span: sp });
1893         }
1894     }
1895
1896     pub(super) fn parameter_without_type(
1897         &mut self,
1898         err: &mut Diagnostic,
1899         pat: P<ast::Pat>,
1900         require_name: bool,
1901         first_param: bool,
1902     ) -> Option<Ident> {
1903         // If we find a pattern followed by an identifier, it could be an (incorrect)
1904         // C-style parameter declaration.
1905         if self.check_ident()
1906             && self.look_ahead(1, |t| {
1907                 *t == token::Comma || *t == token::CloseDelim(Delimiter::Parenthesis)
1908             })
1909         {
1910             // `fn foo(String s) {}`
1911             let ident = self.parse_ident().unwrap();
1912             let span = pat.span.with_hi(ident.span.hi());
1913
1914             err.span_suggestion(
1915                 span,
1916                 "declare the type after the parameter binding",
1917                 "<identifier>: <type>",
1918                 Applicability::HasPlaceholders,
1919             );
1920             return Some(ident);
1921         } else if require_name
1922             && (self.token == token::Comma
1923                 || self.token == token::Lt
1924                 || self.token == token::CloseDelim(Delimiter::Parenthesis))
1925         {
1926             let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
1927
1928             let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
1929                 match pat.kind {
1930                     PatKind::Ident(_, ident, _) => (
1931                         ident,
1932                         "self: ",
1933                         ": TypeName".to_string(),
1934                         "_: ",
1935                         pat.span.shrink_to_lo(),
1936                         pat.span.shrink_to_hi(),
1937                         pat.span.shrink_to_lo(),
1938                     ),
1939                     // Also catches `fn foo(&a)`.
1940                     PatKind::Ref(ref inner_pat, mutab)
1941                         if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
1942                     {
1943                         match inner_pat.clone().into_inner().kind {
1944                             PatKind::Ident(_, ident, _) => {
1945                                 let mutab = mutab.prefix_str();
1946                                 (
1947                                     ident,
1948                                     "self: ",
1949                                     format!("{ident}: &{mutab}TypeName"),
1950                                     "_: ",
1951                                     pat.span.shrink_to_lo(),
1952                                     pat.span,
1953                                     pat.span.shrink_to_lo(),
1954                                 )
1955                             }
1956                             _ => unreachable!(),
1957                         }
1958                     }
1959                     _ => {
1960                         // Otherwise, try to get a type and emit a suggestion.
1961                         if let Some(ty) = pat.to_ty() {
1962                             err.span_suggestion_verbose(
1963                                 pat.span,
1964                                 "explicitly ignore the parameter name",
1965                                 format!("_: {}", pprust::ty_to_string(&ty)),
1966                                 Applicability::MachineApplicable,
1967                             );
1968                             err.note(rfc_note);
1969                         }
1970
1971                         return None;
1972                     }
1973                 };
1974
1975             // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}`
1976             if first_param {
1977                 err.span_suggestion(
1978                     self_span,
1979                     "if this is a `self` type, give it a parameter name",
1980                     self_sugg,
1981                     Applicability::MaybeIncorrect,
1982                 );
1983             }
1984             // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to
1985             // `fn foo(HashMap: TypeName<u32>)`.
1986             if self.token != token::Lt {
1987                 err.span_suggestion(
1988                     param_span,
1989                     "if this is a parameter name, give it a type",
1990                     param_sugg,
1991                     Applicability::HasPlaceholders,
1992                 );
1993             }
1994             err.span_suggestion(
1995                 type_span,
1996                 "if this is a type, explicitly ignore the parameter name",
1997                 type_sugg,
1998                 Applicability::MachineApplicable,
1999             );
2000             err.note(rfc_note);
2001
2002             // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name.
2003             return if self.token == token::Lt { None } else { Some(ident) };
2004         }
2005         None
2006     }
2007
2008     pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2009         let pat = self.parse_pat_no_top_alt(Some("argument name"))?;
2010         self.expect(&token::Colon)?;
2011         let ty = self.parse_ty()?;
2012
2013         self.sess.emit_err(PatternMethodParamWithoutBody { span: pat.span });
2014
2015         // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2016         let pat =
2017             P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2018         Ok((pat, ty))
2019     }
2020
2021     pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2022         let span = param.pat.span;
2023         param.ty.kind = TyKind::Err;
2024         self.sess.emit_err(SelfParamNotFirst { span });
2025         Ok(param)
2026     }
2027
2028     pub(super) fn consume_block(&mut self, delim: Delimiter, consume_close: ConsumeClosingDelim) {
2029         let mut brace_depth = 0;
2030         loop {
2031             if self.eat(&token::OpenDelim(delim)) {
2032                 brace_depth += 1;
2033             } else if self.check(&token::CloseDelim(delim)) {
2034                 if brace_depth == 0 {
2035                     if let ConsumeClosingDelim::Yes = consume_close {
2036                         // Some of the callers of this method expect to be able to parse the
2037                         // closing delimiter themselves, so we leave it alone. Otherwise we advance
2038                         // the parser.
2039                         self.bump();
2040                     }
2041                     return;
2042                 } else {
2043                     self.bump();
2044                     brace_depth -= 1;
2045                     continue;
2046                 }
2047             } else if self.token == token::Eof {
2048                 return;
2049             } else {
2050                 self.bump();
2051             }
2052         }
2053     }
2054
2055     pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2056         let (span, msg) = match (&self.token.kind, self.subparser_name) {
2057             (&token::Eof, Some(origin)) => {
2058                 let sp = self.prev_token.span.shrink_to_hi();
2059                 (sp, format!("expected expression, found end of {origin}"))
2060             }
2061             _ => (
2062                 self.token.span,
2063                 format!("expected expression, found {}", super::token_descr(&self.token),),
2064             ),
2065         };
2066         let mut err = self.struct_span_err(span, &msg);
2067         let sp = self.sess.source_map().start_point(self.token.span);
2068         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
2069             err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2070         }
2071         err.span_label(span, "expected expression");
2072         err
2073     }
2074
2075     fn consume_tts(
2076         &mut self,
2077         mut acc: i64, // `i64` because malformed code can have more closing delims than opening.
2078         // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`.
2079         modifier: &[(token::TokenKind, i64)],
2080     ) {
2081         while acc > 0 {
2082             if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) {
2083                 acc += *val;
2084             }
2085             if self.token.kind == token::Eof {
2086                 break;
2087             }
2088             self.bump();
2089         }
2090     }
2091
2092     /// Replace duplicated recovered parameters with `_` pattern to avoid unnecessary errors.
2093     ///
2094     /// This is necessary because at this point we don't know whether we parsed a function with
2095     /// anonymous parameters or a function with names but no types. In order to minimize
2096     /// unnecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where
2097     /// the parameters are *names* (so we don't emit errors about not being able to find `b` in
2098     /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`,
2099     /// we deduplicate them to not complain about duplicated parameter names.
2100     pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) {
2101         let mut seen_inputs = FxHashSet::default();
2102         for input in fn_inputs.iter_mut() {
2103             let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) =
2104                 (&input.pat.kind, &input.ty.kind)
2105             {
2106                 Some(*ident)
2107             } else {
2108                 None
2109             };
2110             if let Some(ident) = opt_ident {
2111                 if seen_inputs.contains(&ident) {
2112                     input.pat.kind = PatKind::Wild;
2113                 }
2114                 seen_inputs.insert(ident);
2115             }
2116         }
2117     }
2118
2119     /// Handle encountering a symbol in a generic argument list that is not a `,` or `>`. In this
2120     /// case, we emit an error and try to suggest enclosing a const argument in braces if it looks
2121     /// like the user has forgotten them.
2122     pub fn handle_ambiguous_unbraced_const_arg(
2123         &mut self,
2124         args: &mut Vec<AngleBracketedArg>,
2125     ) -> PResult<'a, bool> {
2126         // If we haven't encountered a closing `>`, then the argument is malformed.
2127         // It's likely that the user has written a const expression without enclosing it
2128         // in braces, so we try to recover here.
2129         let arg = args.pop().unwrap();
2130         // FIXME: for some reason using `unexpected` or `expected_one_of_not_found` has
2131         // adverse side-effects to subsequent errors and seems to advance the parser.
2132         // We are causing this error here exclusively in case that a `const` expression
2133         // could be recovered from the current parser state, even if followed by more
2134         // arguments after a comma.
2135         let mut err = self.struct_span_err(
2136             self.token.span,
2137             &format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2138         );
2139         err.span_label(self.token.span, "expected one of `,` or `>`");
2140         match self.recover_const_arg(arg.span(), err) {
2141             Ok(arg) => {
2142                 args.push(AngleBracketedArg::Arg(arg));
2143                 if self.eat(&token::Comma) {
2144                     return Ok(true); // Continue
2145                 }
2146             }
2147             Err(mut err) => {
2148                 args.push(arg);
2149                 // We will emit a more generic error later.
2150                 err.delay_as_bug();
2151             }
2152         }
2153         return Ok(false); // Don't continue.
2154     }
2155
2156     /// Attempt to parse a generic const argument that has not been enclosed in braces.
2157     /// There are a limited number of expressions that are permitted without being encoded
2158     /// in braces:
2159     /// - Literals.
2160     /// - Single-segment paths (i.e. standalone generic const parameters).
2161     /// All other expressions that can be parsed will emit an error suggesting the expression be
2162     /// wrapped in braces.
2163     pub fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2164         let start = self.token.span;
2165         let expr = self.parse_expr_res(Restrictions::CONST_EXPR, None).map_err(|mut err| {
2166             err.span_label(
2167                 start.shrink_to_lo(),
2168                 "while parsing a const generic argument starting here",
2169             );
2170             err
2171         })?;
2172         if !self.expr_is_valid_const_arg(&expr) {
2173             self.sess.emit_err(ConstGenericWithoutBraces {
2174                 span: expr.span,
2175                 sugg: ConstGenericWithoutBracesSugg {
2176                     left: expr.span.shrink_to_lo(),
2177                     right: expr.span.shrink_to_hi(),
2178                 },
2179             });
2180         }
2181         Ok(expr)
2182     }
2183
2184     fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2185         let snapshot = self.create_snapshot_for_diagnostic();
2186         let param = match self.parse_const_param(AttrVec::new()) {
2187             Ok(param) => param,
2188             Err(err) => {
2189                 err.cancel();
2190                 self.restore_snapshot(snapshot);
2191                 return None;
2192             }
2193         };
2194
2195         let ident = param.ident.to_string();
2196         let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) {
2197             (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2198                 Some(match &params[..] {
2199                     [] => UnexpectedConstParamDeclarationSugg::AddParam {
2200                         impl_generics: *impl_generics,
2201                         incorrect_decl: param.span(),
2202                         snippet,
2203                         ident,
2204                     },
2205                     [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2206                         impl_generics_end: generic.span().shrink_to_hi(),
2207                         incorrect_decl: param.span(),
2208                         snippet,
2209                         ident,
2210                     },
2211                 })
2212             }
2213             _ => None,
2214         };
2215         self.sess.emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2216
2217         let value = self.mk_expr_err(param.span());
2218         Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2219     }
2220
2221     pub fn recover_const_param_declaration(
2222         &mut self,
2223         ty_generics: Option<&Generics>,
2224     ) -> PResult<'a, Option<GenericArg>> {
2225         // We have to check for a few different cases.
2226         if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2227             return Ok(Some(arg));
2228         }
2229
2230         // We haven't consumed `const` yet.
2231         let start = self.token.span;
2232         self.bump(); // `const`
2233
2234         // Detect and recover from the old, pre-RFC2000 syntax for const generics.
2235         let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2236         if self.check_const_arg() {
2237             err.to_remove = Some(start.until(self.token.span));
2238             self.sess.emit_err(err);
2239             Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2240         } else {
2241             let after_kw_const = self.token.span;
2242             self.recover_const_arg(after_kw_const, err.into_diagnostic(&self.sess.span_diagnostic))
2243                 .map(Some)
2244         }
2245     }
2246
2247     /// Try to recover from possible generic const argument without `{` and `}`.
2248     ///
2249     /// When encountering code like `foo::< bar + 3 >` or `foo::< bar - baz >` we suggest
2250     /// `foo::<{ bar + 3 }>` and `foo::<{ bar - baz }>`, respectively. We only provide a suggestion
2251     /// if we think that the resulting expression would be well formed.
2252     pub fn recover_const_arg(
2253         &mut self,
2254         start: Span,
2255         mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2256     ) -> PResult<'a, GenericArg> {
2257         let is_op_or_dot = AssocOp::from_token(&self.token)
2258             .and_then(|op| {
2259                 if let AssocOp::Greater
2260                 | AssocOp::Less
2261                 | AssocOp::ShiftRight
2262                 | AssocOp::GreaterEqual
2263                 // Don't recover from `foo::<bar = baz>`, because this could be an attempt to
2264                 // assign a value to a defaulted generic parameter.
2265                 | AssocOp::Assign
2266                 | AssocOp::AssignOp(_) = op
2267                 {
2268                     None
2269                 } else {
2270                     Some(op)
2271                 }
2272             })
2273             .is_some()
2274             || self.token.kind == TokenKind::Dot;
2275         // This will be true when a trait object type `Foo +` or a path which was a `const fn` with
2276         // type params has been parsed.
2277         let was_op =
2278             matches!(self.prev_token.kind, token::BinOp(token::Plus | token::Shr) | token::Gt);
2279         if !is_op_or_dot && !was_op {
2280             // We perform these checks and early return to avoid taking a snapshot unnecessarily.
2281             return Err(err);
2282         }
2283         let snapshot = self.create_snapshot_for_diagnostic();
2284         if is_op_or_dot {
2285             self.bump();
2286         }
2287         match self.parse_expr_res(Restrictions::CONST_EXPR, None) {
2288             Ok(expr) => {
2289                 // Find a mistake like `MyTrait<Assoc == S::Assoc>`.
2290                 if token::EqEq == snapshot.token.kind {
2291                     err.span_suggestion(
2292                         snapshot.token.span,
2293                         "if you meant to use an associated type binding, replace `==` with `=`",
2294                         "=",
2295                         Applicability::MaybeIncorrect,
2296                     );
2297                     let value = self.mk_expr_err(start.to(expr.span));
2298                     err.emit();
2299                     return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2300                 } else if token::Colon == snapshot.token.kind
2301                     && expr.span.lo() == snapshot.token.span.hi()
2302                     && matches!(expr.kind, ExprKind::Path(..))
2303                 {
2304                     // Find a mistake like "foo::var:A".
2305                     err.span_suggestion(
2306                         snapshot.token.span,
2307                         "write a path separator here",
2308                         "::",
2309                         Applicability::MaybeIncorrect,
2310                     );
2311                     err.emit();
2312                     return Ok(GenericArg::Type(self.mk_ty(start.to(expr.span), TyKind::Err)));
2313                 } else if token::Comma == self.token.kind || self.token.kind.should_end_const_arg()
2314                 {
2315                     // Avoid the following output by checking that we consumed a full const arg:
2316                     // help: expressions must be enclosed in braces to be used as const generic
2317                     //       arguments
2318                     //    |
2319                     // LL |     let sr: Vec<{ (u32, _, _) = vec![] };
2320                     //    |                 ^                      ^
2321                     return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2322                 }
2323             }
2324             Err(err) => {
2325                 err.cancel();
2326             }
2327         }
2328         self.restore_snapshot(snapshot);
2329         Err(err)
2330     }
2331
2332     /// Creates a dummy const argument, and reports that the expression must be enclosed in braces
2333     pub fn dummy_const_arg_needs_braces(
2334         &self,
2335         mut err: DiagnosticBuilder<'a, ErrorGuaranteed>,
2336         span: Span,
2337     ) -> GenericArg {
2338         err.multipart_suggestion(
2339             "expressions must be enclosed in braces to be used as const generic \
2340              arguments",
2341             vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2342             Applicability::MaybeIncorrect,
2343         );
2344         let value = self.mk_expr_err(span);
2345         err.emit();
2346         GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2347     }
2348
2349     /// Some special error handling for the "top-level" patterns in a match arm,
2350     /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2351     pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2352         &mut self,
2353         mut first_pat: P<Pat>,
2354         expected: Expected,
2355     ) -> P<Pat> {
2356         if token::Colon != self.token.kind {
2357             return first_pat;
2358         }
2359         if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2360             || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2361         {
2362             return first_pat;
2363         }
2364         // The pattern looks like it might be a path with a `::` -> `:` typo:
2365         // `match foo { bar:baz => {} }`
2366         let span = self.token.span;
2367         // We only emit "unexpected `:`" error here if we can successfully parse the
2368         // whole pattern correctly in that case.
2369         let snapshot = self.create_snapshot_for_diagnostic();
2370
2371         // Create error for "unexpected `:`".
2372         match self.expected_one_of_not_found(&[], &[]) {
2373             Err(mut err) => {
2374                 self.bump(); // Skip the `:`.
2375                 match self.parse_pat_no_top_alt(expected) {
2376                     Err(inner_err) => {
2377                         // Carry on as if we had not done anything, callers will emit a
2378                         // reasonable error.
2379                         inner_err.cancel();
2380                         err.cancel();
2381                         self.restore_snapshot(snapshot);
2382                     }
2383                     Ok(mut pat) => {
2384                         // We've parsed the rest of the pattern.
2385                         let new_span = first_pat.span.to(pat.span);
2386                         let mut show_sugg = false;
2387                         // Try to construct a recovered pattern.
2388                         match &mut pat.kind {
2389                             PatKind::Struct(qself @ None, path, ..)
2390                             | PatKind::TupleStruct(qself @ None, path, _)
2391                             | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2392                                 PatKind::Ident(_, ident, _) => {
2393                                     path.segments.insert(0, PathSegment::from_ident(*ident));
2394                                     path.span = new_span;
2395                                     show_sugg = true;
2396                                     first_pat = pat;
2397                                 }
2398                                 PatKind::Path(old_qself, old_path) => {
2399                                     path.segments = old_path
2400                                         .segments
2401                                         .iter()
2402                                         .cloned()
2403                                         .chain(take(&mut path.segments))
2404                                         .collect();
2405                                     path.span = new_span;
2406                                     *qself = old_qself.clone();
2407                                     first_pat = pat;
2408                                     show_sugg = true;
2409                                 }
2410                                 _ => {}
2411                             },
2412                             PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
2413                                 match &first_pat.kind {
2414                                     PatKind::Ident(_, old_ident, _) => {
2415                                         let path = PatKind::Path(
2416                                             None,
2417                                             Path {
2418                                                 span: new_span,
2419                                                 segments: thin_vec![
2420                                                     PathSegment::from_ident(*old_ident),
2421                                                     PathSegment::from_ident(*ident),
2422                                                 ],
2423                                                 tokens: None,
2424                                             },
2425                                         );
2426                                         first_pat = self.mk_pat(new_span, path);
2427                                         show_sugg = true;
2428                                     }
2429                                     PatKind::Path(old_qself, old_path) => {
2430                                         let mut segments = old_path.segments.clone();
2431                                         segments.push(PathSegment::from_ident(*ident));
2432                                         let path = PatKind::Path(
2433                                             old_qself.clone(),
2434                                             Path { span: new_span, segments, tokens: None },
2435                                         );
2436                                         first_pat = self.mk_pat(new_span, path);
2437                                         show_sugg = true;
2438                                     }
2439                                     _ => {}
2440                                 }
2441                             }
2442                             _ => {}
2443                         }
2444                         if show_sugg {
2445                             err.span_suggestion(
2446                                 span,
2447                                 "maybe write a path separator here",
2448                                 "::",
2449                                 Applicability::MaybeIncorrect,
2450                             );
2451                         } else {
2452                             first_pat = self.mk_pat(new_span, PatKind::Wild);
2453                         }
2454                         err.emit();
2455                     }
2456                 }
2457             }
2458             _ => {
2459                 // Carry on as if we had not done anything. This should be unreachable.
2460                 self.restore_snapshot(snapshot);
2461             }
2462         };
2463         first_pat
2464     }
2465
2466     pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
2467         // Check for `'a : {`
2468         if !(self.check_lifetime()
2469             && self.look_ahead(1, |tok| tok.kind == token::Colon)
2470             && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Brace)))
2471         {
2472             return false;
2473         }
2474         let label = self.eat_label().expect("just checked if a label exists");
2475         self.bump(); // eat `:`
2476         let span = label.ident.span.to(self.prev_token.span);
2477         let mut err = self.struct_span_err(span, "block label not supported here");
2478         err.span_label(span, "not supported here");
2479         err.tool_only_span_suggestion(
2480             label.ident.span.until(self.token.span),
2481             "remove this block label",
2482             "",
2483             Applicability::MachineApplicable,
2484         );
2485         err.emit();
2486         true
2487     }
2488
2489     /// Some special error handling for the "top-level" patterns in a match arm,
2490     /// `for` loop, `let`, &c. (in contrast to subpatterns within such).
2491     pub(crate) fn maybe_recover_unexpected_comma(
2492         &mut self,
2493         lo: Span,
2494         rt: CommaRecoveryMode,
2495     ) -> PResult<'a, ()> {
2496         if self.token != token::Comma {
2497             return Ok(());
2498         }
2499
2500         // An unexpected comma after a top-level pattern is a clue that the
2501         // user (perhaps more accustomed to some other language) forgot the
2502         // parentheses in what should have been a tuple pattern; return a
2503         // suggestion-enhanced error here rather than choking on the comma later.
2504         let comma_span = self.token.span;
2505         self.bump();
2506         if let Err(err) = self.skip_pat_list() {
2507             // We didn't expect this to work anyway; we just wanted to advance to the
2508             // end of the comma-sequence so we know the span to suggest parenthesizing.
2509             err.cancel();
2510         }
2511         let seq_span = lo.to(self.prev_token.span);
2512         let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern");
2513         if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2514             err.multipart_suggestion(
2515                 &format!(
2516                     "try adding parentheses to match on a tuple{}",
2517                     if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2518                 ),
2519                 vec![
2520                     (seq_span.shrink_to_lo(), "(".to_string()),
2521                     (seq_span.shrink_to_hi(), ")".to_string()),
2522                 ],
2523                 Applicability::MachineApplicable,
2524             );
2525             if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2526                 err.span_suggestion(
2527                     seq_span,
2528                     "...or a vertical bar to match on multiple alternatives",
2529                     seq_snippet.replace(',', " |"),
2530                     Applicability::MachineApplicable,
2531                 );
2532             }
2533         }
2534         Err(err)
2535     }
2536
2537     pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2538         let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2539         let qself_position = qself.as_ref().map(|qself| qself.position);
2540         for (i, segments) in path.segments.windows(2).enumerate() {
2541             if qself_position.map(|pos| i < pos).unwrap_or(false) {
2542                 continue;
2543             }
2544             if let [a, b] = segments {
2545                 let (a_span, b_span) = (a.span(), b.span());
2546                 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2547                 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2548                     return Err(DoubleColonInBound {
2549                         span: path.span.shrink_to_hi(),
2550                         between: between_span,
2551                     }
2552                     .into_diagnostic(&self.sess.span_diagnostic));
2553                 }
2554             }
2555         }
2556         Ok(())
2557     }
2558
2559     /// Parse and throw away a parenthesized comma separated
2560     /// sequence of patterns until `)` is reached.
2561     fn skip_pat_list(&mut self) -> PResult<'a, ()> {
2562         while !self.check(&token::CloseDelim(Delimiter::Parenthesis)) {
2563             self.parse_pat_no_top_alt(None)?;
2564             if !self.eat(&token::Comma) {
2565                 return Ok(());
2566             }
2567         }
2568         Ok(())
2569     }
2570 }