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