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