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