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