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