1use std::fmt::Write;
2use std::mem;
3
4use ast::token::IdentKind;
5use rustc_ast as ast;
6use rustc_ast::ast::*;
7use rustc_ast::token::{self, Delimiter, MetaVarKind, TokenKind};
8use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
9use rustc_ast::util::case::Case;
10use rustc_ast_pretty::pprust;
11use rustc_errors::codes::*;
12use rustc_errors::{Applicability, PResult, StashKey, msg, struct_span_code_err};
13use rustc_span::edit_distance::edit_distance;
14use rustc_span::edition::Edition;
15use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
16use thin_vec::{ThinVec, thin_vec};
17use tracing::debug;
18
19use super::diagnostics::ConsumeClosingDelim;
20use super::{
21 AllowConstBlockItems, AttrWrapper, ExpTokenPair, FnContext, FnParseMode, FollowedByType,
22 ForceCollect, IsDotDotDot, Parser, PathStyle, Recovered, Trailing, UsePreAttrPos,
23};
24use crate::diagnostics::{
25 self, MacroExpandsToAdtField, UseDoubleColonSuggestion, UseRegularStructSuggestion,
26};
27use crate::exp;
28
29impl<'a> Parser<'a> {
30 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
32 let (attrs, items, spans) = self.parse_mod(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eof,
token_type: crate::parser::token_type::TokenType::Eof,
}exp!(Eof))?;
33 Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
34 }
35
36 fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemKind> {
38 let safety = self.parse_safety(Case::Sensitive);
39 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Mod,
token_type: crate::parser::token_type::TokenType::KwMod,
}exp!(Mod))?;
40 let ident = self.parse_ident()?;
41 let mod_kind = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
42 ModKind::Unloaded
43 } else {
44 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))?;
45 let (inner_attrs, items, inner_span) = self.parse_mod(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
46 attrs.extend(inner_attrs);
47 ModKind::Loaded(items, Inline::Yes, inner_span)
48 };
49 Ok(ItemKind::Mod(safety, ident, mod_kind))
50 }
51
52 pub fn parse_mod(
57 &mut self,
58 term: ExpTokenPair,
59 ) -> PResult<'a, (AttrVec, ThinVec<Box<Item>>, ModSpans)> {
60 let lo = self.token.span;
61 let attrs = self.parse_inner_attributes()?;
62
63 let post_attr_lo = self.token.span;
64 let mut items: ThinVec<Box<_>> = ThinVec::new();
65
66 loop {
69 while self.maybe_consume_incorrect_semicolon(items.last().map(|x| &**x)) {} let Some(item) = self.parse_item(ForceCollect::No, AllowConstBlockItems::Yes)? else {
71 break;
72 };
73 items.push(item);
74 }
75
76 if !self.eat(term) {
77 let token_str = super::token_descr(&self.token);
78 if !self.maybe_consume_incorrect_semicolon(items.last().map(|x| &**x)) {
79 let is_let = self.token.is_keyword(kw::Let);
80 let is_let_mut = is_let && self.look_ahead(1, |t| t.is_keyword(kw::Mut));
81 let let_has_ident = is_let && !is_let_mut && self.is_kw_followed_by_ident(kw::Let);
82
83 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected item, found {0}",
token_str))
})format!("expected item, found {token_str}");
84 let mut err = self.dcx().struct_span_err(self.token.span, msg);
85
86 let label = if is_let {
87 "`let` cannot be used for global variables"
88 } else {
89 "expected item"
90 };
91 err.span_label(self.token.span, label);
92
93 if is_let {
94 if is_let_mut {
95 err.help("consider using `static` and a `Mutex` instead of `let mut`");
96 } else if let_has_ident {
97 err.span_suggestion_short(
98 self.token.span,
99 "consider using `static` or `const` instead of `let`",
100 "static",
101 Applicability::MaybeIncorrect,
102 );
103 } else {
104 err.help("consider using `static` or `const` instead of `let`");
105 }
106 }
107 err.note("for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>");
108 return Err(err);
109 }
110 }
111
112 let inject_use_span = post_attr_lo.with_hi(post_attr_lo.lo());
113 let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
114 Ok((attrs, items, mod_spans))
115 }
116}
117
118enum ReuseKind {
119 Path,
120 Impl,
121}
122
123impl<'a> Parser<'a> {
124 pub fn parse_item(
125 &mut self,
126 force_collect: ForceCollect,
127 allow_const_block_items: AllowConstBlockItems,
128 ) -> PResult<'a, Option<Box<Item>>> {
129 let fn_parse_mode = FnParseMode {
130 req_name: |_, _| true,
131 context: FnContext::Free,
132 req_body: true,
133 allow_const_params: true,
134 };
135 self.parse_item_(fn_parse_mode, force_collect, allow_const_block_items)
136 .map(|i| i.map(Box::new))
137 }
138
139 fn parse_item_(
140 &mut self,
141 fn_parse_mode: FnParseMode,
142 force_collect: ForceCollect,
143 const_block_items_allowed: AllowConstBlockItems,
144 ) -> PResult<'a, Option<Item>> {
145 self.recover_vcs_conflict_marker();
146 let attrs = self.parse_outer_attributes()?;
147 self.recover_vcs_conflict_marker();
148 self.parse_item_common(
149 attrs,
150 true,
151 false,
152 fn_parse_mode,
153 force_collect,
154 const_block_items_allowed,
155 )
156 }
157
158 pub(super) fn parse_item_common(
159 &mut self,
160 attrs: AttrWrapper,
161 mac_allowed: bool,
162 attrs_allowed: bool,
163 fn_parse_mode: FnParseMode,
164 force_collect: ForceCollect,
165 allow_const_block_items: AllowConstBlockItems,
166 ) -> PResult<'a, Option<Item>> {
167 if let Some(item) = self.eat_metavar_seq(MetaVarKind::Item, |this| {
168 this.parse_item(ForceCollect::Yes, allow_const_block_items)
169 }) {
170 let mut item = item.expect("an actual item");
171 attrs.prepend_to_nt_inner(&mut item.attrs);
172 return Ok(Some(*item));
173 }
174
175 self.collect_tokens(None, attrs, force_collect, |this, mut attrs| {
176 let lo = this.token.span;
177 let vis = this.parse_visibility(FollowedByType::No)?;
178 let mut def = this.parse_defaultness();
179 let kind = this.parse_item_kind(
180 &mut attrs,
181 mac_allowed,
182 allow_const_block_items,
183 lo,
184 &vis,
185 &mut def,
186 fn_parse_mode,
187 Case::Sensitive,
188 )?;
189 if let Some(kind) = kind {
190 this.error_on_unconsumed_default(def, &kind);
191 let span = lo.to(this.prev_token.span);
192 let id = DUMMY_NODE_ID;
193 let item = Item { attrs, id, kind, vis, span, tokens: None };
194 return Ok((Some(item), Trailing::No, UsePreAttrPos::No));
195 }
196
197 if !#[allow(non_exhaustive_omitted_patterns)] match vis.kind {
VisibilityKind::Inherited => true,
_ => false,
}matches!(vis.kind, VisibilityKind::Inherited) {
199 let vis_str = pprust::vis_to_string(&vis).trim_end().to_string();
200 let mut err = this.dcx().create_err(diagnostics::VisibilityNotFollowedByItem {
201 span: vis.span,
202 vis: vis_str,
203 });
204 if let Some((ident, _)) = this.token.ident()
205 && !ident.is_used_keyword()
206 && let Some((similar_kw, is_incorrect_case)) = ident
207 .name
208 .find_similar(&rustc_span::symbol::used_keywords(|| ident.span.edition()))
209 {
210 err.subdiagnostic(diagnostics::MisspelledKw {
211 similar_kw: similar_kw.to_string(),
212 span: ident.span,
213 is_incorrect_case,
214 });
215 }
216 err.emit();
217 }
218
219 if let Defaultness::Default(span) = def {
220 this.dcx().emit_err(diagnostics::DefaultNotFollowedByItem { span });
221 } else if let Defaultness::Final(span) = def {
222 this.dcx().emit_err(diagnostics::FinalNotFollowedByItem { span });
223 }
224
225 if !attrs_allowed {
226 this.recover_attrs_no_item(&attrs)?;
227 }
228 Ok((None, Trailing::No, UsePreAttrPos::No))
229 })
230 }
231
232 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
234 match def {
235 Defaultness::Default(span) => {
236 self.dcx().emit_err(diagnostics::InappropriateDefault {
237 span,
238 article: kind.article(),
239 descr: kind.descr(),
240 });
241 }
242 Defaultness::Final(span) => {
243 self.dcx().emit_err(diagnostics::InappropriateFinal {
244 span,
245 article: kind.article(),
246 descr: kind.descr(),
247 });
248 }
249 Defaultness::Implicit => (),
250 }
251 }
252
253 fn parse_item_kind(
255 &mut self,
256 attrs: &mut AttrVec,
257 macros_allowed: bool,
258 allow_const_block_items: AllowConstBlockItems,
259 lo: Span,
260 vis: &Visibility,
261 def: &mut Defaultness,
262 fn_parse_mode: FnParseMode,
263 case: Case,
264 ) -> PResult<'a, Option<ItemKind>> {
265 let check_pub = def == &Defaultness::Implicit;
266 let mut def_ = || mem::replace(def, Defaultness::Implicit);
267
268 let info = if !self.is_use_closure() && self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Use,
token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use), case) {
269 self.parse_use_item()?
270 } else if self.check_fn_front_matter(check_pub, case) {
271 let defaultness = def_();
273 if let Defaultness::Default(span) = defaultness {
274 self.psess.gated_spans.gate(sym::min_specialization, span);
278 self.psess.gated_spans.ungate_last(sym::specialization, span);
279 }
280 let (ident, sig, generics, contract, body) =
281 self.parse_fn(attrs, fn_parse_mode, lo, vis, case)?;
282 ItemKind::Fn(Box::new(Fn {
283 defaultness,
284 ident,
285 sig,
286 generics,
287 contract,
288 body,
289 define_opaque: None,
290 eii_impl: None,
291 }))
292 } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Extern,
token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern), case) {
293 if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Crate,
token_type: crate::parser::token_type::TokenType::KwCrate,
}exp!(Crate), case) {
294 self.parse_item_extern_crate()?
296 } else {
297 self.parse_item_foreign_mod(attrs, Safety::Default)?
299 }
300 } else if self.is_unsafe_foreign_mod() {
301 let safety = self.parse_safety(Case::Sensitive);
303 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Extern,
token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern))?;
304 self.parse_item_foreign_mod(attrs, safety)?
305 } else if let Some(safety) = self.parse_global_static_front_matter(case) {
306 let mutability = self.parse_mutability();
308 self.parse_static_item(safety, mutability)?
309 } else if self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Trait,
token_type: crate::parser::token_type::TokenType::KwTrait,
}exp!(Trait), case) || self.check_trait_front_matter() {
310 self.parse_item_trait(attrs, lo)?
312 } else if self.check_impl_frontmatter(0) {
313 self.parse_item_impl(attrs, def_(), false)?
315 } else if let AllowConstBlockItems::Yes | AllowConstBlockItems::DoesNotMatter =
316 allow_const_block_items
317 && self.check_inline_const(0)
318 {
319 if let AllowConstBlockItems::DoesNotMatter = allow_const_block_items {
321 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/item.rs:321",
"rustc_parse::parser::item", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/item.rs"),
::tracing_core::__macro_support::Option::Some(321u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser::item"),
::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!("Parsing a const block item that does not matter: {0:?}",
self.token.span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Parsing a const block item that does not matter: {:?}", self.token.span);
322 };
323 ItemKind::ConstBlock(self.parse_const_block_item()?)
324 } else if let Const::Yes(const_span) = self.parse_constness(case) {
325 self.recover_const_mut(const_span);
327 self.recover_missing_kw_before_item()?;
328 let (ident, generics, ty, body) = self.parse_const_item(const_span)?;
329 ItemKind::Const(Box::new(ConstItem {
330 defaultness: def_(),
331 ident,
332 generics,
333 ty,
334 body,
335 define_opaque: None,
336 }))
337 } else if let Some(kind) = self.is_reuse_item() {
338 self.parse_item_delegation(attrs, def_(), kind)?
339 } else if self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Mod,
token_type: crate::parser::token_type::TokenType::KwMod,
}exp!(Mod), case)
340 || self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe), case) && self.is_keyword_ahead(1, &[kw::Mod])
341 {
342 self.parse_item_mod(attrs)?
344 } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Type,
token_type: crate::parser::token_type::TokenType::KwType,
}exp!(Type), case) {
345 self.parse_type_alias(def_())?
347 } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Enum,
token_type: crate::parser::token_type::TokenType::KwEnum,
}exp!(Enum), case) {
348 self.parse_item_enum()?
350 } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Struct,
token_type: crate::parser::token_type::TokenType::KwStruct,
}exp!(Struct), case) {
351 self.parse_item_struct()?
353 } else if self.is_kw_followed_by_ident(kw::Union) {
354 self.bump(); self.parse_item_union()?
357 } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Macro,
token_type: crate::parser::token_type::TokenType::KwMacro,
}exp!(Macro), case) {
358 self.parse_item_decl_macro(lo)?
360 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
361 self.parse_item_macro_rules(vis, has_bang)?
363 } else if self.isnt_macro_invocation()
364 && (self.token.is_ident_named(sym::import)
365 || self.token.is_ident_named(sym::using)
366 || self.token.is_ident_named(sym::include)
367 || self.token.is_ident_named(sym::require))
368 {
369 return self.recover_import_as_use();
370 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
371 self.recover_missing_kw_before_item()?;
372 return Ok(None);
373 } else if self.isnt_macro_invocation() && case == Case::Sensitive {
374 _ = def_;
375
376 return self.parse_item_kind(
378 attrs,
379 macros_allowed,
380 allow_const_block_items,
381 lo,
382 vis,
383 def,
384 fn_parse_mode,
385 Case::Insensitive,
386 );
387 } else if macros_allowed && self.check_path() {
388 let is_field_in_trait = fn_parse_mode.context == FnContext::Trait
391 && self.token.is_path_start()
392 && self.look_ahead(1, |t| t.kind == token::Colon);
393 if is_field_in_trait {
394 return self.recover_field_in_trait();
395 }
396 if self.isnt_macro_invocation() {
397 self.recover_missing_kw_before_item()?;
398 }
399 ItemKind::MacCall(Box::new(self.parse_item_macro(vis)?))
401 } else {
402 return Ok(None);
403 };
404 Ok(Some(info))
405 }
406
407 fn recover_import_as_use(&mut self) -> PResult<'a, Option<ItemKind>> {
408 let span = self.token.span;
409 let token_name = super::token_descr(&self.token);
410 let snapshot = self.create_snapshot_for_diagnostic();
411 self.bump();
412 match self.parse_use_item() {
413 Ok(u) => {
414 self.dcx().emit_err(diagnostics::RecoverImportAsUse { span, token_name });
415 Ok(Some(u))
416 }
417 Err(e) => {
418 e.cancel();
419 self.restore_snapshot(snapshot);
420 Ok(None)
421 }
422 }
423 }
424
425 fn recover_field_in_trait(&mut self) -> PResult<'a, Option<ItemKind>> {
426 let ident_span = self.token.span;
427 let ident_str = pprust::token_to_string(&self.token).into_owned();
428 let is_self = self.token.is_keyword(kw::SelfLower);
429
430 self.bump(); self.bump(); let ty_str = match self.parse_ty() {
434 Ok(ty) => pprust::ty_to_string(&ty),
435 Err(e) => {
436 e.cancel();
437 String::from("Type")
438 }
439 };
440 let _ = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
442 let _ = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi));
443
444 let span = ident_span.to(self.prev_token.span);
445 let sugg = if is_self {
446 diagnostics::FieldNotAllowedInTraitSugg::SelfReceiver { ty: ty_str }
447 } else {
448 diagnostics::FieldNotAllowedInTraitSugg::Method { ident: ident_str, ty: ty_str }
449 };
450 let err = self.dcx().create_err(diagnostics::FieldNotAllowedInTrait { span, sugg });
451 Err(err)
452 }
453
454 fn parse_use_item(&mut self) -> PResult<'a, ItemKind> {
455 let use_token_span = self.prev_token.span;
456 let tree = self.parse_use_tree(use_token_span, None)?;
457 if let Err(mut e) = self.expect_semi() {
458 match tree.kind {
459 UseTreeKind::Glob(_) => {
460 e.note("the wildcard token must be last on the path");
461 }
462 UseTreeKind::Nested { .. } => {
463 e.note("glob-like brace syntax must be last on the path");
464 }
465 _ => (),
466 }
467 return Err(e);
468 }
469 Ok(ItemKind::Use(tree))
470 }
471
472 pub(super) fn is_path_start_item(&mut self) -> bool {
474 self.is_kw_followed_by_ident(kw::Union) || self.is_reuse_item().is_some() || self.check_trait_front_matter() || self.is_async_fn() || #[allow(non_exhaustive_omitted_patterns)] match self.is_macro_rules_item() {
IsMacroRulesItem::Yes { .. } => true,
_ => false,
}matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) }
480
481 fn is_reuse_item(&mut self) -> Option<ReuseKind> {
482 if !self.token.is_keyword(kw::Reuse) {
483 return None;
484 }
485
486 if self.look_ahead(1, |t| t.is_path_start() && *t != token::PathSep) {
488 Some(ReuseKind::Path)
489 } else if self.check_impl_frontmatter(1) {
490 Some(ReuseKind::Impl)
491 } else {
492 None
493 }
494 }
495
496 fn isnt_macro_invocation(&mut self) -> bool {
498 self.check_ident() && self.look_ahead(1, |t| *t != token::Bang && *t != token::PathSep)
499 }
500
501 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
504 let is_pub = self.prev_token.is_keyword(kw::Pub);
505 let is_const = self.prev_token.is_keyword(kw::Const);
506 let ident_span = self.token.span;
507 let span = if is_pub { self.prev_token.span.to(ident_span) } else { ident_span };
508 let insert_span = ident_span.shrink_to_lo();
509
510 let ident = if let Some(ident) = self.token.non_reserved_ident()
511 && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen))
512 && self.look_ahead(1, |t| {
513 #[allow(non_exhaustive_omitted_patterns)] match t.kind {
token::Lt | token::OpenBrace | token::OpenParen => true,
_ => false,
}matches!(t.kind, token::Lt | token::OpenBrace | token::OpenParen)
514 }) {
515 self.bump(); ident
517 } else {
518 return Ok(());
519 };
520
521 let mut found_generics = false;
522 if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Lt,
token_type: crate::parser::token_type::TokenType::Lt,
}exp!(Lt)) {
523 found_generics = true;
524 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)]);
525 self.bump(); }
527
528 let err = if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
529 if self.look_ahead(1, |t| *t == token::CloseBrace) {
531 Some(diagnostics::MissingKeywordForItemDefinition::EnumOrStruct { span })
533 } else if self.look_ahead(2, |t| *t == token::Colon)
534 || self.look_ahead(3, |t| *t == token::Colon)
535 {
536 Some(diagnostics::MissingKeywordForItemDefinition::Struct {
538 span,
539 insert_span,
540 ident,
541 })
542 } else {
543 Some(diagnostics::MissingKeywordForItemDefinition::Enum {
544 span,
545 insert_span,
546 ident,
547 })
548 }
549 } else if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
550 self.bump(); let is_method = self.recover_self_param();
553
554 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::Yes);
555
556 let err = if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::RArrow,
token_type: crate::parser::token_type::TokenType::RArrow,
}exp!(RArrow)) || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
557 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)]);
558 self.bump(); 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);
560 if is_method {
561 diagnostics::MissingKeywordForItemDefinition::Method {
562 span,
563 insert_span,
564 ident,
565 }
566 } else {
567 diagnostics::MissingKeywordForItemDefinition::Function {
568 span,
569 insert_span,
570 ident,
571 }
572 }
573 } else if is_pub && self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
574 diagnostics::MissingKeywordForItemDefinition::Struct { span, insert_span, ident }
575 } else {
576 diagnostics::MissingKeywordForItemDefinition::Ambiguous {
577 span,
578 subdiag: if found_generics {
579 None
580 } else if let Ok(snippet) = self.span_to_snippet(ident_span) {
581 Some(diagnostics::AmbiguousMissingKwForItemSub::SuggestMacro {
582 span: ident_span,
583 snippet,
584 })
585 } else {
586 Some(diagnostics::AmbiguousMissingKwForItemSub::HelpMacro)
587 },
588 }
589 };
590 Some(err)
591 } else if found_generics {
592 Some(diagnostics::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: None })
593 } else {
594 None
595 };
596
597 if let Some(err) = err { Err(self.dcx().create_err(err)) } else { Ok(()) }
598 }
599
600 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
602 let path = self.parse_path(PathStyle::Mod)?; self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; match self.parse_delim_args() {
605 Ok(args) => {
607 self.eat_semi_for_macro_if_needed(&args, Some(&path));
608 self.complain_if_pub_macro(vis, false);
609 Ok(MacCall { path, args })
610 }
611
612 Err(mut err) => {
613 if self.token.is_ident()
615 && let [segment] = path.segments.as_slice()
616 && edit_distance("macro_rules", &segment.ident.to_string(), 2).is_some()
617 {
618 err.span_suggestion_verbose(
619 path.span,
620 "perhaps you meant to define a macro",
621 "macro_rules",
622 Applicability::MachineApplicable,
623 );
624 }
625 Err(err)
626 }
627 }
628 }
629
630 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
632 let ([start @ end] | [start, .., end]) = attrs else {
633 return Ok(());
634 };
635 let msg = if end.is_doc_comment() {
636 "expected item after doc comment"
637 } else {
638 "expected item after attributes"
639 };
640 let mut err = self.dcx().struct_span_err(end.span, msg);
641 if end.is_doc_comment() {
642 err.span_label(end.span, "this doc comment doesn't document anything");
643 } else {
644 err.span_label(end.span, "expected an item after this");
645 if self.token == TokenKind::Semi {
646 err.span_suggestion_verbose(
647 self.token.span,
648 "remove the semicolon after the attribute",
649 "",
650 Applicability::MaybeIncorrect,
651 );
652 }
653 }
654 if let [.., penultimate, _] = attrs {
655 err.span_label(start.span.to(penultimate.span), "other attributes here");
656 }
657 Err(err)
658 }
659
660 fn is_async_fn(&self) -> bool {
661 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
662 }
663
664 fn parse_polarity(&mut self) -> ast::ImplPolarity {
665 if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) && self.look_ahead(1, |t| t.can_begin_type()) {
667 self.psess.gated_spans.gate(sym::negative_impls, self.token.span);
668 self.bump(); ast::ImplPolarity::Negative(self.prev_token.span)
670 } else {
671 ast::ImplPolarity::Positive
672 }
673 }
674
675 fn parse_item_impl(
690 &mut self,
691 attrs: &mut AttrVec,
692 defaultness: Defaultness,
693 is_reuse: bool,
694 ) -> PResult<'a, ItemKind> {
695 let constness = self.parse_constness(Case::Sensitive);
696 let safety = self.parse_safety(Case::Sensitive);
697 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Impl,
token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl))?;
698 let mut generics_snapshot = None;
699 let mut generics = if self.choose_generics_over_qpath(0) {
701 self.parse_generics()?
702 } else {
703 if self.look_ahead(0, |t| t == &token::Lt)
706 && self.look_ahead(1, |t| t.is_ident())
707 && self.look_ahead(2, |t| t == &token::Lt)
708 {
709 generics_snapshot = Some(self.create_snapshot_for_diagnostic());
710 }
711
712 let mut generics = Generics::default();
713 generics.span = self.prev_token.span.shrink_to_hi();
716 generics
717 };
718
719 if let Const::Yes(span) = constness {
720 self.psess.gated_spans.gate(sym::const_trait_impl, span);
721 }
722
723 if (self.token_uninterpolated_span().at_least_rust_2018()
725 && self.token.is_keyword(kw::Async))
726 || self.is_kw_followed_by_ident(kw::Async)
727 {
728 self.bump();
729 self.dcx().emit_err(diagnostics::AsyncImpl { span: self.prev_token.span });
730 }
731
732 let polarity = self.parse_polarity();
733
734 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
736 {
737 let span = self.prev_token.span.between(self.token.span);
738 return Err(self.dcx().create_err(diagnostics::MissingTraitInTraitImpl {
739 span,
740 for_span: span.to(self.token.span),
741 }));
742 } else {
743 self.parse_ty_with_generics_recovery(&generics).map_err(|e| {
744 let Some(mut snapshot) = generics_snapshot else {
745 return e;
746 };
747 snapshot.maybe_type_in_generic_parameter(e)
748 })?
749 };
750 let has_for = self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::For,
token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For));
752 let missing_for_span = self.prev_token.span.between(self.token.span);
753
754 let ty_second = if self.token == token::DotDot {
755 self.bump(); Some(self.mk_ty(self.prev_token.span, TyKind::Dummy))
762 } else if has_for || self.token.can_begin_type() {
763 Some(self.parse_ty()?)
764 } else {
765 None
766 };
767
768 generics.where_clause = self.parse_where_clause()?;
769
770 let impl_items = if is_reuse {
771 Default::default()
772 } else {
773 self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?
774 };
775
776 let (of_trait, self_ty) = match ty_second {
777 Some(ty_second) => {
778 if !has_for {
780 self.dcx()
781 .emit_err(diagnostics::MissingForInTraitImpl { span: missing_for_span });
782 }
783
784 let ty_first = *ty_first;
785 let path = match ty_first.kind {
786 TyKind::Path(None, path) => path,
788 other => {
789 if let TyKind::ImplTrait(_, bounds) = other
790 && let [bound] = bounds.as_slice()
791 && let GenericBound::Trait(poly_trait_ref) = bound
792 {
793 let extra_impl_kw = ty_first.span.until(bound.span());
797 self.dcx().emit_err(diagnostics::ExtraImplKeywordInTraitImpl {
798 extra_impl_kw,
799 impl_trait_span: ty_first.span,
800 });
801 poly_trait_ref.trait_ref.path.clone()
802 } else {
803 return Err(self.dcx().create_err(
804 diagnostics::ExpectedTraitInTraitImplFoundType {
805 span: ty_first.span,
806 },
807 ));
808 }
809 }
810 };
811 let trait_ref = TraitRef { path, ref_id: ty_first.id };
812
813 let of_trait =
814 Some(Box::new(TraitImplHeader { defaultness, safety, polarity, trait_ref }));
815 (of_trait, ty_second)
816 }
817 None => {
818 let self_ty = ty_first;
819 let error = |modifier, modifier_name, modifier_span| {
820 self.dcx().create_err(diagnostics::TraitImplModifierInInherentImpl {
821 span: self_ty.span,
822 modifier,
823 modifier_name,
824 modifier_span,
825 self_ty: self_ty.span,
826 })
827 };
828
829 if let Safety::Unsafe(span) = safety {
830 error("unsafe", "unsafe", span).with_code(E0197).emit();
831 }
832 if let ImplPolarity::Negative(span) = polarity {
833 error("!", "negative", span).emit();
834 }
835 if let Defaultness::Default(def_span) = defaultness {
836 error("default", "default", def_span).emit();
837 }
838 if let Const::Yes(span) = constness {
839 self.psess.gated_spans.gate(sym::const_trait_impl, span);
840 }
841 (None, self_ty)
842 }
843 };
844
845 Ok(ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, constness }))
846 }
847
848 fn parse_item_delegation(
849 &mut self,
850 attrs: &mut AttrVec,
851 defaultness: Defaultness,
852 kind: ReuseKind,
853 ) -> PResult<'a, ItemKind> {
854 let span = self.token.span;
855 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Reuse,
token_type: crate::parser::token_type::TokenType::KwReuse,
}exp!(Reuse))?;
856
857 let item_kind = match kind {
858 ReuseKind::Path => self.parse_path_like_delegation(),
859 ReuseKind::Impl => self.parse_impl_delegation(span, attrs, defaultness),
860 }?;
861
862 self.psess.gated_spans.gate(sym::fn_delegation, span.to(self.prev_token.span));
863
864 Ok(item_kind)
865 }
866
867 fn parse_delegation_body(&mut self) -> PResult<'a, Option<Box<Block>>> {
868 Ok(if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
869 Some(self.parse_block()?)
870 } else {
871 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))?;
872 None
873 })
874 }
875
876 fn parse_impl_delegation(
877 &mut self,
878 span: Span,
879 attrs: &mut AttrVec,
880 defaultness: Defaultness,
881 ) -> PResult<'a, ItemKind> {
882 let mut impl_item = self.parse_item_impl(attrs, defaultness, true)?;
883 let ItemKind::Impl(Impl { items, of_trait, .. }) = &mut impl_item else { ::core::panicking::unreachable_default_msg()unreachable!() };
884
885 let until_expr_span = span.to(self.prev_token.span);
886
887 let Some(of_trait) = of_trait else {
888 return Err(self
889 .dcx()
890 .create_err(diagnostics::ImplReuseInherentImpl { span: until_expr_span }));
891 };
892
893 let body = self.parse_delegation_body()?;
894 let whole_reuse_span = span.to(self.prev_token.span);
895
896 items.push(Box::new(AssocItem {
897 id: DUMMY_NODE_ID,
898 attrs: Default::default(),
899 span: whole_reuse_span,
900 tokens: None,
901 vis: Visibility { kind: VisibilityKind::Inherited, span: whole_reuse_span },
902 kind: AssocItemKind::DelegationMac(Box::new(DelegationMac {
903 qself: None,
904 prefix: of_trait.trait_ref.path.clone(),
905 suffixes: DelegationSuffixes::Glob(whole_reuse_span),
906 body,
907 })),
908 }));
909
910 Ok(impl_item)
911 }
912
913 fn parse_path_like_delegation(&mut self) -> PResult<'a, ItemKind> {
914 let (qself, path) = if self.eat_lt() {
915 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
916 (Some(qself), path)
917 } else {
918 (None, self.parse_path(PathStyle::Expr)?)
919 };
920
921 let rename = |this: &mut Self| {
922 Ok(if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::As,
token_type: crate::parser::token_type::TokenType::KwAs,
}exp!(As)) { Some(this.parse_ident()?) } else { None })
923 };
924
925 Ok(if self.eat_path_sep() {
926 let suffixes = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
927 DelegationSuffixes::Glob(self.prev_token.span)
928 } else {
929 let parse_suffix = |p: &mut Self| Ok((p.parse_path_segment_ident()?, rename(p)?));
930 DelegationSuffixes::List(
931 self.parse_delim_comma_seq(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), parse_suffix)?.0,
932 )
933 };
934
935 ItemKind::DelegationMac(Box::new(DelegationMac {
936 qself,
937 prefix: path,
938 suffixes,
939 body: self.parse_delegation_body()?,
940 }))
941 } else {
942 let rename = rename(self)?;
943 let ident = rename.unwrap_or_else(|| path.segments.last().unwrap().ident);
944
945 ItemKind::Delegation(Box::new(Delegation {
946 id: DUMMY_NODE_ID,
947 qself,
948 path,
949 ident,
950 rename,
951 body: self.parse_delegation_body()?,
952 source: DelegationSource::Single,
953 }))
954 })
955 }
956
957 fn parse_item_list<T>(
958 &mut self,
959 attrs: &mut AttrVec,
960 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
961 ) -> PResult<'a, ThinVec<T>> {
962 let open_brace_span = self.token.span;
963
964 if self.token == TokenKind::Semi {
966 self.dcx().emit_err(diagnostics::UseEmptyBlockNotSemi { span: self.token.span });
967 self.bump();
968 return Ok(ThinVec::new());
969 }
970
971 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))?;
972 attrs.extend(self.parse_inner_attributes()?);
973
974 let mut items = ThinVec::new();
975 while !self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
976 if self.recover_doc_comment_before_brace() {
977 continue;
978 }
979 self.recover_vcs_conflict_marker();
980 match parse_item(self) {
981 Ok(None) => {
982 let mut is_unnecessary_semicolon = (self.token == token::Semi
983 && self.prev_token == token::Semi)
984 || !items.is_empty()
985 && self
1003 .span_to_snippet(self.prev_token.span)
1004 .is_ok_and(|snippet| snippet == "}")
1005 && self.token == token::Semi;
1006 let mut semicolon_span = self.token.span;
1007 if !is_unnecessary_semicolon {
1008 is_unnecessary_semicolon =
1010 self.token == token::OpenBrace && self.prev_token == token::Semi;
1011 semicolon_span = self.prev_token.span;
1012 }
1013 let non_item_span = self.token.span;
1015 let is_let = self.token.is_keyword(kw::Let);
1016
1017 let mut err =
1018 self.dcx().struct_span_err(non_item_span, "non-item in item list");
1019 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);
1020 if is_let {
1021 err.span_suggestion_verbose(
1022 non_item_span,
1023 "consider using `const` instead of `let` for associated const",
1024 "const",
1025 Applicability::MachineApplicable,
1026 );
1027 } else {
1028 err.span_label(open_brace_span, "item list starts here")
1029 .span_label(non_item_span, "non-item starts here")
1030 .span_label(self.prev_token.span, "item list ends here");
1031 }
1032 if is_unnecessary_semicolon {
1033 err.span_suggestion_verbose(
1034 semicolon_span,
1035 "consider removing this semicolon",
1036 "",
1037 Applicability::MaybeIncorrect,
1038 );
1039 }
1040 err.emit();
1041 break;
1042 }
1043 Ok(Some(item)) => items.extend(item),
1044 Err(err) => {
1045 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);
1046 err.with_span_label(
1047 open_brace_span,
1048 "while parsing this item list starting here",
1049 )
1050 .with_span_label(self.prev_token.span, "the item list ends here")
1051 .emit();
1052 break;
1053 }
1054 }
1055 }
1056 Ok(items)
1057 }
1058
1059 fn recover_doc_comment_before_brace(&mut self) -> bool {
1061 if let token::DocComment(..) = self.token.kind {
1062 if self.look_ahead(1, |tok| tok == &token::CloseBrace) {
1063 {
self.dcx().struct_span_err(self.token.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("found a documentation comment that doesn\'t document anything"))
})).with_code(E0584)
}struct_span_code_err!(
1065 self.dcx(),
1066 self.token.span,
1067 E0584,
1068 "found a documentation comment that doesn't document anything",
1069 )
1070 .with_span_label(self.token.span, "this doc comment doesn't document anything")
1071 .with_help(
1072 "doc comments must come before what they document, if a comment was \
1073 intended use `//`",
1074 )
1075 .emit();
1076 self.bump();
1077 return true;
1078 }
1079 }
1080 false
1081 }
1082
1083 fn parse_defaultness(&mut self) -> Defaultness {
1085 if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Default,
token_type: crate::parser::token_type::TokenType::KwDefault,
}exp!(Default))
1089 && self.look_ahead(1, |t| t.non_raw_ident().is_some_and(|i| i.name != kw::As))
1090 {
1091 self.psess.gated_spans.gate(sym::specialization, self.token.span);
1092 self.bump(); Defaultness::Default(self.prev_token_uninterpolated_span())
1094 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Final,
token_type: crate::parser::token_type::TokenType::KwFinal,
}exp!(Final)) {
1095 self.psess.gated_spans.gate(sym::final_associated_functions, self.prev_token.span);
1096 Defaultness::Final(self.prev_token_uninterpolated_span())
1097 } else {
1098 Defaultness::Implicit
1099 }
1100 }
1101
1102 fn check_trait_front_matter(&mut self) -> bool {
1104 const SUFFIXES: &[&[Symbol]] = &[
1105 &[kw::Trait],
1106 &[kw::Auto, kw::Trait],
1107 &[kw::Unsafe, kw::Trait],
1108 &[kw::Unsafe, kw::Auto, kw::Trait],
1109 &[kw::Const, kw::Trait],
1110 &[kw::Const, kw::Auto, kw::Trait],
1111 &[kw::Const, kw::Unsafe, kw::Trait],
1112 &[kw::Const, kw::Unsafe, kw::Auto, kw::Trait],
1113 ];
1114 if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Impl,
token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl)) && self.look_ahead(1, |t| t == &token::OpenParen) {
1116 if self.is_keyword_ahead(2, &[kw::In]) {
1118 return true;
1119 }
1120 if self.is_keyword_ahead(2, &[kw::Crate, kw::SelfLower, kw::Super])
1122 && self.look_ahead(3, |t| t == &token::CloseParen)
1123 && SUFFIXES.iter().any(|suffix| {
1124 suffix.iter().enumerate().all(|(i, kw)| self.is_keyword_ahead(i + 4, &[*kw]))
1125 })
1126 {
1127 return true;
1128 }
1129 SUFFIXES.iter().any(|suffix| {
1131 suffix.iter().enumerate().all(|(i, kw)| {
1132 self.tree_look_ahead(i + 2, |t| {
1133 if let TokenTree::Token(token, _) = t {
1134 token.is_keyword(*kw)
1135 } else {
1136 false
1137 }
1138 })
1139 .unwrap_or(false)
1140 })
1141 })
1142 } else {
1143 SUFFIXES.iter().any(|suffix| {
1144 suffix.iter().enumerate().all(|(i, kw)| {
1145 if i == 0 {
1147 match *kw {
1148 kw::Const => self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)),
1149 kw::Unsafe => self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe)),
1150 kw::Auto => self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Auto,
token_type: crate::parser::token_type::TokenType::KwAuto,
}exp!(Auto)),
1151 kw::Trait => self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Trait,
token_type: crate::parser::token_type::TokenType::KwTrait,
}exp!(Trait)),
1152 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1153 }
1154 } else {
1155 self.is_keyword_ahead(i, &[*kw])
1156 }
1157 })
1158 })
1159 }
1160 }
1161
1162 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemKind> {
1164 let impl_restriction = self.parse_impl_restriction()?;
1165 let constness = self.parse_constness(Case::Sensitive);
1166 if let Const::Yes(span) = constness {
1167 self.psess.gated_spans.gate(sym::const_trait_impl, span);
1168 }
1169 let safety = self.parse_safety(Case::Sensitive);
1170 let is_auto = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Auto,
token_type: crate::parser::token_type::TokenType::KwAuto,
}exp!(Auto)) {
1172 self.psess.gated_spans.gate(sym::auto_traits, self.prev_token.span);
1173 IsAuto::Yes
1174 } else {
1175 IsAuto::No
1176 };
1177
1178 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Trait,
token_type: crate::parser::token_type::TokenType::KwTrait,
}exp!(Trait))?;
1179 let ident = self.parse_ident()?;
1180 let mut generics = self.parse_generics()?;
1181
1182 let had_colon = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon));
1184 let span_at_colon = self.prev_token.span;
1185 let bounds = if had_colon { self.parse_generic_bounds()? } else { ThinVec::new() };
1186
1187 let span_before_eq = self.prev_token.span;
1188 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1189 if had_colon {
1191 let span = span_at_colon.to(span_before_eq);
1192 self.dcx().emit_err(diagnostics::BoundsNotAllowedOnTraitAliases { span });
1193 }
1194
1195 let bounds = self.parse_generic_bounds()?;
1196 generics.where_clause = self.parse_where_clause()?;
1197 self.expect_semi()?;
1198
1199 let whole_span = lo.to(self.prev_token.span);
1200 if is_auto == IsAuto::Yes {
1201 self.dcx().emit_err(diagnostics::TraitAliasCannotBeAuto { span: whole_span });
1202 }
1203 if let Safety::Unsafe(_) = safety {
1204 self.dcx().emit_err(diagnostics::TraitAliasCannotBeUnsafe { span: whole_span });
1205 }
1206 if let RestrictionKind::Restricted { .. } = impl_restriction.kind {
1207 self.dcx()
1208 .emit_err(diagnostics::TraitAliasCannotBeImplRestricted { span: whole_span });
1209 }
1210
1211 self.psess.gated_spans.gate(sym::trait_alias, whole_span);
1212
1213 Ok(ItemKind::TraitAlias(Box::new(TraitAlias { constness, ident, generics, bounds })))
1214 } else {
1215 generics.where_clause = self.parse_where_clause()?;
1217 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
1218 Ok(ItemKind::Trait(Box::new(Trait {
1219 impl_restriction,
1220 constness,
1221 is_auto,
1222 safety,
1223 ident,
1224 generics,
1225 bounds,
1226 items,
1227 })))
1228 }
1229 }
1230
1231 pub fn parse_impl_item(
1232 &mut self,
1233 force_collect: ForceCollect,
1234 ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1235 let fn_parse_mode = FnParseMode {
1236 req_name: |_, _| true,
1237 context: FnContext::Impl,
1238 req_body: true,
1239 allow_const_params: true,
1240 };
1241 self.parse_assoc_item(fn_parse_mode, force_collect)
1242 }
1243
1244 pub fn parse_trait_item(
1245 &mut self,
1246 force_collect: ForceCollect,
1247 ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1248 let fn_parse_mode = FnParseMode {
1249 req_name: |edition, _| edition >= Edition::Edition2018,
1250 context: FnContext::Trait,
1251 req_body: false,
1252 allow_const_params: true,
1253 };
1254 self.parse_assoc_item(fn_parse_mode, force_collect)
1255 }
1256
1257 fn parse_assoc_item(
1259 &mut self,
1260 fn_parse_mode: FnParseMode,
1261 force_collect: ForceCollect,
1262 ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1263 Ok(self
1264 .parse_item_(
1265 fn_parse_mode,
1266 force_collect,
1267 AllowConstBlockItems::DoesNotMatter, )?
1269 .map(|Item { attrs, id, span, vis, kind, tokens }| {
1270 let kind = match AssocItemKind::try_from(kind) {
1271 Ok(kind) => kind,
1272 Err(kind) => match kind {
1273 ItemKind::Static(StaticItem {
1274 ident,
1275 ty,
1276 safety: _,
1277 mutability: _,
1278 expr,
1279 define_opaque,
1280 eii_impl: _,
1281 }) => {
1282 self.dcx()
1283 .emit_err(diagnostics::AssociatedStaticItemNotAllowed { span });
1284 AssocItemKind::Const(Box::new(ConstItem {
1285 defaultness: Defaultness::Implicit,
1286 ident,
1287 generics: Generics::default(),
1288 ty,
1289 body: expr,
1290 define_opaque,
1291 }))
1292 }
1293 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
1294 },
1295 };
1296 Some(Box::new(Item { attrs, id, span, vis, kind, tokens }))
1297 }))
1298 }
1299
1300 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemKind> {
1306 let ident = self.parse_ident()?;
1307 let mut generics = self.parse_generics()?;
1308
1309 let bounds =
1311 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) { self.parse_generic_bounds()? } else { ThinVec::new() };
1312 generics.where_clause = self.parse_where_clause()?;
1313
1314 let ty = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) { Some(self.parse_ty()?) } else { None };
1315
1316 let after_where_clause = self.parse_where_clause()?;
1317
1318 self.expect_semi()?;
1319
1320 Ok(ItemKind::TyAlias(Box::new(TyAlias {
1321 defaultness,
1322 ident,
1323 generics,
1324 after_where_clause,
1325 bounds,
1326 ty,
1327 })))
1328 }
1329
1330 fn parse_use_tree<'b>(
1340 &mut self,
1341 use_token_span: Span,
1342 use_path: Option<&'b UsePathList<'b>>,
1343 ) -> PResult<'a, UseTree> {
1344 let lo = self.token.span;
1345
1346 let mut prefix = ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo() };
1347 let kind =
1348 if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) || self.is_import_coupler() {
1349 let mod_sep_ctxt = self.token.span.ctxt();
1351 if self.eat_path_sep() {
1352 prefix
1353 .segments
1354 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1355 }
1356
1357 self.parse_use_tree_glob_or_nested(use_token_span, use_path)?
1358 } else {
1359 prefix = self.parse_path(PathStyle::Mod)?;
1361
1362 if self.eat_path_sep() {
1363 let use_path = UsePathList { elements: &prefix.segments, prev: use_path };
1364 self.parse_use_tree_glob_or_nested(use_token_span, Some(&use_path))?
1365 } else {
1366 while self.eat_noexpect(&token::Colon) {
1368 self.dcx().emit_err(diagnostics::SingleColonImportPath {
1369 span: self.prev_token.span,
1370 });
1371
1372 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1374 prefix.span = lo.to(self.prev_token.span);
1375 }
1376
1377 UseTreeKind::Simple(self.parse_rename()?)
1378 }
1379 };
1380
1381 Ok(UseTree { prefix, kind })
1382 }
1383
1384 fn parse_use_tree_glob_or_nested<'b>(
1386 &mut self,
1387 use_token_span: Span,
1388 use_path: Option<&'b UsePathList<'b>>,
1389 ) -> PResult<'a, UseTreeKind> {
1390 Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Star,
token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
1391 UseTreeKind::Glob(self.prev_token.span)
1392 } else {
1393 let lo = self.token.span;
1394 UseTreeKind::Nested {
1395 items: self.parse_use_tree_list(use_token_span, use_path)?,
1396 span: lo.to(self.prev_token.span),
1397 }
1398 })
1399 }
1400
1401 fn parse_use_tree_list<'b>(
1407 &mut self,
1408 use_token_span: Span,
1409 prefix: Option<&'b UsePathList<'b>>,
1410 ) -> PResult<'a, ThinVec<UseTreeAndId>> {
1411 self.parse_delim_comma_seq(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), |p| {
1412 p.recover_vcs_conflict_marker();
1413
1414 let mut attr_span = None;
1415 let attrs = p.parse_outer_attributes()?;
1416 if !attrs.is_empty() {
1417 let raw_attrs = attrs.take_for_recovery(&p.psess);
1418 attr_span =
1419 Some(raw_attrs.first().unwrap().span.to(raw_attrs.last().unwrap().span));
1420 }
1421
1422 let use_tree = p.parse_use_tree(use_token_span, prefix)?;
1423
1424 if let Some(attr_span) = attr_span {
1425 p.emit_error_attr_in_use_tree(use_token_span, prefix, use_tree.span(), attr_span);
1426 }
1427
1428 Ok(UseTreeAndId { inner: use_tree, id: DUMMY_NODE_ID })
1429 })
1430 .map(|(r, _)| r)
1431 }
1432
1433 fn emit_error_attr_in_use_tree(
1434 &self,
1435 use_token_span: Span,
1436 mut prefix: Option<&UsePathList<'_>>,
1437 use_tree_span: Span,
1438 attr_span: Span,
1439 ) {
1440 let Ok(attr) = self.psess.source_map().span_to_snippet(attr_span) else { return };
1441
1442 let prefix: Vec<_> = {
1443 let mut tmp = Vec::new();
1444 while let Some(prefix_) = prefix {
1445 tmp.push(prefix_.elements);
1446 prefix = prefix_.prev;
1447 }
1448 tmp.reverse();
1449 tmp.into_iter().flatten().collect()
1450 };
1451
1452 let prefix: String = prefix
1453 .iter()
1454 .map(|seg| if seg.ident.name == kw::PathRoot { "" } else { seg.ident.as_str() })
1455 .intersperse("::")
1456 .collect();
1457
1458 let mut comma_reached = false;
1459 let Ok(tree_span) = self.psess.source_map().span_extend_while(use_tree_span, |c| {
1460 if comma_reached {
1461 return false;
1462 }
1463 comma_reached = c == ',';
1464 c.is_whitespace() || comma_reached
1465 }) else {
1466 return;
1467 };
1468
1469 let Ok(use_tree) = self.psess.source_map().span_to_snippet(use_tree_span) else { return };
1470
1471 let code = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nuse {1}::{2};\n", attr,
prefix, use_tree))
})format!("{attr}\nuse {prefix}::{use_tree};\n");
1473
1474 self.dcx().emit_err(crate::diagnostics::AttrInUseTree {
1475 attr_span,
1476 sub: Some(crate::diagnostics::AttrInUseTreeSugg {
1477 use_lo: use_token_span.shrink_to_lo(),
1478 attr_span,
1479 tree_span,
1480 code,
1481 }),
1482 });
1483 }
1484
1485 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1486 if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::As,
token_type: crate::parser::token_type::TokenType::KwAs,
}exp!(As)) {
1487 self.parse_ident_or_underscore().map(Some)
1488 } else {
1489 Ok(None)
1490 }
1491 }
1492
1493 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1494 if let Some(ident @ Ident { name: kw::Underscore, .. }) = self.token.non_raw_ident() {
1495 self.bump();
1496 Ok(ident)
1497 } else {
1498 self.parse_ident()
1499 }
1500 }
1501
1502 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemKind> {
1511 let orig_ident = self.parse_crate_name_with_dashes()?;
1513 let (orig_name, item_ident) = if let Some(rename) = self.parse_rename()? {
1514 (Some(orig_ident.name), rename)
1515 } else {
1516 (None, orig_ident)
1517 };
1518 self.expect_semi()?;
1519 Ok(ItemKind::ExternCrate(orig_name, item_ident))
1520 }
1521
1522 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1523 let ident = if self.token.is_keyword(kw::SelfLower) {
1524 self.parse_path_segment_ident()
1525 } else {
1526 self.parse_ident()
1527 }?;
1528
1529 let dash = crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Minus,
token_type: crate::parser::token_type::TokenType::Minus,
}exp!(Minus);
1530 if self.token != dash.tok {
1531 return Ok(ident);
1532 }
1533
1534 let mut dashes = ::alloc::vec::Vec::new()vec![];
1536 let mut idents = ::alloc::vec::Vec::new()vec![];
1537 while self.eat(dash) {
1538 dashes.push(self.prev_token.span);
1539 idents.push(self.parse_ident()?);
1540 }
1541
1542 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1543 let mut fixed_name = ident.name.to_string();
1544 for part in idents {
1545 fixed_name.write_fmt(format_args!("_{0}", part.name))write!(fixed_name, "_{}", part.name).unwrap();
1546 }
1547
1548 self.dcx().emit_err(diagnostics::ExternCrateNameWithDashes {
1549 span: fixed_name_sp,
1550 sugg: diagnostics::ExternCrateNameWithDashesSugg { dashes },
1551 });
1552
1553 Ok(Ident::from_str_and_span(&fixed_name, fixed_name_sp))
1554 }
1555
1556 fn parse_item_foreign_mod(
1567 &mut self,
1568 attrs: &mut AttrVec,
1569 mut safety: Safety,
1570 ) -> PResult<'a, ItemKind> {
1571 let extern_span = self.prev_token_uninterpolated_span();
1572 let abi = self.parse_abi(); if safety == Safety::Default
1575 && self.token.is_keyword(kw::Unsafe)
1576 && self.look_ahead(1, |t| *t == token::OpenBrace)
1577 {
1578 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)).unwrap_err().emit();
1579 safety = Safety::Unsafe(self.token.span);
1580 let _ = self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe));
1581 }
1582 Ok(ItemKind::ForeignMod(ast::ForeignMod {
1583 extern_span,
1584 safety,
1585 abi,
1586 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1587 }))
1588 }
1589
1590 pub fn parse_foreign_item(
1592 &mut self,
1593 force_collect: ForceCollect,
1594 ) -> PResult<'a, Option<Option<Box<ForeignItem>>>> {
1595 let fn_parse_mode = FnParseMode {
1596 req_name: |_, is_dot_dot_dot| is_dot_dot_dot == IsDotDotDot::No,
1597 context: FnContext::Free,
1598 req_body: false,
1599 allow_const_params: false,
1600 };
1601 Ok(self
1602 .parse_item_(
1603 fn_parse_mode,
1604 force_collect,
1605 AllowConstBlockItems::DoesNotMatter, )?
1607 .map(|Item { attrs, id, span, vis, kind, tokens }| {
1608 let kind = match ForeignItemKind::try_from(kind) {
1609 Ok(kind) => kind,
1610 Err(kind) => match kind {
1611 ItemKind::Const(ConstItem { ident, ty, body, .. }) => {
1612 let const_span = Some(span.with_hi(ident.span.lo()))
1613 .filter(|span| span.can_be_used_for_suggestions());
1614 self.dcx().emit_err(diagnostics::ExternItemCannotBeConst {
1615 ident_span: ident.span,
1616 const_span,
1617 });
1618 ForeignItemKind::Static(Box::new(StaticItem {
1619 ident,
1620 ty,
1621 mutability: Mutability::Not,
1622 expr: body,
1623 safety: Safety::Default,
1624 define_opaque: None,
1625 eii_impl: None,
1626 }))
1627 }
1628 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1629 },
1630 };
1631 Some(Box::new(Item { attrs, id, span, vis, kind, tokens }))
1632 }))
1633 }
1634
1635 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &'static str) -> Option<T> {
1636 let span = self.psess.source_map().guess_head_span(span);
1638 let descr = kind.descr();
1639 let help = match kind {
1640 ItemKind::DelegationMac(DelegationMac {
1641 suffixes: DelegationSuffixes::Glob(_),
1642 ..
1643 }) => false,
1644 _ => true,
1645 };
1646 self.dcx().emit_err(diagnostics::BadItemKind { span, descr, ctx, help });
1647 None
1648 }
1649
1650 fn is_use_closure(&self) -> bool {
1651 if self.token.is_keyword(kw::Use) {
1652 self.look_ahead(1, |token| {
1654 let dist =
1656 if token.is_keyword(kw::Move) || token.is_keyword(kw::Async) { 2 } else { 1 };
1657
1658 self.look_ahead(dist, |token| #[allow(non_exhaustive_omitted_patterns)] match token.kind {
token::Or | token::OrOr => true,
_ => false,
}matches!(token.kind, token::Or | token::OrOr))
1659 })
1660 } else {
1661 false
1662 }
1663 }
1664
1665 pub(super) fn is_unsafe_foreign_mod(&self) -> bool {
1666 if !self.token.is_keyword(kw::Unsafe) {
1668 return false;
1669 }
1670 if !self.is_keyword_ahead(1, &[kw::Extern]) {
1672 return false;
1673 }
1674
1675 let n = if self.look_ahead(2, |t| t.can_begin_string_literal()) { 3 } else { 2 };
1677
1678 self.tree_look_ahead(n, |t| #[allow(non_exhaustive_omitted_patterns)] match t {
TokenTree::Delimited(_, _, Delimiter::Brace, _) => true,
_ => false,
}matches!(t, TokenTree::Delimited(_, _, Delimiter::Brace, _)))
1683 == Some(true)
1684 }
1685
1686 fn parse_global_static_front_matter(&mut self, case: Case) -> Option<Safety> {
1687 let is_global_static = if self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Static,
token_type: crate::parser::token_type::TokenType::KwStatic,
}exp!(Static), case) {
1688 !self.look_ahead(1, |token| {
1690 if token.is_keyword_case(kw::Move, case) || token.is_keyword_case(kw::Use, case) {
1691 return true;
1692 }
1693 #[allow(non_exhaustive_omitted_patterns)] match token.kind {
token::Or | token::OrOr => true,
_ => false,
}matches!(token.kind, token::Or | token::OrOr)
1694 })
1695 } else {
1696 (self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe), case)
1698 || self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Safe,
token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe), case))
1699 && self.look_ahead(1, |t| t.is_keyword_case(kw::Static, case))
1700 };
1701
1702 if is_global_static {
1703 let safety = self.parse_safety(case);
1704 let _ = self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Static,
token_type: crate::parser::token_type::TokenType::KwStatic,
}exp!(Static), case);
1705 Some(safety)
1706 } else {
1707 None
1708 }
1709 }
1710
1711 fn recover_const_mut(&mut self, const_span: Span) {
1713 if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Mut,
token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {
1714 let span = self.prev_token.span;
1715 self.dcx()
1716 .emit_err(diagnostics::ConstGlobalCannotBeMutable { ident_span: span, const_span });
1717 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Let,
token_type: crate::parser::token_type::TokenType::KwLet,
}exp!(Let)) {
1718 let span = self.prev_token.span;
1719 self.dcx()
1720 .emit_err(diagnostics::ConstLetMutuallyExclusive { span: const_span.to(span) });
1721 }
1722 }
1723
1724 fn parse_const_block_item(&mut self) -> PResult<'a, ConstBlockItem> {
1725 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1726 let const_span = self.prev_token.span;
1727 self.psess.gated_spans.gate(sym::const_block_items, const_span);
1728 let block = self.parse_block()?;
1729 Ok(ConstBlockItem { id: DUMMY_NODE_ID, span: const_span.to(block.span), block })
1730 }
1731
1732 fn parse_static_item(
1739 &mut self,
1740 safety: Safety,
1741 mutability: Mutability,
1742 ) -> PResult<'a, ItemKind> {
1743 let ident = self.parse_ident()?;
1744
1745 if self.token == TokenKind::Lt && self.may_recover() {
1746 let generics = self.parse_generics()?;
1747 self.dcx().emit_err(diagnostics::StaticWithGenerics { span: generics.span });
1748 }
1749
1750 let ty = match (self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)), self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) | self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))) {
1753 (true, false) => self.parse_ty()?,
1754 (colon, _) => self.recover_missing_global_item_type(colon, Some(mutability)),
1757 };
1758
1759 let expr = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) { Some(self.parse_expr()?) } else { None };
1760
1761 self.expect_semi()?;
1762
1763 let item =
1764 StaticItem { ident, ty, safety, mutability, expr, define_opaque: None, eii_impl: None };
1765 Ok(ItemKind::Static(Box::new(item)))
1766 }
1767
1768 fn parse_const_item(
1777 &mut self,
1778 const_span: Span,
1779 ) -> PResult<'a, (Ident, Generics, Box<Ty>, Option<Box<Expr>>)> {
1780 let ident = self.parse_ident_or_underscore()?;
1781
1782 let mut generics = self.parse_generics()?;
1783
1784 if !generics.span.is_empty() {
1787 self.psess.gated_spans.gate(sym::generic_const_items, generics.span);
1788 }
1789
1790 let ty = match (
1793 self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)),
1794 self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) | self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) | self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Where,
token_type: crate::parser::token_type::TokenType::KwWhere,
}exp!(Where)),
1795 ) {
1796 (true, false) => self.parse_ty()?,
1797 (colon, _) => self.recover_missing_global_item_type(colon, None),
1799 };
1800
1801 let before_where_clause =
1804 if self.may_recover() { self.parse_where_clause()? } else { WhereClause::default() };
1805
1806 let rhs = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) { Some(self.parse_expr()?) } else { None };
1807
1808 let after_where_clause = self.parse_where_clause()?;
1809
1810 if before_where_clause.has_where_token
1814 && let Some(rhs) = &rhs
1815 {
1816 self.dcx().emit_err(diagnostics::WhereClauseBeforeConstBody {
1817 span: before_where_clause.span,
1818 name: ident.span,
1819 body: rhs.span,
1820 sugg: if !after_where_clause.has_where_token {
1821 self.psess.source_map().span_to_snippet(rhs.span).ok().map(|body_s| {
1822 diagnostics::WhereClauseBeforeConstBodySugg {
1823 left: before_where_clause.span.shrink_to_lo(),
1824 snippet: body_s,
1825 right: before_where_clause.span.shrink_to_hi().to(rhs.span),
1826 }
1827 })
1828 } else {
1829 None
1832 },
1833 });
1834 }
1835
1836 let mut predicates = before_where_clause.predicates;
1843 predicates.extend(after_where_clause.predicates);
1844 let where_clause = WhereClause {
1845 has_where_token: before_where_clause.has_where_token
1846 || after_where_clause.has_where_token,
1847 predicates,
1848 span: if after_where_clause.has_where_token {
1849 after_where_clause.span
1850 } else {
1851 before_where_clause.span
1852 },
1853 };
1854
1855 if where_clause.has_where_token {
1856 self.psess.gated_spans.gate(sym::generic_const_items, where_clause.span);
1857 }
1858
1859 generics.where_clause = where_clause;
1860
1861 if let Some(rhs) = self.try_recover_const_missing_semi(&rhs, const_span) {
1862 return Ok((ident, generics, ty, Some(rhs)));
1863 }
1864 self.expect_semi()?;
1865
1866 Ok((ident, generics, ty, rhs))
1867 }
1868
1869 fn recover_missing_global_item_type(
1872 &mut self,
1873 colon_present: bool,
1874 m: Option<Mutability>,
1875 ) -> Box<Ty> {
1876 let kind = match m {
1879 Some(Mutability::Mut) => "static mut",
1880 Some(Mutability::Not) => "static",
1881 None => "const",
1882 };
1883
1884 let colon = match colon_present {
1885 true => "",
1886 false => ":",
1887 };
1888
1889 let span = self.prev_token.span.shrink_to_hi();
1890 let err = self.dcx().create_err(diagnostics::MissingConstType { span, colon, kind });
1891 err.stash(span, StashKey::ItemNoType);
1892
1893 Box::new(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID })
1896 }
1897
1898 fn parse_item_enum(&mut self) -> PResult<'a, ItemKind> {
1900 if self.token.is_keyword(kw::Struct) {
1901 let span = self.prev_token.span.to(self.token.span);
1902 let err = diagnostics::EnumStructMutuallyExclusive { span };
1903 if self.look_ahead(1, |t| t.is_ident()) {
1904 self.bump();
1905 self.dcx().emit_err(err);
1906 } else {
1907 return Err(self.dcx().create_err(err));
1908 }
1909 }
1910
1911 let prev_span = self.prev_token.span;
1912 let ident = self.parse_ident()?;
1913 let mut generics = self.parse_generics()?;
1914 generics.where_clause = self.parse_where_clause()?;
1915
1916 let (variants, _) = if self.token == TokenKind::Semi {
1918 self.dcx().emit_err(diagnostics::UseEmptyBlockNotSemi { span: self.token.span });
1919 self.bump();
1920 (::thin_vec::ThinVec::new()thin_vec![], Trailing::No)
1921 } else {
1922 self.parse_delim_comma_seq(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), |p| {
1923 if p.recover_inner_attributes()? && p.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp![CloseBrace]) {
1924 return Ok(None);
1925 }
1926 p.parse_enum_variant(ident.span)
1927 })
1928 .map_err(|mut err| {
1929 err.span_label(ident.span, "while parsing this enum");
1930 if self.prev_token.is_non_reserved_ident() && self.token == token::Colon {
1932 let snapshot = self.create_snapshot_for_diagnostic();
1933 self.bump();
1934 match self.parse_ty() {
1935 Ok(_) => {
1936 err.span_suggestion_verbose(
1937 prev_span,
1938 "perhaps you meant to use `struct` here",
1939 "struct",
1940 Applicability::MaybeIncorrect,
1941 );
1942 }
1943 Err(e) => {
1944 e.cancel();
1945 }
1946 }
1947 self.restore_snapshot(snapshot);
1948 }
1949 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1950 self.bump(); err
1952 })?
1953 };
1954
1955 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1956 Ok(ItemKind::Enum(ident, generics, enum_definition))
1957 }
1958
1959 fn parse_enum_variant(&mut self, span: Span) -> PResult<'a, Option<Variant>> {
1960 self.recover_vcs_conflict_marker();
1961 let variant_attrs = self.parse_outer_attributes()?;
1962 self.recover_vcs_conflict_marker();
1963 let help = "enum variants can be `Variant`, `Variant = <integer>`, \
1964 `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`";
1965 self.collect_tokens(None, variant_attrs, ForceCollect::No, |this, variant_attrs| {
1966 let vlo = this.token.span;
1967
1968 let vis = this.parse_visibility(FollowedByType::No)?;
1969 if !this.recover_nested_adt_item(kw::Enum)? {
1970 return Ok((None, Trailing::No, UsePreAttrPos::No));
1971 }
1972 let ident = this.parse_field_ident("enum", vlo)?;
1973
1974 if this.token == token::Bang {
1975 if let Err(err) = this.unexpected() {
1976 err.with_note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("macros cannot expand to enum variants"))msg!("macros cannot expand to enum variants")).emit();
1977 }
1978
1979 this.bump();
1980 this.parse_delim_args()?;
1981
1982 return Ok((None, Trailing::from(this.token == token::Comma), UsePreAttrPos::No));
1983 }
1984
1985 let struct_def = if this.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
1986 let (fields, recovered) =
1988 match this.parse_record_struct_body("struct", ident.span, false) {
1989 Ok((fields, recovered)) => (fields, recovered),
1990 Err(mut err) => {
1991 if this.token == token::Colon {
1992 return Err(err);
1994 }
1995 this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1996 this.bump(); err.span_label(span, "while parsing this enum");
1998 err.help(help);
1999 let guar = err.emit_err();
2000 (::thin_vec::ThinVec::new()thin_vec![], Recovered::Yes(guar))
2001 }
2002 };
2003 VariantData::Struct { fields, recovered }
2004 } else if this.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
2005 let body = match this.parse_tuple_struct_body() {
2006 Ok(body) => body,
2007 Err(mut err) => {
2008 if this.token == token::Colon {
2009 return Err(err);
2011 }
2012 this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
2013 this.bump(); err.span_label(span, "while parsing this enum");
2015 err.help(help);
2016 err.emit();
2017 ::thin_vec::ThinVec::new()thin_vec![]
2018 }
2019 };
2020 VariantData::Tuple(body, DUMMY_NODE_ID)
2021 } else {
2022 VariantData::Unit(DUMMY_NODE_ID)
2023 };
2024
2025 let disr_expr =
2026 if this.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) { Some(this.parse_expr_anon_const()?) } else { None };
2027
2028 let span = vlo.to(this.prev_token.span);
2029 if ident.name == kw::Underscore {
2030 this.psess.gated_spans.gate(sym::unnamed_enum_variants, span);
2031 }
2032 let vr = ast::Variant {
2033 ident,
2034 vis,
2035 id: DUMMY_NODE_ID,
2036 attrs: variant_attrs,
2037 data: struct_def,
2038 disr_expr,
2039 span,
2040 is_placeholder: false,
2041 };
2042
2043 Ok((Some(vr), Trailing::from(this.token == token::Comma), UsePreAttrPos::No))
2044 })
2045 .map_err(|mut err| {
2046 err.help(help);
2047 err
2048 })
2049 }
2050
2051 fn parse_item_struct(&mut self) -> PResult<'a, ItemKind> {
2053 let ident = self.parse_ident()?;
2054
2055 let mut generics = self.parse_generics()?;
2056
2057 let vdata = if self.token.is_keyword(kw::Where) {
2072 let tuple_struct_body;
2073 (generics.where_clause, tuple_struct_body) =
2074 self.parse_struct_where_clause(ident, generics.span)?;
2075
2076 if let Some(body) = tuple_struct_body {
2077 let body = VariantData::Tuple(body, DUMMY_NODE_ID);
2079 self.expect_semi()?;
2080 body
2081 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
2082 VariantData::Unit(DUMMY_NODE_ID)
2084 } else {
2085 let (fields, recovered) = self.parse_record_struct_body(
2087 "struct",
2088 ident.span,
2089 generics.where_clause.has_where_token,
2090 )?;
2091 VariantData::Struct { fields, recovered }
2092 }
2093 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
2095 VariantData::Unit(DUMMY_NODE_ID)
2096 } else if self.token == token::OpenBrace {
2098 let (fields, recovered) = self.parse_record_struct_body(
2099 "struct",
2100 ident.span,
2101 generics.where_clause.has_where_token,
2102 )?;
2103 VariantData::Struct { fields, recovered }
2104 } else if self.token == token::OpenParen {
2106 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
2107 generics.where_clause = self.parse_where_clause()?;
2108 self.expect_semi()?;
2109 body
2110 } else {
2111 let err = diagnostics::UnexpectedTokenAfterStructName::new(self.token.span, self.token);
2112 return Err(self.dcx().create_err(err));
2113 };
2114
2115 Ok(ItemKind::Struct(ident, generics, vdata))
2116 }
2117
2118 fn parse_item_union(&mut self) -> PResult<'a, ItemKind> {
2120 let ident = self.parse_ident()?;
2121
2122 let mut generics = self.parse_generics()?;
2123
2124 let vdata = if self.token.is_keyword(kw::Where) {
2125 generics.where_clause = self.parse_where_clause()?;
2126 let (fields, recovered) = self.parse_record_struct_body(
2127 "union",
2128 ident.span,
2129 generics.where_clause.has_where_token,
2130 )?;
2131 VariantData::Struct { fields, recovered }
2132 } else if self.token == token::OpenBrace {
2133 let (fields, recovered) = self.parse_record_struct_body(
2134 "union",
2135 ident.span,
2136 generics.where_clause.has_where_token,
2137 )?;
2138 VariantData::Struct { fields, recovered }
2139 } else {
2140 let token_str = super::token_descr(&self.token);
2141 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `where` or `{{` after union name, found {0}",
token_str))
})format!("expected `where` or `{{` after union name, found {token_str}");
2142 let mut err = self.dcx().struct_span_err(self.token.span, msg);
2143 err.span_label(self.token.span, "expected `where` or `{` after union name");
2144 return Err(err);
2145 };
2146
2147 Ok(ItemKind::Union(ident, generics, vdata))
2148 }
2149
2150 pub(crate) fn parse_record_struct_body(
2155 &mut self,
2156 adt_ty: &str,
2157 ident_span: Span,
2158 parsed_where: bool,
2159 ) -> PResult<'a, (ThinVec<FieldDef>, Recovered)> {
2160 let mut fields = ThinVec::new();
2161 let mut recovered = Recovered::No;
2162 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2163 while self.token != token::CloseBrace {
2164 if self.recover_inner_attributes()? && self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp![CloseBrace]) {
2165 break;
2166 }
2167 match self.parse_field_def(adt_ty, ident_span) {
2168 Ok(field) => {
2169 fields.push(field);
2170 }
2171 Err(mut err) => {
2172 self.consume_block(
2173 crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace),
2174 crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace),
2175 ConsumeClosingDelim::No,
2176 );
2177 err.span_label(ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("while parsing this {0}", adt_ty))
})format!("while parsing this {adt_ty}"));
2178 let guar = err.emit_err();
2179 recovered = Recovered::Yes(guar);
2180 break;
2181 }
2182 }
2183 }
2184 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
2185 } else {
2186 let token_str = super::token_descr(&self.token);
2187 let where_str = if parsed_where { "" } else { "`where`, or " };
2188 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}`{{` after struct name, found {1}",
where_str, token_str))
})format!("expected {where_str}`{{` after struct name, found {token_str}");
2189 let mut err = self.dcx().struct_span_err(self.token.span, msg);
2190 err.span_label(self.token.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}`{{` after struct name",
where_str))
})format!("expected {where_str}`{{` after struct name",));
2191 return Err(err);
2192 }
2193
2194 Ok((fields, recovered))
2195 }
2196
2197 fn parse_unsafe_field(&mut self) -> Safety {
2198 if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Unsafe,
token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe)) {
2200 let span = self.prev_token.span;
2201 self.psess.gated_spans.gate(sym::unsafe_fields, span);
2202 Safety::Unsafe(span)
2203 } else {
2204 Safety::Default
2205 }
2206 }
2207 pub(super) fn parse_tuple_struct_body(&mut self) -> PResult<'a, ThinVec<FieldDef>> {
2210 let openparen_span = self.token.span;
2211 let mut encountered_colon = false;
2212 self.parse_paren_comma_seq(|p| {
2213 let attrs = p.parse_outer_attributes()?;
2214 p.collect_tokens(None, attrs, ForceCollect::No, |p, attrs| {
2215 let mut snapshot = None;
2216 if p.is_vcs_conflict_marker(&TokenKind::Shl, &TokenKind::Lt) {
2217 snapshot = Some(p.create_snapshot_for_diagnostic());
2221 }
2222 let lo = p.token.span;
2223 let vis = match p.parse_visibility(FollowedByType::Yes) {
2224 Ok(vis) => vis,
2225 Err(err) => {
2226 if let Some(ref mut snapshot) = snapshot {
2227 snapshot.recover_vcs_conflict_marker();
2228 }
2229 return Err(err);
2230 }
2231 };
2232 let mut_restriction = p.parse_mut_restriction()?;
2233 encountered_colon |=
2234 p.token.is_ident() && p.look_ahead(1, |tok| tok == &token::Colon);
2235 let ty = match p.parse_ty() {
2238 Ok(ty) => ty,
2239 Err(err) => {
2240 if let Some(ref mut snapshot) = snapshot {
2241 snapshot.recover_vcs_conflict_marker();
2242 }
2243 return Err(err);
2244 }
2245 };
2246 let mut default = None;
2247 if p.token == token::Eq {
2248 let mut snapshot = p.create_snapshot_for_diagnostic();
2249 snapshot.bump();
2250 match snapshot.parse_expr_anon_const() {
2251 Ok(const_expr) => {
2252 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2253 p.psess.gated_spans.gate(sym::default_field_values, sp);
2254 p.restore_snapshot(snapshot);
2255 default = Some(const_expr);
2256 }
2257 Err(err) => {
2258 err.cancel();
2259 }
2260 }
2261 }
2262
2263 Ok((
2264 FieldDef {
2265 span: lo.to(ty.span),
2266 vis,
2267 extras: Self::field_def_extras(Safety::Default, mut_restriction, default),
2268 ident: None,
2269 id: DUMMY_NODE_ID,
2270 ty,
2271 attrs,
2272 is_placeholder: false,
2273 },
2274 Trailing::from(p.token == token::Comma),
2275 UsePreAttrPos::No,
2276 ))
2277 })
2278 })
2279 .map(|(r, _)| r)
2280 .map_err(|mut error| {
2281 if self.token == token::Colon {
2282 error.subdiagnostic(UseDoubleColonSuggestion { colon: self.token.span });
2283 }
2284 if encountered_colon {
2285 self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
2286 self.bump();
2287 error.subdiagnostic(UseRegularStructSuggestion {
2288 open: openparen_span,
2289 close: self.prev_token.span,
2290 semicolon: if self.token == token::Semi { Some(self.token.span) } else { None },
2291 });
2292 }
2293 error
2294 })
2295 }
2296
2297 fn field_def_extras(
2298 safety: Safety,
2299 mut_restriction: MutRestriction,
2300 default: Option<AnonConst>,
2301 ) -> Option<Box<FieldDefExtras>> {
2302 match (safety, mut_restriction, default) {
2303 (
2304 Safety::Default,
2305 MutRestriction { kind: RestrictionKind::Unrestricted, span: _ },
2308 None,
2309 ) => None,
2310 (safety, mut_restriction, default) => {
2311 Some(Box::new(FieldDefExtras { safety, mut_restriction, default }))
2312 }
2313 }
2314 }
2315
2316 fn parse_field_def(&mut self, adt_ty: &str, ident_span: Span) -> PResult<'a, FieldDef> {
2318 self.recover_vcs_conflict_marker();
2319 let attrs = self.parse_outer_attributes()?;
2320 self.recover_vcs_conflict_marker();
2321 self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2322 let lo = this.token.span;
2323 let vis = this.parse_visibility(FollowedByType::No)?;
2324 let mut_restriction = this.parse_mut_restriction()?;
2325 let safety = this.parse_unsafe_field();
2326 this.parse_single_struct_field(
2327 adt_ty,
2328 lo,
2329 vis,
2330 mut_restriction,
2331 safety,
2332 attrs,
2333 ident_span,
2334 )
2335 .map(|field| (field, Trailing::No, UsePreAttrPos::No))
2336 })
2337 }
2338
2339 fn parse_single_struct_field(
2341 &mut self,
2342 adt_ty: &str,
2343 lo: Span,
2344 vis: Visibility,
2345 mut_restriction: MutRestriction,
2346 safety: Safety,
2347 attrs: AttrVec,
2348 ident_span: Span,
2349 ) -> PResult<'a, FieldDef> {
2350 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, mut_restriction, safety, attrs)?;
2351 match self.token.kind {
2352 token::Comma => {
2353 self.bump();
2354 }
2355 token::Semi => {
2356 self.bump();
2357 let sp = self.prev_token.span;
2358 let mut err =
2359 self.dcx().struct_span_err(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} fields are separated by `,`",
adt_ty))
})format!("{adt_ty} fields are separated by `,`"));
2360 err.span_suggestion_short(
2361 sp,
2362 "replace `;` with `,`",
2363 ",",
2364 Applicability::MachineApplicable,
2365 );
2366 err.span_label(ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("while parsing this {0}", adt_ty))
})format!("while parsing this {adt_ty}"));
2367 err.emit();
2368 }
2369 token::CloseBrace => {}
2370 token::DocComment(..) => {
2371 let previous_span = self.prev_token.span;
2372 let mut err = diagnostics::DocCommentDoesNotDocumentAnything {
2373 span: self.token.span,
2374 missing_comma: None,
2375 };
2376 self.bump(); if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) || self.token == token::CloseBrace {
2378 self.dcx().emit_err(err);
2379 } else {
2380 let sp = previous_span.shrink_to_hi();
2381 err.missing_comma = Some(sp);
2382 return Err(self.dcx().create_err(err));
2383 }
2384 }
2385 _ => {
2386 let sp = self.prev_token.span.shrink_to_hi();
2387 let msg =
2388 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `,`, or `}}`, found {0}",
super::token_descr(&self.token)))
})format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token));
2389
2390 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind
2392 && let Some(last_segment) = segments.last()
2393 {
2394 let guar = self.check_trailing_angle_brackets(
2395 last_segment,
2396 &[crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma), crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseBrace,
token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)],
2397 );
2398 if let Some(_guar) = guar {
2399 let _ = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
2402
2403 return Ok(a_var);
2406 }
2407 }
2408
2409 let mut err = self.dcx().struct_span_err(sp, msg);
2410
2411 if self.token.is_ident()
2412 || (self.token == TokenKind::Pound
2413 && (self.look_ahead(1, |t| t == &token::OpenBracket)))
2414 {
2415 err.span_suggestion(
2418 sp,
2419 "try adding a comma",
2420 ",",
2421 Applicability::MachineApplicable,
2422 );
2423 err.emit();
2424 } else {
2425 return Err(err);
2426 }
2427 }
2428 }
2429 Ok(a_var)
2430 }
2431
2432 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
2433 if let Err(err) = self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) {
2434 let sm = self.psess.source_map();
2435 let eq_typo = self.token == token::Eq && self.look_ahead(1, |t| t.is_path_start());
2436 let semi_typo = self.token == token::Semi
2437 && self.look_ahead(1, |t| {
2438 t.is_path_start()
2439 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
2442 (Ok(l), Ok(r)) => l.line == r.line,
2443 _ => true,
2444 }
2445 });
2446 if eq_typo || semi_typo {
2447 self.bump();
2448 err.with_span_suggestion_short(
2450 self.prev_token.span,
2451 "field names and their types are separated with `:`",
2452 ":",
2453 Applicability::MachineApplicable,
2454 )
2455 .emit();
2456 } else {
2457 return Err(err);
2458 }
2459 }
2460 Ok(())
2461 }
2462
2463 fn parse_name_and_ty(
2465 &mut self,
2466 adt_ty: &str,
2467 lo: Span,
2468 vis: Visibility,
2469 mut_restriction: MutRestriction,
2470 safety: Safety,
2471 attrs: AttrVec,
2472 ) -> PResult<'a, FieldDef> {
2473 let name = self.parse_field_ident(adt_ty, lo)?;
2474 if self.token == token::Bang {
2475 if let Err(mut err) = self.unexpected() {
2476 err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
2478 return Err(err);
2479 }
2480 }
2481 self.expect_field_ty_separator()?;
2482 let ty = self.parse_ty()?;
2483 if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
2484 return Err(self
2485 .dcx()
2486 .struct_span_err(self.token.span, "found single colon in a struct field type path")
2487 .with_span_suggestion_verbose(
2488 self.token.span,
2489 "write a path separator here",
2490 "::",
2491 Applicability::MaybeIncorrect,
2492 ));
2493 }
2494 let default = if self.token == token::Eq {
2495 self.bump();
2496 let const_expr = self.parse_expr_anon_const()?;
2497 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2498 self.psess.gated_spans.gate(sym::default_field_values, sp);
2499 Some(const_expr)
2500 } else {
2501 None
2502 };
2503 Ok(FieldDef {
2504 span: lo.to(self.prev_token.span),
2505 ident: Some(name),
2506 vis,
2507 extras: Self::field_def_extras(safety, mut_restriction, default),
2508 id: DUMMY_NODE_ID,
2509 ty,
2510 attrs,
2511 is_placeholder: false,
2512 })
2513 }
2514
2515 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
2518 let (ident, kind) = self.ident_or_err(true)?;
2519 if token::ident_of_kind_is_reserved(ident, kind)
2520 && !(ident.name == kw::Underscore && adt_ty == "enum")
2521 {
2522 let snapshot = self.create_snapshot_for_diagnostic();
2523 let err = if self.check_fn_front_matter(false, Case::Sensitive) {
2524 let inherited_vis = Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited };
2525 let fn_parse_mode = FnParseMode {
2527 req_name: |_, _| true,
2528 context: FnContext::Free,
2529 req_body: true,
2530 allow_const_params: true,
2531 };
2532 match self.parse_fn(
2533 &mut AttrVec::new(),
2534 fn_parse_mode,
2535 lo,
2536 &inherited_vis,
2537 Case::Insensitive,
2538 ) {
2539 Ok(_) => self
2540 .dcx()
2541 .struct_span_err(
2542 lo.to(self.prev_token.span),
2543 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("functions are not allowed in {0} definitions",
adt_ty))
})format!("functions are not allowed in {adt_ty} definitions"),
2544 )
2545 .with_help(
2546 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
2547 )
2548 .with_help(
2549 "see https://doc.rust-lang.org/book/ch05-03-method-syntax.html \
2550 for more information",
2551 ),
2552 Err(err) => {
2553 err.cancel();
2554 self.restore_snapshot(snapshot);
2555 self.expected_ident_found_err()
2556 }
2557 }
2558 } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Struct,
token_type: crate::parser::token_type::TokenType::KwStruct,
}exp!(Struct)) {
2559 match self.parse_item_struct() {
2560 Ok(item) => {
2561 let ItemKind::Struct(ident, ..) = item else { ::core::panicking::unreachable_default_msg()unreachable!() };
2562 self.dcx()
2563 .struct_span_err(
2564 lo.with_hi(ident.span.hi()),
2565 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("structs are not allowed in {0} definitions",
adt_ty))
})format!("structs are not allowed in {adt_ty} definitions"),
2566 )
2567 .with_help(
2568 "consider creating a new `struct` definition instead of nesting",
2569 )
2570 }
2571 Err(err) => {
2572 err.cancel();
2573 self.restore_snapshot(snapshot);
2574 self.expected_ident_found_err()
2575 }
2576 }
2577 } else {
2578 let mut err = self.expected_ident_found_err();
2579 if self.eat_keyword_noexpect(kw::Let)
2580 && let removal_span = self.prev_token.span.until(self.token.span)
2581 && let Ok(ident) = self
2582 .parse_ident_common(false)
2583 .map_err(|err| err.cancel())
2585 && self.token == TokenKind::Colon
2586 {
2587 err.span_suggestion_verbose(
2588 removal_span,
2589 "remove the `let` keyword",
2590 String::new(),
2591 Applicability::MachineApplicable,
2592 );
2593 err.note("the `let` keyword is not allowed in `struct` fields");
2594 err.note(
2595 "see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> \
2596 for more information",
2597 );
2598 err.emit();
2599 return Ok(ident);
2600 } else {
2601 self.restore_snapshot(snapshot);
2602 }
2603 err
2604 };
2605 return Err(err);
2606 }
2607 self.bump();
2608 Ok(ident)
2609 }
2610
2611 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemKind> {
2619 let ident = self.parse_ident()?;
2620 let body = if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2621 self.parse_delim_args()? } else if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
2623 let params = self.parse_token_tree(); let pspan = params.span();
2625 if !self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2626 self.unexpected()?;
2627 }
2628 let body = self.parse_token_tree(); let bspan = body.span();
2631 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); let tokens = TokenStream::new(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[params, arrow, body]))vec![params, arrow, body]);
2633 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
2634 Box::new(DelimArgs { dspan, delim: Delimiter::Brace, tokens })
2635 } else {
2636 self.unexpected_any()?
2637 };
2638
2639 self.psess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
2640 Ok(ItemKind::MacroDef(
2641 ident,
2642 ast::MacroDef { body, macro_rules: false, eii_declaration: None },
2643 ))
2644 }
2645
2646 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
2648 if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::MacroRules,
token_type: crate::parser::token_type::TokenType::KwMacroRules,
}exp!(MacroRules)) {
2649 let macro_rules_span = self.token.span;
2650
2651 if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) {
2652 return IsMacroRulesItem::Yes { has_bang: true };
2653 } else if self.look_ahead(1, |t| t.is_ident()) {
2654 self.dcx().emit_err(diagnostics::MacroRulesMissingBang {
2656 span: macro_rules_span,
2657 hi: macro_rules_span.shrink_to_hi(),
2658 });
2659
2660 return IsMacroRulesItem::Yes { has_bang: false };
2661 }
2662 }
2663
2664 IsMacroRulesItem::No
2665 }
2666
2667 fn parse_item_macro_rules(
2669 &mut self,
2670 vis: &Visibility,
2671 has_bang: bool,
2672 ) -> PResult<'a, ItemKind> {
2673 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::MacroRules,
token_type: crate::parser::token_type::TokenType::KwMacroRules,
}exp!(MacroRules))?; if has_bang {
2676 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; }
2678 let ident = self.parse_ident()?;
2679
2680 if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Bang,
token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
2681 let span = self.prev_token.span;
2683 self.dcx().emit_err(diagnostics::MacroNameRemoveBang { span });
2684 }
2685
2686 let body = self.parse_delim_args()?;
2687 self.eat_semi_for_macro_if_needed(&body, None);
2688 self.complain_if_pub_macro(vis, true);
2689
2690 Ok(ItemKind::MacroDef(
2691 ident,
2692 ast::MacroDef { body, macro_rules: true, eii_declaration: None },
2693 ))
2694 }
2695
2696 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
2699 if let VisibilityKind::Inherited = vis.kind {
2700 return;
2701 }
2702
2703 let vstr = pprust::vis_to_string(vis);
2704 let vstr = vstr.trim_end();
2705 if macro_rules {
2706 self.dcx().emit_err(diagnostics::MacroRulesVisibility { span: vis.span, vis: vstr });
2707 } else {
2708 self.dcx()
2709 .emit_err(diagnostics::MacroInvocationVisibility { span: vis.span, vis: vstr });
2710 }
2711 }
2712
2713 fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs, path: Option<&Path>) {
2714 if args.need_semicolon() && !self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
2715 self.report_invalid_macro_expansion_item(args, path);
2716 }
2717 }
2718
2719 pub fn parse_test_binder_constraints(&mut self) -> PResult<'a, Box<TestBinderConstraints>> {
2721 self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Impl,
token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl))?;
2722 let mut generics = self.parse_generics()?;
2723 generics.where_clause = self.parse_where_clause()?;
2724 let body = self.parse_test_binder_body()?;
2725 Ok(Box::new(TestBinderConstraints { generics, body: Box::new(body) }))
2726 }
2727
2728 pub fn parse_test_binder_body(&mut self) -> PResult<'a, TestBinderBody> {
2729 let mut items: Vec<TestBinderItem> = Vec::new();
2730 let mut span = self.token.span;
2731 self.parse_delim_comma_seq(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), |this| {
2732 match this.token.ident() {
2733 Some((Ident { name: sym::predicates, .. }, IdentKind::Normal)) => {
2734 let span = this.token.span;
2735 this.bump();
2736 items.extend(
2737 this.parse_where_clause_predicates(None, span)?
2738 .0
2739 .into_iter()
2740 .map(TestBinderItem::Predicate),
2741 );
2742 }
2743 Some((Ident { name: sym::forall, .. }, IdentKind::Normal)) => {
2744 items.push(TestBinderItem::Forall(this.parse_test_binder_forall()?));
2745 }
2746 Some((Ident { name: sym::exists, .. }, IdentKind::Normal)) => {
2747 items.push(TestBinderItem::Exists(this.parse_test_binder_exists()?));
2748 }
2749
2750 _ if this.token.is_lifetime() && this.look_ahead(1, |t| t.kind == token::Eq) => {
2751 let lhs = this.expect_lifetime();
2752 this.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
2753 if !this.check_lifetime() {
2754 this.unexpected()?;
2755 }
2756 let rhs = this.expect_lifetime();
2757 items.push(TestBinderItem::RegionEquality(TestBinderRegionEquality {
2758 lhs,
2759 rhs,
2760 }));
2761 }
2762 _ => items.push(TestBinderItem::Constraint(this.parse_test_binder_constraint()?)),
2763 }
2764 Ok(())
2765 })?;
2766 span = span.to(self.prev_token.span);
2767 Ok(TestBinderBody { items, span })
2768 }
2769
2770 pub fn parse_test_binder_forall(&mut self) -> PResult<'a, TestBinderForall> {
2771 let span = self.token.span;
2772 self.bump();
2773
2774 let mut generics = self.parse_generics()?;
2775 generics.where_clause = self.parse_where_clause()?;
2776
2777 let body = self.parse_test_binder_body()?;
2778
2779 let assert_on_exit = if let Some((i, IdentKind::Normal)) = self.token.ident()
2780 && i.name == sym::expect
2781 {
2782 self.bump();
2783 let items = self
2784 .parse_delim_comma_seq(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), |this| {
2785 this.parse_test_binder_constraint()
2786 })?
2787 .0;
2788 Some(items)
2789 } else {
2790 None
2791 };
2792
2793 Ok(TestBinderForall { span, node_id: DUMMY_NODE_ID, generics, body, assert_on_exit })
2794 }
2795
2796 pub fn parse_test_binder_exists(&mut self) -> PResult<'a, TestBinderExists> {
2797 let span = self.token.span;
2798 self.bump();
2799 let params = self.parse_generics()?.params;
2800 let body = self.parse_test_binder_body()?;
2801 Ok(TestBinderExists { span, node_id: DUMMY_NODE_ID, params, body })
2802 }
2803
2804 pub fn parse_test_binder_constraint(&mut self) -> PResult<'a, TestBinderConstraint> {
2805 match self.token.ident() {
2806 Some((Ident { name: sym::and, .. }, IdentKind::Normal)) => {
2807 self.bump();
2808 let items = self
2809 .parse_delim_comma_seq(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), |this| {
2810 this.parse_test_binder_constraint()
2811 })?
2812 .0;
2813 Ok(TestBinderConstraint::And { items })
2814 }
2815 Some((Ident { name: sym::or, .. }, IdentKind::Normal)) => {
2816 self.bump();
2817 let items = self
2818 .parse_delim_comma_seq(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), |this| {
2819 this.parse_test_binder_constraint()
2820 })?
2821 .0;
2822 Ok(TestBinderConstraint::Or { items })
2823 }
2824 Some((Ident { name: sym::ambiguity, .. }, IdentKind::Normal)) => {
2825 let span = self.token.span;
2826 self.bump();
2827 Ok(TestBinderConstraint::Ambiguity { span })
2828 }
2829 _ if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::For,
token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) => {
2830 let bound_type_constraint = self.parse_test_binder_bound_type_constraint()?;
2831 Ok(TestBinderConstraint::AliasOutlives { bound_type_constraint })
2832 }
2833 _ if self.token.lifetime().is_some() => {
2834 let lhs = self.expect_lifetime();
2835 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon))?;
2836 if !self.check_lifetime() {
2837 self.unexpected()?;
2838 }
2839 let rhs = self.expect_lifetime();
2840 Ok(TestBinderConstraint::Lifetime { lhs, rhs })
2841 }
2842 _ if self.token.can_begin_type() => {
2843 let lhs = self.parse_ty_for_where_clause()?;
2844 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon))?;
2845 if !self.check_lifetime() {
2846 self.unexpected()?;
2847 }
2848 let rhs = self.expect_lifetime();
2849 Ok(TestBinderConstraint::PlaceholderOutlives { lhs, rhs })
2850 }
2851 _ => Err(self.dcx().struct_span_err(self.token.span, "unexpected token")),
2852 }
2853 }
2854
2855 fn parse_test_binder_bound_type_constraint(
2856 &mut self,
2857 ) -> PResult<'a, TestBinderBoundTypeConstraint> {
2858 let lo = self.token.span;
2859 let ast::WhereBoundPredicate { bound_generic_params, bounded_ty, bounds } =
2860 self.parse_ty_where_predicate_kind()?;
2861 let mut rhs = None;
2862 for bound in bounds {
2863 match bound {
2864 GenericBound::Trait(poly_trait_ref) => {
2865 self.dcx().span_err(poly_trait_ref.span, "trait bounds aren't supported here");
2866 }
2867 GenericBound::Use(_, span) => {
2868 self.dcx().span_err(span, "use bounds aren't supported here");
2869 }
2870 GenericBound::Outlives(lifetime) => {
2871 if rhs.is_some() {
2872 self.dcx().span_err(
2873 lifetime.ident.span,
2874 "only one lifetime on the rhs supported",
2875 );
2876 } else {
2877 rhs = Some(lifetime);
2878 }
2879 }
2880 }
2881 }
2882 match rhs {
2883 Some(rhs) => Ok(TestBinderBoundTypeConstraint {
2884 span: lo.to(self.prev_token.span),
2885 node_id: DUMMY_NODE_ID,
2886 params: bound_generic_params,
2887 lhs: bounded_ty,
2888 rhs,
2889 }),
2890 None => Err(self.dcx().struct_span_err(
2891 bounded_ty.span,
2892 "expected a single lifetime on the rhs of this constraint",
2893 )),
2894 }
2895 }
2896
2897 fn report_invalid_macro_expansion_item(&self, args: &DelimArgs, path: Option<&Path>) {
2898 let span = args.dspan.entire();
2899 let mut err = self.dcx().struct_span_err(
2900 span,
2901 "macros that expand to items must be delimited with braces or followed by a semicolon",
2902 );
2903 if !span.from_expansion() {
2906 let DelimSpan { open, close } = args.dspan;
2907 if let Some(path) = path
2910 && path.segments.first().is_some_and(|seg| seg.ident.name == sym::macro_rules)
2911 && args.delim == Delimiter::Parenthesis
2912 {
2913 let replace =
2914 if path.span.hi() + rustc_span::BytePos(1) < open.lo() { "" } else { " " };
2915 err.multipart_suggestion(
2916 "to define a macro, remove the parentheses around the macro name",
2917 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(open, replace.to_string()), (close, String::new())]))vec![(open, replace.to_string()), (close, String::new())],
2918 Applicability::MachineApplicable,
2919 );
2920 } else {
2921 err.multipart_suggestion(
2922 "change the delimiters to curly braces",
2923 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(open, "{".to_string()), (close, '}'.to_string())]))vec![(open, "{".to_string()), (close, '}'.to_string())],
2924 Applicability::MaybeIncorrect,
2925 );
2926 err.span_suggestion_verbose(
2927 span.with_neighbor(self.token.span).shrink_to_hi(),
2928 "add a semicolon",
2929 ';',
2930 Applicability::MaybeIncorrect,
2931 );
2932 }
2933 }
2934 err.emit();
2935 }
2936
2937 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2940 if (self.token.is_keyword(kw::Enum)
2941 || self.token.is_keyword(kw::Struct)
2942 || self.token.is_keyword(kw::Union))
2943 && self.look_ahead(1, |t| t.is_ident())
2944 {
2945 let kw_token = self.token;
2946 let kw_str = pprust::token_to_string(&kw_token);
2947 let item = self.parse_item(
2948 ForceCollect::No,
2949 AllowConstBlockItems::DoesNotMatter, )?;
2951 let mut item = item.unwrap().span;
2952 if self.token == token::Comma {
2953 item = item.to(self.token.span);
2954 }
2955 self.dcx().emit_err(diagnostics::NestedAdt {
2956 span: kw_token.span,
2957 item,
2958 kw_str,
2959 keyword: keyword.as_str(),
2960 });
2961 return Ok(false);
2963 }
2964 Ok(true)
2965 }
2966
2967 fn check_impl_frontmatter(&mut self, look_ahead: usize) -> bool {
2968 const ALL_QUALS: &[Symbol] = &[kw::Const, kw::Unsafe];
2969 if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Impl,
token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl)) {
2972 return true;
2973 }
2974 let mut i = 0;
2975 while i < ALL_QUALS.len() {
2976 let action = self.look_ahead(i + look_ahead, |token| {
2977 if token.is_keyword(kw::Impl) {
2978 return Some(true);
2979 }
2980 if ALL_QUALS.iter().any(|&qual| token.is_keyword(qual)) {
2981 return None;
2983 }
2984 Some(false)
2985 });
2986 if let Some(ret) = action {
2987 return ret;
2988 }
2989 i += 1;
2990 }
2991
2992 self.is_keyword_ahead(i, &[kw::Impl])
2993 }
2994
2995 fn try_recover_const_missing_semi(
3003 &mut self,
3004 rhs: &Option<Box<Expr>>,
3005 const_span: Span,
3006 ) -> Option<Box<Expr>> {
3007 if self.token == TokenKind::Semi {
3008 return None;
3009 }
3010 let Some(rhs) = rhs else {
3011 return None;
3012 };
3013 if !self.in_fn_body || !self.may_recover() || rhs.span.from_expansion() {
3014 return None;
3015 }
3016 if let Some((span, guar)) =
3017 self.missing_semi_from_binop("const", rhs, Some(const_span.shrink_to_lo()))
3018 {
3019 self.fn_body_missing_semi_guar = Some(guar);
3020 Some(self.mk_expr(span, ExprKind::Err(guar)))
3021 } else {
3022 None
3023 }
3024 }
3025}
3026
3027enum IsMacroRulesItem {
3028 Yes { has_bang: bool },
3029 No,
3030}
3031
3032struct UsePathList<'a> {
3033 elements: &'a [ast::PathSegment],
3034 prev: Option<&'a Self>,
3035}