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