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, AwaitSuggestion,
30 BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi, ComparisonOperatorsCannotBeChained,
31 ComparisonOperatorsCannotBeChainedSugg, DocCommentDoesNotDocumentAnything, DoubleColonInBound,
32 ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg, ExprParenthesesNeeded, FoundPathInGenerics,
33 GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg,
34 HelpIdentifierStartsWithNumber, HelpUseLatestEdition, InInTypo, IncorrectAwait,
35 IncorrectSemicolon, IncorrectUseOfAwait, IncorrectUseOfUse, MisspelledKw,
36 PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
37 StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, SuggAddMissingLetStmt,
38 SuggEscapeIdentifier, SuggRemoveComma, SuggestBindTypeParameter, SuggestIntroduceTypeParameter,
39 TernaryOperator, TernaryOperatorSuggestion, UnexpectedConstInGenericParam,
40 UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets,
41 UseEqInstead, WrapType,
42};
43use crate::exp;
44use crate::parser::attr::InnerAttrPolicy;
45use crate::parser::{FnContext, IsDotDotDot};
46
47pub(super) fn dummy_arg(ident: Ident, guar: ErrorGuaranteed) -> Param {
49 let pat = Box::new(Pat {
50 id: ast::DUMMY_NODE_ID,
51 kind: PatKind::Ident(BindingMode::NONE, ident, None),
52 span: ident.span,
53 });
54 let ty = Ty { kind: TyKind::Err(guar), span: ident.span, id: ast::DUMMY_NODE_ID };
55 Param {
56 attrs: AttrVec::default(),
57 id: ast::DUMMY_NODE_ID,
58 pat,
59 span: ident.span,
60 ty: Box::new(ty),
61 is_placeholder: false,
62 }
63}
64
65pub(super) trait RecoverQPath: Sized + 'static {
66 const PATH_STYLE: PathStyle = PathStyle::Expr;
67 fn to_ty(&self) -> Option<Box<Ty>>;
68 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self;
69}
70
71impl<T: RecoverQPath> RecoverQPath for Box<T> {
72 const PATH_STYLE: PathStyle = T::PATH_STYLE;
73 fn to_ty(&self) -> Option<Box<Ty>> {
74 T::to_ty(self)
75 }
76 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
77 Box::new(T::recovered(qself, path))
78 }
79}
80
81impl RecoverQPath for Ty {
82 const PATH_STYLE: PathStyle = PathStyle::Type;
83 fn to_ty(&self) -> Option<Box<Ty>> {
84 Some(Box::new(self.clone()))
85 }
86 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
87 Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
88 }
89}
90
91impl RecoverQPath for Pat {
92 const PATH_STYLE: PathStyle = PathStyle::Pat;
93 fn to_ty(&self) -> Option<Box<Ty>> {
94 self.to_ty()
95 }
96 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
97 Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
98 }
99}
100
101impl RecoverQPath for Expr {
102 fn to_ty(&self) -> Option<Box<Ty>> {
103 self.to_ty()
104 }
105 fn recovered(qself: Option<Box<QSelf>>, path: ast::Path) -> Self {
106 Self {
107 span: path.span,
108 kind: ExprKind::Path(qself, path),
109 attrs: AttrVec::new(),
110 id: ast::DUMMY_NODE_ID,
111 tokens: None,
112 }
113 }
114}
115
116pub(crate) enum ConsumeClosingDelim {
118 Yes,
119 No,
120}
121
122#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AttemptLocalParseRecovery { }
#[automatically_derived]
impl ::core::clone::Clone for AttemptLocalParseRecovery {
#[inline]
fn clone(&self) -> AttemptLocalParseRecovery { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AttemptLocalParseRecovery { }Copy)]
123pub enum AttemptLocalParseRecovery {
124 Yes,
125 No,
126}
127
128impl AttemptLocalParseRecovery {
129 pub(super) fn yes(&self) -> bool {
130 match self {
131 AttemptLocalParseRecovery::Yes => true,
132 AttemptLocalParseRecovery::No => false,
133 }
134 }
135
136 pub(super) fn no(&self) -> bool {
137 match self {
138 AttemptLocalParseRecovery::Yes => false,
139 AttemptLocalParseRecovery::No => true,
140 }
141 }
142}
143
144#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IncDecRecovery { }
#[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)]
147struct IncDecRecovery {
148 standalone: IsStandalone,
150 op: IncOrDec,
152 fixity: UnaryFixity,
154}
155
156#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IsStandalone { }
#[automatically_derived]
impl ::core::clone::Clone for IsStandalone {
#[inline]
fn clone(&self) -> IsStandalone { *self }
}Clone)]
158enum IsStandalone {
159 Standalone,
161 Subexpr,
163}
164
165#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IncOrDec { }
#[automatically_derived]
impl ::core::clone::Clone for IncOrDec {
#[inline]
fn clone(&self) -> IncOrDec { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for IncOrDec { }
#[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 { }Eq)]
166enum IncOrDec {
167 Inc,
168 Dec,
169}
170
171#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnaryFixity { }
#[automatically_derived]
impl ::core::clone::Clone for UnaryFixity {
#[inline]
fn clone(&self) -> UnaryFixity { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for UnaryFixity { }
#[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 { }Eq)]
172enum UnaryFixity {
173 Pre,
174 Post,
175}
176
177impl IncOrDec {
178 fn chr(&self) -> char {
179 match self {
180 Self::Inc => '+',
181 Self::Dec => '-',
182 }
183 }
184
185 fn name(&self) -> &'static str {
186 match self {
187 Self::Inc => "increment",
188 Self::Dec => "decrement",
189 }
190 }
191}
192
193impl std::fmt::Display for UnaryFixity {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 match self {
196 Self::Pre => f.write_fmt(format_args!("prefix"))write!(f, "prefix"),
197 Self::Post => f.write_fmt(format_args!("postfix"))write!(f, "postfix"),
198 }
199 }
200}
201
202fn find_similar_kw(lookup: Ident, candidates: &[Symbol]) -> Option<MisspelledKw> {
207 lookup.name.find_similar(candidates).map(|(similar_kw, is_incorrect_case)| MisspelledKw {
208 similar_kw: similar_kw.to_string(),
209 is_incorrect_case,
210 span: lookup.span,
211 })
212}
213
214struct MultiSugg {
215 msg: String,
216 patches: Vec<(Span, String)>,
217 applicability: Applicability,
218}
219
220impl MultiSugg {
221 fn emit(self, err: &mut Diag<'_>) {
222 err.multipart_suggestion(self.msg, self.patches, self.applicability);
223 }
224
225 fn emit_verbose(self, err: &mut Diag<'_>) {
226 err.multipart_suggestion(self.msg, self.patches, self.applicability);
227 }
228}
229
230pub struct SnapshotParser<'a> {
234 parser: Parser<'a>,
235}
236
237impl<'a> Deref for SnapshotParser<'a> {
238 type Target = Parser<'a>;
239
240 fn deref(&self) -> &Self::Target {
241 &self.parser
242 }
243}
244
245impl<'a> DerefMut for SnapshotParser<'a> {
246 fn deref_mut(&mut self) -> &mut Self::Target {
247 &mut self.parser
248 }
249}
250
251impl<'a> Parser<'a> {
252 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
253 self.psess.dcx()
254 }
255
256 pub fn restore_snapshot(&mut self, snapshot: SnapshotParser<'a>) {
258 *self = snapshot.parser;
259 }
260
261 pub fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> {
263 let snapshot = self.clone();
264 SnapshotParser { parser: snapshot }
265 }
266
267 pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
268 self.psess.source_map().span_to_snippet(span)
269 }
270
271 pub(super) fn expected_ident_found(
275 &mut self,
276 recover: bool,
277 ) -> PResult<'a, (Ident, IdentIsRaw)> {
278 let valid_follow = &[
279 TokenKind::Eq,
280 TokenKind::Colon,
281 TokenKind::Comma,
282 TokenKind::Semi,
283 TokenKind::PathSep,
284 TokenKind::OpenBrace,
285 TokenKind::OpenParen,
286 TokenKind::CloseBrace,
287 TokenKind::CloseParen,
288 ];
289 if let TokenKind::DocComment(..) = self.prev_token.kind
290 && valid_follow.contains(&self.token.kind)
291 {
292 let err = self.dcx().create_err(DocCommentDoesNotDocumentAnything {
293 span: self.prev_token.span,
294 missing_comma: None,
295 });
296 return Err(err);
297 }
298
299 let mut recovered_ident = None;
300 let bad_token = self.token;
303
304 let suggest_raw = if let Some((ident, IdentIsRaw::No)) = self.token.ident()
306 && ident.is_raw_guess()
307 && self.look_ahead(1, |t| valid_follow.contains(&t.kind))
308 {
309 recovered_ident = Some((ident, IdentIsRaw::Yes));
310
311 let ident_name = ident.name.to_string();
314
315 Some(SuggEscapeIdentifier { span: ident.span.shrink_to_lo(), ident_name })
316 } else {
317 None
318 };
319
320 let suggest_remove_comma =
321 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
322 if recover {
323 self.bump();
324 recovered_ident = self.ident_or_err(false).ok();
325 };
326
327 Some(SuggRemoveComma { span: bad_token.span })
328 } else {
329 None
330 };
331
332 let help_cannot_start_number = self.is_lit_bad_ident().map(|(len, valid_portion)| {
333 let (invalid, valid) = self.token.span.split_at(len as u32);
334
335 recovered_ident = Some((Ident::new(valid_portion, valid), IdentIsRaw::No));
336
337 HelpIdentifierStartsWithNumber { num_span: invalid }
338 });
339
340 let mut err = self.dcx().create_err(ExpectedIdentifier {
341 span: bad_token.span,
342 token: bad_token,
343 suggest_raw,
344 suggest_remove_comma,
345 help_cannot_start_number,
346 });
347
348 if self.token == token::Lt {
352 if let Some((Ident { name, .. }, IdentIsRaw::No)) = self.prev_token.ident()
355 && let kw::Fn | kw::Type | kw::Struct | kw::Enum | kw::Union | kw::Trait = name
356 {
357 match self.parse_generics() {
358 Ok(generics) => {
359 if !self.look_ahead(1, |t| *t == token::Lt)
360 && let Ok(snippet) =
361 self.psess.source_map().span_to_snippet(generics.span)
362 {
363 err.multipart_suggestion(
364 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("place the generic parameter name after the {0} name",
name))
})format!("place the generic parameter name after the {name} name"),
365 ::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),
(generics.span, String::new())]))vec![
366 (self.token.span.shrink_to_hi(), snippet),
367 (generics.span, String::new()),
368 ],
369 Applicability::MaybeIncorrect,
370 );
371 } else {
372 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("place the generic parameter name after the {0} name",
name))
})format!(
373 "place the generic parameter name after the {name} name"
374 ));
375 }
376 }
377 Err(err) => err.cancel(),
380 }
381 }
382 }
383
384 if let Some(recovered_ident) = recovered_ident
385 && recover
386 {
387 err.emit();
388 Ok(recovered_ident)
389 } else {
390 Err(err)
391 }
392 }
393
394 pub(super) fn expected_ident_found_err(&mut self) -> Diag<'a> {
395 self.expected_ident_found(false).unwrap_err()
396 }
397
398 pub(super) fn is_lit_bad_ident(&mut self) -> Option<(usize, Symbol)> {
404 if let token::Literal(Lit {
408 kind: token::LitKind::Integer | token::LitKind::Float,
409 symbol,
410 suffix: Some(suffix), }) = self.token.kind
412 && rustc_ast::MetaItemLit::from_token(&self.token).is_none()
413 {
414 Some((symbol.as_str().len(), suffix))
415 } else {
416 None
417 }
418 }
419
420 pub(super) fn expected_one_of_not_found(
421 &mut self,
422 edible: &[ExpTokenPair],
423 inedible: &[ExpTokenPair],
424 ) -> PResult<'a, ErrorGuaranteed> {
425 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:425",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(425u32),
::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);
426 fn tokens_to_string(tokens: &[TokenType]) -> String {
427 let mut i = tokens.iter();
428 let b = i.next().map_or_else(String::new, |t| t.to_string());
430 i.enumerate().fold(b, |mut b, (i, a)| {
431 if tokens.len() > 2 && i == tokens.len() - 2 {
432 b.push_str(", or ");
433 } else if tokens.len() == 2 && i == tokens.len() - 2 {
434 b.push_str(" or ");
435 } else {
436 b.push_str(", ");
437 }
438 b.push_str(&a.to_string());
439 b
440 })
441 }
442
443 for exp in edible.iter().chain(inedible.iter()) {
444 self.expected_token_types.insert(exp.token_type);
445 }
446 let mut expected: Vec<_> = self.expected_token_types.iter().collect();
447 expected.sort_by_cached_key(|x| x.to_string());
448 expected.dedup();
449
450 let sm = self.psess.source_map();
451
452 if expected.contains(&TokenType::Semi) {
454 if self.prev_token == token::Question
457 && let Err(e) = self.maybe_recover_from_ternary_operator(None)
458 {
459 return Err(e);
460 }
461
462 if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
463 } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
465 } else if [token::Comma, token::Colon].contains(&self.token.kind)
467 && self.prev_token == token::CloseParen
468 {
469 } else if self.look_ahead(1, |t| {
478 t == &token::CloseBrace || t.can_begin_expr() && *t != token::Colon
479 }) && [token::Comma, token::Colon].contains(&self.token.kind)
480 {
481 let guar = self.dcx().emit_err(ExpectedSemi {
488 span: self.token.span,
489 token: self.token,
490 unexpected_token_label: None,
491 sugg: ExpectedSemiSugg::ChangeToSemi(self.token.span),
492 });
493 self.bump();
494 return Ok(guar);
495 } else if self.look_ahead(0, |t| {
496 t == &token::CloseBrace
497 || ((t.can_begin_expr() || t.can_begin_item())
498 && t != &token::Semi
499 && t != &token::Pound)
500 || (sm.is_multiline(
502 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
503 ) && t == &token::Pound)
504 }) && !expected.contains(&TokenType::Comma)
505 {
506 let span = self.prev_token.span.shrink_to_hi();
512 let guar = self.dcx().emit_err(ExpectedSemi {
513 span,
514 token: self.token,
515 unexpected_token_label: Some(self.token.span),
516 sugg: ExpectedSemiSugg::AddSemi(span),
517 });
518 return Ok(guar);
519 }
520 }
521
522 if self.token == TokenKind::EqEq
523 && self.prev_token.is_ident()
524 && expected.contains(&TokenType::Eq)
525 {
526 return Err(self.dcx().create_err(UseEqInstead { span: self.token.span }));
528 }
529
530 if (self.token.is_keyword(kw::Move) || self.token.is_keyword(kw::Use))
531 && self.prev_token.is_keyword(kw::Async)
532 {
533 let span = self.prev_token.span.to(self.token.span);
535 if self.token.is_keyword(kw::Move) {
536 return Err(self.dcx().create_err(AsyncMoveBlockIn2015 { span }));
537 } else {
538 return Err(self.dcx().create_err(AsyncUseBlockIn2015 { span }));
540 }
541 }
542
543 let expect = tokens_to_string(&expected);
544 let actual = super::token_descr(&self.token);
545 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
546 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}");
547 let short_expect = if expected.len() > 6 {
548 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} possible tokens",
expected.len()))
})format!("{} possible tokens", expected.len())
549 } else {
550 expect
551 };
552 (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}")))
553 } else if expected.is_empty() {
554 (
555 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unexpected token: {0}", actual))
})format!("unexpected token: {actual}"),
556 (self.prev_token.span, "unexpected token after this".to_string()),
557 )
558 } else {
559 (
560 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}", expect,
actual))
})format!("expected {expect}, found {actual}"),
561 (self.prev_token.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}", expect))
})format!("expected {expect}")),
562 )
563 };
564 self.last_unexpected_token_span = Some(self.token.span);
565 let mut err = self.dcx().struct_span_err(self.token.span, msg_exp);
567
568 self.label_expected_raw_ref(&mut err);
569
570 if self.token == token::FatArrow
572 && expected.iter().any(|tok| #[allow(non_exhaustive_omitted_patterns)] match tok {
TokenType::Operator | TokenType::Le => true,
_ => false,
}matches!(tok, TokenType::Operator | TokenType::Le))
573 && !expected
574 .iter()
575 .any(|tok| #[allow(non_exhaustive_omitted_patterns)] match tok {
TokenType::FatArrow | TokenType::CloseBrace => true,
_ => false,
}matches!(tok, TokenType::FatArrow | TokenType::CloseBrace))
576 {
577 err.span_suggestion_verbose(
578 self.token.span,
579 "you might have meant to write a \"greater than or equal to\" comparison",
580 ">=",
581 Applicability::MaybeIncorrect,
582 );
583 }
584
585 if let Some((ident, IdentIsRaw::No)) = self.prev_token.ident()
586 && let "def" | "fun" | "func" | "function" = ident.name.as_str()
587 {
588 err.span_suggestion_short(
589 self.prev_token.span,
590 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("write `fn` instead of `{0}` to declare a function",
ident.name))
})format!("write `fn` instead of `{}` to declare a function", ident.name),
591 "fn",
592 Applicability::MachineApplicable,
593 );
594 }
595
596 if let TokenKind::Ident(prev, _) = &self.prev_token.kind
597 && let TokenKind::Ident(cur, _) = &self.token.kind
598 {
599 let concat = Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prev, cur))
})format!("{prev}{cur}"));
600 let ident = Ident::new(concat, DUMMY_SP);
601 if ident.is_used_keyword() || ident.is_reserved() || ident.is_raw_guess() {
602 let concat_span = self.prev_token.span.to(self.token.span);
603 err.span_suggestion_verbose(
604 concat_span,
605 ::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}`"),
606 concat,
607 Applicability::MachineApplicable,
608 );
609 }
610 }
611
612 if ((self.prev_token == TokenKind::Ident(sym::character('c'), IdentIsRaw::No)
620 && #[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, .. })))
621 || (self.prev_token == TokenKind::Ident(sym::cr, IdentIsRaw::No)
622 && #[allow(non_exhaustive_omitted_patterns)] match &self.token.kind {
TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound =>
true,
_ => false,
}matches!(
623 &self.token.kind,
624 TokenKind::Literal(token::Lit { kind: token::Str, .. }) | token::Pound
625 )))
626 && self.prev_token.span.hi() == self.token.span.lo()
627 && !self.token.span.at_least_rust_2021()
628 {
629 err.note("you may be trying to write a c-string literal");
630 err.note("c-string literals require Rust 2021 or later");
631 err.subdiagnostic(HelpUseLatestEdition::new());
632 }
633
634 if self.prev_token.is_ident_named(sym::public)
636 && (self.token.can_begin_item() || self.token == TokenKind::OpenParen)
637 {
638 err.span_suggestion_short(
639 self.prev_token.span,
640 "write `pub` instead of `public` to make the item public",
641 "pub",
642 Applicability::MachineApplicable,
643 );
644 }
645
646 if let token::DocComment(kind, style, _) = self.token.kind {
647 if !expected.contains(&TokenType::Comma) {
657 let pos = self.token.span.lo() + BytePos(2);
659 let span = self.token.span.with_lo(pos).with_hi(pos);
660 err.span_suggestion_verbose(
661 span,
662 ::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!(
663 "add a space before {} to write a regular comment",
664 match (kind, style) {
665 (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`",
666 (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`",
667 (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`",
668 (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`",
669 },
670 ),
671 " ".to_string(),
672 Applicability::MaybeIncorrect,
673 );
674 }
675 }
676
677 let sp = if self.token == token::Eof {
678 self.prev_token.span
680 } else {
681 label_sp
682 };
683
684 if self.check_too_many_raw_str_terminators(&mut err) {
685 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)) {
686 let guar = err.emit();
687 return Ok(guar);
688 } else {
689 return Err(err);
690 }
691 }
692
693 if self.prev_token.span == DUMMY_SP {
694 err.span_label(self.token.span, label_exp);
697 } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) {
698 err.span_label(self.token.span, label_exp);
711 } else {
712 err.span_label(sp, label_exp);
713 err.span_label(self.token.span, "unexpected token");
714 }
715
716 if let Suggestions::Enabled(list) = &err.suggestions
718 && list.is_empty()
719 {
720 self.check_for_misspelled_kw(&mut err, &expected);
721 }
722 Err(err)
723 }
724
725 pub(super) fn is_expected_raw_ref_mut(&self) -> bool {
726 self.prev_token.is_keyword(kw::Raw)
727 && self.expected_token_types.contains(TokenType::KwMut)
728 && self.expected_token_types.contains(TokenType::KwConst)
729 && self.token.can_begin_expr()
730 }
731
732 pub(super) fn label_expected_raw_ref(&mut self, err: &mut Diag<'_>) {
737 if self.is_expected_raw_ref_mut() {
738 err.span_suggestions(
739 self.prev_token.span.shrink_to_hi(),
740 "`&raw` must be followed by `const` or `mut` to be a raw reference expression",
741 [" const".to_string(), " mut".to_string()],
742 Applicability::MaybeIncorrect,
743 );
744 }
745 }
746
747 fn check_for_misspelled_kw(&self, err: &mut Diag<'_>, expected: &[TokenType]) {
750 let Some((curr_ident, _)) = self.token.ident() else {
751 return;
752 };
753 let expected_token_types: &[TokenType] =
754 expected.len().checked_sub(10).map_or(&expected, |index| &expected[index..]);
755 let expected_keywords: Vec<Symbol> =
756 expected_token_types.iter().filter_map(|token| token.is_keyword()).collect();
757
758 if !expected_keywords.is_empty()
763 && !curr_ident.is_used_keyword()
764 && let Some(misspelled_kw) = find_similar_kw(curr_ident, &expected_keywords)
765 {
766 err.subdiagnostic(misspelled_kw);
767 err.seal_suggestions();
770 } else if let Some((prev_ident, _)) = self.prev_token.ident()
771 && !prev_ident.is_used_keyword()
772 {
773 let all_keywords = used_keywords(|| prev_ident.span.edition());
778
779 if let Some(misspelled_kw) = find_similar_kw(prev_ident, &all_keywords) {
784 err.subdiagnostic(misspelled_kw);
785 err.seal_suggestions();
788 }
789 }
790 }
791
792 pub(super) fn attr_on_non_tail_expr(&self, expr: &Expr) -> ErrorGuaranteed {
794 let span = self.prev_token.span.shrink_to_hi();
796 let mut err = self.dcx().create_err(ExpectedSemi {
797 span,
798 token: self.token,
799 unexpected_token_label: Some(self.token.span),
800 sugg: ExpectedSemiSugg::AddSemi(span),
801 });
802 let attr_span = match &expr.attrs[..] {
803 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
804 [only] => only.span,
805 [first, rest @ ..] => {
806 for attr in rest {
807 err.span_label(attr.span, "");
808 }
809 first.span
810 }
811 };
812 err.span_label(
813 attr_span,
814 ::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!(
815 "only `;` terminated statements or tail expressions are allowed after {}",
816 if expr.attrs.len() == 1 { "this attribute" } else { "these attributes" },
817 ),
818 );
819 if self.token == token::Pound && self.look_ahead(1, |t| *t == token::OpenBracket) {
820 err.span_label(span, "expected `;` here");
826 err.multipart_suggestion(
827 "alternatively, consider surrounding the expression with a block",
828 ::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![
829 (expr.span.shrink_to_lo(), "{ ".to_string()),
830 (expr.span.shrink_to_hi(), " }".to_string()),
831 ],
832 Applicability::MachineApplicable,
833 );
834
835 let mut snapshot = self.create_snapshot_for_diagnostic();
837 if let [attr] = &expr.attrs[..]
838 && let ast::AttrKind::Normal(attr_kind) = &attr.kind
839 && let [segment] = &attr_kind.item.path.segments[..]
840 && segment.ident.name == sym::cfg
841 && let Some(args_span) = attr_kind.item.args.span()
842 && let next_attr = match snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None))
843 {
844 Ok(next_attr) => next_attr,
845 Err(inner_err) => {
846 inner_err.cancel();
847 return err.emit();
848 }
849 }
850 && let ast::AttrKind::Normal(next_attr_kind) = next_attr.kind
851 && let Some(next_attr_args_span) = next_attr_kind.item.args.span()
852 && let [next_segment] = &next_attr_kind.item.path.segments[..]
853 && next_segment.ident.name == sym::cfg
854 {
855 let next_expr = match snapshot.parse_expr() {
856 Ok(next_expr) => next_expr,
857 Err(inner_err) => {
858 inner_err.cancel();
859 return err.emit();
860 }
861 };
862 let margin = self.psess.source_map().span_to_margin(next_expr.span).unwrap_or(0);
869 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![
870 (attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()),
871 (args_span.shrink_to_hi().with_hi(attr.span.hi()), " {".to_string()),
872 (expr.span.shrink_to_lo(), " ".to_string()),
873 (
874 next_attr.span.with_hi(next_segment.span().hi()),
875 "} else if cfg!".to_string(),
876 ),
877 (
878 next_attr_args_span.shrink_to_hi().with_hi(next_attr.span.hi()),
879 " {".to_string(),
880 ),
881 (next_expr.span.shrink_to_lo(), " ".to_string()),
882 (next_expr.span.shrink_to_hi(), format!("\n{}}}", " ".repeat(margin))),
883 ];
884 err.multipart_suggestion(
885 "it seems like you are trying to provide different expressions depending on \
886 `cfg`, consider using `if cfg!(..)`",
887 sugg,
888 Applicability::MachineApplicable,
889 );
890 }
891 }
892
893 err.emit()
894 }
895
896 fn check_too_many_raw_str_terminators(&mut self, err: &mut Diag<'_>) -> bool {
897 let sm = self.psess.source_map();
898 match (&self.prev_token.kind, &self.token.kind) {
899 (
900 TokenKind::Literal(Lit {
901 kind: LitKind::StrRaw(n_hashes) | LitKind::ByteStrRaw(n_hashes),
902 ..
903 }),
904 TokenKind::Pound,
905 ) if !sm.is_multiline(
906 self.prev_token.span.shrink_to_hi().until(self.token.span.shrink_to_lo()),
907 ) =>
908 {
909 let n_hashes: u8 = *n_hashes;
910 err.primary_message("too many `#` when terminating raw string");
911 let str_span = self.prev_token.span;
912 let mut span = self.token.span;
913 let mut count = 0;
914 while self.token == TokenKind::Pound
915 && !sm.is_multiline(span.shrink_to_hi().until(self.token.span.shrink_to_lo()))
916 {
917 span = span.with_hi(self.token.span.hi());
918 self.bump();
919 count += 1;
920 }
921 err.span(span);
922 err.span_suggestion_verbose(
923 span,
924 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("remove the extra `#`{0}",
if count == 1 { "" } else { "s" }))
})format!("remove the extra `#`{}", pluralize!(count)),
925 "",
926 Applicability::MachineApplicable,
927 );
928 err.span_label(
929 str_span,
930 ::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)),
931 );
932 true
933 }
934 _ => false,
935 }
936 }
937
938 pub(super) fn maybe_suggest_struct_literal(
939 &mut self,
940 lo: Span,
941 s: BlockCheckMode,
942 maybe_struct_name: token::Token,
943 ) -> Option<PResult<'a, Box<Block>>> {
944 if self.token.is_ident() && self.look_ahead(1, |t| t == &token::Colon) {
945 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:949",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(949u32),
::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);
950 let mut snapshot = self.create_snapshot_for_diagnostic();
951 let path = Path { segments: ThinVec::new(), span: self.prev_token.span.shrink_to_lo() };
952 let struct_expr = snapshot.parse_expr_struct(None, path, false);
953 let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No);
954 return Some(match (struct_expr, block_tail) {
955 (Ok(expr), Err(err)) => {
956 err.cancel();
965 self.restore_snapshot(snapshot);
966 let guar = self.dcx().emit_err(StructLiteralBodyWithoutPath {
967 span: expr.span,
968 sugg: StructLiteralBodyWithoutPathSugg {
969 before: expr.span.shrink_to_lo(),
970 after: expr.span.shrink_to_hi(),
971 },
972 });
973 Ok(self.mk_block(
974 {
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)],
975 s,
976 lo.to(self.prev_token.span),
977 ))
978 }
979 (Err(err), Ok(tail)) => {
980 err.cancel();
982 Ok(tail)
983 }
984 (Err(snapshot_err), Err(err)) => {
985 snapshot_err.cancel();
987 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);
988 Err(err)
989 }
990 (Ok(_), Ok(tail)) => Ok(tail),
991 });
992 }
993 None
994 }
995
996 pub(super) fn recover_closure_body(
997 &mut self,
998 mut err: Diag<'a>,
999 before: token::Token,
1000 prev: token::Token,
1001 token: token::Token,
1002 lo: Span,
1003 decl_hi: Span,
1004 ) -> PResult<'a, Box<Expr>> {
1005 err.span_label(lo.to(decl_hi), "while parsing the body of this closure");
1006 let guar = match before.kind {
1007 token::OpenBrace if token.kind != token::OpenBrace => {
1008 err.multipart_suggestion(
1010 "you might have meant to open the body of the closure, instead of enclosing \
1011 the closure in a block",
1012 ::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![
1013 (before.span, String::new()),
1014 (prev.span.shrink_to_hi(), " {".to_string()),
1015 ],
1016 Applicability::MaybeIncorrect,
1017 );
1018 let guar = err.emit();
1019 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1020 guar
1021 }
1022 token::OpenParen if token.kind != token::OpenBrace => {
1023 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)]);
1026
1027 err.multipart_suggestion(
1028 "you might have meant to open the body of the closure",
1029 ::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![
1030 (prev.span.shrink_to_hi(), " {".to_string()),
1031 (self.token.span.shrink_to_lo(), "}".to_string()),
1032 ],
1033 Applicability::MaybeIncorrect,
1034 );
1035 err.emit()
1036 }
1037 _ if token.kind != token::OpenBrace => {
1038 err.multipart_suggestion(
1041 "you might have meant to open the body of the closure",
1042 ::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())],
1043 Applicability::HasPlaceholders,
1044 );
1045 return Err(err);
1046 }
1047 _ => return Err(err),
1048 };
1049 Ok(self.mk_expr_err(lo.to(self.token.span), guar))
1050 }
1051
1052 pub(super) fn eat_to_tokens(&mut self, closes: &[ExpTokenPair]) {
1055 if let Err(err) = self
1056 .parse_seq_to_before_tokens(closes, &[], SeqSep::none(), |p| Ok(p.parse_token_tree()))
1057 {
1058 err.cancel();
1059 }
1060 }
1061
1062 pub(super) fn check_trailing_angle_brackets(
1073 &mut self,
1074 segment: &PathSegment,
1075 end: &[ExpTokenPair],
1076 ) -> Option<ErrorGuaranteed> {
1077 if !self.may_recover() {
1078 return None;
1079 }
1080
1081 let parsed_angle_bracket_args =
1106 segment.args.as_ref().is_some_and(|args| args.is_angle_bracketed());
1107
1108 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:1108",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1108u32),
::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!(
1109 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
1110 parsed_angle_bracket_args,
1111 );
1112 if !parsed_angle_bracket_args {
1113 return None;
1114 }
1115
1116 let lo = self.token.span;
1119
1120 let mut position = 0;
1124
1125 let mut number_of_shr = 0;
1129 let mut number_of_gt = 0;
1130 while self.look_ahead(position, |t| {
1131 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:1131",
"rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1131u32),
::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);
1132 if *t == token::Shr {
1133 number_of_shr += 1;
1134 true
1135 } else if *t == token::Gt {
1136 number_of_gt += 1;
1137 true
1138 } else {
1139 false
1140 }
1141 }) {
1142 position += 1;
1143 }
1144
1145 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:1146",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1146u32),
::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!(
1147 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
1148 number_of_gt, number_of_shr,
1149 );
1150 if number_of_gt < 1 && number_of_shr < 1 {
1151 return None;
1152 }
1153
1154 if self.look_ahead(position, |t| {
1157 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:1157",
"rustc_parse::parser::diagnostics", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1157u32),
::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);
1158 end.iter().any(|exp| exp.tok == t.kind)
1159 }) {
1160 self.eat_to_tokens(end);
1163 let span = lo.to(self.prev_token.span);
1164
1165 let num_extra_brackets = number_of_gt + number_of_shr * 2;
1166 return Some(self.dcx().emit_err(UnmatchedAngleBrackets { span, num_extra_brackets }));
1167 }
1168 None
1169 }
1170
1171 pub(super) fn check_turbofish_missing_angle_brackets(&mut self, segment: &mut PathSegment) {
1174 if !self.may_recover() {
1175 return;
1176 }
1177
1178 if self.token == token::PathSep && segment.args.is_none() {
1179 let snapshot = self.create_snapshot_for_diagnostic();
1180 self.bump();
1181 let lo = self.token.span;
1182 match self.parse_angle_args(None) {
1183 Ok(args) => {
1184 let span = lo.to(self.prev_token.span);
1185 let mut trailing_span = self.prev_token.span.shrink_to_hi();
1187 while self.token == token::Shr || self.token == token::Gt {
1188 trailing_span = trailing_span.to(self.token.span);
1189 self.bump();
1190 }
1191 if self.token == token::OpenParen {
1192 segment.args = Some(AngleBracketedArgs { args, span }.into());
1194
1195 self.dcx().emit_err(GenericParamsWithoutAngleBrackets {
1196 span,
1197 sugg: GenericParamsWithoutAngleBracketsSugg {
1198 left: span.shrink_to_lo(),
1199 right: trailing_span,
1200 },
1201 });
1202 } else {
1203 self.restore_snapshot(snapshot);
1205 }
1206 }
1207 Err(err) => {
1208 err.cancel();
1211 self.restore_snapshot(snapshot);
1212 }
1213 }
1214 }
1215 }
1216
1217 pub(super) fn check_mistyped_turbofish_with_multiple_type_params(
1220 &mut self,
1221 mut e: Diag<'a>,
1222 expr: &mut Box<Expr>,
1223 ) -> PResult<'a, ErrorGuaranteed> {
1224 if let ExprKind::Binary(binop, _, _) = &expr.kind
1225 && let ast::BinOpKind::Lt = binop.node
1226 && self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))
1227 {
1228 let x = self.parse_seq_to_before_end(
1229 crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt),
1230 SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
1231 |p| match p.parse_generic_arg(None)? {
1232 Some(arg) => Ok(arg),
1233 None => p.unexpected_any(),
1235 },
1236 );
1237 match x {
1238 Ok((_, _, Recovered::No)) => {
1239 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
1240 e.span_suggestion_verbose(
1242 binop.span.shrink_to_lo(),
1243 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"),
1244 "::",
1245 Applicability::MaybeIncorrect,
1246 );
1247 match self.parse_expr() {
1248 Ok(_) => {
1249 let guar = e.emit();
1253 *expr = self.mk_expr_err(expr.span.to(self.prev_token.span), guar);
1254 return Ok(guar);
1255 }
1256 Err(err) => {
1257 err.cancel();
1258 }
1259 }
1260 }
1261 }
1262 Ok((_, _, Recovered::Yes(_))) => {}
1263 Err(err) => {
1264 err.cancel();
1265 }
1266 }
1267 }
1268 Err(e)
1269 }
1270
1271 pub(super) fn suggest_add_missing_let_for_stmt(&mut self, err: &mut Diag<'a>) {
1274 if self.token == token::Colon {
1275 let prev_span = self.prev_token.span.shrink_to_lo();
1276 let snapshot = self.create_snapshot_for_diagnostic();
1277 self.bump();
1278 match self.parse_ty() {
1279 Ok(_) => {
1280 if self.token == token::Eq {
1281 let sugg = SuggAddMissingLetStmt { span: prev_span };
1282 sugg.add_to_diag(err);
1283 }
1284 }
1285 Err(e) => {
1286 e.cancel();
1287 }
1288 }
1289 self.restore_snapshot(snapshot);
1290 }
1291 }
1292
1293 fn attempt_chained_comparison_suggestion(
1297 &mut self,
1298 err: &mut ComparisonOperatorsCannotBeChained,
1299 inner_op: &Expr,
1300 outer_op: &Spanned<AssocOp>,
1301 ) -> bool {
1302 if let ExprKind::Binary(op, l1, r1) = &inner_op.kind {
1303 if let ExprKind::Field(_, ident) = l1.kind
1304 && !ident.is_numeric()
1305 && !#[allow(non_exhaustive_omitted_patterns)] match r1.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(r1.kind, ExprKind::Lit(_))
1306 {
1307 return false;
1310 }
1311 return match (op.node, &outer_op.node) {
1312 (BinOpKind::Eq, AssocOp::Binary(BinOpKind::Eq)) |
1314 (BinOpKind::Lt, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1316 (BinOpKind::Le, AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le)) |
1317 (BinOpKind::Gt, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) |
1319 (BinOpKind::Ge, AssocOp::Binary(BinOpKind::Gt | BinOpKind::Ge)) => {
1320 let expr_to_str = |e: &Expr| {
1321 self.span_to_snippet(e.span).unwrap_or_else(|_| pprust::expr_to_string(e))
1322 };
1323 err.chaining_sugg =
1324 Some(ComparisonOperatorsCannotBeChainedSugg::SplitComparison {
1325 span: inner_op.span.shrink_to_hi(),
1326 middle_term: expr_to_str(r1),
1327 });
1328 false }
1330 (
1332 BinOpKind::Eq,
1333 AssocOp::Binary(BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge),
1334 ) => {
1335 let snapshot = self.create_snapshot_for_diagnostic();
1337 match self.parse_expr() {
1338 Ok(r2) => {
1339 err.chaining_sugg =
1342 Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1343 left: r1.span.shrink_to_lo(),
1344 right: r2.span.shrink_to_hi(),
1345 });
1346 true
1347 }
1348 Err(expr_err) => {
1349 expr_err.cancel();
1350 self.restore_snapshot(snapshot);
1351 true
1352 }
1353 }
1354 }
1355 (
1357 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge,
1358 AssocOp::Binary(BinOpKind::Eq),
1359 ) => {
1360 let snapshot = self.create_snapshot_for_diagnostic();
1361 match self.parse_expr() {
1364 Ok(_) => {
1365 err.chaining_sugg =
1366 Some(ComparisonOperatorsCannotBeChainedSugg::Parenthesize {
1367 left: l1.span.shrink_to_lo(),
1368 right: r1.span.shrink_to_hi(),
1369 });
1370 true
1371 }
1372 Err(expr_err) => {
1373 expr_err.cancel();
1374 self.restore_snapshot(snapshot);
1375 false
1376 }
1377 }
1378 }
1379 _ => false,
1380 };
1381 }
1382 false
1383 }
1384
1385 pub(super) fn check_no_chained_comparison(
1404 &mut self,
1405 inner_op: &Expr,
1406 outer_op: &Spanned<AssocOp>,
1407 ) -> PResult<'a, Option<Box<Expr>>> {
1408 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!(
1409 outer_op.node.is_comparison(),
1410 "check_no_chained_comparison: {:?} is not comparison",
1411 outer_op.node,
1412 );
1413
1414 let mk_err_expr =
1415 |this: &Self, span, guar| Ok(Some(this.mk_expr(span, ExprKind::Err(guar))));
1416
1417 match &inner_op.kind {
1418 ExprKind::Binary(op, l1, r1) if op.node.is_comparison() => {
1419 let mut err = ComparisonOperatorsCannotBeChained {
1420 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],
1421 suggest_turbofish: None,
1422 help_turbofish: false,
1423 chaining_sugg: None,
1424 };
1425
1426 if op.node == BinOpKind::Lt && outer_op.node == AssocOp::Binary(BinOpKind::Lt)
1429 || outer_op.node == AssocOp::Binary(BinOpKind::Gt)
1430 {
1431 if outer_op.node == AssocOp::Binary(BinOpKind::Lt) {
1432 let snapshot = self.create_snapshot_for_diagnostic();
1433 self.bump();
1434 let modifiers = [(token::Lt, 1), (token::Gt, -1), (token::Shr, -2)];
1436 self.consume_tts(1, &modifiers);
1437
1438 if !#[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
token::OpenParen | token::PathSep => true,
_ => false,
}matches!(self.token.kind, token::OpenParen | token::PathSep) {
1439 self.restore_snapshot(snapshot);
1442 }
1443 }
1444 return if self.token == token::PathSep {
1445 if let ExprKind::Binary(o, ..) = inner_op.kind
1448 && o.node == BinOpKind::Lt
1449 {
1450 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1451 } else {
1452 err.help_turbofish = true;
1453 }
1454
1455 let snapshot = self.create_snapshot_for_diagnostic();
1456 self.bump(); match self.parse_expr() {
1460 Ok(_) => {
1461 let guar = self.dcx().emit_err(err);
1463 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1467 }
1468 Err(expr_err) => {
1469 expr_err.cancel();
1470 self.restore_snapshot(snapshot);
1473 Err(self.dcx().create_err(err))
1474 }
1475 }
1476 } else if self.token == token::OpenParen {
1477 if let ExprKind::Binary(o, ..) = inner_op.kind
1480 && o.node == BinOpKind::Lt
1481 {
1482 err.suggest_turbofish = Some(op.span.shrink_to_lo());
1483 } else {
1484 err.help_turbofish = true;
1485 }
1486 match self.consume_fn_args() {
1488 Err(()) => Err(self.dcx().create_err(err)),
1489 Ok(()) => {
1490 let guar = self.dcx().emit_err(err);
1491 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1495 }
1496 }
1497 } else {
1498 if !#[allow(non_exhaustive_omitted_patterns)] match l1.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(l1.kind, ExprKind::Lit(_))
1499 && !#[allow(non_exhaustive_omitted_patterns)] match r1.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(r1.kind, ExprKind::Lit(_))
1500 {
1501 err.help_turbofish = true;
1504 }
1505
1506 let recovered = self
1509 .attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1510 if recovered {
1511 let guar = self.dcx().emit_err(err);
1512 mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar)
1513 } else {
1514 Err(self.dcx().create_err(err))
1516 }
1517 };
1518 }
1519 let recovered =
1520 self.attempt_chained_comparison_suggestion(&mut err, inner_op, outer_op);
1521 let guar = self.dcx().emit_err(err);
1522 if recovered {
1523 return mk_err_expr(self, inner_op.span.to(self.prev_token.span), guar);
1524 }
1525 }
1526 _ => {}
1527 }
1528 Ok(None)
1529 }
1530
1531 fn consume_fn_args(&mut self) -> Result<(), ()> {
1532 let snapshot = self.create_snapshot_for_diagnostic();
1533 self.bump(); let modifiers = [(token::OpenParen, 1), (token::CloseParen, -1)];
1537 self.consume_tts(1, &modifiers);
1538
1539 if self.token == token::Eof {
1540 self.restore_snapshot(snapshot);
1542 Err(())
1543 } else {
1544 Ok(())
1546 }
1547 }
1548
1549 pub(super) fn maybe_report_ambiguous_plus(&mut self, impl_dyn_multi: bool, ty: &Ty) {
1550 if impl_dyn_multi {
1551 self.dcx().emit_err(AmbiguousPlus {
1552 span: ty.span,
1553 suggestion: AddParen { lo: ty.span.shrink_to_lo(), hi: ty.span.shrink_to_hi() },
1554 });
1555 }
1556 }
1557
1558 pub(super) fn maybe_recover_from_question_mark(&mut self, ty: Box<Ty>) -> Box<Ty> {
1560 if self.token == token::Question {
1561 self.bump();
1562 let guar = self.dcx().emit_err(QuestionMarkInType {
1563 span: self.prev_token.span,
1564 sugg: QuestionMarkInTypeSugg {
1565 left: ty.span.shrink_to_lo(),
1566 right: self.prev_token.span,
1567 },
1568 });
1569 self.mk_ty(ty.span.to(self.prev_token.span), TyKind::Err(guar))
1570 } else {
1571 ty
1572 }
1573 }
1574
1575 pub(super) fn maybe_recover_from_ternary_operator(
1581 &mut self,
1582 cond: Option<Span>,
1583 ) -> PResult<'a, ()> {
1584 if self.prev_token != token::Question {
1585 return PResult::Ok(());
1586 }
1587
1588 let question = self.prev_token.span;
1589 let lo = cond.unwrap_or(question).lo();
1590 let snapshot = self.create_snapshot_for_diagnostic();
1591
1592 if match self.parse_expr() {
1593 Ok(_) => true,
1594 Err(err) => {
1595 err.cancel();
1596 self.token == token::Colon
1599 }
1600 } {
1601 if self.eat_noexpect(&token::Colon) {
1602 let colon = self.prev_token.span;
1603 match self.parse_expr() {
1604 Ok(expr) => {
1605 let sugg = cond.map(|cond| TernaryOperatorSuggestion {
1606 before_cond: cond.shrink_to_lo(),
1607 question,
1608 colon,
1609 end: expr.span.shrink_to_hi(),
1610 });
1611 return Err(self.dcx().create_err(TernaryOperator {
1612 span: self.prev_token.span.with_lo(lo),
1613 sugg,
1614 no_sugg: sugg.is_none(),
1615 }));
1616 }
1617 Err(err) => {
1618 err.cancel();
1619 }
1620 };
1621 }
1622 }
1623 self.restore_snapshot(snapshot);
1624 Ok(())
1625 }
1626
1627 pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
1628 if !self.token.is_like_plus() {
1630 return Ok(());
1631 }
1632
1633 self.bump(); let _bounds = self.parse_generic_bounds()?;
1635 let sub = match &ty.kind {
1636 TyKind::Ref(_lifetime, mut_ty) => {
1637 let lo = mut_ty.ty.span.shrink_to_lo();
1638 let hi = self.prev_token.span.shrink_to_hi();
1639 BadTypePlusSub::AddParen { suggestion: AddParen { lo, hi } }
1640 }
1641 TyKind::Ptr(..) | TyKind::FnPtr(..) => {
1642 BadTypePlusSub::ForgotParen { span: ty.span.to(self.prev_token.span) }
1643 }
1644 _ => BadTypePlusSub::ExpectPath { span: ty.span },
1645 };
1646
1647 self.dcx().emit_err(BadTypePlus { span: ty.span, sub });
1648
1649 Ok(())
1650 }
1651
1652 pub(super) fn recover_from_prefix_increment(
1653 &mut self,
1654 operand_expr: Box<Expr>,
1655 op_span: Span,
1656 start_stmt: bool,
1657 ) -> PResult<'a, Box<Expr>> {
1658 let standalone = if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr };
1659 let kind = IncDecRecovery { standalone, op: IncOrDec::Inc, fixity: UnaryFixity::Pre };
1660 self.recover_from_inc_dec(operand_expr, kind, op_span)
1661 }
1662
1663 pub(super) fn recover_from_postfix_increment(
1664 &mut self,
1665 operand_expr: Box<Expr>,
1666 op_span: Span,
1667 start_stmt: bool,
1668 ) -> PResult<'a, Box<Expr>> {
1669 let kind = IncDecRecovery {
1670 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1671 op: IncOrDec::Inc,
1672 fixity: UnaryFixity::Post,
1673 };
1674 self.recover_from_inc_dec(operand_expr, kind, op_span)
1675 }
1676
1677 pub(super) fn recover_from_postfix_decrement(
1678 &mut self,
1679 operand_expr: Box<Expr>,
1680 op_span: Span,
1681 start_stmt: bool,
1682 ) -> PResult<'a, Box<Expr>> {
1683 let kind = IncDecRecovery {
1684 standalone: if start_stmt { IsStandalone::Standalone } else { IsStandalone::Subexpr },
1685 op: IncOrDec::Dec,
1686 fixity: UnaryFixity::Post,
1687 };
1688 self.recover_from_inc_dec(operand_expr, kind, op_span)
1689 }
1690
1691 fn recover_from_inc_dec(
1692 &mut self,
1693 base: Box<Expr>,
1694 kind: IncDecRecovery,
1695 op_span: Span,
1696 ) -> PResult<'a, Box<Expr>> {
1697 let mut err = self.dcx().struct_span_err(
1698 op_span,
1699 ::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()),
1700 );
1701 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));
1702
1703 let help_base_case = |mut err: Diag<'_, ErrorGuaranteed>, base| {
1704 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()));
1705 err.emit();
1706 Ok(base)
1707 };
1708
1709 let spans = match kind.fixity {
1711 UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
1712 UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
1713 };
1714
1715 match kind.standalone {
1716 IsStandalone::Standalone => {
1717 self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err)
1718 }
1719 IsStandalone::Subexpr => {
1720 let Ok(base_src) = self.span_to_snippet(base.span) else {
1721 return help_base_case(err, base);
1722 };
1723 match kind.fixity {
1724 UnaryFixity::Pre => {
1725 self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1726 }
1727 UnaryFixity::Post => {
1728 if !#[allow(non_exhaustive_omitted_patterns)] match base.kind {
ExprKind::Binary(_, _, _) => true,
_ => false,
}matches!(base.kind, ExprKind::Binary(_, _, _)) {
1731 self.postfix_inc_dec_suggest(base_src, kind, spans).emit(&mut err)
1732 }
1733 }
1734 }
1735 }
1736 }
1737 Err(err)
1738 }
1739
1740 fn prefix_inc_dec_suggest(
1741 &mut self,
1742 base_src: String,
1743 kind: IncDecRecovery,
1744 (pre_span, post_span): (Span, Span),
1745 ) -> MultiSugg {
1746 MultiSugg {
1747 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()),
1748 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![
1749 (pre_span, "{ ".to_string()),
1750 (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)),
1751 ],
1752 applicability: Applicability::MachineApplicable,
1753 }
1754 }
1755
1756 fn postfix_inc_dec_suggest(
1757 &mut self,
1758 base_src: String,
1759 kind: IncDecRecovery,
1760 (pre_span, post_span): (Span, Span),
1761 ) -> MultiSugg {
1762 let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
1763 MultiSugg {
1764 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()),
1765 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![
1766 (pre_span, format!("{{ let {tmp_var} = ")),
1767 (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)),
1768 ],
1769 applicability: Applicability::HasPlaceholders,
1770 }
1771 }
1772
1773 fn inc_dec_standalone_suggest(
1774 &mut self,
1775 kind: IncDecRecovery,
1776 (pre_span, post_span): (Span, Span),
1777 ) -> MultiSugg {
1778 let mut patches = Vec::new();
1779
1780 if !pre_span.is_empty() {
1781 patches.push((pre_span, String::new()));
1782 }
1783
1784 patches.push((post_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}= 1", kind.op.chr()))
})format!(" {}= 1", kind.op.chr())));
1785 MultiSugg {
1786 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `{0}= 1` instead",
kind.op.chr()))
})format!("use `{}= 1` instead", kind.op.chr()),
1787 patches,
1788 applicability: Applicability::MachineApplicable,
1789 }
1790 }
1791
1792 pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>(
1796 &mut self,
1797 base: T,
1798 ) -> PResult<'a, T> {
1799 if self.may_recover() && self.token == token::PathSep {
1801 return self.recover_from_bad_qpath(base);
1802 }
1803 Ok(base)
1804 }
1805
1806 #[cold]
1807 fn recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T) -> PResult<'a, T> {
1808 if let Some(ty) = base.to_ty() {
1809 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1810 }
1811 Ok(base)
1812 }
1813
1814 pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(
1817 &mut self,
1818 ty_span: Span,
1819 ty: Box<Ty>,
1820 ) -> PResult<'a, T> {
1821 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep))?;
1822
1823 let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP };
1824 self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?;
1825 path.span = ty_span.to(self.prev_token.span);
1826
1827 self.dcx().emit_err(BadQPathStage2 {
1828 span: ty_span,
1829 wrap: WrapType { lo: ty_span.shrink_to_lo(), hi: ty_span.shrink_to_hi() },
1830 });
1831
1832 let path_span = ty_span.shrink_to_hi(); Ok(T::recovered(Some(Box::new(QSelf { ty, path_span, position: 0 })), path))
1834 }
1835
1836 pub fn maybe_consume_incorrect_semicolon(&mut self, previous_item: Option<&Item>) -> bool {
1839 if self.token != TokenKind::Semi {
1840 return false;
1841 }
1842
1843 let err = match previous_item {
1846 Some(previous_item) => {
1847 let name = match previous_item.kind {
1848 ItemKind::Struct(..) => "braced struct",
1851 _ => previous_item.kind.descr(),
1852 };
1853 IncorrectSemicolon { span: self.token.span, name, show_help: true }
1854 }
1855 None => IncorrectSemicolon { span: self.token.span, name: "", show_help: false },
1856 };
1857 self.dcx().emit_err(err);
1858
1859 self.bump();
1860 true
1861 }
1862
1863 pub(super) fn unexpected_err(&mut self, t: &TokenKind) -> Diag<'a> {
1865 let token_str = pprust::token_kind_to_string(t);
1866 let this_token_str = super::token_descr(&self.token);
1867 let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) {
1868 (token::Eof, Some(_)) => {
1870 let sp = self.prev_token.span.shrink_to_hi();
1871 (sp, sp)
1872 }
1873 _ if self.prev_token.span == DUMMY_SP => (self.token.span, self.token.span),
1876 (token::Eof, None) => (self.prev_token.span, self.token.span),
1878 _ => (self.prev_token.span.shrink_to_hi(), self.token.span),
1879 };
1880 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!(
1881 "expected `{}`, found {}",
1882 token_str,
1883 match (&self.token.kind, self.subparser_name) {
1884 (token::Eof, Some(origin)) => format!("end of {origin}"),
1885 _ => this_token_str,
1886 },
1887 );
1888 let mut err = self.dcx().struct_span_err(sp, msg);
1889 let label_exp = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`", token_str))
})format!("expected `{token_str}`");
1890 let sm = self.psess.source_map();
1891 if !sm.is_multiline(prev_sp.until(sp)) {
1892 err.span_label(sp, label_exp);
1895 } else {
1896 err.span_label(prev_sp, label_exp);
1897 err.span_label(sp, "unexpected token");
1898 }
1899 err
1900 }
1901
1902 pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> {
1903 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() {
1904 return Ok(());
1905 }
1906 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)).map(drop) }
1908
1909 pub(super) fn recover_colon_as_semi(&mut self) -> bool {
1910 let line_idx = |span: Span| {
1911 self.psess
1912 .source_map()
1913 .span_to_lines(span)
1914 .ok()
1915 .and_then(|lines| Some(lines.lines.get(0)?.line_index))
1916 };
1917
1918 if self.may_recover()
1919 && self.token == token::Colon
1920 && self.look_ahead(1, |next| line_idx(self.token.span) < line_idx(next.span))
1921 {
1922 self.dcx().emit_err(ColonAsSemi { span: self.token.span });
1923 self.bump();
1924 return true;
1925 }
1926
1927 false
1928 }
1929
1930 pub(super) fn recover_incorrect_await_syntax(
1933 &mut self,
1934 await_sp: Span,
1935 ) -> PResult<'a, Box<Expr>> {
1936 let (hi, expr, is_question) = if self.token == token::Bang {
1937 self.recover_await_macro()?
1939 } else {
1940 self.recover_await_prefix(await_sp)?
1941 };
1942 let (sp, guar) = self.error_on_incorrect_await(await_sp, hi, &expr, is_question);
1943 let expr = self.mk_expr_err(await_sp.to(sp), guar);
1944 self.maybe_recover_from_bad_qpath(expr)
1945 }
1946
1947 fn recover_await_macro(&mut self) -> PResult<'a, (Span, Box<Expr>, bool)> {
1948 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?;
1949 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1950 let expr = self.parse_expr()?;
1951 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1952 Ok((self.prev_token.span, expr, false))
1953 }
1954
1955 fn recover_await_prefix(&mut self, await_sp: Span) -> PResult<'a, (Span, Box<Expr>, bool)> {
1956 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 {
1958 self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)
1962 } else {
1963 self.parse_expr()
1964 }
1965 .map_err(|mut err| {
1966 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"));
1967 err
1968 })?;
1969 Ok((expr.span, expr, is_question))
1970 }
1971
1972 fn error_on_incorrect_await(
1973 &self,
1974 lo: Span,
1975 hi: Span,
1976 expr: &Expr,
1977 is_question: bool,
1978 ) -> (Span, ErrorGuaranteed) {
1979 let span = lo.to(hi);
1980 let guar = self.dcx().emit_err(IncorrectAwait {
1981 span,
1982 suggestion: AwaitSuggestion {
1983 removal: lo.until(expr.span),
1984 dot_await: expr.span.shrink_to_hi(),
1985 question_mark: if is_question { "?" } else { "" },
1986 },
1987 });
1988 (span, guar)
1989 }
1990
1991 pub(super) fn recover_from_await_method_call(&mut self) {
1993 if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
1994 let lo = self.token.span;
1996 self.bump(); let span = lo.to(self.token.span);
1998 self.bump(); self.dcx().emit_err(IncorrectUseOfAwait { span });
2001 }
2002 }
2003 pub(super) fn recover_from_use(&mut self) {
2006 if self.token == token::OpenParen && self.look_ahead(1, |t| t == &token::CloseParen) {
2007 let lo = self.token.span;
2009 self.bump(); let span = lo.to(self.token.span);
2011 self.bump(); self.dcx().emit_err(IncorrectUseOfUse { span });
2014 }
2015 }
2016
2017 pub(super) fn try_macro_suggestion(&mut self) -> PResult<'a, Box<Expr>> {
2018 let is_try = self.token.is_keyword(kw::Try);
2019 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 {
2023 let lo = self.token.span;
2024 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;
2031 self.bump(); let mut err = self.dcx().struct_span_err(lo.to(hi), "use of deprecated `try` macro");
2033 err.note("in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated");
2034 let prefix = if is_empty { "" } else { "alternatively, " };
2035 if !is_empty {
2036 err.multipart_suggestion(
2037 "you can use the `?` operator instead",
2038 ::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())],
2039 Applicability::MachineApplicable,
2040 );
2041 }
2042 err.span_suggestion_verbose(
2043 lo.shrink_to_lo(),
2044 ::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!(
2045 "{prefix}you can still access the deprecated `try!()` macro using the \
2046 \"raw identifier\" syntax"
2047 ),
2048 "r#",
2049 Applicability::MachineApplicable,
2050 );
2051 let guar = err.emit();
2052 Ok(self.mk_expr_err(lo.to(hi), guar))
2053 } else {
2054 Err(self.expected_expression_found()) }
2056 }
2057
2058 pub(super) fn expect_gt_or_maybe_suggest_closing_generics(
2065 &mut self,
2066 params: &[ast::GenericParam],
2067 ) -> PResult<'a, ()> {
2068 let Err(mut err) = self.expect_gt() else {
2069 return Ok(());
2070 };
2071 if let [.., ast::GenericParam { bounds, .. }] = params
2073 && let Some(poly) = bounds
2074 .iter()
2075 .filter_map(|bound| match bound {
2076 ast::GenericBound::Trait(poly) => Some(poly),
2077 _ => None,
2078 })
2079 .next_back()
2080 {
2081 err.span_suggestion_verbose(
2082 poly.span.shrink_to_hi(),
2083 "you might have meant to end the type parameters here",
2084 ">",
2085 Applicability::MaybeIncorrect,
2086 );
2087 }
2088 Err(err)
2089 }
2090
2091 pub(super) fn recover_seq_parse_error(
2092 &mut self,
2093 open: ExpTokenPair,
2094 close: ExpTokenPair,
2095 lo: Span,
2096 err: Diag<'a>,
2097 ) -> Box<Expr> {
2098 let guar = err.emit();
2099 self.consume_block(open, close, ConsumeClosingDelim::Yes);
2101 self.mk_expr(lo.to(self.prev_token.span), ExprKind::Err(guar))
2102 }
2103
2104 pub(super) fn recover_stmt(&mut self) {
2109 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
2110 }
2111
2112 pub(super) fn recover_stmt_(
2120 &mut self,
2121 break_on_semi: SemiColonMode,
2122 break_on_block: BlockMode,
2123 ) {
2124 let mut brace_depth = 0;
2125 let mut bracket_depth = 0;
2126 let mut in_block = false;
2127 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:2127",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2127u32),
::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);
2128 loop {
2129 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:2129",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2129u32),
::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);
2130 match self.token.kind {
2131 token::OpenBrace => {
2132 brace_depth += 1;
2133 self.bump();
2134 if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0
2135 {
2136 in_block = true;
2137 }
2138 }
2139 token::OpenBracket => {
2140 bracket_depth += 1;
2141 self.bump();
2142 }
2143 token::CloseBrace => {
2144 if brace_depth == 0 {
2145 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:2145",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2145u32),
::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);
2146 break;
2147 }
2148 brace_depth -= 1;
2149 self.bump();
2150 if in_block && bracket_depth == 0 && brace_depth == 0 {
2151 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:2151",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2151u32),
::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);
2152 break;
2153 }
2154 }
2155 token::CloseBracket => {
2156 bracket_depth -= 1;
2157 if bracket_depth < 0 {
2158 bracket_depth = 0;
2159 }
2160 self.bump();
2161 }
2162 token::Eof => {
2163 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:2163",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(2163u32),
::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");
2164 break;
2165 }
2166 token::Semi => {
2167 self.bump();
2168 if break_on_semi == SemiColonMode::Break
2169 && brace_depth == 0
2170 && bracket_depth == 0
2171 {
2172 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/parser/diagnostics.rs:2172",
"rustc_parse::parser::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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 - Semi")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("recover_stmt_ return - Semi");
2173 break;
2174 }
2175 }
2176 token::Comma
2177 if break_on_semi == SemiColonMode::Comma
2178 && brace_depth == 0
2179 && bracket_depth == 0 =>
2180 {
2181 break;
2182 }
2183 _ => self.bump(),
2184 }
2185 }
2186 }
2187
2188 pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) {
2189 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)) {
2190 self.dcx().emit_err(InInTypo {
2192 span: self.prev_token.span,
2193 sugg_span: in_span.until(self.prev_token.span),
2194 });
2195 }
2196 }
2197
2198 pub(super) fn parameter_without_type(
2199 &mut self,
2200 err: &mut Diag<'_>,
2201 pat: Box<ast::Pat>,
2202 require_name: bool,
2203 first_param: bool,
2204 fn_parse_mode: &crate::parser::FnParseMode,
2205 ) -> Option<Ident> {
2206 if self.check_ident()
2209 && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen)
2210 {
2211 let ident = self.parse_ident_common(true).unwrap();
2213 let span = pat.span.with_hi(ident.span.hi());
2214
2215 err.span_suggestion_verbose(
2216 span,
2217 "declare the type after the parameter binding",
2218 "<identifier>: <type>",
2219 Applicability::HasPlaceholders,
2220 );
2221 return Some(ident);
2222 } else if require_name
2223 && (self.token == token::Comma
2224 || self.token == token::Lt
2225 || self.token == token::CloseParen)
2226 {
2227 let maybe_emit_anon_params_note = |this: &mut Self, err: &mut Diag<'_>| {
2228 let ed = this.token.span.with_neighbor(this.prev_token.span).edition();
2229 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)
2230 && (fn_parse_mode.req_name)(ed, IsDotDotDot::No)
2231 {
2232 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2233 }
2234 };
2235
2236 let (ident, self_sugg, param_sugg, type_sugg, self_span, param_span, type_span) =
2237 match pat.kind {
2238 PatKind::Ident(_, ident, _) => (
2239 ident,
2240 "self: ",
2241 ": TypeName".to_string(),
2242 "_: ",
2243 pat.span.shrink_to_lo(),
2244 pat.span.shrink_to_hi(),
2245 pat.span.shrink_to_lo(),
2246 ),
2247 PatKind::Ref(ref inner_pat, _, _)
2248 if let PatKind::Ref(_, _, _) = &inner_pat.kind
2251 && let PatKind::Path(_, path) = &pat.peel_refs().kind
2252 && let [a, ..] = path.segments.as_slice()
2253 && a.ident.name == kw::SelfLower =>
2254 {
2255 let mut inner = inner_pat;
2256 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];
2257
2258 while let PatKind::Ref(ref inner_type, _, _) = inner.kind {
2259 inner = inner_type;
2260 span_vec.push(inner.span.shrink_to_lo());
2261 }
2262
2263 let span = match span_vec.len() {
2264 0 | 1 => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2266 2 => span_vec[0].until(inner_pat.span.shrink_to_lo()),
2267 _ => span_vec[0].until(span_vec[span_vec.len() - 2].shrink_to_lo()),
2268 };
2269
2270 err.span_suggestion_verbose(
2271 span,
2272 "`self` should be `self`, `&self` or `&mut self`, consider removing extra references",
2273 "".to_string(),
2274 Applicability::MachineApplicable,
2275 );
2276
2277 return None;
2278 }
2279 PatKind::Ref(ref inner_pat, pinned, mutab)
2281 if let PatKind::Ident(_, ident, _) = inner_pat.clone().kind =>
2282 {
2283 let mutab = pinned.prefix_str(mutab);
2284 (
2285 ident,
2286 "self: ",
2287 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: &{1}TypeName", ident, mutab))
})format!("{ident}: &{mutab}TypeName"),
2288 "_: ",
2289 pat.span.shrink_to_lo(),
2290 pat.span,
2291 pat.span.shrink_to_lo(),
2292 )
2293 }
2294 _ => {
2295 if let Some(_) = pat.to_ty() {
2297 err.span_suggestion_verbose(
2298 pat.span.shrink_to_lo(),
2299 "explicitly ignore the parameter name",
2300 "_: ".to_string(),
2301 Applicability::MachineApplicable,
2302 );
2303 maybe_emit_anon_params_note(self, err);
2304 }
2305
2306 return None;
2307 }
2308 };
2309
2310 if first_param
2312 && #[allow(non_exhaustive_omitted_patterns)] match fn_parse_mode.context {
FnContext::Trait | FnContext::Impl => true,
_ => false,
}matches!(
2314 fn_parse_mode.context,
2315 FnContext::Trait | FnContext::Impl
2316 )
2317 {
2318 err.span_suggestion_verbose(
2319 self_span,
2320 "if this is a `self` type, give it a parameter name",
2321 self_sugg,
2322 Applicability::MaybeIncorrect,
2323 );
2324 }
2325 if self.token != token::Lt {
2328 err.span_suggestion_verbose(
2329 param_span,
2330 "if this is a parameter name, give it a type",
2331 param_sugg,
2332 Applicability::HasPlaceholders,
2333 );
2334 }
2335 err.span_suggestion_verbose(
2336 type_span,
2337 "if this is a type, explicitly ignore the parameter name",
2338 type_sugg,
2339 Applicability::MachineApplicable,
2340 );
2341 maybe_emit_anon_params_note(self, err);
2342
2343 return if self.token == token::Lt { None } else { Some(ident) };
2345 }
2346 None
2347 }
2348
2349 #[cold]
2350 pub(super) fn recover_arg_parse(
2351 &mut self,
2352 context: FnContext,
2353 ) -> PResult<'a, (Box<ast::Pat>, Box<ast::Ty>)> {
2354 let pat = self.parse_pat_no_top_alt(Some(Expected::ArgumentName), None)?;
2355 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon))?;
2356 let ty = self.parse_ty()?;
2357 self.dcx().emit_err(PatternMethodParamWithoutBody {
2358 span: pat.span,
2359 target: match context {
2360 FnContext::Trait => "methods without bodies",
2361 FnContext::FunctionPtrType => "function pointer types",
2362 FnContext::ParenthesizedArgumentList => "parenthesized argument list",
2363 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"),
2364 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"),
2365 },
2366 });
2367
2368 let pat = Box::new(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID });
2370 Ok((pat, ty))
2371 }
2372
2373 pub(super) fn recover_bad_self_param(&mut self, mut param: Param) -> PResult<'a, Param> {
2374 let span = param.pat.span;
2375 let guar = self.dcx().emit_err(SelfParamNotFirst { span });
2376 param.ty.kind = TyKind::Err(guar);
2377 Ok(param)
2378 }
2379
2380 pub(super) fn consume_block(
2381 &mut self,
2382 open: ExpTokenPair,
2383 close: ExpTokenPair,
2384 consume_close: ConsumeClosingDelim,
2385 ) {
2386 let mut brace_depth = 0;
2387 loop {
2388 if self.eat(open) {
2389 brace_depth += 1;
2390 } else if self.check(close) {
2391 if brace_depth == 0 {
2392 if let ConsumeClosingDelim::Yes = consume_close {
2393 self.bump();
2397 }
2398 return;
2399 } else {
2400 self.bump();
2401 brace_depth -= 1;
2402 continue;
2403 }
2404 } else if self.token == token::Eof {
2405 return;
2406 } else {
2407 self.bump();
2408 }
2409 }
2410 }
2411
2412 pub(super) fn expected_expression_found(&self) -> Diag<'a> {
2413 let (span, msg) = match (&self.token.kind, self.subparser_name) {
2414 (&token::Eof, Some(origin)) => {
2415 let sp = self.prev_token.span.shrink_to_hi();
2416 (sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected expression, found end of {0}",
origin))
})format!("expected expression, found end of {origin}"))
2417 }
2418 _ => (
2419 self.token.span,
2420 ::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)),
2421 ),
2422 };
2423 let mut err = self.dcx().struct_span_err(span, msg);
2424 let sp = self.psess.source_map().start_point(self.token.span);
2425 if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
2426 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
2427 }
2428 err.span_label(span, "expected expression");
2429 err
2430 }
2431
2432 fn consume_tts(
2433 &mut self,
2434 mut acc: i64, modifier: &[(token::TokenKind, i64)],
2437 ) {
2438 while acc > 0 {
2439 if let Some((_, val)) = modifier.iter().find(|(t, _)| self.token == *t) {
2440 acc += *val;
2441 }
2442 if self.token == token::Eof {
2443 break;
2444 }
2445 self.bump();
2446 }
2447 }
2448
2449 pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut ThinVec<Param>) {
2458 let mut seen_inputs = FxHashSet::default();
2459 for input in fn_inputs.iter_mut() {
2460 let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err(_)) =
2461 (&input.pat.kind, &input.ty.kind)
2462 {
2463 Some(*ident)
2464 } else {
2465 None
2466 };
2467 if let Some(ident) = opt_ident {
2468 if seen_inputs.contains(&ident) {
2469 input.pat.kind = PatKind::Wild;
2470 }
2471 seen_inputs.insert(ident);
2472 }
2473 }
2474 }
2475
2476 pub(super) fn handle_ambiguous_unbraced_const_arg(
2480 &mut self,
2481 args: &mut ThinVec<AngleBracketedArg>,
2482 ) -> PResult<'a, bool> {
2483 let arg = args.pop().unwrap();
2487 let mut err = self.dcx().struct_span_err(
2493 self.token.span,
2494 ::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)),
2495 );
2496 err.span_label(self.token.span, "expected one of `,` or `>`");
2497 match self.recover_const_arg(arg.span(), err) {
2498 Ok(arg) => {
2499 args.push(AngleBracketedArg::Arg(arg));
2500 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
2501 return Ok(true); }
2503 }
2504 Err(err) => {
2505 args.push(arg);
2506 err.delay_as_bug();
2508 }
2509 }
2510 Ok(false) }
2512
2513 fn recover_const_param_decl(&mut self, ty_generics: Option<&Generics>) -> Option<GenericArg> {
2514 let snapshot = self.create_snapshot_for_diagnostic();
2515 let param = match self.parse_const_param(AttrVec::new()) {
2516 Ok(param) => param,
2517 Err(err) => {
2518 err.cancel();
2519 self.restore_snapshot(snapshot);
2520 return None;
2521 }
2522 };
2523
2524 let ident = param.ident.to_string();
2525 let sugg = match (ty_generics, self.psess.source_map().span_to_snippet(param.span())) {
2526 (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => {
2527 Some(match ¶ms[..] {
2528 [] => UnexpectedConstParamDeclarationSugg::AddParam {
2529 impl_generics: *impl_generics,
2530 incorrect_decl: param.span(),
2531 snippet,
2532 ident,
2533 },
2534 [.., generic] => UnexpectedConstParamDeclarationSugg::AppendParam {
2535 impl_generics_end: generic.span().shrink_to_hi(),
2536 incorrect_decl: param.span(),
2537 snippet,
2538 ident,
2539 },
2540 })
2541 }
2542 _ => None,
2543 };
2544 let guar =
2545 self.dcx().emit_err(UnexpectedConstParamDeclaration { span: param.span(), sugg });
2546
2547 let value = self.mk_expr_err(param.span(), guar);
2548 Some(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }))
2549 }
2550
2551 pub(super) fn recover_const_param_declaration(
2552 &mut self,
2553 ty_generics: Option<&Generics>,
2554 ) -> PResult<'a, Option<GenericArg>> {
2555 if let Some(arg) = self.recover_const_param_decl(ty_generics) {
2557 return Ok(Some(arg));
2558 }
2559
2560 let start = self.token.span;
2562 self.bump(); let mut err = UnexpectedConstInGenericParam { span: start, to_remove: None };
2566 if self.check_const_arg() {
2567 err.to_remove = Some(start.until(self.token.span));
2568 self.dcx().emit_err(err);
2569 Ok(Some(GenericArg::Const(self.parse_const_arg()?)))
2570 } else {
2571 let after_kw_const = self.token.span;
2572 self.recover_const_arg(after_kw_const, self.dcx().create_err(err)).map(Some)
2573 }
2574 }
2575
2576 pub(super) fn recover_const_arg(
2582 &mut self,
2583 start: Span,
2584 mut err: Diag<'a>,
2585 ) -> PResult<'a, GenericArg> {
2586 let is_op_or_dot = AssocOp::from_token(&self.token)
2587 .and_then(|op| {
2588 if let AssocOp::Binary(
2589 BinOpKind::Gt
2590 | BinOpKind::Lt
2591 | BinOpKind::Shr
2592 | BinOpKind::Ge
2593 )
2594 | AssocOp::Assign
2597 | AssocOp::AssignOp(_) = op
2598 {
2599 None
2600 } else {
2601 Some(op)
2602 }
2603 })
2604 .is_some()
2605 || self.token == TokenKind::Dot;
2606 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);
2609 if !is_op_or_dot && !was_op {
2610 return Err(err);
2612 }
2613 let snapshot = self.create_snapshot_for_diagnostic();
2614 if is_op_or_dot {
2615 self.bump();
2616 }
2617 match (|| self.parse_expr_res(Restrictions::CONST_EXPR))() {
2618 Ok(expr) => {
2619 if snapshot.token == token::EqEq {
2621 err.span_suggestion_verbose(
2622 snapshot.token.span,
2623 "if you meant to use an associated type binding, replace `==` with `=`",
2624 "=",
2625 Applicability::MaybeIncorrect,
2626 );
2627 let guar = err.emit();
2628 let value = self.mk_expr_err(start.to(expr.span), guar);
2629 return Ok(GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value }));
2630 } else if snapshot.token == token::Colon
2631 && expr.span.lo() == snapshot.token.span.hi()
2632 && #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Path(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Path(..))
2633 {
2634 err.span_suggestion_verbose(
2636 snapshot.token.span,
2637 "write a path separator here",
2638 "::",
2639 Applicability::MaybeIncorrect,
2640 );
2641 let guar = err.emit();
2642 return Ok(GenericArg::Type(
2643 self.mk_ty(start.to(expr.span), TyKind::Err(guar)),
2644 ));
2645 } else if self.token == token::Comma || self.token.kind.should_end_const_arg() {
2646 return Ok(self.dummy_const_arg_needs_braces(err, start.to(expr.span)));
2653 }
2654 }
2655 Err(err) => {
2656 err.cancel();
2657 }
2658 }
2659 self.restore_snapshot(snapshot);
2660 Err(err)
2661 }
2662
2663 pub(crate) fn recover_unbraced_const_arg_that_can_begin_ty(
2667 &mut self,
2668 mut snapshot: SnapshotParser<'a>,
2669 ) -> Option<Box<ast::Expr>> {
2670 match (|| snapshot.parse_expr_res(Restrictions::CONST_EXPR))() {
2671 Ok(expr) if let token::Comma | token::Gt = snapshot.token.kind => {
2674 self.restore_snapshot(snapshot);
2675 Some(expr)
2676 }
2677 Ok(_) => None,
2678 Err(err) => {
2679 err.cancel();
2680 None
2681 }
2682 }
2683 }
2684
2685 pub(super) fn dummy_const_arg_needs_braces(&self, mut err: Diag<'a>, span: Span) -> GenericArg {
2687 err.multipart_suggestion(
2688 "expressions must be enclosed in braces to be used as const generic \
2689 arguments",
2690 ::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())],
2691 Applicability::MaybeIncorrect,
2692 );
2693 let guar = err.emit();
2694 let value = self.mk_expr_err(span, guar);
2695 GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
2696 }
2697
2698 #[cold]
2701 pub(crate) fn recover_colon_colon_in_pat_typo(
2702 &mut self,
2703 mut first_pat: Pat,
2704 expected: Option<Expected>,
2705 ) -> Pat {
2706 if token::Colon != self.token.kind {
2707 return first_pat;
2708 }
2709
2710 let colon_span = self.token.span;
2713 let mut snapshot_pat = self.create_snapshot_for_diagnostic();
2716 let mut snapshot_type = self.create_snapshot_for_diagnostic();
2717
2718 match self.expected_one_of_not_found(&[], &[]) {
2720 Err(mut err) => {
2721 snapshot_pat.bump();
2723 snapshot_type.bump();
2724 match snapshot_pat.parse_pat_no_top_alt(expected, None) {
2725 Err(inner_err) => {
2726 inner_err.cancel();
2727 }
2728 Ok(mut pat) => {
2729 let new_span = first_pat.span.to(pat.span);
2731 let mut show_sugg = false;
2732 match &mut pat.kind {
2734 PatKind::Struct(qself @ None, path, ..)
2735 | PatKind::TupleStruct(qself @ None, path, _)
2736 | PatKind::Path(qself @ None, path) => match &first_pat.kind {
2737 PatKind::Ident(_, ident, _) => {
2738 path.segments.insert(0, PathSegment::from_ident(*ident));
2739 path.span = new_span;
2740 show_sugg = true;
2741 first_pat = pat;
2742 }
2743 PatKind::Path(old_qself, old_path) => {
2744 path.segments = old_path
2745 .segments
2746 .iter()
2747 .cloned()
2748 .chain(take(&mut path.segments))
2749 .collect();
2750 path.span = new_span;
2751 *qself = old_qself.clone();
2752 first_pat = pat;
2753 show_sugg = true;
2754 }
2755 _ => {}
2756 },
2757 PatKind::Ident(BindingMode::NONE, ident, None) => {
2758 match &first_pat.kind {
2759 PatKind::Ident(_, old_ident, _) => {
2760 let path = PatKind::Path(
2761 None,
2762 Path {
2763 span: new_span,
2764 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![
2765 PathSegment::from_ident(*old_ident),
2766 PathSegment::from_ident(*ident),
2767 ],
2768 },
2769 );
2770 first_pat = self.mk_pat(new_span, path);
2771 show_sugg = true;
2772 }
2773 PatKind::Path(old_qself, old_path) => {
2774 let mut segments = old_path.segments.clone();
2775 segments.push(PathSegment::from_ident(*ident));
2776 let path = PatKind::Path(
2777 old_qself.clone(),
2778 Path { span: new_span, segments },
2779 );
2780 first_pat = self.mk_pat(new_span, path);
2781 show_sugg = true;
2782 }
2783 _ => {}
2784 }
2785 }
2786 _ => {}
2787 }
2788 if show_sugg {
2789 err.span_suggestion_verbose(
2790 colon_span.until(self.look_ahead(1, |t| t.span)),
2791 "maybe write a path separator here",
2792 "::",
2793 Applicability::MaybeIncorrect,
2794 );
2795 } else {
2796 first_pat = self.mk_pat(
2797 new_span,
2798 PatKind::Err(
2799 self.dcx()
2800 .span_delayed_bug(colon_span, "recovered bad path pattern"),
2801 ),
2802 );
2803 }
2804 self.restore_snapshot(snapshot_pat);
2805 }
2806 }
2807 match snapshot_type.parse_ty() {
2808 Err(inner_err) => {
2809 inner_err.cancel();
2810 }
2811 Ok(ty) => {
2812 err.span_label(ty.span, "specifying the type of a pattern isn't supported");
2813 self.restore_snapshot(snapshot_type);
2814 let new_span = first_pat.span.to(ty.span);
2815 first_pat =
2816 self.mk_pat(
2817 new_span,
2818 PatKind::Err(self.dcx().span_delayed_bug(
2819 colon_span,
2820 "recovered bad pattern with type",
2821 )),
2822 );
2823 }
2824 }
2825 err.emit();
2826 }
2827 _ => {
2828 }
2830 };
2831 first_pat
2832 }
2833
2834 pub(crate) fn maybe_recover_unexpected_block_label(
2837 &mut self,
2838 loop_header: Option<Span>,
2839 ) -> bool {
2840 if !(self.check_lifetime()
2842 && self.look_ahead(1, |t| *t == token::Colon)
2843 && self.look_ahead(2, |t| *t == token::OpenBrace))
2844 {
2845 return false;
2846 }
2847 let label = self.eat_label().expect("just checked if a label exists");
2848 self.bump(); let span = label.ident.span.to(self.prev_token.span);
2850 let mut diag = self
2851 .dcx()
2852 .struct_span_err(span, "block label not supported here")
2853 .with_span_label(span, "not supported here");
2854 if let Some(loop_header) = loop_header {
2855 diag.multipart_suggestion(
2856 "if you meant to label the loop, move this label before the loop",
2857 ::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![
2858 (label.ident.span.until(self.token.span), String::from("")),
2859 (loop_header.shrink_to_lo(), format!("{}: ", label.ident)),
2860 ],
2861 Applicability::MachineApplicable,
2862 );
2863 } else {
2864 diag.tool_only_span_suggestion(
2865 label.ident.span.until(self.token.span),
2866 "remove this block label",
2867 "",
2868 Applicability::MachineApplicable,
2869 );
2870 }
2871 diag.emit();
2872 true
2873 }
2874
2875 pub(crate) fn maybe_recover_unexpected_comma(
2878 &mut self,
2879 lo: Span,
2880 rt: CommaRecoveryMode,
2881 ) -> PResult<'a, ()> {
2882 if self.token != token::Comma {
2883 return Ok(());
2884 }
2885 self.recover_unexpected_comma(lo, rt)
2886 }
2887
2888 #[cold]
2889 fn recover_unexpected_comma(&mut self, lo: Span, rt: CommaRecoveryMode) -> PResult<'a, ()> {
2890 let comma_span = self.token.span;
2895 self.bump();
2896 if let Err(err) = self.skip_pat_list() {
2897 err.cancel();
2900 }
2901 let seq_span = lo.to(self.prev_token.span);
2902 let mut err = self.dcx().struct_span_err(comma_span, "unexpected `,` in pattern");
2903 err.multipart_suggestion(
2904 ::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!(
2905 "try adding parentheses to match on a tuple{}",
2906 if let CommaRecoveryMode::LikelyTuple = rt { "" } else { "..." },
2907 ),
2908 ::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![
2909 (seq_span.shrink_to_lo(), "(".to_string()),
2910 (seq_span.shrink_to_hi(), ")".to_string()),
2911 ],
2912 Applicability::MachineApplicable,
2913 );
2914 if let CommaRecoveryMode::EitherTupleOrPipe = rt {
2915 err.span_suggestion_verbose(
2916 comma_span,
2917 "...or a vertical bar to match on alternatives",
2918 " |",
2919 Applicability::MachineApplicable,
2920 );
2921 }
2922 Err(err)
2923 }
2924
2925 pub(crate) fn maybe_recover_bounds_doubled_colon(&mut self, ty: &Ty) -> PResult<'a, ()> {
2926 let TyKind::Path(qself, path) = &ty.kind else { return Ok(()) };
2927 let qself_position = qself.as_ref().map(|qself| qself.position);
2928 for (i, segments) in path.segments.windows(2).enumerate() {
2929 if qself_position.is_some_and(|pos| i < pos) {
2930 continue;
2931 }
2932 if let [a, b] = segments {
2933 let (a_span, b_span) = (a.span(), b.span());
2934 let between_span = a_span.shrink_to_hi().to(b_span.shrink_to_lo());
2935 if self.span_to_snippet(between_span).as_deref() == Ok(":: ") {
2936 return Err(self.dcx().create_err(DoubleColonInBound {
2937 span: path.span.shrink_to_hi(),
2938 between: between_span,
2939 }));
2940 }
2941 }
2942 }
2943 Ok(())
2944 }
2945
2946 pub(crate) fn maybe_err_dotdotlt_syntax(&self, maybe_lt: Token, mut err: Diag<'a>) -> Diag<'a> {
2948 if maybe_lt == token::Lt
2949 && (self.expected_token_types.contains(TokenType::Gt)
2950 || #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
token::Literal(..) => true,
_ => false,
}matches!(self.token.kind, token::Literal(..)))
2951 {
2952 err.span_suggestion_verbose(
2953 maybe_lt.span,
2954 "remove the `<` to write an exclusive range",
2955 "",
2956 Applicability::MachineApplicable,
2957 );
2958 }
2959 err
2960 }
2961
2962 pub(super) fn is_vcs_conflict_marker(
2970 &mut self,
2971 long_kind: &TokenKind,
2972 short_kind: &TokenKind,
2973 ) -> bool {
2974 if long_kind == short_kind {
2975 (0..7).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2977 } else {
2978 (0..3).all(|i| self.look_ahead(i, |tok| tok == long_kind))
2980 && self.look_ahead(3, |tok| tok == short_kind || tok == long_kind)
2981 }
2982 }
2983
2984 fn conflict_marker(
2985 &mut self,
2986 long_kind: &TokenKind,
2987 short_kind: &TokenKind,
2988 expected: Option<usize>,
2989 ) -> Option<(Span, usize)> {
2990 if self.is_vcs_conflict_marker(long_kind, short_kind) {
2991 let lo = self.token.span;
2992 if self.psess.source_map().span_to_margin(lo) != Some(0) {
2993 return None;
2994 }
2995 let mut len = 0;
2996 while self.token.kind == *long_kind || self.token.kind == *short_kind {
2997 if self.token.kind.break_two_token_op(1).is_some() {
2998 len += 2;
2999 } else {
3000 len += 1;
3001 }
3002 self.bump();
3003 if expected == Some(len) {
3004 break;
3005 }
3006 }
3007 if expected.is_some() && expected != Some(len) {
3008 return None;
3009 }
3010 return Some((lo.to(self.prev_token.span), len));
3011 }
3012 None
3013 }
3014
3015 pub(super) fn recover_vcs_conflict_marker(&mut self) {
3016 let Some((start, len)) = self.conflict_marker(&TokenKind::Shl, &TokenKind::Lt, None) else {
3018 return;
3019 };
3020 let mut spans = Vec::with_capacity(2);
3021 spans.push(start);
3022 let mut middlediff3 = None;
3024 let mut middle = None;
3026 let mut end = None;
3028 loop {
3029 if self.token == TokenKind::Eof {
3030 break;
3031 }
3032 if let Some((span, _)) =
3033 self.conflict_marker(&TokenKind::OrOr, &TokenKind::Or, Some(len))
3034 {
3035 middlediff3 = Some(span);
3036 }
3037 if let Some((span, _)) =
3038 self.conflict_marker(&TokenKind::EqEq, &TokenKind::Eq, Some(len))
3039 {
3040 middle = Some(span);
3041 }
3042 if let Some((span, _)) =
3043 self.conflict_marker(&TokenKind::Shr, &TokenKind::Gt, Some(len))
3044 {
3045 spans.push(span);
3046 end = Some(span);
3047 break;
3048 }
3049 self.bump();
3050 }
3051
3052 let mut err = self.dcx().struct_span_fatal(spans, "encountered diff marker");
3053 let middle_marker = match middlediff3 {
3054 Some(middlediff3) => {
3056 err.span_label(
3057 middlediff3,
3058 "between this marker and `=======` is the base code (what the two refs \
3059 diverged from)",
3060 );
3061 "|||||||"
3062 }
3063 None => "=======",
3064 };
3065 err.span_label(
3066 start,
3067 ::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!(
3068 "between this marker and `{middle_marker}` is the code that you are merging into",
3069 ),
3070 );
3071
3072 if let Some(middle) = middle {
3073 err.span_label(middle, "between this marker and `>>>>>>>` is the incoming code");
3074 }
3075 if let Some(end) = end {
3076 err.span_label(end, "this marker concludes the conflict region");
3077 }
3078 err.note(
3079 "conflict markers indicate that a merge was started but could not be completed due \
3080 to merge conflicts\n\
3081 to resolve a conflict, keep only the code you want and then delete the lines \
3082 containing conflict markers",
3083 );
3084 err.help(
3085 "if you are in a merge, the top section is the code you already had checked out and \
3086 the bottom section is the new code\n\
3087 if you are in a rebase, the top section is the code being rebased onto and the bottom \
3088 section is the code you had checked out which is being rebased",
3089 );
3090
3091 err.note(
3092 "for an explanation on these markers from the `git` documentation, visit \
3093 <https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_checking_out_conflicts>",
3094 );
3095
3096 err.emit();
3097 }
3098
3099 fn skip_pat_list(&mut self) -> PResult<'a, ()> {
3102 while !self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)) {
3103 self.parse_pat_no_top_alt(None, None)?;
3104 if !self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
3105 return Ok(());
3106 }
3107 }
3108 Ok(())
3109 }
3110 pub(super) fn maybe_type_in_generic_parameter(&mut self, origin_error: Diag<'a>) -> Diag<'a> {
3111 if !self.may_recover() {
3112 return origin_error;
3113 }
3114 self.with_recovery(super::Recovery::Forbidden, |snapshot| {
3115 snapshot.bump();
3116 let lo = snapshot.token.span.shrink_to_lo();
3117
3118 let ty = match snapshot.parse_ty() {
3119 Ok(t) => t,
3120 Err(err) => {
3121 err.cancel();
3122 return origin_error;
3123 }
3124 };
3125 let TyKind::Path(_, path) = ty.kind else {
3126 return origin_error;
3127 };
3128 let Some(GenericArgs::AngleBracketed(AngleBracketedArgs { span: _, ref args })) =
3129 path.segments[0].args
3130 else {
3131 return origin_error;
3132 };
3133
3134 let path_span = path.span;
3135 let mut new_error = snapshot.dcx().create_err(FoundPathInGenerics {
3136 span: path_span,
3137 path: snapshot.span_to_snippet(path_span).unwrap(),
3138 });
3139 new_error.subdiagnostic(SuggestBindTypeParameter { span: lo });
3140 origin_error.cancel();
3141
3142 let params = args
3143 .iter()
3144 .map(|arg| snapshot.span_to_snippet(arg.span()).unwrap())
3145 .collect::<Vec<_>>()
3146 .join(", ");
3147 new_error.subdiagnostic(SuggestIntroduceTypeParameter {
3148 span: path_span,
3149 parameters: params,
3150 });
3151 new_error
3152 })
3153 }
3154}