1use std::mem::take;
2use std::ops::{Deref, DerefMut};
3
4use ast::token::IdentIsRaw;
5use rustc_ast::token::{self, Lit, LitKind, Token, TokenKind};
6use rustc_ast::util::parser::AssocOp;
7use rustc_ast::{
8 self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AttrVec, BinOpKind, BindingMode,
9 Block, BlockCheckMode, Expr, ExprKind, GenericArg, GenericArgs, Generics, Item, ItemKind,
10 Param, Pat, PatKind, Path, PathSegment, QSelf, Recovered, Ty, TyKind,
11};
12use rustc_ast_pretty::pprust;
13use rustc_data_structures::fx::FxHashSet;
14use rustc_errors::{
15 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, PResult, Subdiagnostic, Suggestions, msg,
16 pluralize,
17};
18use rustc_span::symbol::used_keywords;
19use rustc_span::{BytePos, DUMMY_SP, Ident, Span, SpanSnippetError, Spanned, Symbol, kw, sym};
20use thin_vec::{ThinVec, thin_vec};
21use tracing::{debug, trace};
22
23use super::pat::Expected;
24use super::{
25 BlockMode, CommaRecoveryMode, ExpTokenPair, Parser, PathStyle, Restrictions, SemiColonMode,
26 SeqSep, TokenType,
27};
28use crate::diagnostics::{
29 AddParen, AmbiguousPlus, AsyncMoveBlockIn2015, AsyncUseBlockIn2015, AttributeOnParamType,
30 AwaitSuggestion, BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi,
31 ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
32 DocCommentDoesNotDocumentAnything, DocCommentOnParamType, DoubleColonInBound,
33 ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg, ExprParenthesesNeeded, FoundPathInGenerics,
34 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg,
35 HelpIdentifierStartsWithNumber, HelpUseLatestEdition, InInTypo, IncorrectAwait,
36 IncorrectSemicolon, IncorrectUseOfAwait, IncorrectUseOfUse, MisspelledKw,
37 PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
38 StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, SuggAddMissingLetStmt,
39 SuggEscapeIdentifier, SuggRemoveComma, SuggestBindTypeParameter, SuggestIntroduceTypeParameter,
40 TernaryOperator, TernaryOperatorSuggestion, UnexpectedConstInGenericParam,
41 UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets,
42 UseEqInstead, WrapType,
43};
44use crate::exp;
45use crate::parser::attr::InnerAttrPolicy;
46use crate::parser::{FnContext, IsDotDotDot};
47
48pub(super) fn dummy_arg(ident: Ident, guar: ErrorGuaranteed) -> Param {
50 let pat = Box::new(Pat {
51 id: ast::DUMMY_NODE_ID,
52 kind: PatKind::Ident(BindingMode::NONE, ident, None),
53 span: ident.span,
54 });
55 let ty = Ty { kind: TyKind::Err(guar), span: ident.span, id: ast::DUMMY_NODE_ID };
56 Param {
57 attrs: AttrVec::default(),
58 id: ast::DUMMY_NODE_ID,
59 pat,
60 span: ident.span,
61 ty: Box::new(ty),
62 is_placeholder: false,
63 }
64}
65
66pub(super) trait RecoverQPath: Sized + 'static {
67 const PATH_STYLE: PathStyle = PathStyle::Expr;
68 fn to_ty(&self) -> Option<Box<Ty>>;
69 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self;
70}
71
72impl<T: RecoverQPath> RecoverQPath for Box<T> {
73 const PATH_STYLE: PathStyle = T::PATH_STYLE;
74 fn to_ty(&self) -> Option<Box<Ty>> {
75 T::to_ty(self)
76 }
77 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
78 Box::new(T::recovered(qself, path))
79 }
80}
81
82impl RecoverQPath for Ty {
83 const PATH_STYLE: PathStyle = PathStyle::Type;
84 fn to_ty(&self) -> Option<Box<Ty>> {
85 Some(Box::new(self.clone()))
86 }
87 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
88 Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
89 }
90}
91
92impl RecoverQPath for Pat {
93 const PATH_STYLE: PathStyle = PathStyle::Pat;
94 fn to_ty(&self) -> Option<Box<Ty>> {
95 self.to_ty()
96 }
97 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
98 Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
99 }
100}
101
102impl RecoverQPath for Expr {
103 fn to_ty(&self) -> Option<Box<Ty>> {
104 self.to_ty()
105 }
106 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
107 Self {
108 span: path.span,
109 kind: ExprKind::Path(qself, path),
110 attrs: AttrVec::new(),
111 id: ast::DUMMY_NODE_ID,
112 tokens: None,
113 }
114 }
115}
116
117pub(crate) enum ConsumeClosingDelim {
119 Yes,
120 No,
121}
122
123#[derive(#[automatically_derived]
impl ::core::clone::Clone for AttemptLocalParseRecovery {
#[inline]
fn clone(&self) -> AttemptLocalParseRecovery { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AttemptLocalParseRecovery { }Copy)]
124pub enum AttemptLocalParseRecovery {
125 Yes,
126 No,
127}
128
129impl AttemptLocalParseRecovery {
130 pub(super) fn yes(&self) -> bool {
131 match self {
132 AttemptLocalParseRecovery::Yes => true,
133 AttemptLocalParseRecovery::No => false,
134 }
135 }
136
137 pub(super) fn no(&self) -> bool {
138 match self {
139 AttemptLocalParseRecovery::Yes => false,
140 AttemptLocalParseRecovery::No => true,
141 }
142 }
143}
144
145#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IncDecRecovery {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"IncDecRecovery", "standalone", &self.standalone, "op", &self.op,
"fixity", &&self.fixity)
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for IncDecRecovery { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IncDecRecovery {
#[inline]
fn clone(&self) -> IncDecRecovery {
let _: ::core::clone::AssertParamIsClone<IsStandalone>;
let _: ::core::clone::AssertParamIsClone<IncOrDec>;
let _: ::core::clone::AssertParamIsClone<UnaryFixity>;
*self
}
}Clone)]
148struct IncDecRecovery {
149 standalone: IsStandalone,
151 op: IncOrDec,
153 fixity: UnaryFixity,
155}
156
157#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsStandalone {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
IsStandalone::Standalone => "Standalone",
IsStandalone::Subexpr => "Subexpr",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for IsStandalone { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsStandalone {
#[inline]
fn clone(&self) -> IsStandalone { *self }
}Clone)]
159enum IsStandalone {
160 Standalone,
162 Subexpr,
164}
165
166#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IncOrDec {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { IncOrDec::Inc => "Inc", IncOrDec::Dec => "Dec", })
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for IncOrDec { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IncOrDec {
#[inline]
fn clone(&self) -> IncOrDec { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for IncOrDec {
#[inline]
fn eq(&self, other: &IncOrDec) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IncOrDec {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
167enum IncOrDec {
168 Inc,
169 Dec,
170}
171
172#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UnaryFixity {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
UnaryFixity::Pre => "Pre",
UnaryFixity::Post => "Post",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for UnaryFixity { }Copy, #[automatically_derived]
impl ::core::clone::Clone for UnaryFixity {
#[inline]
fn clone(&self) -> UnaryFixity { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for UnaryFixity {
#[inline]
fn eq(&self, other: &UnaryFixity) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UnaryFixity {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
173enum UnaryFixity {
174 Pre,
175 Post,
176}
177
178impl IncOrDec {
179 fn chr(&self) -> char {
180 match self {
181 Self::Inc => '+',
182 Self::Dec => '-',
183 }
184 }
185
186 fn name(&self) -> &'static str {
187 match self {
188 Self::Inc => "increment",
189 Self::Dec => "decrement",
190 }
191 }
192}
193
194impl std::fmt::Display for UnaryFixity {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 match self {
197 Self::Pre => f.write_fmt(format_args!("prefix"))write!(f, "prefix"),
198 Self::Post => f.write_fmt(format_args!("postfix"))write!(f, "postfix"),
199 }
200 }
201}
202
203fn find_similar_kw(lookup: Ident, candidates: &[Symbol]) -> Option<MisspelledKw> {
208 lookup.name.find_similar(candidates).map(|(similar_kw, is_incorrect_case)| MisspelledKw {
209 similar_kw: similar_kw.to_string(),
210 is_incorrect_case,
211 span: lookup.span,
212 })
213}
214
215struct MultiSugg {
216 msg: String,
217 patches: Vec<(Span, String)>,
218 applicability: Applicability,
219}
220
221impl MultiSugg {
222 fn emit(self, err: &mut Diag<'_>) {
223 err.multipart_suggestion(self.msg, self.patches, self.applicability);
224 }
225
226 fn emit_verbose(self, err: &mut Diag<'_>) {
227 err.multipart_suggestion(self.msg, self.patches, self.applicability);
228 }
229}
230
231pub struct SnapshotParser<'a> {
235 parser: Parser<'a>,
236}
237
238impl<'a> Deref for SnapshotParser<'a> {
239 type Target = Parser<'a>;
240
241 fn deref(&self) -> &Self::Target {
242 &self.parser
243 }
244}
245
246impl<'a> DerefMut for SnapshotParser<'a> {
247 fn deref_mut(&mut self) -> &mut Self::Target {
248 &mut self.parser
249 }
250}
251
252impl<'a> Parser<'a> {
253 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
254 self.psess.dcx()
255 }
256
257 pub fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
259 *self = snapshot.parser;
260 }
261
262 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
264 let snapshot = self.clone();
265 SnapshotParser { parser: snapshot }
266 }
267
268 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
269 self.psess.source_map().span_to_snippet(span)
270 }
271
272 pub(super) fn expected_ident_found(
276 &mut self,
277 recover: bool,
278 ) -> PResult<'a, (Ident, IdentIsRaw)> {
279 let valid_follow = &[
280 TokenKind::Eq,
281 TokenKind::Colon,
282 TokenKind::Comma,
283 TokenKind::Semi,
284 TokenKind::PathSep,
285 TokenKind::OpenBrace,
286 TokenKind::OpenParen,
287 TokenKind::CloseBrace,
288 TokenKind::CloseParen,
289 ];
290 if let TokenKind::DocComment(..) = self.prev_token.kind
291 && valid_follow.contains(&self.token.kind)
292 {
293 let err = self.dcx().create_err(DocCommentDoesNotDocumentAnything {
294 span: self.prev_token.span,
295 missing_comma: None,
296 });
297 return Err(err);
298 }
299
300 let mut recovered_ident = None;
301 let bad_token = self.token;
304
305 let suggest_raw = if let Some((ident, IdentIsRaw::No)) = self.token.ident()
307 && ident.is_raw_guess()
308 && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
309 {
310 recovered_ident = Some((ident, IdentIsRaw::Yes));
311
312 let ident_name = ident.name.to_string();
315
316 Some(SuggEscapeIdentifier { span: ident.span.shrink_to_lo(), ident_name })
317 } else {
318 None
319 };
320
321 let suggest_remove_comma =
322 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
323 if recover {
324 self.bump();
325 recovered_ident = self.ident_or_err(false).ok();
326 };
327
328 Some(SuggRemoveComma { span: bad_token.span })
329 } else {
330 None
331 };
332
333 let help_cannot_start_number = self.is_lit_bad_ident().map(|(len, valid_portion)| {
334 let (invalid, valid) = self.token.span.split_at(len as u32);
335
336 recovered_ident = Some((Ident::new(valid_portion, valid), IdentIsRaw::No));
337
338 HelpIdentifierStartsWithNumber { num_span: invalid }
339 });
340
341 let err = ExpectedIdentifier {
342 span: bad_token.span,
343 token: bad_token,
344 suggest_raw,
345 suggest_remove_comma,
346 help_cannot_start_number,
347 };
348 let mut err = self.dcx().create_err(err);
349
350 if self.token == token::Lt {
354 let valid_prev_keywords =
356 [kw::Fn, kw::Type, kw::Struct, kw::Enum, kw::Union, kw::Trait];
357
358 let maybe_keyword = self.prev_token;
364 if valid_prev_keywords.into_iter().any(|x| maybe_keyword.is_keyword(x)) {
365 match self.parse_generics() {
368 Ok(generic) => {
369 if let TokenKind::Ident(symbol, _) = maybe_keyword.kind {
370 let ident_name = symbol;
371 if !self.look_ahead(1, |t| *t == token::Lt)
377 && let Ok(snippet) =
378 self.psess.source_map().span_to_snippet(generic.span)
379 {
380 err.multipart_suggestion(
381 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("place the generic parameter name after the {0} name",
ident_name))
})format!("place the generic parameter name after the {ident_name} name"),
382 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.token.span.shrink_to_hi(), snippet),
(generic.span, String::new())]))vec![
383 (self.token.span.shrink_to_hi(), snippet),
384 (generic.span, String::new())
385 ],
386 Applicability::MaybeIncorrect,
387 );
388 } else {
389 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("place the generic parameter name after the {0} name",
ident_name))
})format!(
390 "place the generic parameter name after the {ident_name} name"
391 ));
392 }
393 }
394 }
395 Err(err) => {
396 err.cancel();
400 }
401 }
402 }
403 }
404
405 if let Some(recovered_ident) = recovered_ident
406 && recover
407 {
408 err.emit();
409 Ok(recovered_ident)
410 } else {
411 Err(err)
412 }
413 }
414
415 pub(super) fn expected_ident_found_err(&mut self) -> Diag<'a> {
416 self.expected_ident_found(false).unwrap_err()
417 }
418
419 pub(super) fn is_lit_bad_ident(&mut self) -> Option<(usize, Symbol)> {
425 if let token::Literal(Lit {
429 kind: token::LitKind::Integer | token::LitKind::Float,
430 symbol,
431 suffix: Some(suffix), }) = self.token.kind
433 && rustc_ast::MetaItemLit::from_token(&self.token).is_none()
434 {
435 Some((symbol.as_str().len(), suffix))
436 } else {
437 None
438 }
439 }
440
441 pub(super) fn expected_one_of_not_found(
442 &mut self,
443 edible: &[ExpTokenPair],
444 inedible: &[ExpTokenPair],
445 ) -> PResult<'a, ErrorGuaranteed> {
446 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:446",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(446u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expected_one_of_not_found(edible: {0:?}, inedible: {1:?})",
edible, inedible) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("expected_one_of_not_found(edible: {:?}, inedible: {:?})", edible, inedible);
447 fn tokens_to_string(tokens: &[TokenType]) -> String {
448 let mut i = tokens.iter();
449 let b = i.next().map_or_else(String::new, |t| t.to_string());
451 i.enumerate().fold(b, |mut b, (i, a)| {
452 if tokens.len() > 2 && i == tokens.len() - 2 {
453 b.push_str(", or ");
454 } else if tokens.len() == 2 && i == tokens.len() - 2 {
455 b.push_str(" or ");
456 } else {
457 b.push_str(", ");
458 }
459 b.push_str(&a.to_string());
460 b
461 })
462 }
463
464 for exp in edible.iter().chain(inedible.iter()) {
465 self.expected_token_types.insert(exp.token_type);
466 }
467 let mut expected: Vec<_> = self.expected_token_types.iter().collect();
468 expected.sort_by_cached_key(|x| x.to_string());
469 expected.dedup();
470
471 let sm = self.psess.source_map();
472
473 if expected.contains(&TokenType::Semi) {
475 if self.prev_token == token::Question
478 && let Err(e) = self.maybe_recover_from_ternary_operator(None)
479 {
480 return Err(e);
481 }
482
483 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
484 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
486 } else if [token::Comma, token::Colon].contains(&self.token.kind)
488 && self.prev_token == token::CloseParen
489 {
490 } else if self.look_ahead(1, |t| {
499 t == &token::CloseBrace || t.can_begin_expr() && *t != token::Colon
500 }) && [token::Comma, token::Colon].contains(&self.token.kind)
501 {
502 let guar = self.dcx().emit_err(ExpectedSemi {
509 span: self.token.span,
510 token: self.token,
511 unexpected_token_label: None,
512 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
513 });
514 self.bump();
515 return Ok(guar);
516 } else if self.look_ahead(0, |t| {
517 t == &token::CloseBrace
518 || ((t.can_begin_expr() || t.can_begin_item())
519 && t != &token::Semi
520 && t != &token::Pound)
521 || (sm.is_multiline(
523 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
524 ) && t == &token::Pound)
525 }) && !expected.contains(&TokenType::Comma)
526 {
527 let span = self.prev_token.span.shrink_to_hi();
533 let guar = self.dcx().emit_err(ExpectedSemi {
534 span,
535 token: self.token,
536 unexpected_token_label: Some(self.token.span),
537 sugg: ExpectedSemiSugg::AddSemi(span),
538 });
539 return Ok(guar);
540 }
541 }
542
543 if self.token == TokenKind::EqEq
544 && self.prev_token.is_ident()
545 && expected.contains(&TokenType::Eq)
546 {
547 return Err(self.dcx().create_err(UseEqInstead { span: self.token.span }));
549 }
550
551 if (self.token.is_keyword(kw::Move) || self.token.is_keyword(kw::Use))
552 && self.prev_token.is_keyword(kw::Async)
553 {
554 let span = self.prev_token.span.to(self.token.span);
556 if self.token.is_keyword(kw::Move) {
557 return Err(self.dcx().create_err(AsyncMoveBlockIn2015 { span }));
558 } else {
559 return Err(self.dcx().create_err(AsyncUseBlockIn2015 { span }));
561 }
562 }
563
564 let expect = tokens_to_string(&expected);
565 let actual = super::token_descr(&self.token);
566 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
567 let fmt = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected one of {0}, found {1}",
expect, actual))
})format!("expected one of {expect}, found {actual}");
568 let short_expect = if expected.len() > 6 {
569 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} possible tokens",
expected.len()))
})format!("{} possible tokens", expected.len())
570 } else {
571 expect
572 };
573 (fmt, (self.prev_token.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected one of {0}",
short_expect))
})format!("expected one of {short_expect}")))
574 } else if expected.is_empty() {
575 (
576 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unexpected token: {0}", actual))
})format!("unexpected token: {actual}"),
577 (self.prev_token.span, "unexpected token after this".to_string()),
578 )
579 } else {
580 (
581 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}", expect,
actual))
})format!("expected {expect}, found {actual}"),
582 (self.prev_token.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}", expect))
})format!("expected {expect}")),
583 )
584 };
585 self.last_unexpected_token_span = Some(self.token.span);
586 let mut err = self.dcx().struct_span_err(self.token.span, msg_exp);
588
589 self.label_expected_raw_ref(&mut err);
590
591 if self.token == token::FatArrow
593 && expected.iter().any(|tok| #[allow(non_exhaustive_omitted_patterns)] match tok {
TokenType::Operator | TokenType::Le => true,
_ => false,
}matches!(tok, TokenType::Operator | TokenType::Le))
594 && !expected
595 .iter()
596 .any(|tok| #[allow(non_exhaustive_omitted_patterns)] match tok {
TokenType::FatArrow | TokenType::CloseBrace => true,
_ => false,
}matches!(tok, TokenType::FatArrow | TokenType::CloseBrace))
597 {
598 err.span_suggestion_verbose(
599 self.token.span,
600 "you might have meant to write a \"greater than or equal to\" comparison",
601 ">=",
602 Applicability::MaybeIncorrect,
603 );
604 }
605
606 if let TokenKind::Ident(symbol, _) = &self.prev_token.kind {
607 if ["def", "fun", "func", "function"].contains(&symbol.as_str()) {
608 err.span_suggestion_short(
609 self.prev_token.span,
610 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("write `fn` instead of `{0}` to declare a function",
symbol))
})format!("write `fn` instead of `{symbol}` to declare a function"),
611 "fn",
612 Applicability::MachineApplicable,
613 );
614 }
615 }
616
617 if let TokenKind::Ident(prev, _) = &self.prev_token.kind
618 && let TokenKind::Ident(cur, _) = &self.token.kind
619 {
620 let concat = Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prev, cur))
})format!("{prev}{cur}"));
621 let ident = Ident::new(concat, DUMMY_SP);
622 if ident.is_used_keyword() || ident.is_reserved() || ident.is_raw_guess() {
623 let concat_span = self.prev_token.span.to(self.token.span);
624 err.span_suggestion_verbose(
625 concat_span,
626 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing the space to spell keyword `{0}`",
concat))
})format!("consider removing the space to spell keyword `{concat}`"),
627 concat,
628 Applicability::MachineApplicable,
629 );
630 }
631 }
632
633 if ((self.prev_token == TokenKind::Ident(sym::character('c'), IdentIsRaw::No)
641 && #[allow(non_exhaustive_omitted_patterns)] match &self.token.kind {
TokenKind::Literal(token::Lit { kind: token::Str, .. }) => true,
_ => false,
}matches!(&self.token.kind, TokenKind::Literal(token::Lit { kind: token::Str, .. })))
642 || (self.prev_token == TokenKind::Ident(sym::cr, IdentIsRaw::No)
643 && #[allow(non_exhaustive_omitted_patterns)] match &self.token.kind {
TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound =>
true,
_ => false,
}matches!(
644 &self.token.kind,
645 TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound
646 )))
647 && self.prev_token.span.hi() == self.token.span.lo()
648 && !self.token.span.at_least_rust_2021()
649 {
650 err.note("you may be trying to write a c-string literal");
651 err.note("c-string literals require Rust 2021 or later");
652 err.subdiagnostic(HelpUseLatestEdition::new());
653 }
654
655 if self.prev_token.is_ident_named(sym::public)
657 && (self.token.can_begin_item() || self.token == TokenKind::OpenParen)
658 {
659 err.span_suggestion_short(
660 self.prev_token.span,
661 "write `pub` instead of `public` to make the item public",
662 "pub",
663 Applicability::MachineApplicable,
664 );
665 }
666
667 if let token::DocComment(kind, style, _) = self.token.kind {
668 if !expected.contains(&TokenType::Comma) {
678 let pos = self.token.span.lo() + BytePos(2);
680 let span = self.token.span.with_lo(pos).with_hi(pos);
681 err.span_suggestion_verbose(
682 span,
683 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add a space before {0} to write a regular comment",
match (kind, style) {
(token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`",
(token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`",
(token::CommentKind::Line, ast::AttrStyle::Outer) =>
"the last `/`",
(token::CommentKind::Block, ast::AttrStyle::Outer) =>
"the last `*`",
}))
})format!(
684 "add a space before {} to write a regular comment",
685 match (kind, style) {
686 (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`",
687 (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`",
688 (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`",
689 (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`",
690 },
691 ),
692 " ".to_string(),
693 Applicability::MaybeIncorrect,
694 );
695 }
696 }
697
698 let sp = if self.token == token::Eof {
699 self.prev_token.span
701 } else {
702 label_sp
703 };
704
705 if self.check_too_many_raw_str_terminators(&mut err) {
706 if expected.contains(&TokenType::Semi) && self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
707 let guar = err.emit();
708 return Ok(guar);
709 } else {
710 return Err(err);
711 }
712 }
713
714 if self.prev_token.span == DUMMY_SP {
715 err.span_label(self.token.span, label_exp);
718 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
719 err.span_label(self.token.span, label_exp);
732 } else {
733 err.span_label(sp, label_exp);
734 err.span_label(self.token.span, "unexpected token");
735 }
736
737 if let Suggestions::Enabled(list) = &err.suggestions
739 && list.is_empty()
740 {
741 self.check_for_misspelled_kw(&mut err, &expected);
742 }
743 Err(err)
744 }
745
746 pub(super) fn is_expected_raw_ref_mut(&self) -> bool {
747 self.prev_token.is_keyword(kw::Raw)
748 && self.expected_token_types.contains(TokenType::KwMut)
749 && self.expected_token_types.contains(TokenType::KwConst)
750 && self.token.can_begin_expr()
751 }
752
753 pub(super) fn label_expected_raw_ref(&mut self, err: &mut Diag<'_>) {
758 if self.is_expected_raw_ref_mut() {
759 err.span_suggestions(
760 self.prev_token.span.shrink_to_hi(),
761 "`&raw` must be followed by `const` or `mut` to be a raw reference expression",
762 [" const".to_string(), " mut".to_string()],
763 Applicability::MaybeIncorrect,
764 );
765 }
766 }
767
768 fn check_for_misspelled_kw(&self, err: &mut Diag<'_>, expected: &[TokenType]) {
771 let Some((curr_ident, _)) = self.token.ident() else {
772 return;
773 };
774 let expected_token_types: &[TokenType] =
775 expected.len().checked_sub(10).map_or(&expected, |index| &expected[index..]);
776 let expected_keywords: Vec<Symbol> =
777 expected_token_types.iter().filter_map(|token| token.is_keyword()).collect();
778
779 if !expected_keywords.is_empty()
784 && !curr_ident.is_used_keyword()
785 && let Some(misspelled_kw) = find_similar_kw(curr_ident, &expected_keywords)
786 {
787 err.subdiagnostic(misspelled_kw);
788 err.seal_suggestions();
791 } else if let Some((prev_ident, _)) = self.prev_token.ident()
792 && !prev_ident.is_used_keyword()
793 {
794 let all_keywords = used_keywords(|| prev_ident.span.edition());
799
800 if let Some(misspelled_kw) = find_similar_kw(prev_ident, &all_keywords) {
805 err.subdiagnostic(misspelled_kw);
806 err.seal_suggestions();
809 }
810 }
811 }
812
813 pub(super) fn attr_on_non_tail_expr(&self, expr: &Expr) -> ErrorGuaranteed {
815 let span = self.prev_token.span.shrink_to_hi();
817 let mut err = self.dcx().create_err(ExpectedSemi {
818 span,
819 token: self.token,
820 unexpected_token_label: Some(self.token.span),
821 sugg: ExpectedSemiSugg::AddSemi(span),
822 });
823 let attr_span = match &expr.attrs[..] {
824 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
825 [only] => only.span,
826 [first, rest @ ..] => {
827 for attr in rest {
828 err.span_label(attr.span, "");
829 }
830 first.span
831 }
832 };
833 err.span_label(
834 attr_span,
835 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("only `;` terminated statements or tail expressions are allowed after {0}",
if expr.attrs.len() == 1 {
"this attribute"
} else { "these attributes" }))
})format!(
836 "only `;` terminated statements or tail expressions are allowed after {}",
837 if expr.attrs.len() == 1 { "this attribute" } else { "these attributes" },
838 ),
839 );
840 if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
841 err.span_label(span, "expected `;` here");
847 err.multipart_suggestion(
848 "alternatively, consider surrounding the expression with a block",
849 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.shrink_to_lo(), "{ ".to_string()),
(expr.span.shrink_to_hi(), " }".to_string())]))vec![
850 (expr.span.shrink_to_lo(), "{ ".to_string()),
851 (expr.span.shrink_to_hi(), " }".to_string()),
852 ],
853 Applicability::MachineApplicable,
854 );
855
856 let mut snapshot = self.create_snapshot_for_diagnostic();
858 if let [attr] = &expr.attrs[..]
859 && let ast::AttrKind::Normal(attr_kind) = &attr.kind
860 && let [segment] = &attr_kind.item.path.segments[..]
861 && segment.ident.name == sym::cfg
862 && let Some(args_span) = attr_kind.item.args.span()
863 && let next_attr = match snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None))
864 {
865 Ok(next_attr) => next_attr,
866 Err(inner_err) => {
867 inner_err.cancel();
868 return err.emit();
869 }
870 }
871 && let ast::AttrKind::Normal(next_attr_kind) = next_attr.kind
872 && let Some(next_attr_args_span) = next_attr_kind.item.args.span()
873 && let [next_segment] = &next_attr_kind.item.path.segments[..]
874 && next_segment.ident.name == sym::cfg
875 {
876 let next_expr = match snapshot.parse_expr() {
877 Ok(next_expr) => next_expr,
878 Err(inner_err) => {
879 inner_err.cancel();
880 return err.emit();
881 }
882 };
883 let margin = self.psess.source_map().span_to_margin(next_expr.span).unwrap_or(0);
890 let sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()),
(args_span.shrink_to_hi().with_hi(attr.span.hi()),
" {".to_string()),
(expr.span.shrink_to_lo(), " ".to_string()),
(next_attr.span.with_hi(next_segment.span().hi()),
"} else if cfg!".to_string()),
(next_attr_args_span.shrink_to_hi().with_hi(next_attr.span.hi()),
" {".to_string()),
(next_expr.span.shrink_to_lo(), " ".to_string()),
(next_expr.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}}}",
" ".repeat(margin)))
}))]))vec![
891 (attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()),
892 (args_span.shrink_to_hi().with_hi(attr.span.hi()), " {".to_string()),
893 (expr.span.shrink_to_lo(), " ".to_string()),
894 (
895 next_attr.span.with_hi(next_segment.span().hi()),
896 "} else if cfg!".to_string(),
897 ),
898 (
899 next_attr_args_span.shrink_to_hi().with_hi(next_attr.span.hi()),
900 " {".to_string(),
901 ),
902 (next_expr.span.shrink_to_lo(), " ".to_string()),
903 (next_expr.span.shrink_to_hi(), format!("\n{}}}", " ".repeat(margin))),
904 ];
905 err.multipart_suggestion(
906 "it seems like you are trying to provide different expressions depending on \
907 `cfg`, consider using `if cfg!(..)`",
908 sugg,
909 Applicability::MachineApplicable,
910 );
911 }
912 }
913
914 err.emit()
915 }
916
917 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diag<'_>) -> bool {
918 let sm = self.psess.source_map();
919 match (&self.prev_token.kind, &self.token.kind) {
920 (
921 TokenKind::Literal(Lit {
922 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
923 ..
924 }),
925 TokenKind::Pound,
926 ) if !sm.is_multiline(
927 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
928 ) =>
929 {
930 let n_hashes: u8 = *n_hashes;
931 err.primary_message("too many `#` when terminating raw string");
932 let str_span = self.prev_token.span;
933 let mut span = self.token.span;
934 let mut count = 0;
935 while self.token == TokenKind::Pound
936 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
937 {
938 span = span.with_hi(self.token.span.hi());
939 self.bump();
940 count += 1;
941 }
942 err.span(span);
943 err.span_suggestion_verbose(
944 span,
945 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("remove the extra `#`{0}",
if count == 1 { "" } else { "s" }))
})format!("remove the extra `#`{}", pluralize!(count)),
946 "",
947 Applicability::MachineApplicable,
948 );
949 err.span_label(
950 str_span,
951 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this raw string started with {1} `#`{0}",
if n_hashes == 1 { "" } else { "s" }, n_hashes))
})format!("this raw string started with {n_hashes} `#`{}", pluralize!(n_hashes)),
952 );
953 true
954 }
955 _ => false,
956 }
957 }
958
959 pub(super) fn maybe_suggest_struct_literal(
960 &mut self,
961 lo: Span,
962 s: BlockCheckMode,
963 maybe_struct_name: token::Token,
964 ) -> Option<PResult<'a, Box<Block>>> {
965 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
966 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:970",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(970u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("maybe_struct_name")
}> =
::tracing::__macro_support::FieldName::new("maybe_struct_name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.token")
}> =
::tracing::__macro_support::FieldName::new("self.token");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&maybe_struct_name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.token)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?maybe_struct_name, ?self.token);
971 let mut snapshot = self.create_snapshot_for_diagnostic();
972 let path = Path { segments: ThinVec::new(), span: self.prev_token.span.shrink_to_lo() };
973 let struct_expr = snapshot.parse_expr_struct(None, path, false);
974 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
975 return Some(match (struct_expr, block_tail) {
976 (Ok(expr), Err(err)) => {
977 err.cancel();
986 self.restore_snapshot(snapshot);
987 let guar = self.dcx().emit_err(StructLiteralBodyWithoutPath {
988 span: expr.span,
989 sugg: StructLiteralBodyWithoutPathSugg {
990 before: expr.span.shrink_to_lo(),
991 after: expr.span.shrink_to_hi(),
992 },
993 });
994 Ok(self.mk_block(
995 {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(self.mk_stmt_err(expr.span, guar));
vec
}thin_vec![self.mk_stmt_err(expr.span, guar)],
996 s,
997 lo.to(self.prev_token.span),
998 ))
999 }
1000 (Err(err), Ok(tail)) => {
1001 err.cancel();
1003 Ok(tail)
1004 }
1005 (Err(snapshot_err), Err(err)) => {
1006 snapshot_err.cancel();
1008 self.consume_block(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace), crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace), ConsumeClosingDelim::Yes);
1009 Err(err)
1010 }
1011 (Ok(_), Ok(tail)) => Ok(tail),
1012 });
1013 }
1014 None
1015 }
1016
1017 pub(super) fn recover_closure_body(
1018 &mut self,
1019 mut err: Diag<'a>,
1020 before: token::Token,
1021 prev: token::Token,
1022 token: token::Token,
1023 lo: Span,
1024 decl_hi: Span,
1025 ) -> PResult<'a, Box<Expr>> {
1026 err.span_label(lo.to(decl_hi), "while parsing the body of this closure");
1027 let guar = match before.kind {
1028 token::OpenBrace if token.kind != token::OpenBrace => {
1029 err.multipart_suggestion(
1031 "you might have meant to open the body of the closure, instead of enclosing \
1032 the closure in a block",
1033 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(before.span, String::new()),
(prev.span.shrink_to_hi(), " {".to_string())]))vec![
1034 (before.span, String::new()),
1035 (prev.span.shrink_to_hi(), " {".to_string()),
1036 ],
1037 Applicability::MaybeIncorrect,
1038 );
1039 let guar = err.emit();
1040 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1041 guar
1042 }
1043 token::OpenParen if token.kind != token::OpenBrace => {
1044 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen), crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)]);
1047
1048 err.multipart_suggestion(
1049 "you might have meant to open the body of the closure",
1050 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(prev.span.shrink_to_hi(), " {".to_string()),
(self.token.span.shrink_to_lo(), "}".to_string())]))vec![
1051 (prev.span.shrink_to_hi(), " {".to_string()),
1052 (self.token.span.shrink_to_lo(), "}".to_string()),
1053 ],
1054 Applicability::MaybeIncorrect,
1055 );
1056 err.emit()
1057 }
1058 _ if token.kind != token::OpenBrace => {
1059 err.multipart_suggestion(
1062 "you might have meant to open the body of the closure",
1063 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(prev.span.shrink_to_hi(), " {".to_string())]))vec![(prev.span.shrink_to_hi(), " {".to_string())],
1064 Applicability::HasPlaceholders,
1065 );
1066 return Err(err);
1067 }
1068 _ => return Err(err),
1069 };
1070 Ok(self.mk_expr_err(lo.to(self.token.span), guar))
1071 }
1072
1073 pub(super) fn eat_to_tokens(&mut self, closes: &[ExpTokenPair]) {
1076 if let Err(err) = self
1077 .parse_seq_to_before_tokens(closes, &[], SeqSep::none(), |p| Ok(p.parse_token_tree()))
1078 {
1079 err.cancel();
1080 }
1081 }
1082
1083 pub(super) fn check_trailing_angle_brackets(
1094 &mut self,
1095 segment: &PathSegment,
1096 end: &[ExpTokenPair],
1097 ) -> Option<ErrorGuaranteed> {
1098 if !self.may_recover() {
1099 return None;
1100 }
1101
1102 let parsed_angle_bracket_args =
1127 segment.args.as_ref().is_some_and(|args| args.is_angle_bracketed());
1128
1129 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:1129",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1129u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: parsed_angle_bracket_args={0:?}",
parsed_angle_bracket_args) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1130 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
1131 parsed_angle_bracket_args,
1132 );
1133 if !parsed_angle_bracket_args {
1134 return None;
1135 }
1136
1137 let lo = self.token.span;
1140
1141 let mut position = 0;
1145
1146 let mut number_of_shr = 0;
1150 let mut number_of_gt = 0;
1151 while self.look_ahead(position, |t| {
1152 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:1152",
"rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1152u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: t={0:?}",
t) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("check_trailing_angle_brackets: t={:?}", t);
1153 if *t == token::Shr {
1154 number_of_shr += 1;
1155 true
1156 } else if *t == token::Gt {
1157 number_of_gt += 1;
1158 true
1159 } else {
1160 false
1161 }
1162 }) {
1163 position += 1;
1164 }
1165
1166 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:1167",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1167u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: number_of_gt={0:?} number_of_shr={1:?}",
number_of_gt, number_of_shr) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1168 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
1169 number_of_gt, number_of_shr,
1170 );
1171 if number_of_gt < 1 && number_of_shr < 1 {
1172 return None;
1173 }
1174
1175 if self.look_ahead(position, |t| {
1178 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:1178",
"rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1178u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_trailing_angle_brackets: t={0:?}",
t) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("check_trailing_angle_brackets: t={:?}", t);
1179 end.iter().any(|exp| exp.tok == t.kind)
1180 }) {
1181 self.eat_to_tokens(end);
1184 let span = lo.to(self.prev_token.span);
1185
1186 let num_extra_brackets = number_of_gt + number_of_shr * 2;
1187 return Some(self.dcx().emit_err(UnmatchedAngleBrackets { span, num_extra_brackets }));
1188 }
1189 None
1190 }
1191
1192 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
1195 if !self.may_recover() {
1196 return;
1197 }
1198
1199 if self.token == token::PathSep && segment.args.is_none() {
1200 let snapshot = self.create_snapshot_for_diagnostic();
1201 self.bump();
1202 let lo = self.token.span;
1203 match self.parse_angle_args(None) {
1204 Ok(args) => {
1205 let span = lo.to(self.prev_token.span);
1206 let mut trailing_span = self.prev_token.span.shrink_to_hi();
1208 while self.token == token::Shr || self.token == token::Gt {
1209 trailing_span = trailing_span.to(self.token.span);
1210 self.bump();
1211 }
1212 if self.token == token::OpenParen {
1213 segment.args = Some(AngleBracketedArgs { args, span }.into());
1215
1216 self.dcx().emit_err(GenericParamsWithoutAngleBrackets {
1217 span,
1218 sugg: GenericParamsWithoutAngleBracketsSugg {
1219 left: span.shrink_to_lo(),
1220 right: trailing_span,
1221 },
1222 });
1223 } else {
1224 self.restore_snapshot(snapshot);
1226 }
1227 }
1228 Err(err) => {
1229 err.cancel();
1232 self.restore_snapshot(snapshot);
1233 }
1234 }
1235 }
1236 }
1237
1238 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
1241 &mut self,
1242 mut e: Diag<'a>,
1243 expr: &mut Box<Expr>,
1244 ) -> PResult<'a, ErrorGuaranteed> {
1245 if let ExprKind::Binary(binop, _, _) = &expr.kind
1246 && let ast::BinOpKind::Lt = binop.node
1247 && self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))
1248 {
1249 let x = self.parse_seq_to_before_end(
1250 crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt),
1251 SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
1252 |p| match p.parse_generic_arg(None)? {
1253 Some(arg) => Ok(arg),
1254 None => p.unexpected_any(),
1256 },
1257 );
1258 match x {
1259 Ok((_, _, Recovered::No)) => {
1260 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
1261 e.span_suggestion_verbose(
1263 binop.span.shrink_to_lo(),
1264 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments"))msg!("use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments"),
1265 "::",
1266 Applicability::MaybeIncorrect,
1267 );
1268 match self.parse_expr() {
1269 Ok(_) => {
1270 let guar = e.emit();
1274 *expr = self.mk_expr_err(expr.span.to(self.prev_token.span), guar);
1275 return Ok(guar);
1276 }
1277 Err(err) => {
1278 err.cancel();
1279 }
1280 }
1281 }
1282 }
1283 Ok((_, _, Recovered::Yes(_))) => {}
1284 Err(err) => {
1285 err.cancel();
1286 }
1287 }
1288 }
1289 Err(e)
1290 }
1291
1292 pub(super) fn suggest_add_missing_let_for_stmt(&mut self, err: &mut Diag<'a>) {
1295 if self.token == token::Colon {
1296 let prev_span = self.prev_token.span.shrink_to_lo();
1297 let snapshot = self.create_snapshot_for_diagnostic();
1298 self.bump();
1299 match self.parse_ty() {
1300 Ok(_) => {
1301 if self.token == token::Eq {
1302 let sugg = SuggAddMissingLetStmt { span: prev_span };
1303 sugg.add_to_diag(err);
1304 }
1305 }
1306 Err(e) => {
1307 e.cancel();
1308 }
1309 }
1310 self.restore_snapshot(snapshot);
1311 }
1312 }
1313
1314 fn attempt_chained_comparison_suggestion(
1318 &mut self,
1319 err: &mut ComparisonOperatorsCannotBeChained,
1320 inner_op: &Expr,
1321 outer_op: &Spanned<AssocOp>,
1322 ) -> bool {
1323 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
1324 if let ExprKind::Field(_, ident) = l1.kind
1325 && !ident.is_numeric()
1326 && !#[allow(non_exhaustive_omitted_patterns)] match r1.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(r1.kind, ExprKind::Lit(_))
1327 {
1328 return false;
1331 }
1332 return match (op.node, &outer_op.node) {
1333 (BinOpKind::Eq, AssocOp::Binary(BinOpKind::Eq)) |
1335 (BinOpKind::Lt, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1337 (BinOpKind::Le, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1338 (BinOpKind::Gt, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) |
1340 (BinOpKind::Ge, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) => {
1341 let expr_to_str = |e: &Expr| {
1342 self.span_to_snippet(e.span).unwrap_or_else(|_| pprust::expr_to_string(e))
1343 };
1344 err.chaining_sugg =
1345 Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
1346 span: inner_op.span.shrink_to_hi(),
1347 middle_term: expr_to_str(r1),
1348 });
1349 false }
1351 (
1353 BinOpKind::Eq,
1354 AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge),
1355 ) => {
1356 let snapshot = self.create_snapshot_for_diagnostic();
1358 match self.parse_expr() {
1359 Ok(r2) => {
1360 err.chaining_sugg =
1363 Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1364 left: r1.span.shrink_to_lo(),
1365 right: r2.span.shrink_to_hi(),
1366 });
1367 true
1368 }
1369 Err(expr_err) => {
1370 expr_err.cancel();
1371 self.restore_snapshot(snapshot);
1372 true
1373 }
1374 }
1375 }
1376 (
1378 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge,
1379 AssocOp::Binary(BinOpKind::Eq),
1380 ) => {
1381 let snapshot = self.create_snapshot_for_diagnostic();
1382 match self.parse_expr() {
1385 Ok(_) => {
1386 err.chaining_sugg =
1387 Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1388 left: l1.span.shrink_to_lo(),
1389 right: r1.span.shrink_to_hi(),
1390 });
1391 true
1392 }
1393 Err(expr_err) => {
1394 expr_err.cancel();
1395 self.restore_snapshot(snapshot);
1396 false
1397 }
1398 }
1399 }
1400 _ => false,
1401 };
1402 }
1403 false
1404 }
1405
1406 pub(super) fn check_no_chained_comparison(
1425 &mut self,
1426 inner_op: &Expr,
1427 outer_op: &Spanned<AssocOp>,
1428 ) -> PResult<'a, Option<Box<Expr>>> {
1429 if true {
if !outer_op.node.is_comparison() {
{
::core::panicking::panic_fmt(format_args!("check_no_chained_comparison: {0:?} is not comparison",
outer_op.node));
}
};
};debug_assert!(
1430 outer_op.node.is_comparison(),
1431 "check_no_chained_comparison: {:?} is not comparison",
1432 outer_op.node,
1433 );
1434
1435 let mk_err_expr =
1436 |this: &Self, span, guar| Ok(Some(this.mk_expr(span, ExprKind::Err(guar))));
1437
1438 match &inner_op.kind {
1439 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1440 let mut err = ComparisonOperatorsCannotBeChained {
1441 span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[op.span, self.prev_token.span]))vec![op.span, self.prev_token.span],
1442 suggest_turbofish: None,
1443 help_turbofish: false,
1444 chaining_sugg: None,
1445 };
1446
1447 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Binary(BinOpKind::Lt)
1450 || outer_op.node == AssocOp::Binary(BinOpKind::Gt)
1451 {
1452 if outer_op.node == AssocOp::Binary(BinOpKind::Lt) {
1453 let snapshot = self.create_snapshot_for_diagnostic();
1454 self.bump();
1455 let modifiers = [(token::Lt, 1), (token::Gt, -1), (token::Shr, -2)];
1457 self.consume_tts(1, &modifiers);
1458
1459 if !#[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
token::OpenParen | token::PathSep => true,
_ => false,
}matches!(self.token.kind, token::OpenParen | token::PathSep) {
1460 self.restore_snapshot(snapshot);
1463 }
1464 }
1465 return if self.token == token::PathSep {
1466 if let ExprKind::Binary(o, ..) = inner_op.kind
1469 && o.node == BinOpKind::Lt
1470 {
1471 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1472 } else {
1473 err.help_turbofish = true;
1474 }
1475
1476 let snapshot = self.create_snapshot_for_diagnostic();
1477 self.bump(); match self.parse_expr() {
1481 Ok(_) => {
1482 let guar = self.dcx().emit_err(err);
1484 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1488 }
1489 Err(expr_err) => {
1490 expr_err.cancel();
1491 self.restore_snapshot(snapshot);
1494 Err(self.dcx().create_err(err))
1495 }
1496 }
1497 } else if self.token == token::OpenParen {
1498 if let ExprKind::Binary(o, ..) = inner_op.kind
1501 && o.node == BinOpKind::Lt
1502 {
1503 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1504 } else {
1505 err.help_turbofish = true;
1506 }
1507 match self.consume_fn_args() {
1509 Err(()) => Err(self.dcx().create_err(err)),
1510 Ok(()) => {
1511 let guar = self.dcx().emit_err(err);
1512 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1516 }
1517 }
1518 } else {
1519 if !#[allow(non_exhaustive_omitted_patterns)] match l1.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(l1.kind, ExprKind::Lit(_))
1520 && !#[allow(non_exhaustive_omitted_patterns)] match r1.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(r1.kind, ExprKind::Lit(_))
1521 {
1522 err.help_turbofish = true;
1525 }
1526
1527 let recovered = self
1530 .attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1531 if recovered {
1532 let guar = self.dcx().emit_err(err);
1533 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1534 } else {
1535 Err(self.dcx().create_err(err))
1537 }
1538 };
1539 }
1540 let recovered =
1541 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1542 let guar = self.dcx().emit_err(err);
1543 if recovered {
1544 return mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar);
1545 }
1546 }
1547 _ => {}
1548 }
1549 Ok(None)
1550 }
1551
1552 fn consume_fn_args(&mut self) -> Result<(), ()> {
1553 let snapshot = self.create_snapshot_for_diagnostic();
1554 self.bump(); let modifiers = [(token::OpenParen, 1), (token::CloseParen, -1)];
1558 self.consume_tts(1, &modifiers);
1559
1560 if self.token == token::Eof {
1561 self.restore_snapshot(snapshot);
1563 Err(())
1564 } else {
1565 Ok(())
1567 }
1568 }
1569
1570 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1571 if impl_dyn_multi {
1572 self.dcx().emit_err(AmbiguousPlus {
1573 span: ty.span,
1574 suggestion: AddParen { lo: ty.span.shrink_to_lo(), hi: ty.span.shrink_to_hi() },
1575 });
1576 }
1577 }
1578
1579 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: Box<Ty>) -> Box<Ty> {
1581 if self.token == token::Question {
1582 self.bump();
1583 let guar = self.dcx().emit_err(QuestionMarkInType {
1584 span: self.prev_token.span,
1585 sugg: QuestionMarkInTypeSugg {
1586 left: ty.span.shrink_to_lo(),
1587 right: self.prev_token.span,
1588 },
1589 });
1590 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err(guar))
1591 } else {
1592 ty
1593 }
1594 }
1595
1596 pub(super) fn maybe_recover_from_ternary_operator(
1602 &mut self,
1603 cond: Option<Span>,
1604 ) -> PResult<'a, ()> {
1605 if self.prev_token != token::Question {
1606 return PResult::Ok(());
1607 }
1608
1609 let question = self.prev_token.span;
1610 let lo = cond.unwrap_or(question).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 let colon = self.prev_token.span;
1624 match self.parse_expr() {
1625 Ok(expr) => {
1626 let sugg = cond.map(|cond| TernaryOperatorSuggestion {
1627 before_cond: cond.shrink_to_lo(),
1628 question,
1629 colon,
1630 end: expr.span.shrink_to_hi(),
1631 });
1632 return Err(self.dcx().create_err(TernaryOperator {
1633 span: self.prev_token.span.with_lo(lo),
1634 sugg,
1635 no_sugg: sugg.is_none(),
1636 }));
1637 }
1638 Err(err) => {
1639 err.cancel();
1640 }
1641 };
1642 }
1643 }
1644 self.restore_snapshot(snapshot);
1645 Ok(())
1646 }
1647
1648 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1649 if !self.token.is_like_plus() {
1651 return Ok(());
1652 }
1653
1654 self.bump(); let _bounds = self.parse_generic_bounds()?;
1656 let sub = match &ty.kind {
1657 TyKind::Ref(_lifetime, mut_ty) => {
1658 let lo = mut_ty.ty.span.shrink_to_lo();
1659 let hi = self.prev_token.span.shrink_to_hi();
1660 BadTypePlusSub::AddParen { suggestion: AddParen { lo, hi } }
1661 }
1662 TyKind::Ptr(..) | TyKind::FnPtr(..) => {
1663 BadTypePlusSub::ForgotParen { span: ty.span.to(self.prev_token.span) }
1664 }
1665 _ => BadTypePlusSub::ExpectPath { span: ty.span },
1666 };
1667
1668 self.dcx().emit_err(BadTypePlus { span: ty.span, sub });
1669
1670 Ok(())
1671 }
1672
1673 pub(super) fn recover_from_prefix_increment(
1674 &mut self,
1675 operand_expr: Box<Expr>,
1676 op_span: Span,
1677 start_stmt: bool,
1678 ) -> PResult<'a, Box<Expr>> {
1679 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1680 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1681 self.recover_from_inc_dec(operand_expr, kind, op_span)
1682 }
1683
1684 pub(super) fn recover_from_postfix_increment(
1685 &mut self,
1686 operand_expr: Box<Expr>,
1687 op_span: Span,
1688 start_stmt: bool,
1689 ) -> PResult<'a, Box<Expr>> {
1690 let kind = IncDecRecovery {
1691 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1692 op: IncOrDec::Inc,
1693 fixity: UnaryFixity::Post,
1694 };
1695 self.recover_from_inc_dec(operand_expr, kind, op_span)
1696 }
1697
1698 pub(super) fn recover_from_postfix_decrement(
1699 &mut self,
1700 operand_expr: Box<Expr>,
1701 op_span: Span,
1702 start_stmt: bool,
1703 ) -> PResult<'a, Box<Expr>> {
1704 let kind = IncDecRecovery {
1705 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1706 op: IncOrDec::Dec,
1707 fixity: UnaryFixity::Post,
1708 };
1709 self.recover_from_inc_dec(operand_expr, kind, op_span)
1710 }
1711
1712 fn recover_from_inc_dec(
1713 &mut self,
1714 base: Box<Expr>,
1715 kind: IncDecRecovery,
1716 op_span: Span,
1717 ) -> PResult<'a, Box<Expr>> {
1718 let mut err = self.dcx().struct_span_err(
1719 op_span,
1720 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Rust has no {0} {1} operator",
kind.fixity, kind.op.name()))
})format!("Rust has no {} {} operator", kind.fixity, kind.op.name()),
1721 );
1722 err.span_label(op_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a valid {0} operator",
kind.fixity))
})format!("not a valid {} operator", kind.fixity));
1723
1724 let help_base_case = |mut err: Diag<'_, _>, base| {
1725 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()));
1726 err.emit();
1727 Ok(base)
1728 };
1729
1730 let spans = match kind.fixity {
1732 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1733 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1734 };
1735
1736 match kind.standalone {
1737 IsStandalone::Standalone => {
1738 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1739 }
1740 IsStandalone::Subexpr => {
1741 let Ok(base_src) = self.span_to_snippet(base.span) else {
1742 return help_base_case(err, base);
1743 };
1744 match kind.fixity {
1745 UnaryFixity::Pre => {
1746 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1747 }
1748 UnaryFixity::Post => {
1749 if !#[allow(non_exhaustive_omitted_patterns)] match base.kind {
ExprKind::Binary(_, _, _) => true,
_ => false,
}matches!(base.kind, ExprKind::Binary(_, _, _)) {
1752 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1753 }
1754 }
1755 }
1756 }
1757 }
1758 Err(err)
1759 }
1760
1761 fn prefix_inc_dec_suggest(
1762 &mut self,
1763 base_src: String,
1764 kind: IncDecRecovery,
1765 (pre_span, post_span): (Span, Span),
1766 ) -> MultiSugg {
1767 MultiSugg {
1768 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()),
1769 patches: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(pre_span, "{ ".to_string()),
(post_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}= 1; {1} }}",
kind.op.chr(), base_src))
}))]))vec![
1770 (pre_span, "{ ".to_string()),
1771 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1772 ],
1773 applicability: Applicability::MachineApplicable,
1774 }
1775 }
1776
1777 fn postfix_inc_dec_suggest(
1778 &mut self,
1779 base_src: String,
1780 kind: IncDecRecovery,
1781 (pre_span, post_span): (Span, Span),
1782 ) -> MultiSugg {
1783 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1784 MultiSugg {
1785 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()),
1786 patches: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(pre_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{ let {0} = ", tmp_var))
})),
(post_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("; {0} {1}= 1; {2} }}",
base_src, kind.op.chr(), tmp_var))
}))]))vec![
1787 (pre_span, format!("{{ let {tmp_var} = ")),
1788 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1789 ],
1790 applicability: Applicability::HasPlaceholders,
1791 }
1792 }
1793
1794 fn inc_dec_standalone_suggest(
1795 &mut self,
1796 kind: IncDecRecovery,
1797 (pre_span, post_span): (Span, Span),
1798 ) -> MultiSugg {
1799 let mut patches = Vec::new();
1800
1801 if !pre_span.is_empty() {
1802 patches.push((pre_span, String::new()));
1803 }
1804
1805 patches.push((post_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}= 1", kind.op.chr()))
})format!(" {}= 1", kind.op.chr())));
1806 MultiSugg {
1807 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()),
1808 patches,
1809 applicability: Applicability::MachineApplicable,
1810 }
1811 }
1812
1813 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1817 &mut self,
1818 base: T,
1819 ) -> PResult<'a, T> {
1820 if self.may_recover() && self.token == token::PathSep {
1822 return self.recover_from_bad_qpath(base);
1823 }
1824 Ok(base)
1825 }
1826
1827 #[cold]
1828 fn recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T) -> PResult<'a, T> {
1829 if let Some(ty) = base.to_ty() {
1830 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1831 }
1832 Ok(base)
1833 }
1834
1835 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1838 &mut self,
1839 ty_span: Span,
1840 ty: Box<Ty>,
1841 ) -> PResult<'a, T> {
1842 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep))?;
1843
1844 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP };
1845 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1846 path.span = ty_span.to(self.prev_token.span);
1847
1848 self.dcx().emit_err(BadQPathStage2 {
1849 span: ty_span,
1850 wrap: WrapType { lo: ty_span.shrink_to_lo(), hi: ty_span.shrink_to_hi() },
1851 });
1852
1853 let path_span = ty_span.shrink_to_hi(); Ok(T::recovered(Some(Box::new(QSelf { ty, path_span, position: 0 })), path))
1855 }
1856
1857 pub fn maybe_consume_incorrect_semicolon(&mut self, previous_item: Option<&Item>) -> bool {
1860 if self.token != TokenKind::Semi {
1861 return false;
1862 }
1863
1864 let err = match previous_item {
1867 Some(previous_item) => {
1868 let name = match previous_item.kind {
1869 ItemKind::Struct(..) => "braced struct",
1872 _ => previous_item.kind.descr(),
1873 };
1874 IncorrectSemicolon { span: self.token.span, name, show_help: true }
1875 }
1876 None => IncorrectSemicolon { span: self.token.span, name: "", show_help: false },
1877 };
1878 self.dcx().emit_err(err);
1879
1880 self.bump();
1881 true
1882 }
1883
1884 pub(super) fn unexpected_err(&mut self, t: &TokenKind) -> Diag<'a> {
1886 let token_str = pprust::token_kind_to_string(t);
1887 let this_token_str = super::token_descr(&self.token);
1888 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1889 (token::Eof, Some(_)) => {
1891 let sp = self.prev_token.span.shrink_to_hi();
1892 (sp, sp)
1893 }
1894 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1897 (token::Eof, None) => (self.prev_token.span, self.token.span),
1899 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1900 };
1901 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found {1}",
token_str,
match (&self.token.kind, self.subparser_name) {
(token::Eof, Some(origin)) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("end of {0}", origin))
}),
_ => this_token_str,
}))
})format!(
1902 "expected `{}`, found {}",
1903 token_str,
1904 match (&self.token.kind, self.subparser_name) {
1905 (token::Eof, Some(origin)) => format!("end of {origin}"),
1906 _ => this_token_str,
1907 },
1908 );
1909 let mut err = self.dcx().struct_span_err(sp, msg);
1910 let label_exp = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`", token_str))
})format!("expected `{token_str}`");
1911 let sm = self.psess.source_map();
1912 if !sm.is_multiline(prev_sp.until(sp)) {
1913 err.span_label(sp, label_exp);
1916 } else {
1917 err.span_label(prev_sp, label_exp);
1918 err.span_label(sp, "unexpected token");
1919 }
1920 err
1921 }
1922
1923 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1924 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) || self.recover_colon_as_semi() {
1925 return Ok(());
1926 }
1927 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)).map(drop) }
1929
1930 pub(super) fn recover_colon_as_semi(&mut self) -> bool {
1931 let line_idx = |span: Span| {
1932 self.psess
1933 .source_map()
1934 .span_to_lines(span)
1935 .ok()
1936 .and_then(|lines| Some(lines.lines.get(0)?.line_index))
1937 };
1938
1939 if self.may_recover()
1940 && self.token == token::Colon
1941 && self.look_ahead(1, |next| line_idx(self.token.span) < line_idx(next.span))
1942 {
1943 self.dcx().emit_err(ColonAsSemi { span: self.token.span });
1944 self.bump();
1945 return true;
1946 }
1947
1948 false
1949 }
1950
1951 pub(super) fn recover_incorrect_await_syntax(
1954 &mut self,
1955 await_sp: Span,
1956 ) -> PResult<'a, Box<Expr>> {
1957 let (hi, expr, is_question) = if self.token == token::Bang {
1958 self.recover_await_macro()?
1960 } else {
1961 self.recover_await_prefix(await_sp)?
1962 };
1963 let (sp, guar) = self.error_on_incorrect_await(await_sp, hi, &expr, is_question);
1964 let expr = self.mk_expr_err(await_sp.to(sp), guar);
1965 self.maybe_recover_from_bad_qpath(expr)
1966 }
1967
1968 fn recover_await_macro(&mut self) -> PResult<'a, (Span, Box<Expr>, bool)> {
1969 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?;
1970 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1971 let expr = self.parse_expr()?;
1972 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1973 Ok((self.prev_token.span, expr, false))
1974 }
1975
1976 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, Box<Expr>, bool)> {
1977 let is_question = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Question,
token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question)); let expr = if self.token == token::OpenBrace {
1979 self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)
1983 } else {
1984 self.parse_expr()
1985 }
1986 .map_err(|mut err| {
1987 err.span_label(await_sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("while parsing this incorrect await expression"))
})format!("while parsing this incorrect await expression"));
1988 err
1989 })?;
1990 Ok((expr.span, expr, is_question))
1991 }
1992
1993 fn error_on_incorrect_await(
1994 &self,
1995 lo: Span,
1996 hi: Span,
1997 expr: &Expr,
1998 is_question: bool,
1999 ) -> (Span, ErrorGuaranteed) {
2000 let span = lo.to(hi);
2001 let guar = self.dcx().emit_err(IncorrectAwait {
2002 span,
2003 suggestion: AwaitSuggestion {
2004 removal: lo.until(expr.span),
2005 dot_await: expr.span.shrink_to_hi(),
2006 question_mark: if is_question { "?" } else { "" },
2007 },
2008 });
2009 (span, guar)
2010 }
2011
2012 pub(super) fn recover_from_await_method_call(&mut self) {
2014 if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
2015 let lo = self.token.span;
2017 self.bump(); let span = lo.to(self.token.span);
2019 self.bump(); self.dcx().emit_err(IncorrectUseOfAwait { span });
2022 }
2023 }
2024 pub(super) fn recover_from_use(&mut self) {
2027 if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
2028 let lo = self.token.span;
2030 self.bump(); let span = lo.to(self.token.span);
2032 self.bump(); self.dcx().emit_err(IncorrectUseOfUse { span });
2035 }
2036 }
2037
2038 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, Box<Expr>> {
2039 let is_try = self.token.is_keyword(kw::Try);
2040 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 {
2044 let lo = self.token.span;
2045 self.bump(); self.bump(); let try_span = lo.to(self.token.span); self.bump(); let is_empty = self.token == token::CloseParen; self.consume_block(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen), crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen), ConsumeClosingDelim::No); let hi = self.token.span;
2052 self.bump(); let mut err = self.dcx().struct_span_err(lo.to(hi), "use of deprecated `try` macro");
2054 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
2055 let prefix = if is_empty { "" } else { "alternatively, " };
2056 if !is_empty {
2057 err.multipart_suggestion(
2058 "you can use the `?` operator instead",
2059 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(try_span, "".to_owned()), (hi, "?".to_owned())]))vec![(try_span, "".to_owned()), (hi, "?".to_owned())],
2060 Applicability::MachineApplicable,
2061 );
2062 }
2063 err.span_suggestion_verbose(
2064 lo.shrink_to_lo(),
2065 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}you can still access the deprecated `try!()` macro using the \"raw identifier\" syntax",
prefix))
})format!(
2066 "{prefix}you can still access the deprecated `try!()` macro using the \
2067 \"raw identifier\" syntax"
2068 ),
2069 "r#",
2070 Applicability::MachineApplicable,
2071 );
2072 let guar = err.emit();
2073 Ok(self.mk_expr_err(lo.to(hi), guar))
2074 } else {
2075 Err(self.expected_expression_found()) }
2077 }
2078
2079 pub(super) fn expect_gt_or_maybe_suggest_closing_generics(
2086 &mut self,
2087 params: &[ast::GenericParam],
2088 ) -> PResult<'a, ()> {
2089 let Err(mut err) = self.expect_gt() else {
2090 return Ok(());
2091 };
2092 if let [.., ast::GenericParam { bounds, .. }] = params
2094 && let Some(poly) = bounds
2095 .iter()
2096 .filter_map(|bound| match bound {
2097 ast::GenericBound::Trait(poly) => Some(poly),
2098 _ => None,
2099 })
2100 .next_back()
2101 {
2102 err.span_suggestion_verbose(
2103 poly.span.shrink_to_hi(),
2104 "you might have meant to end the type parameters here",
2105 ">",
2106 Applicability::MaybeIncorrect,
2107 );
2108 }
2109 Err(err)
2110 }
2111
2112 pub(super) fn recover_seq_parse_error(
2113 &mut self,
2114 open: ExpTokenPair,
2115 close: ExpTokenPair,
2116 lo: Span,
2117 err: Diag<'a>,
2118 ) -> Box<Expr> {
2119 let guar = err.emit();
2120 self.consume_block(open, close, ConsumeClosingDelim::Yes);
2122 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err(guar))
2123 }
2124
2125 pub(super) fn recover_stmt(&mut self) {
2130 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
2131 }
2132
2133 pub(super) fn recover_stmt_(
2141 &mut self,
2142 break_on_semi: SemiColonMode,
2143 break_on_block: BlockMode,
2144 ) {
2145 let mut brace_depth = 0;
2146 let mut bracket_depth = 0;
2147 let mut in_block = false;
2148 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:2148",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2148u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ enter loop (semi={0:?}, block={1:?})",
break_on_semi, break_on_block) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block);
2149 loop {
2150 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:2150",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2150u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ loop {0:?}",
self.token) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ loop {:?}", self.token);
2151 match self.token.kind {
2152 token::OpenBrace => {
2153 brace_depth += 1;
2154 self.bump();
2155 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
2156 {
2157 in_block = true;
2158 }
2159 }
2160 token::OpenBracket => {
2161 bracket_depth += 1;
2162 self.bump();
2163 }
2164 token::CloseBrace => {
2165 if brace_depth == 0 {
2166 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:2166",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2166u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - close delim {0:?}",
self.token) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ return - close delim {:?}", self.token);
2167 break;
2168 }
2169 brace_depth -= 1;
2170 self.bump();
2171 if in_block && bracket_depth == 0 && brace_depth == 0 {
2172 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:2172",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2172u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - block end {0:?}",
self.token) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ return - block end {:?}", self.token);
2173 break;
2174 }
2175 }
2176 token::CloseBracket => {
2177 bracket_depth -= 1;
2178 if bracket_depth < 0 {
2179 bracket_depth = 0;
2180 }
2181 self.bump();
2182 }
2183 token::Eof => {
2184 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:2184",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2184u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - Eof")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ return - Eof");
2185 break;
2186 }
2187 token::Semi => {
2188 self.bump();
2189 if break_on_semi == SemiColonMode::Break
2190 && brace_depth == 0
2191 && bracket_depth == 0
2192 {
2193 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/diagnostics.rs:2193",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2193u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("recover_stmt_ return - Semi")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ return - Semi");
2194 break;
2195 }
2196 }
2197 token::Comma
2198 if break_on_semi == SemiColonMode::Comma
2199 && brace_depth == 0
2200 && bracket_depth == 0 =>
2201 {
2202 break;
2203 }
2204 _ => self.bump(),
2205 }
2206 }
2207 }
2208
2209 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
2210 if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::In,
token_type: crate::parser::token_type::TokenType::KwIn,
}exp!(In)) {
2211 self.dcx().emit_err(InInTypo {
2213 span: self.prev_token.span,
2214 sugg_span: in_span.until(self.prev_token.span),
2215 });
2216 }
2217 }
2218
2219 pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) {
2220 if let token::DocComment(..) = self.token.kind {
2221 self.dcx().emit_err(DocCommentOnParamType { span: self.token.span });
2222 self.bump();
2223 } else if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
2224 let lo = self.token.span;
2225 while self.token != token::CloseBracket {
2227 self.bump();
2228 }
2229 let sp = lo.to(self.token.span);
2230 self.bump();
2231 self.dcx().emit_err(AttributeOnParamType { span: sp });
2232 }
2233 }
2234
2235 pub(super) fn parameter_without_type(
2236 &mut self,
2237 err: &mut Diag<'_>,
2238 pat: Box<ast::Pat>,
2239 require_name: bool,
2240 first_param: bool,
2241 fn_parse_mode: &crate::parser::FnParseMode,
2242 ) -> Option<Ident> {
2243 if self.check_ident()
2246 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen)
2247 {
2248 let ident = self.parse_ident_common(true).unwrap();
2250 let span = pat.span.with_hi(ident.span.hi());
2251
2252 err.span_suggestion_verbose(
2253 span,
2254 "declare the type after the parameter binding",
2255 "<identifier>: <type>",
2256 Applicability::HasPlaceholders,
2257 );
2258 return Some(ident);
2259 } else if require_name
2260 && (self.token == token::Comma
2261 || self.token == token::Lt
2262 || self.token == token::CloseParen)
2263 {
2264 let maybe_emit_anon_params_note = |this: &mut Self, err: &mut Diag<'_>| {
2265 let ed = this.token.span.with_neighbor(this.prev_token.span).edition();
2266 if #[allow(non_exhaustive_omitted_patterns)] match fn_parse_mode.context {
crate::parser::FnContext::Trait => true,
_ => false,
}matches!(fn_parse_mode.context, crate::parser::FnContext::Trait)
2267 && (fn_parse_mode.req_name)(ed, IsDotDotDot::No)
2268 {
2269 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2270 }
2271 };
2272
2273 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
2274 match pat.kind {
2275 PatKind::Ident(_, ident, _) => (
2276 ident,
2277 "self: ",
2278 ": TypeName".to_string(),
2279 "_: ",
2280 pat.span.shrink_to_lo(),
2281 pat.span.shrink_to_hi(),
2282 pat.span.shrink_to_lo(),
2283 ),
2284 PatKind::Ref(ref inner_pat, _, _)
2285 if let PatKind::Ref(_, _, _) = &inner_pat.kind
2288 && let PatKind::Path(_, path) = &pat.peel_refs().kind
2289 && let [a, ..] = path.segments.as_slice()
2290 && a.ident.name == kw::SelfLower =>
2291 {
2292 let mut inner = inner_pat;
2293 let mut span_vec = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[pat.span]))vec![pat.span];
2294
2295 while let PatKind::Ref(ref inner_type, _, _) = inner.kind {
2296 inner = inner_type;
2297 span_vec.push(inner.span.shrink_to_lo());
2298 }
2299
2300 let span = match span_vec.len() {
2301 0 | 1 => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2303 2 => span_vec[0].until(inner_pat.span.shrink_to_lo()),
2304 _ => span_vec[0].until(span_vec[span_vec.len() - 2].shrink_to_lo()),
2305 };
2306
2307 err.span_suggestion_verbose(
2308 span,
2309 "`self` should be `self`, `&self` or `&mut self`, consider removing extra references",
2310 "".to_string(),
2311 Applicability::MachineApplicable,
2312 );
2313
2314 return None;
2315 }
2316 PatKind::Ref(ref inner_pat, pinned, mutab)
2318 if let PatKind::Ident(_, ident, _) = inner_pat.clone().kind =>
2319 {
2320 let mutab = pinned.prefix_str(mutab);
2321 (
2322 ident,
2323 "self: ",
2324 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: &{1}TypeName", ident, mutab))
})format!("{ident}: &{mutab}TypeName"),
2325 "_: ",
2326 pat.span.shrink_to_lo(),
2327 pat.span,
2328 pat.span.shrink_to_lo(),
2329 )
2330 }
2331 _ => {
2332 if let Some(_) = pat.to_ty() {
2334 err.span_suggestion_verbose(
2335 pat.span.shrink_to_lo(),
2336 "explicitly ignore the parameter name",
2337 "_: ".to_string(),
2338 Applicability::MachineApplicable,
2339 );
2340 maybe_emit_anon_params_note(self, err);
2341 }
2342
2343 return None;
2344 }
2345 };
2346
2347 if first_param
2349 && #[allow(non_exhaustive_omitted_patterns)] match fn_parse_mode.context {
FnContext::Trait | FnContext::Impl => true,
_ => false,
}matches!(
2351 fn_parse_mode.context,
2352 FnContext::Trait | FnContext::Impl
2353 )
2354 {
2355 err.span_suggestion_verbose(
2356 self_span,
2357 "if this is a `self` type, give it a parameter name",
2358 self_sugg,
2359 Applicability::MaybeIncorrect,
2360 );
2361 }
2362 if self.token != token::Lt {
2365 err.span_suggestion_verbose(
2366 param_span,
2367 "if this is a parameter name, give it a type",
2368 param_sugg,
2369 Applicability::HasPlaceholders,
2370 );
2371 }
2372 err.span_suggestion_verbose(
2373 type_span,
2374 "if this is a type, explicitly ignore the parameter name",
2375 type_sugg,
2376 Applicability::MachineApplicable,
2377 );
2378 maybe_emit_anon_params_note(self, err);
2379
2380 return if self.token == token::Lt { None } else { Some(ident) };
2382 }
2383 None
2384 }
2385
2386 #[cold]
2387 pub(super) fn recover_arg_parse(
2388 &mut self,
2389 context: FnContext,
2390 ) -> PResult<'a, (Box<ast::Pat>, Box<ast::Ty>)> {
2391 let pat = self.parse_pat_no_top_alt(Some(Expected::ArgumentName), None)?;
2392 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon))?;
2393 let ty = self.parse_ty()?;
2394 self.dcx().emit_err(PatternMethodParamWithoutBody {
2395 span: pat.span,
2396 target: match context {
2397 FnContext::Trait => "methods without bodies",
2398 FnContext::FunctionPtrType => "function pointer types",
2399 FnContext::Free => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("This method is not called in free functions, as patterns are always allowed there")));
}unreachable!("This method is not called in free functions, as patterns are always allowed there"),
2400 FnContext::Impl => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("This method is not called in impls, as patterns are always allowed there")));
}unreachable!("This method is not called in impls, as patterns are always allowed there"),
2401 },
2402 });
2403
2404 let pat = Box::new(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
2406 Ok((pat, ty))
2407 }
2408
2409 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2410 let span = param.pat.span;
2411 let guar = self.dcx().emit_err(SelfParamNotFirst { span });
2412 param.ty.kind = TyKind::Err(guar);
2413 Ok(param)
2414 }
2415
2416 pub(super) fn consume_block(
2417 &mut self,
2418 open: ExpTokenPair,
2419 close: ExpTokenPair,
2420 consume_close: ConsumeClosingDelim,
2421 ) {
2422 let mut brace_depth = 0;
2423 loop {
2424 if self.eat(open) {
2425 brace_depth += 1;
2426 } else if self.check(close) {
2427 if brace_depth == 0 {
2428 if let ConsumeClosingDelim::Yes = consume_close {
2429 self.bump();
2433 }
2434 return;
2435 } else {
2436 self.bump();
2437 brace_depth -= 1;
2438 continue;
2439 }
2440 } else if self.token == token::Eof {
2441 return;
2442 } else {
2443 self.bump();
2444 }
2445 }
2446 }
2447
2448 pub(super) fn expected_expression_found(&self) -> Diag<'a> {
2449 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2450 (&token::Eof, Some(origin)) => {
2451 let sp = self.prev_token.span.shrink_to_hi();
2452 (sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected expression, found end of {0}",
origin))
})format!("expected expression, found end of {origin}"))
2453 }
2454 _ => (
2455 self.token.span,
2456 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected expression, found {0}",
super::token_descr(&self.token)))
})format!("expected expression, found {}", super::token_descr(&self.token)),
2457 ),
2458 };
2459 let mut err = self.dcx().struct_span_err(span, msg);
2460 let sp = self.psess.source_map().start_point(self.token.span);
2461 if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
2462 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2463 }
2464 err.span_label(span, "expected expression");
2465 err
2466 }
2467
2468 fn consume_tts(
2469 &mut self,
2470 mut acc: i64, modifier: &[(token::TokenKind, i64)],
2473 ) {
2474 while acc > 0 {
2475 if let Some((_, val)) = modifier.iter().find(|(t, _)| self.token == *t) {
2476 acc += *val;
2477 }
2478 if self.token == token::Eof {
2479 break;
2480 }
2481 self.bump();
2482 }
2483 }
2484
2485 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut ThinVec<Param>) {
2494 let mut seen_inputs = FxHashSet::default();
2495 for input in fn_inputs.iter_mut() {
2496 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err(_)) =
2497 (&input.pat.kind, &input.ty.kind)
2498 {
2499 Some(*ident)
2500 } else {
2501 None
2502 };
2503 if let Some(ident) = opt_ident {
2504 if seen_inputs.contains(&ident) {
2505 input.pat.kind = PatKind::Wild;
2506 }
2507 seen_inputs.insert(ident);
2508 }
2509 }
2510 }
2511
2512 pub(super) fn handle_ambiguous_unbraced_const_arg(
2516 &mut self,
2517 args: &mut ThinVec<AngleBracketedArg>,
2518 ) -> PResult<'a, bool> {
2519 let arg = args.pop().unwrap();
2523 let mut err = self.dcx().struct_span_err(
2529 self.token.span,
2530 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected one of `,` or `>`, found {0}",
super::token_descr(&self.token)))
})format!("expected one of `,` or `>`, found {}", super::token_descr(&self.token)),
2531 );
2532 err.span_label(self.token.span, "expected one of `,` or `>`");
2533 match self.recover_const_arg(arg.span(), err) {
2534 Ok(arg) => {
2535 args.push(AngleBracketedArg::Arg(arg));
2536 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
2537 return Ok(true); }
2539 }
2540 Err(err) => {
2541 args.push(arg);
2542 err.delay_as_bug();
2544 }
2545 }
2546 Ok(false) }
2548
2549 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2550 let snapshot = self.create_snapshot_for_diagnostic();
2551 let param = match self.parse_const_param(AttrVec::new()) {
2552 Ok(param) => param,
2553 Err(err) => {
2554 err.cancel();
2555 self.restore_snapshot(snapshot);
2556 return None;
2557 }
2558 };
2559
2560 let ident = param.ident.to_string();
2561 let sugg = match (ty_generics, self.psess.source_map().span_to_snippet(param.span())) {
2562 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2563 Some(match ¶ms[..] {
2564 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2565 impl_generics: *impl_generics,
2566 incorrect_decl: param.span(),
2567 snippet,
2568 ident,
2569 },
2570 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2571 impl_generics_end: generic.span().shrink_to_hi(),
2572 incorrect_decl: param.span(),
2573 snippet,
2574 ident,
2575 },
2576 })
2577 }
2578 _ => None,
2579 };
2580 let guar =
2581 self.dcx().emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2582
2583 let value = self.mk_expr_err(param.span(), guar);
2584 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2585 }
2586
2587 pub(super) fn recover_const_param_declaration(
2588 &mut self,
2589 ty_generics: Option<&Generics>,
2590 ) -> PResult<'a, Option<GenericArg>> {
2591 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2593 return Ok(Some(arg));
2594 }
2595
2596 let start = self.token.span;
2598 self.bump(); let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2602 if self.check_const_arg() {
2603 err.to_remove = Some(start.until(self.token.span));
2604 self.dcx().emit_err(err);
2605 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2606 } else {
2607 let after_kw_const = self.token.span;
2608 self.recover_const_arg(after_kw_const, self.dcx().create_err(err)).map(Some)
2609 }
2610 }
2611
2612 pub(super) fn recover_const_arg(
2618 &mut self,
2619 start: Span,
2620 mut err: Diag<'a>,
2621 ) -> PResult<'a, GenericArg> {
2622 let is_op_or_dot = AssocOp::from_token(&self.token)
2623 .and_then(|op| {
2624 if let AssocOp::Binary(
2625 BinOpKind::Gt
2626 | BinOpKind::Lt
2627 | BinOpKind::Shr
2628 | BinOpKind::Ge
2629 )
2630 | AssocOp::Assign
2633 | AssocOp::AssignOp(_) = op
2634 {
2635 None
2636 } else {
2637 Some(op)
2638 }
2639 })
2640 .is_some()
2641 || self.token == TokenKind::Dot;
2642 let was_op = #[allow(non_exhaustive_omitted_patterns)] match self.prev_token.kind {
token::Plus | token::Shr | token::Gt => true,
_ => false,
}matches!(self.prev_token.kind, token::Plus | token::Shr | token::Gt);
2645 if !is_op_or_dot && !was_op {
2646 return Err(err);
2648 }
2649 let snapshot = self.create_snapshot_for_diagnostic();
2650 if is_op_or_dot {
2651 self.bump();
2652 }
2653 match (|| self.parse_expr_res(Restrictions::CONST_EXPR))() {
2654 Ok(expr) => {
2655 if snapshot.token == token::EqEq {
2657 err.span_suggestion_verbose(
2658 snapshot.token.span,
2659 "if you meant to use an associated type binding, replace `==` with `=`",
2660 "=",
2661 Applicability::MaybeIncorrect,
2662 );
2663 let guar = err.emit();
2664 let value = self.mk_expr_err(start.to(expr.span), guar);
2665 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2666 } else if snapshot.token == token::Colon
2667 && expr.span.lo() == snapshot.token.span.hi()
2668 && #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Path(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Path(..))
2669 {
2670 err.span_suggestion_verbose(
2672 snapshot.token.span,
2673 "write a path separator here",
2674 "::",
2675 Applicability::MaybeIncorrect,
2676 );
2677 let guar = err.emit();
2678 return Ok(GenericArg::Type(
2679 self.mk_ty(start.to(expr.span), TyKind::Err(guar)),
2680 ));
2681 } else if self.token == token::Comma || self.token.kind.should_end_const_arg() {
2682 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2689 }
2690 }
2691 Err(err) => {
2692 err.cancel();
2693 }
2694 }
2695 self.restore_snapshot(snapshot);
2696 Err(err)
2697 }
2698
2699 pub(crate) fn recover_unbraced_const_arg_that_can_begin_ty(
2703 &mut self,
2704 mut snapshot: SnapshotParser<'a>,
2705 ) -> Option<Box<ast::Expr>> {
2706 match (|| snapshot.parse_expr_res(Restrictions::CONST_EXPR))() {
2707 Ok(expr) if let token::Comma | token::Gt = snapshot.token.kind => {
2710 self.restore_snapshot(snapshot);
2711 Some(expr)
2712 }
2713 Ok(_) => None,
2714 Err(err) => {
2715 err.cancel();
2716 None
2717 }
2718 }
2719 }
2720
2721 pub(super) fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
2723 err.multipart_suggestion(
2724 "expressions must be enclosed in braces to be used as const generic \
2725 arguments",
2726 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "{ ".to_string()),
(span.shrink_to_hi(), " }".to_string())]))vec![(span.shrink_to_lo(), "{ ".to_string()), (span.shrink_to_hi(), " }".to_string())],
2727 Applicability::MaybeIncorrect,
2728 );
2729 let guar = err.emit();
2730 let value = self.mk_expr_err(span, guar);
2731 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2732 }
2733
2734 #[cold]
2737 pub(crate) fn recover_colon_colon_in_pat_typo(
2738 &mut self,
2739 mut first_pat: Pat,
2740 expected: Option<Expected>,
2741 ) -> Pat {
2742 if token::Colon != self.token.kind {
2743 return first_pat;
2744 }
2745
2746 let colon_span = self.token.span;
2749 let mut snapshot_pat = self.create_snapshot_for_diagnostic();
2752 let mut snapshot_type = self.create_snapshot_for_diagnostic();
2753
2754 match self.expected_one_of_not_found(&[], &[]) {
2756 Err(mut err) => {
2757 snapshot_pat.bump();
2759 snapshot_type.bump();
2760 match snapshot_pat.parse_pat_no_top_alt(expected, None) {
2761 Err(inner_err) => {
2762 inner_err.cancel();
2763 }
2764 Ok(mut pat) => {
2765 let new_span = first_pat.span.to(pat.span);
2767 let mut show_sugg = false;
2768 match &mut pat.kind {
2770 PatKind::Struct(qself @ None, path, ..)
2771 | PatKind::TupleStruct(qself @ None, path, _)
2772 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2773 PatKind::Ident(_, ident, _) => {
2774 path.segments.insert(0, PathSegment::from_ident(*ident));
2775 path.span = new_span;
2776 show_sugg = true;
2777 first_pat = pat;
2778 }
2779 PatKind::Path(old_qself, old_path) => {
2780 path.segments = old_path
2781 .segments
2782 .iter()
2783 .cloned()
2784 .chain(take(&mut path.segments))
2785 .collect();
2786 path.span = new_span;
2787 *qself = old_qself.clone();
2788 first_pat = pat;
2789 show_sugg = true;
2790 }
2791 _ => {}
2792 },
2793 PatKind::Ident(BindingMode::NONE, ident, None) => {
2794 match &first_pat.kind {
2795 PatKind::Ident(_, old_ident, _) => {
2796 let path = PatKind::Path(
2797 None,
2798 Path {
2799 span: new_span,
2800 segments: {
let len = [(), ()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(PathSegment::from_ident(*old_ident));
vec.push(PathSegment::from_ident(*ident));
vec
}thin_vec![
2801 PathSegment::from_ident(*old_ident),
2802 PathSegment::from_ident(*ident),
2803 ],
2804 },
2805 );
2806 first_pat = self.mk_pat(new_span, path);
2807 show_sugg = true;
2808 }
2809 PatKind::Path(old_qself, old_path) => {
2810 let mut segments = old_path.segments.clone();
2811 segments.push(PathSegment::from_ident(*ident));
2812 let path = PatKind::Path(
2813 old_qself.clone(),
2814 Path { span: new_span, segments },
2815 );
2816 first_pat = self.mk_pat(new_span, path);
2817 show_sugg = true;
2818 }
2819 _ => {}
2820 }
2821 }
2822 _ => {}
2823 }
2824 if show_sugg {
2825 err.span_suggestion_verbose(
2826 colon_span.until(self.look_ahead(1, |t| t.span)),
2827 "maybe write a path separator here",
2828 "::",
2829 Applicability::MaybeIncorrect,
2830 );
2831 } else {
2832 first_pat = self.mk_pat(
2833 new_span,
2834 PatKind::Err(
2835 self.dcx()
2836 .span_delayed_bug(colon_span, "recovered bad path pattern"),
2837 ),
2838 );
2839 }
2840 self.restore_snapshot(snapshot_pat);
2841 }
2842 }
2843 match snapshot_type.parse_ty() {
2844 Err(inner_err) => {
2845 inner_err.cancel();
2846 }
2847 Ok(ty) => {
2848 err.span_label(ty.span, "specifying the type of a pattern isn't supported");
2849 self.restore_snapshot(snapshot_type);
2850 let new_span = first_pat.span.to(ty.span);
2851 first_pat =
2852 self.mk_pat(
2853 new_span,
2854 PatKind::Err(self.dcx().span_delayed_bug(
2855 colon_span,
2856 "recovered bad pattern with type",
2857 )),
2858 );
2859 }
2860 }
2861 err.emit();
2862 }
2863 _ => {
2864 }
2866 };
2867 first_pat
2868 }
2869
2870 pub(crate) fn maybe_recover_unexpected_block_label(
2873 &mut self,
2874 loop_header: Option<Span>,
2875 ) -> bool {
2876 if !(self.check_lifetime()
2878 && self.look_ahead(1, |t| *t == token::Colon)
2879 && self.look_ahead(2, |t| *t == token::OpenBrace))
2880 {
2881 return false;
2882 }
2883 let label = self.eat_label().expect("just checked if a label exists");
2884 self.bump(); let span = label.ident.span.to(self.prev_token.span);
2886 let mut diag = self
2887 .dcx()
2888 .struct_span_err(span, "block label not supported here")
2889 .with_span_label(span, "not supported here");
2890 if let Some(loop_header) = loop_header {
2891 diag.multipart_suggestion(
2892 "if you meant to label the loop, move this label before the loop",
2893 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(label.ident.span.until(self.token.span), String::from("")),
(loop_header.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", label.ident))
}))]))vec![
2894 (label.ident.span.until(self.token.span), String::from("")),
2895 (loop_header.shrink_to_lo(), format!("{}: ", label.ident)),
2896 ],
2897 Applicability::MachineApplicable,
2898 );
2899 } else {
2900 diag.tool_only_span_suggestion(
2901 label.ident.span.until(self.token.span),
2902 "remove this block label",
2903 "",
2904 Applicability::MachineApplicable,
2905 );
2906 }
2907 diag.emit();
2908 true
2909 }
2910
2911 pub(crate) fn maybe_recover_unexpected_comma(
2914 &mut self,
2915 lo: Span,
2916 rt: CommaRecoveryMode,
2917 ) -> PResult<'a, ()> {
2918 if self.token != token::Comma {
2919 return Ok(());
2920 }
2921 self.recover_unexpected_comma(lo, rt)
2922 }
2923
2924 #[cold]
2925 fn recover_unexpected_comma(&mut self, lo: Span, rt: CommaRecoveryMode) -> PResult<'a, ()> {
2926 let comma_span = self.token.span;
2931 self.bump();
2932 if let Err(err) = self.skip_pat_list() {
2933 err.cancel();
2936 }
2937 let seq_span = lo.to(self.prev_token.span);
2938 let mut err = self.dcx().struct_span_err(comma_span, "unexpected `,` in pattern");
2939 err.multipart_suggestion(
2940 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try adding parentheses to match on a tuple{0}",
if let CommaRecoveryMode::LikelyTuple = rt {
""
} else { "..." }))
})format!(
2941 "try adding parentheses to match on a tuple{}",
2942 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2943 ),
2944 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(seq_span.shrink_to_lo(), "(".to_string()),
(seq_span.shrink_to_hi(), ")".to_string())]))vec![
2945 (seq_span.shrink_to_lo(), "(".to_string()),
2946 (seq_span.shrink_to_hi(), ")".to_string()),
2947 ],
2948 Applicability::MachineApplicable,
2949 );
2950 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2951 err.span_suggestion_verbose(
2952 comma_span,
2953 "...or a vertical bar to match on alternatives",
2954 " |",
2955 Applicability::MachineApplicable,
2956 );
2957 }
2958 Err(err)
2959 }
2960
2961 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2962 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2963 let qself_position = qself.as_ref().map(|qself| qself.position);
2964 for (i, segments) in path.segments.windows(2).enumerate() {
2965 if qself_position.is_some_and(|pos| i < pos) {
2966 continue;
2967 }
2968 if let [a, b] = segments {
2969 let (a_span, b_span) = (a.span(), b.span());
2970 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2971 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2972 return Err(self.dcx().create_err(DoubleColonInBound {
2973 span: path.span.shrink_to_hi(),
2974 between: between_span,
2975 }));
2976 }
2977 }
2978 }
2979 Ok(())
2980 }
2981
2982 pub(crate) fn maybe_err_dotdotlt_syntax(&self, maybe_lt: Token, mut err: Diag<'a>) -> Diag<'a> {
2984 if maybe_lt == token::Lt
2985 && (self.expected_token_types.contains(TokenType::Gt)
2986 || #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
token::Literal(..) => true,
_ => false,
}matches!(self.token.kind, token::Literal(..)))
2987 {
2988 err.span_suggestion_verbose(
2989 maybe_lt.span,
2990 "remove the `<` to write an exclusive range",
2991 "",
2992 Applicability::MachineApplicable,
2993 );
2994 }
2995 err
2996 }
2997
2998 pub(super) fn is_vcs_conflict_marker(
3006 &mut self,
3007 long_kind: &TokenKind,
3008 short_kind: &TokenKind,
3009 ) -> bool {
3010 if long_kind == short_kind {
3011 (0..7).all(|i| self.look_ahead(i, |tok| tok == long_kind))
3013 } else {
3014 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
3016 && self.look_ahead(3, |tok| tok == short_kind || tok == long_kind)
3017 }
3018 }
3019
3020 fn conflict_marker(
3021 &mut self,
3022 long_kind: &TokenKind,
3023 short_kind: &TokenKind,
3024 expected: Option<usize>,
3025 ) -> Option<(Span, usize)> {
3026 if self.is_vcs_conflict_marker(long_kind, short_kind) {
3027 let lo = self.token.span;
3028 if self.psess.source_map().span_to_margin(lo) != Some(0) {
3029 return None;
3030 }
3031 let mut len = 0;
3032 while self.token.kind == *long_kind || self.token.kind == *short_kind {
3033 if self.token.kind.break_two_token_op(1).is_some() {
3034 len += 2;
3035 } else {
3036 len += 1;
3037 }
3038 self.bump();
3039 if expected == Some(len) {
3040 break;
3041 }
3042 }
3043 if expected.is_some() && expected != Some(len) {
3044 return None;
3045 }
3046 return Some((lo.to(self.prev_token.span), len));
3047 }
3048 None
3049 }
3050
3051 pub(super) fn recover_vcs_conflict_marker(&mut self) {
3052 let Some((start, len)) = self.conflict_marker(&TokenKind::Shl, &TokenKind::Lt, None) else {
3054 return;
3055 };
3056 let mut spans = Vec::with_capacity(2);
3057 spans.push(start);
3058 let mut middlediff3 = None;
3060 let mut middle = None;
3062 let mut end = None;
3064 loop {
3065 if self.token == TokenKind::Eof {
3066 break;
3067 }
3068 if let Some((span, _)) =
3069 self.conflict_marker(&TokenKind::OrOr, &TokenKind::Or, Some(len))
3070 {
3071 middlediff3 = Some(span);
3072 }
3073 if let Some((span, _)) =
3074 self.conflict_marker(&TokenKind::EqEq, &TokenKind::Eq, Some(len))
3075 {
3076 middle = Some(span);
3077 }
3078 if let Some((span, _)) =
3079 self.conflict_marker(&TokenKind::Shr, &TokenKind::Gt, Some(len))
3080 {
3081 spans.push(span);
3082 end = Some(span);
3083 break;
3084 }
3085 self.bump();
3086 }
3087
3088 let mut err = self.dcx().struct_span_fatal(spans, "encountered diff marker");
3089 let middle_marker = match middlediff3 {
3090 Some(middlediff3) => {
3092 err.span_label(
3093 middlediff3,
3094 "between this marker and `=======` is the base code (what the two refs \
3095 diverged from)",
3096 );
3097 "|||||||"
3098 }
3099 None => "=======",
3100 };
3101 err.span_label(
3102 start,
3103 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("between this marker and `{0}` is the code that you are merging into",
middle_marker))
})format!(
3104 "between this marker and `{middle_marker}` is the code that you are merging into",
3105 ),
3106 );
3107
3108 if let Some(middle) = middle {
3109 err.span_label(middle, "between this marker and `>>>>>>>` is the incoming code");
3110 }
3111 if let Some(end) = end {
3112 err.span_label(end, "this marker concludes the conflict region");
3113 }
3114 err.note(
3115 "conflict markers indicate that a merge was started but could not be completed due \
3116 to merge conflicts\n\
3117 to resolve a conflict, keep only the code you want and then delete the lines \
3118 containing conflict markers",
3119 );
3120 err.help(
3121 "if you are in a merge, the top section is the code you already had checked out and \
3122 the bottom section is the new code\n\
3123 if you are in a rebase, the top section is the code being rebased onto and the bottom \
3124 section is the code you had checked out which is being rebased",
3125 );
3126
3127 err.note(
3128 "for an explanation on these markers from the `git` documentation, visit \
3129 <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
3130 );
3131
3132 err.emit();
3133 }
3134
3135 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
3138 while !self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)) {
3139 self.parse_pat_no_top_alt(None, None)?;
3140 if !self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
3141 return Ok(());
3142 }
3143 }
3144 Ok(())
3145 }
3146 pub(super) fn maybe_type_in_generic_parameter(&mut self, origin_error: Diag<'a>) -> Diag<'a> {
3147 if !self.may_recover() {
3148 return origin_error;
3149 }
3150 self.with_recovery(super::Recovery::Forbidden, |snapshot| {
3151 snapshot.bump();
3152 let lo = snapshot.token.span.shrink_to_lo();
3153
3154 let ty = match snapshot.parse_ty() {
3155 Ok(t) => t,
3156 Err(err) => {
3157 err.cancel();
3158 return origin_error;
3159 }
3160 };
3161 let TyKind::Path(_, path) = ty.kind else {
3162 return origin_error;
3163 };
3164 let Some(GenericArgs::AngleBracketed(AngleBracketedArgs { span: _, ref args })) =
3165 path.segments[0].args
3166 else {
3167 return origin_error;
3168 };
3169
3170 let path_span = path.span;
3171 let mut new_error = snapshot.dcx().create_err(FoundPathInGenerics {
3172 span: path_span,
3173 path: snapshot.span_to_snippet(path_span).unwrap(),
3174 });
3175 new_error.subdiagnostic(SuggestBindTypeParameter { span: lo });
3176 origin_error.cancel();
3177
3178 let params = args
3179 .iter()
3180 .map(|arg| snapshot.span_to_snippet(arg.span()).unwrap())
3181 .collect::<Vec<_>>()
3182 .join(", ");
3183 new_error.subdiagnostic(SuggestIntroduceTypeParameter {
3184 span: path_span,
3185 parameters: params,
3186 });
3187 new_error
3188 })
3189 }
3190}