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