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