1use std::mem::take;
2use std::ops::{Deref, DerefMut};
3
4use ast::token::IdentIsRaw;
5use rustc_ast as ast;
6use rustc_ast::ptr::P;
7use rustc_ast::token::{self, Lit, LitKind, Token, TokenKind};
8use rustc_ast::util::parser::AssocOp;
9use rustc_ast::{
10 AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode, Block,
11 BlockCheckMode, Expr, ExprKind, GenericArg, Generics, Item, ItemKind, Param, Pat, PatKind,
12 Path, PathSegment, QSelf, Recovered, Ty, TyKind,
13};
14use rustc_ast_pretty::pprust;
15use rustc_data_structures::fx::FxHashSet;
16use rustc_errors::{
17 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, PResult, Subdiagnostic, Suggestions,
18 pluralize,
19};
20use rustc_session::errors::ExprParenthesesNeeded;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::source_map::Spanned;
23use rustc_span::symbol::used_keywords;
24use rustc_span::{BytePos, DUMMY_SP, Ident, Span, SpanSnippetError, Symbol, kw, sym};
25use thin_vec::{ThinVec, thin_vec};
26use tracing::{debug, trace};
27
28use super::pat::Expected;
29use super::{
30 BlockMode, CommaRecoveryMode, ExpTokenPair, Parser, PathStyle, Restrictions, SemiColonMode,
31 SeqSep, TokenType,
32};
33use crate::errors::{
34 AddParen, AmbiguousPlus, AsyncMoveBlockIn2015, AsyncUseBlockIn2015, AttributeOnParamType,
35 AwaitSuggestion, BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi,
36 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
37 ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentDoesNotDocumentAnything,
38 DocCommentOnParamType, DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
39 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg,
40 HelpIdentifierStartsWithNumber, HelpUseLatestEdition, InInTypo, IncorrectAwait,
41 IncorrectSemicolon, IncorrectUseOfAwait, IncorrectUseOfUse, PatternMethodParamWithoutBody,
42 QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
43 StructLiteralBodyWithoutPathSugg, SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma,
44 TernaryOperator, UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
45 UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead, WrapType,
46};
47use crate::parser::attr::InnerAttrPolicy;
48use crate::{exp, fluent_generated as fluent};
49
50pub(super) fn dummy_arg(ident: Ident, guar: ErrorGuaranteed) -> Param {
52 let pat = P(Pat {
53 id: ast::DUMMY_NODE_ID,
54 kind: PatKind::Ident(BindingMode::NONE, ident, None),
55 span: ident.span,
56 tokens: None,
57 });
58 let ty = Ty { kind: TyKind::Err(guar), span: ident.span, id: ast::DUMMY_NODE_ID, tokens: None };
59 Param {
60 attrs: AttrVec::default(),
61 id: ast::DUMMY_NODE_ID,
62 pat,
63 span: ident.span,
64 ty: P(ty),
65 is_placeholder: false,
66 }
67}
68
69pub(super) trait RecoverQPath: Sized + 'static {
70 const PATH_STYLE: PathStyle = PathStyle::Expr;
71 fn to_ty(&self) -> Option<P<Ty>>;
72 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self;
73}
74
75impl RecoverQPath for Ty {
76 const PATH_STYLE: PathStyle = PathStyle::Type;
77 fn to_ty(&self) -> Option<P<Ty>> {
78 Some(P(self.clone()))
79 }
80 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
81 Self {
82 span: path.span,
83 kind: TyKind::Path(qself, path),
84 id: ast::DUMMY_NODE_ID,
85 tokens: None,
86 }
87 }
88}
89
90impl RecoverQPath for Pat {
91 const PATH_STYLE: PathStyle = PathStyle::Pat;
92 fn to_ty(&self) -> Option<P<Ty>> {
93 self.to_ty()
94 }
95 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
96 Self {
97 span: path.span,
98 kind: PatKind::Path(qself, path),
99 id: ast::DUMMY_NODE_ID,
100 tokens: None,
101 }
102 }
103}
104
105impl RecoverQPath for Expr {
106 fn to_ty(&self) -> Option<P<Ty>> {
107 self.to_ty()
108 }
109 fn recovered(qself: Option<P<QSelf>>, path: ast::Path) -> Self {
110 Self {
111 span: path.span,
112 kind: ExprKind::Path(qself, path),
113 attrs: AttrVec::new(),
114 id: ast::DUMMY_NODE_ID,
115 tokens: None,
116 }
117 }
118}
119
120pub(crate) enum ConsumeClosingDelim {
122 Yes,
123 No,
124}
125
126#[derive(Clone, Copy)]
127pub enum AttemptLocalParseRecovery {
128 Yes,
129 No,
130}
131
132impl AttemptLocalParseRecovery {
133 pub(super) fn yes(&self) -> bool {
134 match self {
135 AttemptLocalParseRecovery::Yes => true,
136 AttemptLocalParseRecovery::No => false,
137 }
138 }
139
140 pub(super) fn no(&self) -> bool {
141 match self {
142 AttemptLocalParseRecovery::Yes => false,
143 AttemptLocalParseRecovery::No => true,
144 }
145 }
146}
147
148#[derive(Debug, Copy, Clone)]
151struct IncDecRecovery {
152 standalone: IsStandalone,
154 op: IncOrDec,
156 fixity: UnaryFixity,
158}
159
160#[derive(Debug, Copy, Clone)]
162enum IsStandalone {
163 Standalone,
165 Subexpr,
167}
168
169#[derive(Debug, Copy, Clone, PartialEq, Eq)]
170enum IncOrDec {
171 Inc,
172 Dec,
173}
174
175#[derive(Debug, Copy, Clone, PartialEq, Eq)]
176enum UnaryFixity {
177 Pre,
178 Post,
179}
180
181impl IncOrDec {
182 fn chr(&self) -> char {
183 match self {
184 Self::Inc => '+',
185 Self::Dec => '-',
186 }
187 }
188
189 fn name(&self) -> &'static str {
190 match self {
191 Self::Inc => "increment",
192 Self::Dec => "decrement",
193 }
194 }
195}
196
197impl std::fmt::Display for UnaryFixity {
198 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199 match self {
200 Self::Pre => write!(f, "prefix"),
201 Self::Post => write!(f, "postfix"),
202 }
203 }
204}
205
206#[derive(Debug, rustc_macros::Subdiagnostic)]
207#[suggestion(
208 parse_misspelled_kw,
209 applicability = "machine-applicable",
210 code = "{similar_kw}",
211 style = "verbose"
212)]
213struct MisspelledKw {
214 similar_kw: String,
215 #[primary_span]
216 span: Span,
217 is_incorrect_case: bool,
218}
219
220fn find_similar_kw(lookup: Ident, candidates: &[Symbol]) -> Option<MisspelledKw> {
222 let lowercase = lookup.name.as_str().to_lowercase();
223 let lowercase_sym = Symbol::intern(&lowercase);
224 if candidates.contains(&lowercase_sym) {
225 Some(MisspelledKw { similar_kw: lowercase, span: lookup.span, is_incorrect_case: true })
226 } else if let Some(similar_sym) = find_best_match_for_name(candidates, lookup.name, None) {
227 Some(MisspelledKw {
228 similar_kw: similar_sym.to_string(),
229 span: lookup.span,
230 is_incorrect_case: false,
231 })
232 } else {
233 None
234 }
235}
236
237struct MultiSugg {
238 msg: String,
239 patches: Vec<(Span, String)>,
240 applicability: Applicability,
241}
242
243impl MultiSugg {
244 fn emit(self, err: &mut Diag<'_>) {
245 err.multipart_suggestion(self.msg, self.patches, self.applicability);
246 }
247
248 fn emit_verbose(self, err: &mut Diag<'_>) {
249 err.multipart_suggestion_verbose(self.msg, self.patches, self.applicability);
250 }
251}
252
253pub struct SnapshotParser<'a> {
257 parser: Parser<'a>,
258}
259
260impl<'a> Deref for SnapshotParser<'a> {
261 type Target = Parser<'a>;
262
263 fn deref(&self) -> &Self::Target {
264 &self.parser
265 }
266}
267
268impl<'a> DerefMut for SnapshotParser<'a> {
269 fn deref_mut(&mut self) -> &mut Self::Target {
270 &mut self.parser
271 }
272}
273
274impl<'a> Parser<'a> {
275 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
276 self.psess.dcx()
277 }
278
279 pub(super) fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
281 *self = snapshot.parser;
282 }
283
284 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
286 let snapshot = self.clone();
287 SnapshotParser { parser: snapshot }
288 }
289
290 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
291 self.psess.source_map().span_to_snippet(span)
292 }
293
294 pub(super) fn expected_ident_found(
298 &mut self,
299 recover: bool,
300 ) -> PResult<'a, (Ident, IdentIsRaw)> {
301 let valid_follow = &[
302 TokenKind::Eq,
303 TokenKind::Colon,
304 TokenKind::Comma,
305 TokenKind::Semi,
306 TokenKind::PathSep,
307 TokenKind::OpenBrace,
308 TokenKind::OpenParen,
309 TokenKind::CloseBrace,
310 TokenKind::CloseParen,
311 ];
312 if let TokenKind::DocComment(..) = self.prev_token.kind
313 && valid_follow.contains(&self.token.kind)
314 {
315 let err = self.dcx().create_err(DocCommentDoesNotDocumentAnything {
316 span: self.prev_token.span,
317 missing_comma: None,
318 });
319 return Err(err);
320 }
321
322 let mut recovered_ident = None;
323 let bad_token = self.token;
326
327 let suggest_raw = if let Some((ident, IdentIsRaw::No)) = self.token.ident()
329 && ident.is_raw_guess()
330 && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
331 {
332 recovered_ident = Some((ident, IdentIsRaw::Yes));
333
334 let ident_name = ident.name.to_string();
337
338 Some(SuggEscapeIdentifier { span: ident.span.shrink_to_lo(), ident_name })
339 } else {
340 None
341 };
342
343 let suggest_remove_comma =
344 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
345 if recover {
346 self.bump();
347 recovered_ident = self.ident_or_err(false).ok();
348 };
349
350 Some(SuggRemoveComma { span: bad_token.span })
351 } else {
352 None
353 };
354
355 let help_cannot_start_number = self.is_lit_bad_ident().map(|(len, valid_portion)| {
356 let (invalid, valid) = self.token.span.split_at(len as u32);
357
358 recovered_ident = Some((Ident::new(valid_portion, valid), IdentIsRaw::No));
359
360 HelpIdentifierStartsWithNumber { num_span: invalid }
361 });
362
363 let err = ExpectedIdentifier {
364 span: bad_token.span,
365 token: bad_token,
366 suggest_raw,
367 suggest_remove_comma,
368 help_cannot_start_number,
369 };
370 let mut err = self.dcx().create_err(err);
371
372 if self.token == token::Lt {
376 let valid_prev_keywords =
378 [kw::Fn, kw::Type, kw::Struct, kw::Enum, kw::Union, kw::Trait];
379
380 let maybe_keyword = self.prev_token;
386 if valid_prev_keywords.into_iter().any(|x| maybe_keyword.is_keyword(x)) {
387 match self.parse_generics() {
390 Ok(generic) => {
391 if let TokenKind::Ident(symbol, _) = maybe_keyword.kind {
392 let ident_name = symbol;
393 if !self.look_ahead(1, |t| *t == token::Lt)
399 && let Ok(snippet) =
400 self.psess.source_map().span_to_snippet(generic.span)
401 {
402 err.multipart_suggestion_verbose(
403 format!("place the generic parameter name after the {ident_name} name"),
404 vec![
405 (self.token.span.shrink_to_hi(), snippet),
406 (generic.span, String::new())
407 ],
408 Applicability::MaybeIncorrect,
409 );
410 } else {
411 err.help(format!(
412 "place the generic parameter name after the {ident_name} name"
413 ));
414 }
415 }
416 }
417 Err(err) => {
418 err.cancel();
422 }
423 }
424 }
425 }
426
427 if let Some(recovered_ident) = recovered_ident
428 && recover
429 {
430 err.emit();
431 Ok(recovered_ident)
432 } else {
433 Err(err)
434 }
435 }
436
437 pub(super) fn expected_ident_found_err(&mut self) -> Diag<'a> {
438 self.expected_ident_found(false).unwrap_err()
439 }
440
441 pub(super) fn is_lit_bad_ident(&mut self) -> Option<(usize, Symbol)> {
447 if let token::Literal(Lit {
451 kind: token::LitKind::Integer | token::LitKind::Float,
452 symbol,
453 suffix: Some(suffix), }) = self.token.kind
455 && rustc_ast::MetaItemLit::from_token(&self.token).is_none()
456 {
457 Some((symbol.as_str().len(), suffix))
458 } else {
459 None
460 }
461 }
462
463 pub(super) fn expected_one_of_not_found(
464 &mut self,
465 edible: &[ExpTokenPair<'_>],
466 inedible: &[ExpTokenPair<'_>],
467 ) -> PResult<'a, ErrorGuaranteed> {
468 debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
469 fn tokens_to_string(tokens: &[TokenType]) -> String {
470 let mut i = tokens.iter();
471 let b = i.next().map_or_else(String::new, |t| t.to_string());
473 i.enumerate().fold(b, |mut b, (i, a)| {
474 if tokens.len() > 2 && i == tokens.len() - 2 {
475 b.push_str(", or ");
476 } else if tokens.len() == 2 && i == tokens.len() - 2 {
477 b.push_str(" or ");
478 } else {
479 b.push_str(", ");
480 }
481 b.push_str(&a.to_string());
482 b
483 })
484 }
485
486 for exp in edible.iter().chain(inedible.iter()) {
487 self.expected_token_types.insert(exp.token_type);
488 }
489 let mut expected: Vec<_> = self.expected_token_types.iter().collect();
490 expected.sort_by_cached_key(|x| x.to_string());
491 expected.dedup();
492
493 let sm = self.psess.source_map();
494
495 if expected.contains(&TokenType::Semi) {
497 if self.prev_token == token::Question
500 && let Err(e) = self.maybe_recover_from_ternary_operator()
501 {
502 return Err(e);
503 }
504
505 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
506 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
508 } else if [token::Comma, token::Colon].contains(&self.token.kind)
510 && self.prev_token == token::CloseParen
511 {
512 } else if self.look_ahead(1, |t| {
521 t == &token::CloseBrace || t.can_begin_expr() && *t != token::Colon
522 }) && [token::Comma, token::Colon].contains(&self.token.kind)
523 {
524 let guar = self.dcx().emit_err(ExpectedSemi {
531 span: self.token.span,
532 token: self.token,
533 unexpected_token_label: None,
534 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
535 });
536 self.bump();
537 return Ok(guar);
538 } else if self.look_ahead(0, |t| {
539 t == &token::CloseBrace
540 || ((t.can_begin_expr() || t.can_begin_item())
541 && t != &token::Semi
542 && t != &token::Pound)
543 || (sm.is_multiline(
545 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
546 ) && t == &token::Pound)
547 }) && !expected.contains(&TokenType::Comma)
548 {
549 let span = self.prev_token.span.shrink_to_hi();
555 let guar = self.dcx().emit_err(ExpectedSemi {
556 span,
557 token: self.token,
558 unexpected_token_label: Some(self.token.span),
559 sugg: ExpectedSemiSugg::AddSemi(span),
560 });
561 return Ok(guar);
562 }
563 }
564
565 if self.token == TokenKind::EqEq
566 && self.prev_token.is_ident()
567 && expected.contains(&TokenType::Eq)
568 {
569 return Err(self.dcx().create_err(UseEqInstead { span: self.token.span }));
571 }
572
573 if (self.token.is_keyword(kw::Move) || self.token.is_keyword(kw::Use))
574 && self.prev_token.is_keyword(kw::Async)
575 {
576 let span = self.prev_token.span.to(self.token.span);
578 if self.token.is_keyword(kw::Move) {
579 return Err(self.dcx().create_err(AsyncMoveBlockIn2015 { span }));
580 } else {
581 return Err(self.dcx().create_err(AsyncUseBlockIn2015 { span }));
583 }
584 }
585
586 let expect = tokens_to_string(&expected);
587 let actual = super::token_descr(&self.token);
588 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
589 let fmt = format!("expected one of {expect}, found {actual}");
590 let short_expect = if expected.len() > 6 {
591 format!("{} possible tokens", expected.len())
592 } else {
593 expect
594 };
595 (fmt, (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")))
596 } else if expected.is_empty() {
597 (
598 format!("unexpected token: {actual}"),
599 (self.prev_token.span, "unexpected token after this".to_string()),
600 )
601 } else {
602 (
603 format!("expected {expect}, found {actual}"),
604 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
605 )
606 };
607 self.last_unexpected_token_span = Some(self.token.span);
608 let mut err = self.dcx().struct_span_err(self.token.span, msg_exp);
610
611 self.label_expected_raw_ref(&mut err);
612
613 if self.token == token::FatArrow
615 && expected.iter().any(|tok| matches!(tok, TokenType::Operator | TokenType::Le))
616 && !expected.iter().any(|tok| matches!(tok, TokenType::FatArrow | TokenType::Comma))
617 {
618 err.span_suggestion(
619 self.token.span,
620 "you might have meant to write a \"greater than or equal to\" comparison",
621 ">=",
622 Applicability::MaybeIncorrect,
623 );
624 }
625
626 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
627 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
628 err.span_suggestion_short(
629 self.prev_token.span,
630 format!("write `fn` instead of `{symbol}` to declare a function"),
631 "fn",
632 Applicability::MachineApplicable,
633 );
634 }
635 }
636
637 if let TokenKind::Ident(prev, _) = &self.prev_token.kind
638 && let TokenKind::Ident(cur, _) = &self.token.kind
639 {
640 let concat = Symbol::intern(&format!("{prev}{cur}"));
641 let ident = Ident::new(concat, DUMMY_SP);
642 if ident.is_used_keyword() || ident.is_reserved() || ident.is_raw_guess() {
643 let concat_span = self.prev_token.span.to(self.token.span);
644 err.span_suggestion_verbose(
645 concat_span,
646 format!("consider removing the space to spell keyword `{concat}`"),
647 concat,
648 Applicability::MachineApplicable,
649 );
650 }
651 }
652
653 if ((self.prev_token == TokenKind::Ident(sym::c, IdentIsRaw::No)
661 && matches!(&self.token.kind, TokenKind::Literal(token::Lit { kind: token::Str, .. })))
662 || (self.prev_token == TokenKind::Ident(sym::cr, IdentIsRaw::No)
663 && matches!(
664 &self.token.kind,
665 TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound
666 )))
667 && self.prev_token.span.hi() == self.token.span.lo()
668 && !self.token.span.at_least_rust_2021()
669 {
670 err.note("you may be trying to write a c-string literal");
671 err.note("c-string literals require Rust 2021 or later");
672 err.subdiagnostic(HelpUseLatestEdition::new());
673 }
674
675 if self.prev_token.is_ident_named(sym::public)
677 && (self.token.can_begin_item() || self.token == TokenKind::OpenParen)
678 {
679 err.span_suggestion_short(
680 self.prev_token.span,
681 "write `pub` instead of `public` to make the item public",
682 "pub",
683 Applicability::MachineApplicable,
684 );
685 }
686
687 if let token::DocComment(kind, style, _) = self.token.kind {
688 let pos = self.token.span.lo() + BytePos(2);
690 let span = self.token.span.with_lo(pos).with_hi(pos);
691 err.span_suggestion_verbose(
692 span,
693 format!(
694 "add a space before {} to write a regular comment",
695 match (kind, style) {
696 (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`",
697 (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`",
698 (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`",
699 (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`",
700 },
701 ),
702 " ".to_string(),
703 Applicability::MachineApplicable,
704 );
705 }
706
707 let sp = if self.token == token::Eof {
708 self.prev_token.span
710 } else {
711 label_sp
712 };
713
714 if self.check_too_many_raw_str_terminators(&mut err) {
715 if expected.contains(&TokenType::Semi) && self.eat(exp!(Semi)) {
716 let guar = err.emit();
717 return Ok(guar);
718 } else {
719 return Err(err);
720 }
721 }
722
723 if self.prev_token.span == DUMMY_SP {
724 err.span_label(self.token.span, label_exp);
727 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
728 err.span_label(self.token.span, label_exp);
741 } else {
742 err.span_label(sp, label_exp);
743 err.span_label(self.token.span, "unexpected token");
744 }
745
746 if matches!(&err.suggestions, Suggestions::Enabled(list) if list.is_empty()) {
748 self.check_for_misspelled_kw(&mut err, &expected);
749 }
750 Err(err)
751 }
752
753 pub(super) fn label_expected_raw_ref(&mut self, err: &mut Diag<'_>) {
758 if self.prev_token.is_keyword(kw::Raw)
759 && self.expected_token_types.contains(TokenType::KwMut)
760 && self.expected_token_types.contains(TokenType::KwConst)
761 && self.token.can_begin_expr()
762 {
763 err.span_suggestions(
764 self.prev_token.span.shrink_to_hi(),
765 "`&raw` must be followed by `const` or `mut` to be a raw reference expression",
766 [" const".to_string(), " mut".to_string()],
767 Applicability::MaybeIncorrect,
768 );
769 }
770 }
771
772 fn check_for_misspelled_kw(&self, err: &mut Diag<'_>, expected: &[TokenType]) {
775 let Some((curr_ident, _)) = self.token.ident() else {
776 return;
777 };
778 let expected_token_types: &[TokenType] =
779 expected.len().checked_sub(10).map_or(&expected, |index| &expected[index..]);
780 let expected_keywords: Vec<Symbol> =
781 expected_token_types.iter().filter_map(|token| token.is_keyword()).collect();
782
783 if !expected_keywords.is_empty()
788 && !curr_ident.is_used_keyword()
789 && let Some(misspelled_kw) = find_similar_kw(curr_ident, &expected_keywords)
790 {
791 err.subdiagnostic(misspelled_kw);
792 err.seal_suggestions();
795 } else if let Some((prev_ident, _)) = self.prev_token.ident()
796 && !prev_ident.is_used_keyword()
797 {
798 let all_keywords = used_keywords(|| prev_ident.span.edition());
803
804 if let Some(misspelled_kw) = find_similar_kw(prev_ident, &all_keywords) {
809 err.subdiagnostic(misspelled_kw);
810 err.seal_suggestions();
813 }
814 }
815 }
816
817 pub(super) fn attr_on_non_tail_expr(&self, expr: &Expr) -> ErrorGuaranteed {
819 let span = self.prev_token.span.shrink_to_hi();
821 let mut err = self.dcx().create_err(ExpectedSemi {
822 span,
823 token: self.token,
824 unexpected_token_label: Some(self.token.span),
825 sugg: ExpectedSemiSugg::AddSemi(span),
826 });
827 let attr_span = match &expr.attrs[..] {
828 [] => unreachable!(),
829 [only] => only.span,
830 [first, rest @ ..] => {
831 for attr in rest {
832 err.span_label(attr.span, "");
833 }
834 first.span
835 }
836 };
837 err.span_label(
838 attr_span,
839 format!(
840 "only `;` terminated statements or tail expressions are allowed after {}",
841 if expr.attrs.len() == 1 { "this attribute" } else { "these attributes" },
842 ),
843 );
844 if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
845 err.span_label(span, "expected `;` here");
851 err.multipart_suggestion(
852 "alternatively, consider surrounding the expression with a block",
853 vec![
854 (expr.span.shrink_to_lo(), "{ ".to_string()),
855 (expr.span.shrink_to_hi(), " }".to_string()),
856 ],
857 Applicability::MachineApplicable,
858 );
859
860 let mut snapshot = self.create_snapshot_for_diagnostic();
862 if let [attr] = &expr.attrs[..]
863 && let ast::AttrKind::Normal(attr_kind) = &attr.kind
864 && let [segment] = &attr_kind.item.path.segments[..]
865 && segment.ident.name == sym::cfg
866 && let Some(args_span) = attr_kind.item.args.span()
867 && let next_attr = match snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None))
868 {
869 Ok(next_attr) => next_attr,
870 Err(inner_err) => {
871 inner_err.cancel();
872 return err.emit();
873 }
874 }
875 && let ast::AttrKind::Normal(next_attr_kind) = next_attr.kind
876 && let Some(next_attr_args_span) = next_attr_kind.item.args.span()
877 && let [next_segment] = &next_attr_kind.item.path.segments[..]
878 && segment.ident.name == sym::cfg
879 {
880 let next_expr = match snapshot.parse_expr() {
881 Ok(next_expr) => next_expr,
882 Err(inner_err) => {
883 inner_err.cancel();
884 return err.emit();
885 }
886 };
887 let margin = self.psess.source_map().span_to_margin(next_expr.span).unwrap_or(0);
894 let sugg = vec![
895 (attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()),
896 (args_span.shrink_to_hi().with_hi(attr.span.hi()), " {".to_string()),
897 (expr.span.shrink_to_lo(), " ".to_string()),
898 (
899 next_attr.span.with_hi(next_segment.span().hi()),
900 "} else if cfg!".to_string(),
901 ),
902 (
903 next_attr_args_span.shrink_to_hi().with_hi(next_attr.span.hi()),
904 " {".to_string(),
905 ),
906 (next_expr.span.shrink_to_lo(), " ".to_string()),
907 (next_expr.span.shrink_to_hi(), format!("\n{}}}", " ".repeat(margin))),
908 ];
909 err.multipart_suggestion(
910 "it seems like you are trying to provide different expressions depending on \
911 `cfg`, consider using `if cfg!(..)`",
912 sugg,
913 Applicability::MachineApplicable,
914 );
915 }
916 }
917
918 err.emit()
919 }
920
921 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diag<'_>) -> bool {
922 let sm = self.psess.source_map();
923 match (&self.prev_token.kind, &self.token.kind) {
924 (
925 TokenKind::Literal(Lit {
926 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
927 ..
928 }),
929 TokenKind::Pound,
930 ) if !sm.is_multiline(
931 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
932 ) =>
933 {
934 let n_hashes: u8 = *n_hashes;
935 err.primary_message("too many `#` when terminating raw string");
936 let str_span = self.prev_token.span;
937 let mut span = self.token.span;
938 let mut count = 0;
939 while self.token == TokenKind::Pound
940 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
941 {
942 span = span.with_hi(self.token.span.hi());
943 self.bump();
944 count += 1;
945 }
946 err.span(span);
947 err.span_suggestion(
948 span,
949 format!("remove the extra `#`{}", pluralize!(count)),
950 "",
951 Applicability::MachineApplicable,
952 );
953 err.span_label(
954 str_span,
955 format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
956 );
957 true
958 }
959 _ => false,
960 }
961 }
962
963 pub(super) fn maybe_suggest_struct_literal(
964 &mut self,
965 lo: Span,
966 s: BlockCheckMode,
967 maybe_struct_name: token::Token,
968 ) -> Option<PResult<'a, P<Block>>> {
969 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
970 debug!(?maybe_struct_name, ?self.token);
975 let mut snapshot = self.create_snapshot_for_diagnostic();
976 let path = Path {
977 segments: ThinVec::new(),
978 span: self.prev_token.span.shrink_to_lo(),
979 tokens: None,
980 };
981 let struct_expr = snapshot.parse_expr_struct(None, path, false);
982 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
983 return Some(match (struct_expr, block_tail) {
984 (Ok(expr), Err(err)) => {
985 err.cancel();
994 self.restore_snapshot(snapshot);
995 let guar = self.dcx().emit_err(StructLiteralBodyWithoutPath {
996 span: expr.span,
997 sugg: StructLiteralBodyWithoutPathSugg {
998 before: expr.span.shrink_to_lo(),
999 after: expr.span.shrink_to_hi(),
1000 },
1001 });
1002 Ok(self.mk_block(
1003 thin_vec![self.mk_stmt_err(expr.span, guar)],
1004 s,
1005 lo.to(self.prev_token.span),
1006 ))
1007 }
1008 (Err(err), Ok(tail)) => {
1009 err.cancel();
1011 Ok(tail)
1012 }
1013 (Err(snapshot_err), Err(err)) => {
1014 snapshot_err.cancel();
1016 self.consume_block(exp!(OpenBrace), exp!(CloseBrace), ConsumeClosingDelim::Yes);
1017 Err(err)
1018 }
1019 (Ok(_), Ok(tail)) => Ok(tail),
1020 });
1021 }
1022 None
1023 }
1024
1025 pub(super) fn recover_closure_body(
1026 &mut self,
1027 mut err: Diag<'a>,
1028 before: token::Token,
1029 prev: token::Token,
1030 token: token::Token,
1031 lo: Span,
1032 decl_hi: Span,
1033 ) -> PResult<'a, P<Expr>> {
1034 err.span_label(lo.to(decl_hi), "while parsing the body of this closure");
1035 let guar = match before.kind {
1036 token::OpenBrace if token.kind != token::OpenBrace => {
1037 err.multipart_suggestion(
1039 "you might have meant to open the body of the closure, instead of enclosing \
1040 the closure in a block",
1041 vec![
1042 (before.span, String::new()),
1043 (prev.span.shrink_to_hi(), " {".to_string()),
1044 ],
1045 Applicability::MaybeIncorrect,
1046 );
1047 let guar = err.emit();
1048 self.eat_to_tokens(&[exp!(CloseBrace)]);
1049 guar
1050 }
1051 token::OpenParen if token.kind != token::OpenBrace => {
1052 self.eat_to_tokens(&[exp!(CloseParen), exp!(Comma)]);
1055
1056 err.multipart_suggestion_verbose(
1057 "you might have meant to open the body of the closure",
1058 vec![
1059 (prev.span.shrink_to_hi(), " {".to_string()),
1060 (self.token.span.shrink_to_lo(), "}".to_string()),
1061 ],
1062 Applicability::MaybeIncorrect,
1063 );
1064 err.emit()
1065 }
1066 _ if token.kind != token::OpenBrace => {
1067 err.multipart_suggestion_verbose(
1070 "you might have meant to open the body of the closure",
1071 vec![(prev.span.shrink_to_hi(), " {".to_string())],
1072 Applicability::HasPlaceholders,
1073 );
1074 return Err(err);
1075 }
1076 _ => return Err(err),
1077 };
1078 Ok(self.mk_expr_err(lo.to(self.token.span), guar))
1079 }
1080
1081 pub(super) fn eat_to_tokens(&mut self, closes: &[ExpTokenPair<'_>]) {
1084 if let Err(err) = self
1085 .parse_seq_to_before_tokens(closes, &[], SeqSep::none(), |p| Ok(p.parse_token_tree()))
1086 {
1087 err.cancel();
1088 }
1089 }
1090
1091 pub(super) fn check_trailing_angle_brackets(
1102 &mut self,
1103 segment: &PathSegment,
1104 end: &[ExpTokenPair<'_>],
1105 ) -> Option<ErrorGuaranteed> {
1106 if !self.may_recover() {
1107 return None;
1108 }
1109
1110 let parsed_angle_bracket_args =
1135 segment.args.as_ref().is_some_and(|args| args.is_angle_bracketed());
1136
1137 debug!(
1138 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
1139 parsed_angle_bracket_args,
1140 );
1141 if !parsed_angle_bracket_args {
1142 return None;
1143 }
1144
1145 let lo = self.token.span;
1148
1149 let mut position = 0;
1153
1154 let mut number_of_shr = 0;
1158 let mut number_of_gt = 0;
1159 while self.look_ahead(position, |t| {
1160 trace!("check_trailing_angle_brackets: t={:?}", t);
1161 if *t == token::Shr {
1162 number_of_shr += 1;
1163 true
1164 } else if *t == token::Gt {
1165 number_of_gt += 1;
1166 true
1167 } else {
1168 false
1169 }
1170 }) {
1171 position += 1;
1172 }
1173
1174 debug!(
1176 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
1177 number_of_gt, number_of_shr,
1178 );
1179 if number_of_gt < 1 && number_of_shr < 1 {
1180 return None;
1181 }
1182
1183 if self.look_ahead(position, |t| {
1186 trace!("check_trailing_angle_brackets: t={:?}", t);
1187 end.iter().any(|exp| exp.tok == &t.kind)
1188 }) {
1189 self.eat_to_tokens(end);
1192 let span = lo.to(self.prev_token.span);
1193
1194 let num_extra_brackets = number_of_gt + number_of_shr * 2;
1195 return Some(self.dcx().emit_err(UnmatchedAngleBrackets { span, num_extra_brackets }));
1196 }
1197 None
1198 }
1199
1200 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
1203 if !self.may_recover() {
1204 return;
1205 }
1206
1207 if self.token == token::PathSep && segment.args.is_none() {
1208 let snapshot = self.create_snapshot_for_diagnostic();
1209 self.bump();
1210 let lo = self.token.span;
1211 match self.parse_angle_args(None) {
1212 Ok(args) => {
1213 let span = lo.to(self.prev_token.span);
1214 let mut trailing_span = self.prev_token.span.shrink_to_hi();
1216 while self.token == token::Shr || self.token == token::Gt {
1217 trailing_span = trailing_span.to(self.token.span);
1218 self.bump();
1219 }
1220 if self.token == token::OpenParen {
1221 segment.args = Some(AngleBracketedArgs { args, span }.into());
1223
1224 self.dcx().emit_err(GenericParamsWithoutAngleBrackets {
1225 span,
1226 sugg: GenericParamsWithoutAngleBracketsSugg {
1227 left: span.shrink_to_lo(),
1228 right: trailing_span,
1229 },
1230 });
1231 } else {
1232 self.restore_snapshot(snapshot);
1234 }
1235 }
1236 Err(err) => {
1237 err.cancel();
1240 self.restore_snapshot(snapshot);
1241 }
1242 }
1243 }
1244 }
1245
1246 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
1249 &mut self,
1250 mut e: Diag<'a>,
1251 expr: &mut P<Expr>,
1252 ) -> PResult<'a, ErrorGuaranteed> {
1253 if let ExprKind::Binary(binop, _, _) = &expr.kind
1254 && let ast::BinOpKind::Lt = binop.node
1255 && self.eat(exp!(Comma))
1256 {
1257 let x = self.parse_seq_to_before_end(
1258 exp!(Gt),
1259 SeqSep::trailing_allowed(exp!(Comma)),
1260 |p| match p.parse_generic_arg(None)? {
1261 Some(arg) => Ok(arg),
1262 None => p.unexpected_any(),
1264 },
1265 );
1266 match x {
1267 Ok((_, _, Recovered::No)) => {
1268 if self.eat(exp!(Gt)) {
1269 e.span_suggestion_verbose(
1271 binop.span.shrink_to_lo(),
1272 fluent::parse_sugg_turbofish_syntax,
1273 "::",
1274 Applicability::MaybeIncorrect,
1275 );
1276 match self.parse_expr() {
1277 Ok(_) => {
1278 let guar = e.emit();
1282 *expr = self.mk_expr_err(expr.span.to(self.prev_token.span), guar);
1283 return Ok(guar);
1284 }
1285 Err(err) => {
1286 err.cancel();
1287 }
1288 }
1289 }
1290 }
1291 Ok((_, _, Recovered::Yes(_))) => {}
1292 Err(err) => {
1293 err.cancel();
1294 }
1295 }
1296 }
1297 Err(e)
1298 }
1299
1300 pub(super) fn suggest_add_missing_let_for_stmt(&mut self, err: &mut Diag<'a>) {
1303 if self.token == token::Colon {
1304 let prev_span = self.prev_token.span.shrink_to_lo();
1305 let snapshot = self.create_snapshot_for_diagnostic();
1306 self.bump();
1307 match self.parse_ty() {
1308 Ok(_) => {
1309 if self.token == token::Eq {
1310 let sugg = SuggAddMissingLetStmt { span: prev_span };
1311 sugg.add_to_diag(err);
1312 }
1313 }
1314 Err(e) => {
1315 e.cancel();
1316 }
1317 }
1318 self.restore_snapshot(snapshot);
1319 }
1320 }
1321
1322 fn attempt_chained_comparison_suggestion(
1326 &mut self,
1327 err: &mut ComparisonOperatorsCannotBeChained,
1328 inner_op: &Expr,
1329 outer_op: &Spanned<AssocOp>,
1330 ) -> bool {
1331 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
1332 if let ExprKind::Field(_, ident) = l1.kind
1333 && !ident.is_numeric()
1334 && !matches!(r1.kind, ExprKind::Lit(_))
1335 {
1336 return false;
1339 }
1340 return match (op.node, &outer_op.node) {
1341 (BinOpKind::Eq, AssocOp::Binary(BinOpKind::Eq)) |
1343 (BinOpKind::Lt, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1345 (BinOpKind::Le, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1346 (BinOpKind::Gt, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) |
1348 (BinOpKind::Ge, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) => {
1349 let expr_to_str = |e: &Expr| {
1350 self.span_to_snippet(e.span)
1351 .unwrap_or_else(|_| pprust::expr_to_string(e))
1352 };
1353 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
1354 span: inner_op.span.shrink_to_hi(),
1355 middle_term: expr_to_str(r1),
1356 });
1357 false }
1359 (
1361 BinOpKind::Eq,
1362 AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge)
1363 ) => {
1364 let snapshot = self.create_snapshot_for_diagnostic();
1366 match self.parse_expr() {
1367 Ok(r2) => {
1368 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1371 left: r1.span.shrink_to_lo(),
1372 right: r2.span.shrink_to_hi(),
1373 });
1374 true
1375 }
1376 Err(expr_err) => {
1377 expr_err.cancel();
1378 self.restore_snapshot(snapshot);
1379 true
1380 }
1381 }
1382 }
1383 (
1385 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge,
1386 AssocOp::Binary(BinOpKind::Eq)
1387 ) => {
1388 let snapshot = self.create_snapshot_for_diagnostic();
1389 match self.parse_expr() {
1392 Ok(_) => {
1393 err.chaining_sugg = Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1394 left: l1.span.shrink_to_lo(),
1395 right: r1.span.shrink_to_hi(),
1396 });
1397 true
1398 }
1399 Err(expr_err) => {
1400 expr_err.cancel();
1401 self.restore_snapshot(snapshot);
1402 false
1403 }
1404 }
1405 }
1406 _ => false
1407 };
1408 }
1409 false
1410 }
1411
1412 pub(super) fn check_no_chained_comparison(
1431 &mut self,
1432 inner_op: &Expr,
1433 outer_op: &Spanned<AssocOp>,
1434 ) -> PResult<'a, Option<P<Expr>>> {
1435 debug_assert!(
1436 outer_op.node.is_comparison(),
1437 "check_no_chained_comparison: {:?} is not comparison",
1438 outer_op.node,
1439 );
1440
1441 let mk_err_expr =
1442 |this: &Self, span, guar| Ok(Some(this.mk_expr(span, ExprKind::Err(guar))));
1443
1444 match &inner_op.kind {
1445 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1446 let mut err = ComparisonOperatorsCannotBeChained {
1447 span: vec![op.span, self.prev_token.span],
1448 suggest_turbofish: None,
1449 help_turbofish: false,
1450 chaining_sugg: None,
1451 };
1452
1453 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Binary(BinOpKind::Lt)
1456 || outer_op.node == AssocOp::Binary(BinOpKind::Gt)
1457 {
1458 if outer_op.node == AssocOp::Binary(BinOpKind::Lt) {
1459 let snapshot = self.create_snapshot_for_diagnostic();
1460 self.bump();
1461 let modifiers = [(token::Lt, 1), (token::Gt, -1), (token::Shr, -2)];
1463 self.consume_tts(1, &modifiers);
1464
1465 if !matches!(self.token.kind, token::OpenParen | token::PathSep) {
1466 self.restore_snapshot(snapshot);
1469 }
1470 }
1471 return if self.token == token::PathSep {
1472 if let ExprKind::Binary(o, ..) = inner_op.kind
1475 && o.node == BinOpKind::Lt
1476 {
1477 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1478 } else {
1479 err.help_turbofish = true;
1480 }
1481
1482 let snapshot = self.create_snapshot_for_diagnostic();
1483 self.bump(); match self.parse_expr() {
1487 Ok(_) => {
1488 let guar = self.dcx().emit_err(err);
1490 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1494 }
1495 Err(expr_err) => {
1496 expr_err.cancel();
1497 self.restore_snapshot(snapshot);
1500 Err(self.dcx().create_err(err))
1501 }
1502 }
1503 } else if self.token == token::OpenParen {
1504 if let ExprKind::Binary(o, ..) = inner_op.kind
1507 && o.node == BinOpKind::Lt
1508 {
1509 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1510 } else {
1511 err.help_turbofish = true;
1512 }
1513 match self.consume_fn_args() {
1515 Err(()) => Err(self.dcx().create_err(err)),
1516 Ok(()) => {
1517 let guar = self.dcx().emit_err(err);
1518 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1522 }
1523 }
1524 } else {
1525 if !matches!(l1.kind, ExprKind::Lit(_))
1526 && !matches!(r1.kind, ExprKind::Lit(_))
1527 {
1528 err.help_turbofish = true;
1531 }
1532
1533 let recovered = self
1536 .attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1537 if recovered {
1538 let guar = self.dcx().emit_err(err);
1539 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1540 } else {
1541 Err(self.dcx().create_err(err))
1543 }
1544 };
1545 }
1546 let recovered =
1547 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1548 let guar = self.dcx().emit_err(err);
1549 if recovered {
1550 return mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar);
1551 }
1552 }
1553 _ => {}
1554 }
1555 Ok(None)
1556 }
1557
1558 fn consume_fn_args(&mut self) -> Result<(), ()> {
1559 let snapshot = self.create_snapshot_for_diagnostic();
1560 self.bump(); let modifiers = [(token::OpenParen, 1), (token::CloseParen, -1)];
1564 self.consume_tts(1, &modifiers);
1565
1566 if self.token == token::Eof {
1567 self.restore_snapshot(snapshot);
1569 Err(())
1570 } else {
1571 Ok(())
1573 }
1574 }
1575
1576 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1577 if impl_dyn_multi {
1578 self.dcx().emit_err(AmbiguousPlus {
1579 span: ty.span,
1580 suggestion: AddParen { lo: ty.span.shrink_to_lo(), hi: ty.span.shrink_to_hi() },
1581 });
1582 }
1583 }
1584
1585 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: P<Ty>) -> P<Ty> {
1587 if self.token == token::Question {
1588 self.bump();
1589 let guar = self.dcx().emit_err(QuestionMarkInType {
1590 span: self.prev_token.span,
1591 sugg: QuestionMarkInTypeSugg {
1592 left: ty.span.shrink_to_lo(),
1593 right: self.prev_token.span,
1594 },
1595 });
1596 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err(guar))
1597 } else {
1598 ty
1599 }
1600 }
1601
1602 pub(super) fn maybe_recover_from_ternary_operator(&mut self) -> PResult<'a, ()> {
1606 if self.prev_token != token::Question {
1607 return PResult::Ok(());
1608 }
1609
1610 let lo = self.prev_token.span.lo();
1611 let snapshot = self.create_snapshot_for_diagnostic();
1612
1613 if match self.parse_expr() {
1614 Ok(_) => true,
1615 Err(err) => {
1616 err.cancel();
1617 self.token == token::Colon
1620 }
1621 } {
1622 if self.eat_noexpect(&token::Colon) {
1623 match self.parse_expr() {
1624 Ok(_) => {
1625 return Err(self
1626 .dcx()
1627 .create_err(TernaryOperator { span: self.token.span.with_lo(lo) }));
1628 }
1629 Err(err) => {
1630 err.cancel();
1631 }
1632 };
1633 }
1634 }
1635 self.restore_snapshot(snapshot);
1636 Ok(())
1637 }
1638
1639 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1640 if !self.token.is_like_plus() {
1642 return Ok(());
1643 }
1644
1645 self.bump(); let _bounds = self.parse_generic_bounds()?;
1647 let sub = match &ty.kind {
1648 TyKind::Ref(_lifetime, mut_ty) => {
1649 let lo = mut_ty.ty.span.shrink_to_lo();
1650 let hi = self.prev_token.span.shrink_to_hi();
1651 BadTypePlusSub::AddParen { suggestion: AddParen { lo, hi } }
1652 }
1653 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1654 BadTypePlusSub::ForgotParen { span: ty.span.to(self.prev_token.span) }
1655 }
1656 _ => BadTypePlusSub::ExpectPath { span: ty.span },
1657 };
1658
1659 self.dcx().emit_err(BadTypePlus { span: ty.span, sub });
1660
1661 Ok(())
1662 }
1663
1664 pub(super) fn recover_from_prefix_increment(
1665 &mut self,
1666 operand_expr: P<Expr>,
1667 op_span: Span,
1668 start_stmt: bool,
1669 ) -> PResult<'a, P<Expr>> {
1670 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1671 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1672 self.recover_from_inc_dec(operand_expr, kind, op_span)
1673 }
1674
1675 pub(super) fn recover_from_postfix_increment(
1676 &mut self,
1677 operand_expr: P<Expr>,
1678 op_span: Span,
1679 start_stmt: bool,
1680 ) -> PResult<'a, P<Expr>> {
1681 let kind = IncDecRecovery {
1682 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1683 op: IncOrDec::Inc,
1684 fixity: UnaryFixity::Post,
1685 };
1686 self.recover_from_inc_dec(operand_expr, kind, op_span)
1687 }
1688
1689 pub(super) fn recover_from_postfix_decrement(
1690 &mut self,
1691 operand_expr: P<Expr>,
1692 op_span: Span,
1693 start_stmt: bool,
1694 ) -> PResult<'a, P<Expr>> {
1695 let kind = IncDecRecovery {
1696 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1697 op: IncOrDec::Dec,
1698 fixity: UnaryFixity::Post,
1699 };
1700 self.recover_from_inc_dec(operand_expr, kind, op_span)
1701 }
1702
1703 fn recover_from_inc_dec(
1704 &mut self,
1705 base: P<Expr>,
1706 kind: IncDecRecovery,
1707 op_span: Span,
1708 ) -> PResult<'a, P<Expr>> {
1709 let mut err = self.dcx().struct_span_err(
1710 op_span,
1711 format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1712 );
1713 err.span_label(op_span, format!("not a valid {} operator", kind.fixity));
1714
1715 let help_base_case = |mut err: Diag<'_, _>, base| {
1716 err.help(format!("use `{}= 1` instead", kind.op.chr()));
1717 err.emit();
1718 Ok(base)
1719 };
1720
1721 let spans = match kind.fixity {
1723 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1724 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1725 };
1726
1727 match kind.standalone {
1728 IsStandalone::Standalone => {
1729 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1730 }
1731 IsStandalone::Subexpr => {
1732 let Ok(base_src) = self.span_to_snippet(base.span) else {
1733 return help_base_case(err, base);
1734 };
1735 match kind.fixity {
1736 UnaryFixity::Pre => {
1737 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1738 }
1739 UnaryFixity::Post => {
1740 if !matches!(base.kind, ExprKind::Binary(_, _, _)) {
1743 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1744 }
1745 }
1746 }
1747 }
1748 }
1749 Err(err)
1750 }
1751
1752 fn prefix_inc_dec_suggest(
1753 &mut self,
1754 base_src: String,
1755 kind: IncDecRecovery,
1756 (pre_span, post_span): (Span, Span),
1757 ) -> MultiSugg {
1758 MultiSugg {
1759 msg: format!("use `{}= 1` instead", kind.op.chr()),
1760 patches: vec![
1761 (pre_span, "{ ".to_string()),
1762 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1763 ],
1764 applicability: Applicability::MachineApplicable,
1765 }
1766 }
1767
1768 fn postfix_inc_dec_suggest(
1769 &mut self,
1770 base_src: String,
1771 kind: IncDecRecovery,
1772 (pre_span, post_span): (Span, Span),
1773 ) -> MultiSugg {
1774 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1775 MultiSugg {
1776 msg: format!("use `{}= 1` instead", kind.op.chr()),
1777 patches: vec![
1778 (pre_span, format!("{{ let {tmp_var} = ")),
1779 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1780 ],
1781 applicability: Applicability::HasPlaceholders,
1782 }
1783 }
1784
1785 fn inc_dec_standalone_suggest(
1786 &mut self,
1787 kind: IncDecRecovery,
1788 (pre_span, post_span): (Span, Span),
1789 ) -> MultiSugg {
1790 let mut patches = Vec::new();
1791
1792 if !pre_span.is_empty() {
1793 patches.push((pre_span, String::new()));
1794 }
1795
1796 patches.push((post_span, format!(" {}= 1", kind.op.chr())));
1797 MultiSugg {
1798 msg: format!("use `{}= 1` instead", kind.op.chr()),
1799 patches,
1800 applicability: Applicability::MachineApplicable,
1801 }
1802 }
1803
1804 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1808 &mut self,
1809 base: P<T>,
1810 ) -> PResult<'a, P<T>> {
1811 if !self.may_recover() {
1812 return Ok(base);
1813 }
1814
1815 if self.token == token::PathSep {
1817 if let Some(ty) = base.to_ty() {
1818 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1819 }
1820 }
1821 Ok(base)
1822 }
1823
1824 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1827 &mut self,
1828 ty_span: Span,
1829 ty: P<Ty>,
1830 ) -> PResult<'a, P<T>> {
1831 self.expect(exp!(PathSep))?;
1832
1833 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None };
1834 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1835 path.span = ty_span.to(self.prev_token.span);
1836
1837 self.dcx().emit_err(BadQPathStage2 {
1838 span: ty_span,
1839 wrap: WrapType { lo: ty_span.shrink_to_lo(), hi: ty_span.shrink_to_hi() },
1840 });
1841
1842 let path_span = ty_span.shrink_to_hi(); Ok(P(T::recovered(Some(P(QSelf { ty, path_span, position: 0 })), path)))
1844 }
1845
1846 pub fn maybe_consume_incorrect_semicolon(&mut self, previous_item: Option<&Item>) -> bool {
1849 if self.token != TokenKind::Semi {
1850 return false;
1851 }
1852
1853 let err = match previous_item {
1856 Some(previous_item) => {
1857 let name = match previous_item.kind {
1858 ItemKind::Struct(..) => "braced struct",
1861 _ => previous_item.kind.descr(),
1862 };
1863 IncorrectSemicolon { span: self.token.span, name, show_help: true }
1864 }
1865 None => IncorrectSemicolon { span: self.token.span, name: "", show_help: false },
1866 };
1867 self.dcx().emit_err(err);
1868
1869 self.bump();
1870 true
1871 }
1872
1873 pub(super) fn unexpected_try_recover(&mut self, t: &TokenKind) -> PResult<'a, Recovered> {
1876 let token_str = pprust::token_kind_to_string(t);
1877 let this_token_str = super::token_descr(&self.token);
1878 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1879 (token::Eof, Some(_)) => {
1881 let sp = self.prev_token.span.shrink_to_hi();
1882 (sp, sp)
1883 }
1884 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1887 (token::Eof, None) => (self.prev_token.span, self.token.span),
1889 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1890 };
1891 let msg = format!(
1892 "expected `{}`, found {}",
1893 token_str,
1894 match (&self.token.kind, self.subparser_name) {
1895 (token::Eof, Some(origin)) => format!("end of {origin}"),
1896 _ => this_token_str,
1897 },
1898 );
1899 let mut err = self.dcx().struct_span_err(sp, msg);
1900 let label_exp = format!("expected `{token_str}`");
1901 let sm = self.psess.source_map();
1902 if !sm.is_multiline(prev_sp.until(sp)) {
1903 err.span_label(sp, label_exp);
1906 } else {
1907 err.span_label(prev_sp, label_exp);
1908 err.span_label(sp, "unexpected token");
1909 }
1910 Err(err)
1911 }
1912
1913 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1914 if self.eat(exp!(Semi)) || self.recover_colon_as_semi() {
1915 return Ok(());
1916 }
1917 self.expect(exp!(Semi)).map(drop) }
1919
1920 pub(super) fn recover_colon_as_semi(&mut self) -> bool {
1921 let line_idx = |span: Span| {
1922 self.psess
1923 .source_map()
1924 .span_to_lines(span)
1925 .ok()
1926 .and_then(|lines| Some(lines.lines.get(0)?.line_index))
1927 };
1928
1929 if self.may_recover()
1930 && self.token == token::Colon
1931 && self.look_ahead(1, |next| line_idx(self.token.span) < line_idx(next.span))
1932 {
1933 self.dcx().emit_err(ColonAsSemi { span: self.token.span });
1934 self.bump();
1935 return true;
1936 }
1937
1938 false
1939 }
1940
1941 pub(super) fn recover_incorrect_await_syntax(
1944 &mut self,
1945 await_sp: Span,
1946 ) -> PResult<'a, P<Expr>> {
1947 let (hi, expr, is_question) = if self.token == token::Bang {
1948 self.recover_await_macro()?
1950 } else {
1951 self.recover_await_prefix(await_sp)?
1952 };
1953 let (sp, guar) = self.error_on_incorrect_await(await_sp, hi, &expr, is_question);
1954 let expr = self.mk_expr_err(await_sp.to(sp), guar);
1955 self.maybe_recover_from_bad_qpath(expr)
1956 }
1957
1958 fn recover_await_macro(&mut self) -> PResult<'a, (Span, P<Expr>, bool)> {
1959 self.expect(exp!(Bang))?;
1960 self.expect(exp!(OpenParen))?;
1961 let expr = self.parse_expr()?;
1962 self.expect(exp!(CloseParen))?;
1963 Ok((self.prev_token.span, expr, false))
1964 }
1965
1966 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, P<Expr>, bool)> {
1967 let is_question = self.eat(exp!(Question)); let expr = if self.token == token::OpenBrace {
1969 self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)
1973 } else {
1974 self.parse_expr()
1975 }
1976 .map_err(|mut err| {
1977 err.span_label(await_sp, format!("while parsing this incorrect await expression"));
1978 err
1979 })?;
1980 Ok((expr.span, expr, is_question))
1981 }
1982
1983 fn error_on_incorrect_await(
1984 &self,
1985 lo: Span,
1986 hi: Span,
1987 expr: &Expr,
1988 is_question: bool,
1989 ) -> (Span, ErrorGuaranteed) {
1990 let span = lo.to(hi);
1991 let guar = self.dcx().emit_err(IncorrectAwait {
1992 span,
1993 suggestion: AwaitSuggestion {
1994 removal: lo.until(expr.span),
1995 dot_await: expr.span.shrink_to_hi(),
1996 question_mark: if is_question { "?" } else { "" },
1997 },
1998 });
1999 (span, guar)
2000 }
2001
2002 pub(super) fn recover_from_await_method_call(&mut self) {
2004 if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
2005 let lo = self.token.span;
2007 self.bump(); let span = lo.to(self.token.span);
2009 self.bump(); self.dcx().emit_err(IncorrectUseOfAwait { span });
2012 }
2013 }
2014 pub(super) fn recover_from_use(&mut self) {
2017 if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
2018 let lo = self.token.span;
2020 self.bump(); let span = lo.to(self.token.span);
2022 self.bump(); self.dcx().emit_err(IncorrectUseOfUse { span });
2025 }
2026 }
2027
2028 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, P<Expr>> {
2029 let is_try = self.token.is_keyword(kw::Try);
2030 let is_questionmark = self.look_ahead(1, |t| t == &token::Bang); let is_open = self.look_ahead(2, |t| t == &token::OpenParen); if is_try && is_questionmark && is_open {
2034 let lo = self.token.span;
2035 self.bump(); self.bump(); let try_span = lo.to(self.token.span); self.bump(); let is_empty = self.token == token::CloseParen; self.consume_block(exp!(OpenParen), exp!(CloseParen), ConsumeClosingDelim::No); let hi = self.token.span;
2042 self.bump(); let mut err = self.dcx().struct_span_err(lo.to(hi), "use of deprecated `try` macro");
2044 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
2045 let prefix = if is_empty { "" } else { "alternatively, " };
2046 if !is_empty {
2047 err.multipart_suggestion(
2048 "you can use the `?` operator instead",
2049 vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
2050 Applicability::MachineApplicable,
2051 );
2052 }
2053 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);
2054 let guar = err.emit();
2055 Ok(self.mk_expr_err(lo.to(hi), guar))
2056 } else {
2057 Err(self.expected_expression_found()) }
2059 }
2060
2061 pub(super) fn expect_gt_or_maybe_suggest_closing_generics(
2068 &mut self,
2069 params: &[ast::GenericParam],
2070 ) -> PResult<'a, ()> {
2071 let Err(mut err) = self.expect_gt() else {
2072 return Ok(());
2073 };
2074 if let [.., ast::GenericParam { bounds, .. }] = params
2076 && let Some(poly) = bounds
2077 .iter()
2078 .filter_map(|bound| match bound {
2079 ast::GenericBound::Trait(poly) => Some(poly),
2080 _ => None,
2081 })
2082 .next_back()
2083 {
2084 err.span_suggestion_verbose(
2085 poly.span.shrink_to_hi(),
2086 "you might have meant to end the type parameters here",
2087 ">",
2088 Applicability::MaybeIncorrect,
2089 );
2090 }
2091 Err(err)
2092 }
2093
2094 pub(super) fn recover_seq_parse_error(
2095 &mut self,
2096 open: ExpTokenPair<'_>,
2097 close: ExpTokenPair<'_>,
2098 lo: Span,
2099 err: Diag<'a>,
2100 ) -> P<Expr> {
2101 let guar = err.emit();
2102 self.consume_block(open, close, ConsumeClosingDelim::Yes);
2104 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err(guar))
2105 }
2106
2107 pub(super) fn recover_stmt(&mut self) {
2112 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
2113 }
2114
2115 pub(super) fn recover_stmt_(
2123 &mut self,
2124 break_on_semi: SemiColonMode,
2125 break_on_block: BlockMode,
2126 ) {
2127 let mut brace_depth = 0;
2128 let mut bracket_depth = 0;
2129 let mut in_block = false;
2130 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
2131 loop {
2132 debug!("recover_stmt_ loop {:?}", self.token);
2133 match self.token.kind {
2134 token::OpenBrace => {
2135 brace_depth += 1;
2136 self.bump();
2137 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
2138 {
2139 in_block = true;
2140 }
2141 }
2142 token::OpenBracket => {
2143 bracket_depth += 1;
2144 self.bump();
2145 }
2146 token::CloseBrace => {
2147 if brace_depth == 0 {
2148 debug!("recover_stmt_ return - close delim {:?}", self.token);
2149 break;
2150 }
2151 brace_depth -= 1;
2152 self.bump();
2153 if in_block && bracket_depth == 0 && brace_depth == 0 {
2154 debug!("recover_stmt_ return - block end {:?}", self.token);
2155 break;
2156 }
2157 }
2158 token::CloseBracket => {
2159 bracket_depth -= 1;
2160 if bracket_depth < 0 {
2161 bracket_depth = 0;
2162 }
2163 self.bump();
2164 }
2165 token::Eof => {
2166 debug!("recover_stmt_ return - Eof");
2167 break;
2168 }
2169 token::Semi => {
2170 self.bump();
2171 if break_on_semi == SemiColonMode::Break
2172 && brace_depth == 0
2173 && bracket_depth == 0
2174 {
2175 debug!("recover_stmt_ return - Semi");
2176 break;
2177 }
2178 }
2179 token::Comma
2180 if break_on_semi == SemiColonMode::Comma
2181 && brace_depth == 0
2182 && bracket_depth == 0 =>
2183 {
2184 break;
2185 }
2186 _ => self.bump(),
2187 }
2188 }
2189 }
2190
2191 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
2192 if self.eat_keyword(exp!(In)) {
2193 self.dcx().emit_err(InInTypo {
2195 span: self.prev_token.span,
2196 sugg_span: in_span.until(self.prev_token.span),
2197 });
2198 }
2199 }
2200
2201 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
2202 if let token::DocComment(..) = self.token.kind {
2203 self.dcx().emit_err(DocCommentOnParamType { span: self.token.span });
2204 self.bump();
2205 } else if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
2206 let lo = self.token.span;
2207 while self.token != token::CloseBracket {
2209 self.bump();
2210 }
2211 let sp = lo.to(self.token.span);
2212 self.bump();
2213 self.dcx().emit_err(AttributeOnParamType { span: sp });
2214 }
2215 }
2216
2217 pub(super) fn parameter_without_type(
2218 &mut self,
2219 err: &mut Diag<'_>,
2220 pat: P<ast::Pat>,
2221 require_name: bool,
2222 first_param: bool,
2223 ) -> Option<Ident> {
2224 if self.check_ident()
2227 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen)
2228 {
2229 let ident = self.parse_ident().unwrap();
2231 let span = pat.span.with_hi(ident.span.hi());
2232
2233 err.span_suggestion(
2234 span,
2235 "declare the type after the parameter binding",
2236 "<identifier>: <type>",
2237 Applicability::HasPlaceholders,
2238 );
2239 return Some(ident);
2240 } else if require_name
2241 && (self.token == token::Comma
2242 || self.token == token::Lt
2243 || self.token == token::CloseParen)
2244 {
2245 let rfc_note = "anonymous parameters are removed in the 2018 edition (see RFC 1685)";
2246
2247 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
2248 match pat.kind {
2249 PatKind::Ident(_, ident, _) => (
2250 ident,
2251 "self: ",
2252 ": TypeName".to_string(),
2253 "_: ",
2254 pat.span.shrink_to_lo(),
2255 pat.span.shrink_to_hi(),
2256 pat.span.shrink_to_lo(),
2257 ),
2258 PatKind::Ref(ref inner_pat, mutab)
2260 if matches!(inner_pat.clone().into_inner().kind, PatKind::Ident(..)) =>
2261 {
2262 match inner_pat.clone().into_inner().kind {
2263 PatKind::Ident(_, ident, _) => {
2264 let mutab = mutab.prefix_str();
2265 (
2266 ident,
2267 "self: ",
2268 format!("{ident}: &{mutab}TypeName"),
2269 "_: ",
2270 pat.span.shrink_to_lo(),
2271 pat.span,
2272 pat.span.shrink_to_lo(),
2273 )
2274 }
2275 _ => unreachable!(),
2276 }
2277 }
2278 _ => {
2279 if let Some(_) = pat.to_ty() {
2281 err.span_suggestion_verbose(
2282 pat.span.shrink_to_lo(),
2283 "explicitly ignore the parameter name",
2284 "_: ".to_string(),
2285 Applicability::MachineApplicable,
2286 );
2287 err.note(rfc_note);
2288 }
2289
2290 return None;
2291 }
2292 };
2293
2294 if first_param {
2296 err.span_suggestion_verbose(
2297 self_span,
2298 "if this is a `self` type, give it a parameter name",
2299 self_sugg,
2300 Applicability::MaybeIncorrect,
2301 );
2302 }
2303 if self.token != token::Lt {
2306 err.span_suggestion_verbose(
2307 param_span,
2308 "if this is a parameter name, give it a type",
2309 param_sugg,
2310 Applicability::HasPlaceholders,
2311 );
2312 }
2313 err.span_suggestion_verbose(
2314 type_span,
2315 "if this is a type, explicitly ignore the parameter name",
2316 type_sugg,
2317 Applicability::MachineApplicable,
2318 );
2319 err.note(rfc_note);
2320
2321 return if self.token == token::Lt { None } else { Some(ident) };
2323 }
2324 None
2325 }
2326
2327 pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> {
2328 let pat = self.parse_pat_no_top_alt(Some(Expected::ArgumentName), None)?;
2329 self.expect(exp!(Colon))?;
2330 let ty = self.parse_ty()?;
2331
2332 self.dcx().emit_err(PatternMethodParamWithoutBody { span: pat.span });
2333
2334 let pat =
2336 P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID, tokens: None });
2337 Ok((pat, ty))
2338 }
2339
2340 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2341 let span = param.pat.span;
2342 let guar = self.dcx().emit_err(SelfParamNotFirst { span });
2343 param.ty.kind = TyKind::Err(guar);
2344 Ok(param)
2345 }
2346
2347 pub(super) fn consume_block(
2348 &mut self,
2349 open: ExpTokenPair<'_>,
2350 close: ExpTokenPair<'_>,
2351 consume_close: ConsumeClosingDelim,
2352 ) {
2353 let mut brace_depth = 0;
2354 loop {
2355 if self.eat(open) {
2356 brace_depth += 1;
2357 } else if self.check(close) {
2358 if brace_depth == 0 {
2359 if let ConsumeClosingDelim::Yes = consume_close {
2360 self.bump();
2364 }
2365 return;
2366 } else {
2367 self.bump();
2368 brace_depth -= 1;
2369 continue;
2370 }
2371 } else if self.token == token::Eof {
2372 return;
2373 } else {
2374 self.bump();
2375 }
2376 }
2377 }
2378
2379 pub(super) fn expected_expression_found(&self) -> Diag<'a> {
2380 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2381 (&token::Eof, Some(origin)) => {
2382 let sp = self.prev_token.span.shrink_to_hi();
2383 (sp, format!("expected expression, found end of {origin}"))
2384 }
2385 _ => (
2386 self.token.span,
2387 format!("expected expression, found {}", super::token_descr(&self.token)),
2388 ),
2389 };
2390 let mut err = self.dcx().struct_span_err(span, msg);
2391 let sp = self.psess.source_map().start_point(self.token.span);
2392 if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
2393 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2394 }
2395 err.span_label(span, "expected expression");
2396 err
2397 }
2398
2399 fn consume_tts(
2400 &mut self,
2401 mut acc: i64, modifier: &[(token::TokenKind, i64)],
2404 ) {
2405 while acc > 0 {
2406 if let Some((_, val)) = modifier.iter().find(|(t, _)| self.token == *t) {
2407 acc += *val;
2408 }
2409 if self.token == token::Eof {
2410 break;
2411 }
2412 self.bump();
2413 }
2414 }
2415
2416 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut ThinVec<Param>) {
2425 let mut seen_inputs = FxHashSet::default();
2426 for input in fn_inputs.iter_mut() {
2427 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err(_)) =
2428 (&input.pat.kind, &input.ty.kind)
2429 {
2430 Some(*ident)
2431 } else {
2432 None
2433 };
2434 if let Some(ident) = opt_ident {
2435 if seen_inputs.contains(&ident) {
2436 input.pat.kind = PatKind::Wild;
2437 }
2438 seen_inputs.insert(ident);
2439 }
2440 }
2441 }
2442
2443 pub(super) fn handle_ambiguous_unbraced_const_arg(
2447 &mut self,
2448 args: &mut ThinVec<AngleBracketedArg>,
2449 ) -> PResult<'a, bool> {
2450 let arg = args.pop().unwrap();
2454 let mut err = self.dcx().struct_span_err(
2460 self.token.span,
2461 format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2462 );
2463 err.span_label(self.token.span, "expected one of `,` or `>`");
2464 match self.recover_const_arg(arg.span(), err) {
2465 Ok(arg) => {
2466 args.push(AngleBracketedArg::Arg(arg));
2467 if self.eat(exp!(Comma)) {
2468 return Ok(true); }
2470 }
2471 Err(err) => {
2472 args.push(arg);
2473 err.delay_as_bug();
2475 }
2476 }
2477 Ok(false) }
2479
2480 pub(super) fn handle_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, P<Expr>> {
2488 let start = self.token.span;
2489 let attrs = self.parse_outer_attributes()?;
2490 let (expr, _) =
2491 self.parse_expr_res(Restrictions::CONST_EXPR, attrs).map_err(|mut err| {
2492 err.span_label(
2493 start.shrink_to_lo(),
2494 "while parsing a const generic argument starting here",
2495 );
2496 err
2497 })?;
2498 if !self.expr_is_valid_const_arg(&expr) {
2499 self.dcx().emit_err(ConstGenericWithoutBraces {
2500 span: expr.span,
2501 sugg: ConstGenericWithoutBracesSugg {
2502 left: expr.span.shrink_to_lo(),
2503 right: expr.span.shrink_to_hi(),
2504 },
2505 });
2506 }
2507 Ok(expr)
2508 }
2509
2510 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2511 let snapshot = self.create_snapshot_for_diagnostic();
2512 let param = match self.parse_const_param(AttrVec::new()) {
2513 Ok(param) => param,
2514 Err(err) => {
2515 err.cancel();
2516 self.restore_snapshot(snapshot);
2517 return None;
2518 }
2519 };
2520
2521 let ident = param.ident.to_string();
2522 let sugg = match (ty_generics, self.psess.source_map().span_to_snippet(param.span())) {
2523 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2524 Some(match ¶ms[..] {
2525 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2526 impl_generics: *impl_generics,
2527 incorrect_decl: param.span(),
2528 snippet,
2529 ident,
2530 },
2531 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2532 impl_generics_end: generic.span().shrink_to_hi(),
2533 incorrect_decl: param.span(),
2534 snippet,
2535 ident,
2536 },
2537 })
2538 }
2539 _ => None,
2540 };
2541 let guar =
2542 self.dcx().emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2543
2544 let value = self.mk_expr_err(param.span(), guar);
2545 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2546 }
2547
2548 pub(super) fn recover_const_param_declaration(
2549 &mut self,
2550 ty_generics: Option<&Generics>,
2551 ) -> PResult<'a, Option<GenericArg>> {
2552 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2554 return Ok(Some(arg));
2555 }
2556
2557 let start = self.token.span;
2559 self.bump(); let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2563 if self.check_const_arg() {
2564 err.to_remove = Some(start.until(self.token.span));
2565 self.dcx().emit_err(err);
2566 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2567 } else {
2568 let after_kw_const = self.token.span;
2569 self.recover_const_arg(after_kw_const, self.dcx().create_err(err)).map(Some)
2570 }
2571 }
2572
2573 pub(super) fn recover_const_arg(
2579 &mut self,
2580 start: Span,
2581 mut err: Diag<'a>,
2582 ) -> PResult<'a, GenericArg> {
2583 let is_op_or_dot = AssocOp::from_token(&self.token)
2584 .and_then(|op| {
2585 if let AssocOp::Binary(
2586 BinOpKind::Gt
2587 | BinOpKind::Lt
2588 | BinOpKind::Shr
2589 | BinOpKind::Ge
2590 )
2591 | AssocOp::Assign
2594 | AssocOp::AssignOp(_) = op
2595 {
2596 None
2597 } else {
2598 Some(op)
2599 }
2600 })
2601 .is_some()
2602 || self.token == TokenKind::Dot;
2603 let was_op = matches!(self.prev_token.kind, token::Plus | token::Shr | token::Gt);
2606 if !is_op_or_dot && !was_op {
2607 return Err(err);
2609 }
2610 let snapshot = self.create_snapshot_for_diagnostic();
2611 if is_op_or_dot {
2612 self.bump();
2613 }
2614 match (|| {
2615 let attrs = self.parse_outer_attributes()?;
2616 self.parse_expr_res(Restrictions::CONST_EXPR, attrs)
2617 })() {
2618 Ok((expr, _)) => {
2619 if snapshot.token == token::EqEq {
2621 err.span_suggestion(
2622 snapshot.token.span,
2623 "if you meant to use an associated type binding, replace `==` with `=`",
2624 "=",
2625 Applicability::MaybeIncorrect,
2626 );
2627 let guar = err.emit();
2628 let value = self.mk_expr_err(start.to(expr.span), guar);
2629 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2630 } else if snapshot.token == token::Colon
2631 && expr.span.lo() == snapshot.token.span.hi()
2632 && matches!(expr.kind, ExprKind::Path(..))
2633 {
2634 err.span_suggestion(
2636 snapshot.token.span,
2637 "write a path separator here",
2638 "::",
2639 Applicability::MaybeIncorrect,
2640 );
2641 let guar = err.emit();
2642 return Ok(GenericArg::Type(
2643 self.mk_ty(start.to(expr.span), TyKind::Err(guar)),
2644 ));
2645 } else if self.token == token::Comma || self.token.kind.should_end_const_arg() {
2646 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2653 }
2654 }
2655 Err(err) => {
2656 err.cancel();
2657 }
2658 }
2659 self.restore_snapshot(snapshot);
2660 Err(err)
2661 }
2662
2663 pub(crate) fn recover_unbraced_const_arg_that_can_begin_ty(
2667 &mut self,
2668 mut snapshot: SnapshotParser<'a>,
2669 ) -> Option<P<ast::Expr>> {
2670 match (|| {
2671 let attrs = self.parse_outer_attributes()?;
2672 snapshot.parse_expr_res(Restrictions::CONST_EXPR, attrs)
2673 })() {
2674 Ok((expr, _)) if let token::Comma | token::Gt = snapshot.token.kind => {
2677 self.restore_snapshot(snapshot);
2678 Some(expr)
2679 }
2680 Ok(_) => None,
2681 Err(err) => {
2682 err.cancel();
2683 None
2684 }
2685 }
2686 }
2687
2688 pub(super) fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
2690 err.multipart_suggestion(
2691 "expressions must be enclosed in braces to be used as const generic \
2692 arguments",
2693 vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2694 Applicability::MaybeIncorrect,
2695 );
2696 let guar = err.emit();
2697 let value = self.mk_expr_err(span, guar);
2698 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2699 }
2700
2701 pub(crate) fn maybe_recover_colon_colon_in_pat_typo(
2704 &mut self,
2705 mut first_pat: P<Pat>,
2706 expected: Option<Expected>,
2707 ) -> P<Pat> {
2708 if token::Colon != self.token.kind {
2709 return first_pat;
2710 }
2711 if !matches!(first_pat.kind, PatKind::Ident(_, _, None) | PatKind::Path(..))
2712 || !self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
2713 {
2714 let mut snapshot_type = self.create_snapshot_for_diagnostic();
2715 snapshot_type.bump(); match snapshot_type.parse_ty() {
2717 Err(inner_err) => {
2718 inner_err.cancel();
2719 }
2720 Ok(ty) => {
2721 let Err(mut err) = self.expected_one_of_not_found(&[], &[]) else {
2722 return first_pat;
2723 };
2724 err.span_label(ty.span, "specifying the type of a pattern isn't supported");
2725 self.restore_snapshot(snapshot_type);
2726 let span = first_pat.span.to(ty.span);
2727 first_pat = self.mk_pat(span, PatKind::Wild);
2728 err.emit();
2729 }
2730 }
2731 return first_pat;
2732 }
2733 let colon_span = self.token.span;
2736 let mut snapshot_pat = self.create_snapshot_for_diagnostic();
2739 let mut snapshot_type = self.create_snapshot_for_diagnostic();
2740
2741 match self.expected_one_of_not_found(&[], &[]) {
2743 Err(mut err) => {
2744 snapshot_pat.bump();
2746 snapshot_type.bump();
2747 match snapshot_pat.parse_pat_no_top_alt(expected, None) {
2748 Err(inner_err) => {
2749 inner_err.cancel();
2750 }
2751 Ok(mut pat) => {
2752 let new_span = first_pat.span.to(pat.span);
2754 let mut show_sugg = false;
2755 match &mut pat.kind {
2757 PatKind::Struct(qself @ None, path, ..)
2758 | PatKind::TupleStruct(qself @ None, path, _)
2759 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2760 PatKind::Ident(_, ident, _) => {
2761 path.segments.insert(0, PathSegment::from_ident(*ident));
2762 path.span = new_span;
2763 show_sugg = true;
2764 first_pat = pat;
2765 }
2766 PatKind::Path(old_qself, old_path) => {
2767 path.segments = old_path
2768 .segments
2769 .iter()
2770 .cloned()
2771 .chain(take(&mut path.segments))
2772 .collect();
2773 path.span = new_span;
2774 *qself = old_qself.clone();
2775 first_pat = pat;
2776 show_sugg = true;
2777 }
2778 _ => {}
2779 },
2780 PatKind::Ident(BindingMode::NONE, ident, None) => {
2781 match &first_pat.kind {
2782 PatKind::Ident(_, old_ident, _) => {
2783 let path = PatKind::Path(
2784 None,
2785 Path {
2786 span: new_span,
2787 segments: thin_vec![
2788 PathSegment::from_ident(*old_ident),
2789 PathSegment::from_ident(*ident),
2790 ],
2791 tokens: None,
2792 },
2793 );
2794 first_pat = self.mk_pat(new_span, path);
2795 show_sugg = true;
2796 }
2797 PatKind::Path(old_qself, old_path) => {
2798 let mut segments = old_path.segments.clone();
2799 segments.push(PathSegment::from_ident(*ident));
2800 let path = PatKind::Path(
2801 old_qself.clone(),
2802 Path { span: new_span, segments, tokens: None },
2803 );
2804 first_pat = self.mk_pat(new_span, path);
2805 show_sugg = true;
2806 }
2807 _ => {}
2808 }
2809 }
2810 _ => {}
2811 }
2812 if show_sugg {
2813 err.span_suggestion_verbose(
2814 colon_span.until(self.look_ahead(1, |t| t.span)),
2815 "maybe write a path separator here",
2816 "::",
2817 Applicability::MaybeIncorrect,
2818 );
2819 } else {
2820 first_pat = self.mk_pat(new_span, PatKind::Wild);
2821 }
2822 self.restore_snapshot(snapshot_pat);
2823 }
2824 }
2825 match snapshot_type.parse_ty() {
2826 Err(inner_err) => {
2827 inner_err.cancel();
2828 }
2829 Ok(ty) => {
2830 err.span_label(ty.span, "specifying the type of a pattern isn't supported");
2831 self.restore_snapshot(snapshot_type);
2832 let new_span = first_pat.span.to(ty.span);
2833 first_pat = self.mk_pat(new_span, PatKind::Wild);
2834 }
2835 }
2836 err.emit();
2837 }
2838 _ => {
2839 }
2841 };
2842 first_pat
2843 }
2844
2845 pub(crate) fn maybe_recover_unexpected_block_label(
2848 &mut self,
2849 loop_header: Option<Span>,
2850 ) -> bool {
2851 if !(self.check_lifetime()
2853 && self.look_ahead(1, |t| *t == token::Colon)
2854 && self.look_ahead(2, |t| *t == token::OpenBrace))
2855 {
2856 return false;
2857 }
2858 let label = self.eat_label().expect("just checked if a label exists");
2859 self.bump(); let span = label.ident.span.to(self.prev_token.span);
2861 let mut diag = self
2862 .dcx()
2863 .struct_span_err(span, "block label not supported here")
2864 .with_span_label(span, "not supported here");
2865 if let Some(loop_header) = loop_header {
2866 diag.multipart_suggestion(
2867 "if you meant to label the loop, move this label before the loop",
2868 vec![
2869 (label.ident.span.until(self.token.span), String::from("")),
2870 (loop_header.shrink_to_lo(), format!("{}: ", label.ident)),
2871 ],
2872 Applicability::MachineApplicable,
2873 );
2874 } else {
2875 diag.tool_only_span_suggestion(
2876 label.ident.span.until(self.token.span),
2877 "remove this block label",
2878 "",
2879 Applicability::MachineApplicable,
2880 );
2881 }
2882 diag.emit();
2883 true
2884 }
2885
2886 pub(crate) fn maybe_recover_unexpected_comma(
2889 &mut self,
2890 lo: Span,
2891 rt: CommaRecoveryMode,
2892 ) -> PResult<'a, ()> {
2893 if self.token != token::Comma {
2894 return Ok(());
2895 }
2896
2897 let comma_span = self.token.span;
2902 self.bump();
2903 if let Err(err) = self.skip_pat_list() {
2904 err.cancel();
2907 }
2908 let seq_span = lo.to(self.prev_token.span);
2909 let mut err = self.dcx().struct_span_err(comma_span, "unexpected `,` in pattern");
2910 if let Ok(seq_snippet) = self.span_to_snippet(seq_span) {
2911 err.multipart_suggestion(
2912 format!(
2913 "try adding parentheses to match on a tuple{}",
2914 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2915 ),
2916 vec![
2917 (seq_span.shrink_to_lo(), "(".to_string()),
2918 (seq_span.shrink_to_hi(), ")".to_string()),
2919 ],
2920 Applicability::MachineApplicable,
2921 );
2922 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2923 err.span_suggestion(
2924 seq_span,
2925 "...or a vertical bar to match on multiple alternatives",
2926 seq_snippet.replace(',', " |"),
2927 Applicability::MachineApplicable,
2928 );
2929 }
2930 }
2931 Err(err)
2932 }
2933
2934 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2935 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2936 let qself_position = qself.as_ref().map(|qself| qself.position);
2937 for (i, segments) in path.segments.windows(2).enumerate() {
2938 if qself_position.is_some_and(|pos| i < pos) {
2939 continue;
2940 }
2941 if let [a, b] = segments {
2942 let (a_span, b_span) = (a.span(), b.span());
2943 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2944 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2945 return Err(self.dcx().create_err(DoubleColonInBound {
2946 span: path.span.shrink_to_hi(),
2947 between: between_span,
2948 }));
2949 }
2950 }
2951 }
2952 Ok(())
2953 }
2954
2955 pub(crate) fn maybe_err_dotdotlt_syntax(&self, maybe_lt: Token, mut err: Diag<'a>) -> Diag<'a> {
2957 if maybe_lt == token::Lt
2958 && (self.expected_token_types.contains(TokenType::Gt)
2959 || matches!(self.token.kind, token::Literal(..)))
2960 {
2961 err.span_suggestion(
2962 maybe_lt.span,
2963 "remove the `<` to write an exclusive range",
2964 "",
2965 Applicability::MachineApplicable,
2966 );
2967 }
2968 err
2969 }
2970
2971 pub(super) fn is_vcs_conflict_marker(
2979 &mut self,
2980 long_kind: &TokenKind,
2981 short_kind: &TokenKind,
2982 ) -> bool {
2983 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2984 && self.look_ahead(3, |tok| tok == short_kind)
2985 }
2986
2987 fn conflict_marker(&mut self, long_kind: &TokenKind, short_kind: &TokenKind) -> Option<Span> {
2988 if self.is_vcs_conflict_marker(long_kind, short_kind) {
2989 let lo = self.token.span;
2990 for _ in 0..4 {
2991 self.bump();
2992 }
2993 return Some(lo.to(self.prev_token.span));
2994 }
2995 None
2996 }
2997
2998 pub(super) fn recover_vcs_conflict_marker(&mut self) {
2999 let Some(start) = self.conflict_marker(&TokenKind::Shl, &TokenKind::Lt) else {
3001 return;
3002 };
3003 let mut spans = Vec::with_capacity(3);
3004 spans.push(start);
3005 let mut middlediff3 = None;
3007 let mut middle = None;
3009 let mut end = None;
3011 loop {
3012 if self.token == TokenKind::Eof {
3013 break;
3014 }
3015 if let Some(span) = self.conflict_marker(&TokenKind::OrOr, &TokenKind::Or) {
3016 middlediff3 = Some(span);
3017 }
3018 if let Some(span) = self.conflict_marker(&TokenKind::EqEq, &TokenKind::Eq) {
3019 middle = Some(span);
3020 }
3021 if let Some(span) = self.conflict_marker(&TokenKind::Shr, &TokenKind::Gt) {
3022 spans.push(span);
3023 end = Some(span);
3024 break;
3025 }
3026 self.bump();
3027 }
3028
3029 let mut err = self.dcx().struct_span_fatal(spans, "encountered diff marker");
3030 match middlediff3 {
3031 Some(middlediff3) => {
3033 err.span_label(
3034 start,
3035 "between this marker and `|||||||` is the code that we're merging into",
3036 );
3037 err.span_label(middlediff3, "between this marker and `=======` is the base code (what the two refs diverged from)");
3038 }
3039 None => {
3040 err.span_label(
3041 start,
3042 "between this marker and `=======` is the code that we're merging into",
3043 );
3044 }
3045 };
3046
3047 if let Some(middle) = middle {
3048 err.span_label(middle, "between this marker and `>>>>>>>` is the incoming code");
3049 }
3050 if let Some(end) = end {
3051 err.span_label(end, "this marker concludes the conflict region");
3052 }
3053 err.note(
3054 "conflict markers indicate that a merge was started but could not be completed due \
3055 to merge conflicts\n\
3056 to resolve a conflict, keep only the code you want and then delete the lines \
3057 containing conflict markers",
3058 );
3059 err.help(
3060 "if you're having merge conflicts after pulling new code:\n\
3061 the top section is the code you already had and the bottom section is the remote code\n\
3062 if you're in the middle of a rebase:\n\
3063 the top section is the code being rebased onto and the bottom section is the code \
3064 coming from the current commit being rebased",
3065 );
3066
3067 err.note(
3068 "for an explanation on these markers from the `git` documentation:\n\
3069 visit <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
3070 );
3071
3072 err.emit();
3073 }
3074
3075 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
3078 while !self.check(exp!(CloseParen)) {
3079 self.parse_pat_no_top_alt(None, None)?;
3080 if !self.eat(exp!(Comma)) {
3081 return Ok(());
3082 }
3083 }
3084 Ok(())
3085 }
3086}