Skip to main content

rustc_parse/parser/
item.rs

1use std::fmt::Write;
2use std::mem;
3
4use ast::token::IdentIsRaw;
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    /// Parses a source module as a crate. This is the main entry point for the parser.
31    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    /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
37    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    /// Parses the contents of a module (inner attributes followed by module items).
53    /// We exit once we hit `term` which can be either
54    /// - EOF (for files)
55    /// - `}` for mod items
56    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        // There shouldn't be any stray semicolons before or after items.
67        // `parse_item` consumes the appropriate semicolons so any leftover is an error.
68        loop {
69            while self.maybe_consume_incorrect_semicolon(items.last().map(|x| &**x)) {} // Eat all bad semicolons
70            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.data().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 =
130            FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
131        self.parse_item_(fn_parse_mode, force_collect, allow_const_block_items)
132            .map(|i| i.map(Box::new))
133    }
134
135    fn parse_item_(
136        &mut self,
137        fn_parse_mode: FnParseMode,
138        force_collect: ForceCollect,
139        const_block_items_allowed: AllowConstBlockItems,
140    ) -> PResult<'a, Option<Item>> {
141        self.recover_vcs_conflict_marker();
142        let attrs = self.parse_outer_attributes()?;
143        self.recover_vcs_conflict_marker();
144        self.parse_item_common(
145            attrs,
146            true,
147            false,
148            fn_parse_mode,
149            force_collect,
150            const_block_items_allowed,
151        )
152    }
153
154    pub(super) fn parse_item_common(
155        &mut self,
156        attrs: AttrWrapper,
157        mac_allowed: bool,
158        attrs_allowed: bool,
159        fn_parse_mode: FnParseMode,
160        force_collect: ForceCollect,
161        allow_const_block_items: AllowConstBlockItems,
162    ) -> PResult<'a, Option<Item>> {
163        if let Some(item) = self.eat_metavar_seq(MetaVarKind::Item, |this| {
164            this.parse_item(ForceCollect::Yes, allow_const_block_items)
165        }) {
166            let mut item = item.expect("an actual item");
167            attrs.prepend_to_nt_inner(&mut item.attrs);
168            return Ok(Some(*item));
169        }
170
171        self.collect_tokens(None, attrs, force_collect, |this, mut attrs| {
172            let lo = this.token.span;
173            let vis = this.parse_visibility(FollowedByType::No)?;
174            let mut def = this.parse_defaultness();
175            let kind = this.parse_item_kind(
176                &mut attrs,
177                mac_allowed,
178                allow_const_block_items,
179                lo,
180                &vis,
181                &mut def,
182                fn_parse_mode,
183                Case::Sensitive,
184            )?;
185            if let Some(kind) = kind {
186                this.error_on_unconsumed_default(def, &kind);
187                let span = lo.to(this.prev_token.span);
188                let id = DUMMY_NODE_ID;
189                let item = Item { attrs, id, kind, vis, span, tokens: None };
190                return Ok((Some(item), Trailing::No, UsePreAttrPos::No));
191            }
192
193            // At this point, we have failed to parse an item.
194            if !#[allow(non_exhaustive_omitted_patterns)] match vis.kind {
    VisibilityKind::Inherited => true,
    _ => false,
}matches!(vis.kind, VisibilityKind::Inherited) {
195                let vis_str = pprust::vis_to_string(&vis).trim_end().to_string();
196                let mut err = this.dcx().create_err(diagnostics::VisibilityNotFollowedByItem {
197                    span: vis.span,
198                    vis: vis_str,
199                });
200                if let Some((ident, _)) = this.token.ident()
201                    && !ident.is_used_keyword()
202                    && let Some((similar_kw, is_incorrect_case)) = ident
203                        .name
204                        .find_similar(&rustc_span::symbol::used_keywords(|| ident.span.edition()))
205                {
206                    err.subdiagnostic(diagnostics::MisspelledKw {
207                        similar_kw: similar_kw.to_string(),
208                        span: ident.span,
209                        is_incorrect_case,
210                    });
211                }
212                err.emit();
213            }
214
215            if let Defaultness::Default(span) = def {
216                this.dcx().emit_err(diagnostics::DefaultNotFollowedByItem { span });
217            } else if let Defaultness::Final(span) = def {
218                this.dcx().emit_err(diagnostics::FinalNotFollowedByItem { span });
219            }
220
221            if !attrs_allowed {
222                this.recover_attrs_no_item(&attrs)?;
223            }
224            Ok((None, Trailing::No, UsePreAttrPos::No))
225        })
226    }
227
228    /// Error in-case `default`/`final` was parsed in an in-appropriate context.
229    fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
230        match def {
231            Defaultness::Default(span) => {
232                self.dcx().emit_err(diagnostics::InappropriateDefault {
233                    span,
234                    article: kind.article(),
235                    descr: kind.descr(),
236                });
237            }
238            Defaultness::Final(span) => {
239                self.dcx().emit_err(diagnostics::InappropriateFinal {
240                    span,
241                    article: kind.article(),
242                    descr: kind.descr(),
243                });
244            }
245            Defaultness::Implicit => (),
246        }
247    }
248
249    /// Parses one of the items allowed by the flags.
250    fn parse_item_kind(
251        &mut self,
252        attrs: &mut AttrVec,
253        macros_allowed: bool,
254        allow_const_block_items: AllowConstBlockItems,
255        lo: Span,
256        vis: &Visibility,
257        def: &mut Defaultness,
258        fn_parse_mode: FnParseMode,
259        case: Case,
260    ) -> PResult<'a, Option<ItemKind>> {
261        let check_pub = def == &Defaultness::Implicit;
262        let mut def_ = || mem::replace(def, Defaultness::Implicit);
263
264        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) {
265            self.parse_use_item()?
266        } else if self.check_fn_front_matter(check_pub, case) {
267            // FUNCTION ITEM
268            let defaultness = def_();
269            if let Defaultness::Default(span) = defaultness {
270                // Default functions should only require feature `min_specialization`. We remove the
271                // `specialization` tag again as such spans *require* feature `specialization` to be
272                // enabled. In a later stage, we make `specialization` imply `min_specialization`.
273                self.psess.gated_spans.gate(sym::min_specialization, span);
274                self.psess.gated_spans.ungate_last(sym::specialization, span);
275            }
276            let (ident, sig, generics, contract, body) =
277                self.parse_fn(attrs, fn_parse_mode, lo, vis, case)?;
278            ItemKind::Fn(Box::new(Fn {
279                defaultness,
280                ident,
281                sig,
282                generics,
283                contract,
284                body,
285                define_opaque: None,
286                eii_impls: ThinVec::new(),
287            }))
288        } 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) {
289            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) {
290                // EXTERN CRATE
291                self.parse_item_extern_crate()?
292            } else {
293                // EXTERN BLOCK
294                self.parse_item_foreign_mod(attrs, Safety::Default)?
295            }
296        } else if self.is_unsafe_foreign_mod() {
297            // EXTERN BLOCK
298            let safety = self.parse_safety(Case::Sensitive);
299            self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern))?;
300            self.parse_item_foreign_mod(attrs, safety)?
301        } else if let Some(safety) = self.parse_global_static_front_matter(case) {
302            // STATIC ITEM
303            let mutability = self.parse_mutability();
304            self.parse_static_item(safety, mutability)?
305        } 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() {
306            // TRAIT ITEM
307            self.parse_item_trait(attrs, lo)?
308        } else if self.check_impl_frontmatter(0) {
309            // IMPL ITEM
310            self.parse_item_impl(attrs, def_(), false)?
311        } else if let AllowConstBlockItems::Yes | AllowConstBlockItems::DoesNotMatter =
312            allow_const_block_items
313            && self.check_inline_const(0)
314        {
315            // CONST BLOCK ITEM
316            if let AllowConstBlockItems::DoesNotMatter = allow_const_block_items {
317                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/item.rs:317",
                        "rustc_parse::parser::item", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/item.rs"),
                        ::tracing_core::__macro_support::Option::Some(317u32),
                        ::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);
318            };
319            ItemKind::ConstBlock(self.parse_const_block_item()?)
320        } else if let Const::Yes(const_span) = self.parse_constness(case) {
321            // CONST ITEM
322            self.recover_const_mut(const_span);
323            self.recover_missing_kw_before_item()?;
324            let (ident, generics, ty, body) = self.parse_const_item(const_span)?;
325            ItemKind::Const(Box::new(ConstItem {
326                defaultness: def_(),
327                ident,
328                generics,
329                ty,
330                body,
331                kind: ConstItemKind::Body,
332                define_opaque: None,
333            }))
334        } else if let Some(kind) = self.is_reuse_item() {
335            self.parse_item_delegation(attrs, def_(), kind)?
336        } 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)
337            || 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])
338        {
339            // MODULE ITEM
340            self.parse_item_mod(attrs)?
341        } 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) {
342            if let Const::Yes(const_span) = self.parse_constness(case) {
343                // TYPE CONST (mgca)
344                self.recover_const_mut(const_span);
345                self.recover_missing_kw_before_item()?;
346                let (ident, generics, ty, body) = self.parse_const_item(const_span)?;
347                // Make sure this is only allowed if the feature gate is enabled.
348                // #![feature(mgca_type_const_syntax)]
349                self.psess.gated_spans.gate(sym::mgca_type_const_syntax, lo.to(const_span));
350                ItemKind::Const(Box::new(ConstItem {
351                    defaultness: def_(),
352                    ident,
353                    generics,
354                    ty,
355                    body,
356                    kind: ConstItemKind::TypeConst,
357                    define_opaque: None,
358                }))
359            } else {
360                // TYPE ITEM
361                self.parse_type_alias(def_())?
362            }
363        } 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) {
364            // ENUM ITEM
365            self.parse_item_enum()?
366        } 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) {
367            // STRUCT ITEM
368            self.parse_item_struct()?
369        } else if self.is_kw_followed_by_ident(kw::Union) {
370            // UNION ITEM
371            self.bump(); // `union`
372            self.parse_item_union()?
373        } else if self.is_builtin() {
374            // BUILTIN# ITEM
375            return self.parse_item_builtin();
376        } 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) {
377            // MACROS 2.0 ITEM
378            self.parse_item_decl_macro(lo)?
379        } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
380            // MACRO_RULES ITEM
381            self.parse_item_macro_rules(vis, has_bang)?
382        } else if self.isnt_macro_invocation()
383            && (self.token.is_ident_named(sym::import)
384                || self.token.is_ident_named(sym::using)
385                || self.token.is_ident_named(sym::include)
386                || self.token.is_ident_named(sym::require))
387        {
388            return self.recover_import_as_use();
389        } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
390            self.recover_missing_kw_before_item()?;
391            return Ok(None);
392        } else if self.isnt_macro_invocation() && case == Case::Sensitive {
393            _ = def_;
394
395            // Recover wrong cased keywords
396            return self.parse_item_kind(
397                attrs,
398                macros_allowed,
399                allow_const_block_items,
400                lo,
401                vis,
402                def,
403                fn_parse_mode,
404                Case::Insensitive,
405            );
406        } else if macros_allowed && self.check_path() {
407            if self.isnt_macro_invocation() {
408                self.recover_missing_kw_before_item()?;
409            }
410            // MACRO INVOCATION ITEM
411            ItemKind::MacCall(Box::new(self.parse_item_macro(vis)?))
412        } else {
413            return Ok(None);
414        };
415        Ok(Some(info))
416    }
417
418    fn recover_import_as_use(&mut self) -> PResult<'a, Option<ItemKind>> {
419        let span = self.token.span;
420        let token_name = super::token_descr(&self.token);
421        let snapshot = self.create_snapshot_for_diagnostic();
422        self.bump();
423        match self.parse_use_item() {
424            Ok(u) => {
425                self.dcx().emit_err(diagnostics::RecoverImportAsUse { span, token_name });
426                Ok(Some(u))
427            }
428            Err(e) => {
429                e.cancel();
430                self.restore_snapshot(snapshot);
431                Ok(None)
432            }
433        }
434    }
435
436    fn parse_use_item(&mut self) -> PResult<'a, ItemKind> {
437        let tree = self.parse_use_tree()?;
438        if let Err(mut e) = self.expect_semi() {
439            match tree.kind {
440                UseTreeKind::Glob(_) => {
441                    e.note("the wildcard token must be last on the path");
442                }
443                UseTreeKind::Nested { .. } => {
444                    e.note("glob-like brace syntax must be last on the path");
445                }
446                _ => (),
447            }
448            return Err(e);
449        }
450        Ok(ItemKind::Use(tree))
451    }
452
453    /// When parsing a statement, would the start of a path be an item?
454    pub(super) fn is_path_start_item(&mut self) -> bool {
455        self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
456        || self.is_reuse_item().is_some() // yes: `reuse impl Trait for Struct { self.0 }`, yes: `reuse some_path::foo;`
457        || self.check_trait_front_matter() // no: `auto::b`, yes: `auto trait X { .. }`
458        || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
459        || #[allow(non_exhaustive_omitted_patterns)] match self.is_macro_rules_item() {
    IsMacroRulesItem::Yes { .. } => true,
    _ => false,
}matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
460    }
461
462    fn is_reuse_item(&mut self) -> Option<ReuseKind> {
463        if !self.token.is_keyword(kw::Reuse) {
464            return None;
465        }
466
467        // no: `reuse ::path` for compatibility reasons with macro invocations
468        if self.look_ahead(1, |t| t.is_path_start() && *t != token::PathSep) {
469            Some(ReuseKind::Path)
470        } else if self.check_impl_frontmatter(1) {
471            Some(ReuseKind::Impl)
472        } else {
473            None
474        }
475    }
476
477    /// Are we sure this could not possibly be a macro invocation?
478    fn isnt_macro_invocation(&mut self) -> bool {
479        self.check_ident() && self.look_ahead(1, |t| *t != token::Bang && *t != token::PathSep)
480    }
481
482    /// Recover on encountering a struct, enum, or method definition where the user
483    /// forgot to add the `struct`, `enum`, or `fn` keyword
484    fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
485        let is_pub = self.prev_token.is_keyword(kw::Pub);
486        let is_const = self.prev_token.is_keyword(kw::Const);
487        let ident_span = self.token.span;
488        let span = if is_pub { self.prev_token.span.to(ident_span) } else { ident_span };
489        let insert_span = ident_span.shrink_to_lo();
490
491        let ident = if self.token.is_ident()
492            && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen))
493            && self.look_ahead(1, |t| {
494                #[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)
495            }) {
496            self.parse_ident_common(true).unwrap()
497        } else {
498            return Ok(());
499        };
500
501        let mut found_generics = false;
502        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Lt,
    token_type: crate::parser::token_type::TokenType::Lt,
}exp!(Lt)) {
503            found_generics = true;
504            self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)]);
505            self.bump(); // `>`
506        }
507
508        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)) {
509            // possible struct or enum definition where `struct` or `enum` was forgotten
510            if self.look_ahead(1, |t| *t == token::CloseBrace) {
511                // `S {}` could be unit enum or struct
512                Some(diagnostics::MissingKeywordForItemDefinition::EnumOrStruct { span })
513            } else if self.look_ahead(2, |t| *t == token::Colon)
514                || self.look_ahead(3, |t| *t == token::Colon)
515            {
516                // `S { f:` or `S { pub f:`
517                Some(diagnostics::MissingKeywordForItemDefinition::Struct {
518                    span,
519                    insert_span,
520                    ident,
521                })
522            } else {
523                Some(diagnostics::MissingKeywordForItemDefinition::Enum {
524                    span,
525                    insert_span,
526                    ident,
527                })
528            }
529        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
530            // possible function or tuple struct definition where `fn` or `struct` was forgotten
531            self.bump(); // `(`
532            let is_method = self.recover_self_param();
533
534            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);
535
536            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)) {
537                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)]);
538                self.bump(); // `{`
539                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);
540                if is_method {
541                    diagnostics::MissingKeywordForItemDefinition::Method {
542                        span,
543                        insert_span,
544                        ident,
545                    }
546                } else {
547                    diagnostics::MissingKeywordForItemDefinition::Function {
548                        span,
549                        insert_span,
550                        ident,
551                    }
552                }
553            } 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)) {
554                diagnostics::MissingKeywordForItemDefinition::Struct { span, insert_span, ident }
555            } else {
556                diagnostics::MissingKeywordForItemDefinition::Ambiguous {
557                    span,
558                    subdiag: if found_generics {
559                        None
560                    } else if let Ok(snippet) = self.span_to_snippet(ident_span) {
561                        Some(diagnostics::AmbiguousMissingKwForItemSub::SuggestMacro {
562                            span: ident_span,
563                            snippet,
564                        })
565                    } else {
566                        Some(diagnostics::AmbiguousMissingKwForItemSub::HelpMacro)
567                    },
568                }
569            };
570            Some(err)
571        } else if found_generics {
572            Some(diagnostics::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: None })
573        } else {
574            None
575        };
576
577        if let Some(err) = err { Err(self.dcx().create_err(err)) } else { Ok(()) }
578    }
579
580    fn parse_item_builtin(&mut self) -> PResult<'a, Option<ItemKind>> {
581        // To be expanded
582        Ok(None)
583    }
584
585    /// Parses an item macro, e.g., `item!();`.
586    fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
587        let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
588        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
589        match self.parse_delim_args() {
590            // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
591            Ok(args) => {
592                self.eat_semi_for_macro_if_needed(&args, Some(&path));
593                self.complain_if_pub_macro(vis, false);
594                Ok(MacCall { path, args })
595            }
596
597            Err(mut err) => {
598                // Maybe the user misspelled `macro_rules` (issue #91227)
599                if self.token.is_ident()
600                    && let [segment] = path.segments.as_slice()
601                    && edit_distance("macro_rules", &segment.ident.to_string(), 2).is_some()
602                {
603                    err.span_suggestion_verbose(
604                        path.span,
605                        "perhaps you meant to define a macro",
606                        "macro_rules",
607                        Applicability::MachineApplicable,
608                    );
609                }
610                Err(err)
611            }
612        }
613    }
614
615    /// Recover if we parsed attributes and expected an item but there was none.
616    fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
617        let ([start @ end] | [start, .., end]) = attrs else {
618            return Ok(());
619        };
620        let msg = if end.is_doc_comment() {
621            "expected item after doc comment"
622        } else {
623            "expected item after attributes"
624        };
625        let mut err = self.dcx().struct_span_err(end.span, msg);
626        if end.is_doc_comment() {
627            err.span_label(end.span, "this doc comment doesn't document anything");
628        } else {
629            err.span_label(end.span, "expected an item after this");
630            if self.token == TokenKind::Semi {
631                err.span_suggestion_verbose(
632                    self.token.span,
633                    "remove the semicolon after the attribute",
634                    "",
635                    Applicability::MaybeIncorrect,
636                );
637            }
638        }
639        if let [.., penultimate, _] = attrs {
640            err.span_label(start.span.to(penultimate.span), "other attributes here");
641        }
642        Err(err)
643    }
644
645    fn is_async_fn(&self) -> bool {
646        self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
647    }
648
649    fn parse_polarity(&mut self) -> ast::ImplPolarity {
650        // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
651        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()) {
652            self.psess.gated_spans.gate(sym::negative_impls, self.token.span);
653            self.bump(); // `!`
654            ast::ImplPolarity::Negative(self.prev_token.span)
655        } else {
656            ast::ImplPolarity::Positive
657        }
658    }
659
660    /// Parses an implementation item.
661    ///
662    /// ```ignore (illustrative)
663    /// impl<'a, T> TYPE { /* impl items */ }
664    /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
665    /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
666    /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
667    /// ```
668    ///
669    /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
670    /// ```ebnf
671    /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
672    /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
673    /// ```
674    fn parse_item_impl(
675        &mut self,
676        attrs: &mut AttrVec,
677        defaultness: Defaultness,
678        is_reuse: bool,
679    ) -> PResult<'a, ItemKind> {
680        let constness = self.parse_constness(Case::Sensitive);
681        let safety = self.parse_safety(Case::Sensitive);
682        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Impl,
    token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl))?;
683        let mut generics_snapshot = None;
684        // First, parse generic parameters if necessary.
685        let mut generics = if self.choose_generics_over_qpath(0) {
686            self.parse_generics()?
687        } else {
688            // We might be mistakenly trying to use a generic type as a generic parameter.
689            // impl<X<T>> Trait for Y<T> { ... }
690            if self.look_ahead(0, |t| t == &token::Lt)
691                && self.look_ahead(1, |t| t.is_ident())
692                && self.look_ahead(2, |t| t == &token::Lt)
693            {
694                generics_snapshot = Some(self.create_snapshot_for_diagnostic());
695            }
696
697            let mut generics = Generics::default();
698            // impl A for B {}
699            //    /\ this is where `generics.span` should point when there are no type params.
700            generics.span = self.prev_token.span.shrink_to_hi();
701            generics
702        };
703
704        if let Const::Yes(span) = constness {
705            self.psess.gated_spans.gate(sym::const_trait_impl, span);
706        }
707
708        // Parse stray `impl async Trait`
709        if (self.token_uninterpolated_span().at_least_rust_2018()
710            && self.token.is_keyword(kw::Async))
711            || self.is_kw_followed_by_ident(kw::Async)
712        {
713            self.bump();
714            self.dcx().emit_err(diagnostics::AsyncImpl { span: self.prev_token.span });
715        }
716
717        let polarity = self.parse_polarity();
718
719        // Parse both types and traits as a type, then reinterpret if necessary.
720        let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
721        {
722            let span = self.prev_token.span.between(self.token.span);
723            return Err(self.dcx().create_err(diagnostics::MissingTraitInTraitImpl {
724                span,
725                for_span: span.to(self.token.span),
726            }));
727        } else {
728            self.parse_ty_with_generics_recovery(&generics).map_err(|e| {
729                let Some(mut snapshot) = generics_snapshot else {
730                    return e;
731                };
732                snapshot.maybe_type_in_generic_parameter(e)
733            })?
734        };
735        // If `for` is missing we try to recover.
736        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));
737        let missing_for_span = self.prev_token.span.between(self.token.span);
738
739        let ty_second = if self.token == token::DotDot {
740            // We need to report this error after `cfg` expansion for compatibility reasons
741            self.bump(); // `..`, do not add it to expected tokens
742
743            // AST validation later detects this `TyKind::Dummy` and emits an
744            // error. (#121072 will hopefully remove all this special handling
745            // of the obsolete `impl Trait for ..` and then this can go away.)
746            Some(self.mk_ty(self.prev_token.span, TyKind::Dummy))
747        } else if has_for || self.token.can_begin_type() {
748            Some(self.parse_ty()?)
749        } else {
750            None
751        };
752
753        generics.where_clause = self.parse_where_clause()?;
754
755        let impl_items = if is_reuse {
756            Default::default()
757        } else {
758            self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?
759        };
760
761        let (of_trait, self_ty) = match ty_second {
762            Some(ty_second) => {
763                // impl Trait for Type
764                if !has_for {
765                    self.dcx()
766                        .emit_err(diagnostics::MissingForInTraitImpl { span: missing_for_span });
767                }
768
769                let ty_first = *ty_first;
770                let path = match ty_first.kind {
771                    // This notably includes paths passed through `ty` macro fragments (#46438).
772                    TyKind::Path(None, path) => path,
773                    other => {
774                        if let TyKind::ImplTrait(_, bounds) = other
775                            && let [bound] = bounds.as_slice()
776                            && let GenericBound::Trait(poly_trait_ref) = bound
777                        {
778                            // Suggest removing extra `impl` keyword:
779                            // `impl<T: Default> impl Default for Wrapper<T>`
780                            //                   ^^^^^
781                            let extra_impl_kw = ty_first.span.until(bound.span());
782                            self.dcx().emit_err(diagnostics::ExtraImplKeywordInTraitImpl {
783                                extra_impl_kw,
784                                impl_trait_span: ty_first.span,
785                            });
786                            poly_trait_ref.trait_ref.path.clone()
787                        } else {
788                            return Err(self.dcx().create_err(
789                                diagnostics::ExpectedTraitInTraitImplFoundType {
790                                    span: ty_first.span,
791                                },
792                            ));
793                        }
794                    }
795                };
796                let trait_ref = TraitRef { path, ref_id: ty_first.id };
797
798                let of_trait =
799                    Some(Box::new(TraitImplHeader { defaultness, safety, polarity, trait_ref }));
800                (of_trait, ty_second)
801            }
802            None => {
803                let self_ty = ty_first;
804                let error = |modifier, modifier_name, modifier_span| {
805                    self.dcx().create_err(diagnostics::TraitImplModifierInInherentImpl {
806                        span: self_ty.span,
807                        modifier,
808                        modifier_name,
809                        modifier_span,
810                        self_ty: self_ty.span,
811                    })
812                };
813
814                if let Safety::Unsafe(span) = safety {
815                    error("unsafe", "unsafe", span).with_code(E0197).emit();
816                }
817                if let ImplPolarity::Negative(span) = polarity {
818                    error("!", "negative", span).emit();
819                }
820                if let Defaultness::Default(def_span) = defaultness {
821                    error("default", "default", def_span).emit();
822                }
823                if let Const::Yes(span) = constness {
824                    self.psess.gated_spans.gate(sym::const_trait_impl, span);
825                }
826                (None, self_ty)
827            }
828        };
829
830        Ok(ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, constness }))
831    }
832
833    fn parse_item_delegation(
834        &mut self,
835        attrs: &mut AttrVec,
836        defaultness: Defaultness,
837        kind: ReuseKind,
838    ) -> PResult<'a, ItemKind> {
839        let span = self.token.span;
840        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Reuse,
    token_type: crate::parser::token_type::TokenType::KwReuse,
}exp!(Reuse))?;
841
842        let item_kind = match kind {
843            ReuseKind::Path => self.parse_path_like_delegation(),
844            ReuseKind::Impl => self.parse_impl_delegation(span, attrs, defaultness),
845        }?;
846
847        self.psess.gated_spans.gate(sym::fn_delegation, span.to(self.prev_token.span));
848
849        Ok(item_kind)
850    }
851
852    fn parse_delegation_body(&mut self) -> PResult<'a, Option<Box<Block>>> {
853        Ok(if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
854            Some(self.parse_block()?)
855        } else {
856            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))?;
857            None
858        })
859    }
860
861    fn parse_impl_delegation(
862        &mut self,
863        span: Span,
864        attrs: &mut AttrVec,
865        defaultness: Defaultness,
866    ) -> PResult<'a, ItemKind> {
867        let mut impl_item = self.parse_item_impl(attrs, defaultness, true)?;
868        let ItemKind::Impl(Impl { items, of_trait, .. }) = &mut impl_item else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
869
870        let until_expr_span = span.to(self.prev_token.span);
871
872        let Some(of_trait) = of_trait else {
873            return Err(self
874                .dcx()
875                .create_err(diagnostics::ImplReuseInherentImpl { span: until_expr_span }));
876        };
877
878        let body = self.parse_delegation_body()?;
879        let whole_reuse_span = span.to(self.prev_token.span);
880
881        items.push(Box::new(AssocItem {
882            id: DUMMY_NODE_ID,
883            attrs: Default::default(),
884            span: whole_reuse_span,
885            tokens: None,
886            vis: Visibility { kind: VisibilityKind::Inherited, span: whole_reuse_span },
887            kind: AssocItemKind::DelegationMac(Box::new(DelegationMac {
888                qself: None,
889                prefix: of_trait.trait_ref.path.clone(),
890                suffixes: DelegationSuffixes::Glob(whole_reuse_span),
891                body,
892            })),
893        }));
894
895        Ok(impl_item)
896    }
897
898    fn parse_path_like_delegation(&mut self) -> PResult<'a, ItemKind> {
899        let (qself, path) = if self.eat_lt() {
900            let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
901            (Some(qself), path)
902        } else {
903            (None, self.parse_path(PathStyle::Expr)?)
904        };
905
906        let rename = |this: &mut Self| {
907            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 })
908        };
909
910        Ok(if self.eat_path_sep() {
911            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)) {
912                DelegationSuffixes::Glob(self.prev_token.span)
913            } else {
914                let parse_suffix = |p: &mut Self| Ok((p.parse_path_segment_ident()?, rename(p)?));
915                DelegationSuffixes::List(
916                    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,
917                )
918            };
919
920            ItemKind::DelegationMac(Box::new(DelegationMac {
921                qself,
922                prefix: path,
923                suffixes,
924                body: self.parse_delegation_body()?,
925            }))
926        } else {
927            let rename = rename(self)?;
928            let ident = rename.unwrap_or_else(|| path.segments.last().unwrap().ident);
929
930            ItemKind::Delegation(Box::new(Delegation {
931                id: DUMMY_NODE_ID,
932                qself,
933                path,
934                ident,
935                rename,
936                body: self.parse_delegation_body()?,
937                source: DelegationSource::Single,
938            }))
939        })
940    }
941
942    fn parse_item_list<T>(
943        &mut self,
944        attrs: &mut AttrVec,
945        mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
946    ) -> PResult<'a, ThinVec<T>> {
947        let open_brace_span = self.token.span;
948
949        // Recover `impl Ty;` instead of `impl Ty {}`
950        if self.token == TokenKind::Semi {
951            self.dcx().emit_err(diagnostics::UseEmptyBlockNotSemi { span: self.token.span });
952            self.bump();
953            return Ok(ThinVec::new());
954        }
955
956        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))?;
957        attrs.extend(self.parse_inner_attributes()?);
958
959        let mut items = ThinVec::new();
960        while !self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
961            if self.recover_doc_comment_before_brace() {
962                continue;
963            }
964            self.recover_vcs_conflict_marker();
965            match parse_item(self) {
966                Ok(None) => {
967                    let mut is_unnecessary_semicolon = (self.token == token::Semi
968                        && self.prev_token == token::Semi)
969                        || !items.is_empty()
970                        // When the close delim is `)` in a case like the following, `token.kind`
971                        // is expected to be `token::CloseParen`, but the actual `token.kind` is
972                        // `token::CloseBrace`. This is because the `token.kind` of the close delim
973                        // is treated as the same as that of the open delim in
974                        // `TokenTreesReader::parse_token_tree`, even if the delimiters of them are
975                        // different. Therefore, `token.kind` should not be compared here.
976                        //
977                        // issue-60075.rs
978                        // ```
979                        // trait T {
980                        //     fn qux() -> Option<usize> {
981                        //         let _ = if true {
982                        //         });
983                        //          ^ this close delim
984                        //         Some(4)
985                        //     }
986                        // ```
987                        && self
988                            .span_to_snippet(self.prev_token.span)
989                            .is_ok_and(|snippet| snippet == "}")
990                        && self.token == token::Semi;
991                    let mut semicolon_span = self.token.span;
992                    if !is_unnecessary_semicolon {
993                        // #105369, Detect spurious `;` before assoc fn body
994                        is_unnecessary_semicolon =
995                            self.token == token::OpenBrace && self.prev_token == token::Semi;
996                        semicolon_span = self.prev_token.span;
997                    }
998                    // We have to bail or we'll potentially never make progress.
999                    let non_item_span = self.token.span;
1000                    let is_let = self.token.is_keyword(kw::Let);
1001
1002                    let mut err =
1003                        self.dcx().struct_span_err(non_item_span, "non-item in item list");
1004                    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);
1005                    if is_let {
1006                        err.span_suggestion_verbose(
1007                            non_item_span,
1008                            "consider using `const` instead of `let` for associated const",
1009                            "const",
1010                            Applicability::MachineApplicable,
1011                        );
1012                    } else {
1013                        err.span_label(open_brace_span, "item list starts here")
1014                            .span_label(non_item_span, "non-item starts here")
1015                            .span_label(self.prev_token.span, "item list ends here");
1016                    }
1017                    if is_unnecessary_semicolon {
1018                        err.span_suggestion_verbose(
1019                            semicolon_span,
1020                            "consider removing this semicolon",
1021                            "",
1022                            Applicability::MaybeIncorrect,
1023                        );
1024                    }
1025                    err.emit();
1026                    break;
1027                }
1028                Ok(Some(item)) => items.extend(item),
1029                Err(err) => {
1030                    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);
1031                    err.with_span_label(
1032                        open_brace_span,
1033                        "while parsing this item list starting here",
1034                    )
1035                    .with_span_label(self.prev_token.span, "the item list ends here")
1036                    .emit();
1037                    break;
1038                }
1039            }
1040        }
1041        Ok(items)
1042    }
1043
1044    /// Recover on a doc comment before `}`.
1045    fn recover_doc_comment_before_brace(&mut self) -> bool {
1046        if let token::DocComment(..) = self.token.kind {
1047            if self.look_ahead(1, |tok| tok == &token::CloseBrace) {
1048                // FIXME: merge with `DocCommentDoesNotDocumentAnything` (E0585)
1049                {
    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!(
1050                    self.dcx(),
1051                    self.token.span,
1052                    E0584,
1053                    "found a documentation comment that doesn't document anything",
1054                )
1055                .with_span_label(self.token.span, "this doc comment doesn't document anything")
1056                .with_help(
1057                    "doc comments must come before what they document, if a comment was \
1058                    intended use `//`",
1059                )
1060                .emit();
1061                self.bump();
1062                return true;
1063            }
1064        }
1065        false
1066    }
1067
1068    /// Parses defaultness (i.e., `default` or nothing).
1069    fn parse_defaultness(&mut self) -> Defaultness {
1070        // We are interested in `default` followed by another identifier.
1071        // However, we must avoid keywords that occur as binary operators.
1072        // Currently, the only applicable keyword is `as` (`default as Ty`).
1073        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))
1074            && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
1075        {
1076            self.psess.gated_spans.gate(sym::specialization, self.token.span);
1077            self.bump(); // `default`
1078            Defaultness::Default(self.prev_token_uninterpolated_span())
1079        } 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)) {
1080            self.psess.gated_spans.gate(sym::final_associated_functions, self.prev_token.span);
1081            Defaultness::Final(self.prev_token_uninterpolated_span())
1082        } else {
1083            Defaultness::Implicit
1084        }
1085    }
1086
1087    /// Is this an `[impl(in? path)]? const? unsafe? auto? trait` item?
1088    fn check_trait_front_matter(&mut self) -> bool {
1089        const SUFFIXES: &[&[Symbol]] = &[
1090            &[kw::Trait],
1091            &[kw::Auto, kw::Trait],
1092            &[kw::Unsafe, kw::Trait],
1093            &[kw::Unsafe, kw::Auto, kw::Trait],
1094            &[kw::Const, kw::Trait],
1095            &[kw::Const, kw::Auto, kw::Trait],
1096            &[kw::Const, kw::Unsafe, kw::Trait],
1097            &[kw::Const, kw::Unsafe, kw::Auto, kw::Trait],
1098        ];
1099        // `impl(`
1100        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) {
1101            // `impl(in` unambiguously introduces an `impl` restriction
1102            if self.is_keyword_ahead(2, &[kw::In]) {
1103                return true;
1104            }
1105            // `impl(crate | self | super)` + SUFFIX
1106            if self.is_keyword_ahead(2, &[kw::Crate, kw::SelfLower, kw::Super])
1107                && self.look_ahead(3, |t| t == &token::CloseParen)
1108                && SUFFIXES.iter().any(|suffix| {
1109                    suffix.iter().enumerate().all(|(i, kw)| self.is_keyword_ahead(i + 4, &[*kw]))
1110                })
1111            {
1112                return true;
1113            }
1114            // Recover cases like `impl(path::to::module)` + SUFFIX to suggest inserting `in`.
1115            SUFFIXES.iter().any(|suffix| {
1116                suffix.iter().enumerate().all(|(i, kw)| {
1117                    self.tree_look_ahead(i + 2, |t| {
1118                        if let TokenTree::Token(token, _) = t {
1119                            token.is_keyword(*kw)
1120                        } else {
1121                            false
1122                        }
1123                    })
1124                    .unwrap_or(false)
1125                })
1126            })
1127        } else {
1128            SUFFIXES.iter().any(|suffix| {
1129                suffix.iter().enumerate().all(|(i, kw)| {
1130                    // We use `check_keyword` for the first token to include it in the expected tokens.
1131                    if i == 0 {
1132                        match *kw {
1133                            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)),
1134                            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)),
1135                            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)),
1136                            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)),
1137                            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1138                        }
1139                    } else {
1140                        self.is_keyword_ahead(i, &[*kw])
1141                    }
1142                })
1143            })
1144        }
1145    }
1146
1147    /// Parses `[impl(in? path)]? const? unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
1148    fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemKind> {
1149        let impl_restriction = self.parse_impl_restriction()?;
1150        let constness = self.parse_constness(Case::Sensitive);
1151        if let Const::Yes(span) = constness {
1152            self.psess.gated_spans.gate(sym::const_trait_impl, span);
1153        }
1154        let safety = self.parse_safety(Case::Sensitive);
1155        // Parse optional `auto` prefix.
1156        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)) {
1157            self.psess.gated_spans.gate(sym::auto_traits, self.prev_token.span);
1158            IsAuto::Yes
1159        } else {
1160            IsAuto::No
1161        };
1162
1163        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Trait,
    token_type: crate::parser::token_type::TokenType::KwTrait,
}exp!(Trait))?;
1164        let ident = self.parse_ident()?;
1165        let mut generics = self.parse_generics()?;
1166
1167        // Parse optional colon and supertrait bounds.
1168        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));
1169        let span_at_colon = self.prev_token.span;
1170        let bounds = if had_colon { self.parse_generic_bounds()? } else { ThinVec::new() };
1171
1172        let span_before_eq = self.prev_token.span;
1173        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1174            // It's a trait alias.
1175            if had_colon {
1176                let span = span_at_colon.to(span_before_eq);
1177                self.dcx().emit_err(diagnostics::BoundsNotAllowedOnTraitAliases { span });
1178            }
1179
1180            let bounds = self.parse_generic_bounds()?;
1181            generics.where_clause = self.parse_where_clause()?;
1182            self.expect_semi()?;
1183
1184            let whole_span = lo.to(self.prev_token.span);
1185            if is_auto == IsAuto::Yes {
1186                self.dcx().emit_err(diagnostics::TraitAliasCannotBeAuto { span: whole_span });
1187            }
1188            if let Safety::Unsafe(_) = safety {
1189                self.dcx().emit_err(diagnostics::TraitAliasCannotBeUnsafe { span: whole_span });
1190            }
1191            if let RestrictionKind::Restricted { .. } = impl_restriction.kind {
1192                self.dcx()
1193                    .emit_err(diagnostics::TraitAliasCannotBeImplRestricted { span: whole_span });
1194            }
1195
1196            self.psess.gated_spans.gate(sym::trait_alias, whole_span);
1197
1198            Ok(ItemKind::TraitAlias(Box::new(TraitAlias { constness, ident, generics, bounds })))
1199        } else {
1200            // It's a normal trait.
1201            generics.where_clause = self.parse_where_clause()?;
1202            let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
1203            Ok(ItemKind::Trait(Box::new(Trait {
1204                impl_restriction,
1205                constness,
1206                is_auto,
1207                safety,
1208                ident,
1209                generics,
1210                bounds,
1211                items,
1212            })))
1213        }
1214    }
1215
1216    pub fn parse_impl_item(
1217        &mut self,
1218        force_collect: ForceCollect,
1219    ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1220        let fn_parse_mode =
1221            FnParseMode { req_name: |_, _| true, context: FnContext::Impl, req_body: true };
1222        self.parse_assoc_item(fn_parse_mode, force_collect)
1223    }
1224
1225    pub fn parse_trait_item(
1226        &mut self,
1227        force_collect: ForceCollect,
1228    ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1229        let fn_parse_mode = FnParseMode {
1230            req_name: |edition, _| edition >= Edition::Edition2018,
1231            context: FnContext::Trait,
1232            req_body: false,
1233        };
1234        self.parse_assoc_item(fn_parse_mode, force_collect)
1235    }
1236
1237    /// Parses associated items.
1238    fn parse_assoc_item(
1239        &mut self,
1240        fn_parse_mode: FnParseMode,
1241        force_collect: ForceCollect,
1242    ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1243        Ok(self
1244            .parse_item_(
1245                fn_parse_mode,
1246                force_collect,
1247                AllowConstBlockItems::DoesNotMatter, // due to `AssocItemKind::try_from` below
1248            )?
1249            .map(|Item { attrs, id, span, vis, kind, tokens }| {
1250                let kind = match AssocItemKind::try_from(kind) {
1251                    Ok(kind) => kind,
1252                    Err(kind) => match kind {
1253                        ItemKind::Static(StaticItem {
1254                            ident,
1255                            ty,
1256                            safety: _,
1257                            mutability: _,
1258                            expr,
1259                            define_opaque,
1260                            eii_impls: _,
1261                        }) => {
1262                            self.dcx()
1263                                .emit_err(diagnostics::AssociatedStaticItemNotAllowed { span });
1264                            AssocItemKind::Const(Box::new(ConstItem {
1265                                defaultness: Defaultness::Implicit,
1266                                ident,
1267                                generics: Generics::default(),
1268                                ty,
1269                                body: expr,
1270                                kind: ConstItemKind::Body,
1271                                define_opaque,
1272                            }))
1273                        }
1274                        _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
1275                    },
1276                };
1277                Some(Box::new(Item { attrs, id, span, vis, kind, tokens }))
1278            }))
1279    }
1280
1281    /// Parses a `type` alias with the following grammar:
1282    /// ```ebnf
1283    /// TypeAlias = "type" Ident Generics (":" GenericBounds)? WhereClause ("=" Ty)? WhereClause ";" ;
1284    /// ```
1285    /// The `"type"` has already been eaten.
1286    fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemKind> {
1287        let ident = self.parse_ident()?;
1288        let mut generics = self.parse_generics()?;
1289
1290        // Parse optional colon and param bounds.
1291        let bounds =
1292            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() };
1293        generics.where_clause = self.parse_where_clause()?;
1294
1295        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 };
1296
1297        let after_where_clause = self.parse_where_clause()?;
1298
1299        self.expect_semi()?;
1300
1301        Ok(ItemKind::TyAlias(Box::new(TyAlias {
1302            defaultness,
1303            ident,
1304            generics,
1305            after_where_clause,
1306            bounds,
1307            ty,
1308        })))
1309    }
1310
1311    /// Parses a `UseTree`.
1312    ///
1313    /// ```text
1314    /// USE_TREE = [`::`] `*` |
1315    ///            [`::`] `{` USE_TREE_LIST `}` |
1316    ///            PATH `::` `*` |
1317    ///            PATH `::` `{` USE_TREE_LIST `}` |
1318    ///            PATH [`as` IDENT]
1319    /// ```
1320    fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
1321        let lo = self.token.span;
1322
1323        let mut prefix = ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo() };
1324        let kind =
1325            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() {
1326                // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
1327                let mod_sep_ctxt = self.token.span.ctxt();
1328                if self.eat_path_sep() {
1329                    prefix
1330                        .segments
1331                        .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1332                }
1333
1334                self.parse_use_tree_glob_or_nested()?
1335            } else {
1336                // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
1337                prefix = self.parse_path(PathStyle::Mod)?;
1338
1339                if self.eat_path_sep() {
1340                    self.parse_use_tree_glob_or_nested()?
1341                } else {
1342                    // Recover from using a colon as path separator.
1343                    while self.eat_noexpect(&token::Colon) {
1344                        self.dcx().emit_err(diagnostics::SingleColonImportPath {
1345                            span: self.prev_token.span,
1346                        });
1347
1348                        // We parse the rest of the path and append it to the original prefix.
1349                        self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1350                        prefix.span = lo.to(self.prev_token.span);
1351                    }
1352
1353                    UseTreeKind::Simple(self.parse_rename()?)
1354                }
1355            };
1356
1357        Ok(UseTree { prefix, kind })
1358    }
1359
1360    /// Parses `*` or `{...}`.
1361    fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1362        Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Star,
    token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
1363            UseTreeKind::Glob(self.prev_token.span)
1364        } else {
1365            let lo = self.token.span;
1366            UseTreeKind::Nested {
1367                items: self.parse_use_tree_list()?,
1368                span: lo.to(self.prev_token.span),
1369            }
1370        })
1371    }
1372
1373    /// Parses a `UseTreeKind::Nested(list)`.
1374    ///
1375    /// ```text
1376    /// USE_TREE_LIST = ∅ | (USE_TREE `,`)* USE_TREE [`,`]
1377    /// ```
1378    fn parse_use_tree_list(&mut self) -> PResult<'a, ThinVec<(UseTree, ast::NodeId)>> {
1379        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| {
1380            p.recover_vcs_conflict_marker();
1381            Ok((p.parse_use_tree()?, DUMMY_NODE_ID))
1382        })
1383        .map(|(r, _)| r)
1384    }
1385
1386    fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1387        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)) {
1388            self.parse_ident_or_underscore().map(Some)
1389        } else {
1390            Ok(None)
1391        }
1392    }
1393
1394    fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1395        match self.token.ident() {
1396            Some((ident @ Ident { name: kw::Underscore, .. }, IdentIsRaw::No)) => {
1397                self.bump();
1398                Ok(ident)
1399            }
1400            _ => self.parse_ident(),
1401        }
1402    }
1403
1404    /// Parses `extern crate` links.
1405    ///
1406    /// # Examples
1407    ///
1408    /// ```ignore (illustrative)
1409    /// extern crate foo;
1410    /// extern crate bar as foo;
1411    /// ```
1412    fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemKind> {
1413        // Accept `extern crate name-like-this` for better diagnostics
1414        let orig_ident = self.parse_crate_name_with_dashes()?;
1415        let (orig_name, item_ident) = if let Some(rename) = self.parse_rename()? {
1416            (Some(orig_ident.name), rename)
1417        } else {
1418            (None, orig_ident)
1419        };
1420        self.expect_semi()?;
1421        Ok(ItemKind::ExternCrate(orig_name, item_ident))
1422    }
1423
1424    fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1425        let ident = if self.token.is_keyword(kw::SelfLower) {
1426            self.parse_path_segment_ident()
1427        } else {
1428            self.parse_ident()
1429        }?;
1430
1431        let dash = crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Minus,
    token_type: crate::parser::token_type::TokenType::Minus,
}exp!(Minus);
1432        if self.token != dash.tok {
1433            return Ok(ident);
1434        }
1435
1436        // Accept `extern crate name-like-this` for better diagnostics.
1437        let mut dashes = ::alloc::vec::Vec::new()vec![];
1438        let mut idents = ::alloc::vec::Vec::new()vec![];
1439        while self.eat(dash) {
1440            dashes.push(self.prev_token.span);
1441            idents.push(self.parse_ident()?);
1442        }
1443
1444        let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1445        let mut fixed_name = ident.name.to_string();
1446        for part in idents {
1447            fixed_name.write_fmt(format_args!("_{0}", part.name))write!(fixed_name, "_{}", part.name).unwrap();
1448        }
1449
1450        self.dcx().emit_err(diagnostics::ExternCrateNameWithDashes {
1451            span: fixed_name_sp,
1452            sugg: diagnostics::ExternCrateNameWithDashesSugg { dashes },
1453        });
1454
1455        Ok(Ident::from_str_and_span(&fixed_name, fixed_name_sp))
1456    }
1457
1458    /// Parses `extern` for foreign ABIs modules.
1459    ///
1460    /// `extern` is expected to have been consumed before calling this method.
1461    ///
1462    /// # Examples
1463    ///
1464    /// ```ignore (only-for-syntax-highlight)
1465    /// extern "C" {}
1466    /// extern {}
1467    /// ```
1468    fn parse_item_foreign_mod(
1469        &mut self,
1470        attrs: &mut AttrVec,
1471        mut safety: Safety,
1472    ) -> PResult<'a, ItemKind> {
1473        let extern_span = self.prev_token_uninterpolated_span();
1474        let abi = self.parse_abi(); // ABI?
1475        // FIXME: This recovery should be tested better.
1476        if safety == Safety::Default
1477            && self.token.is_keyword(kw::Unsafe)
1478            && self.look_ahead(1, |t| *t == token::OpenBrace)
1479        {
1480            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();
1481            safety = Safety::Unsafe(self.token.span);
1482            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));
1483        }
1484        Ok(ItemKind::ForeignMod(ast::ForeignMod {
1485            extern_span,
1486            safety,
1487            abi,
1488            items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1489        }))
1490    }
1491
1492    /// Parses a foreign item (one in an `extern { ... }` block).
1493    pub fn parse_foreign_item(
1494        &mut self,
1495        force_collect: ForceCollect,
1496    ) -> PResult<'a, Option<Option<Box<ForeignItem>>>> {
1497        let fn_parse_mode = FnParseMode {
1498            req_name: |_, is_dot_dot_dot| is_dot_dot_dot == IsDotDotDot::No,
1499            context: FnContext::Free,
1500            req_body: false,
1501        };
1502        Ok(self
1503            .parse_item_(
1504                fn_parse_mode,
1505                force_collect,
1506                AllowConstBlockItems::DoesNotMatter, // due to `ForeignItemKind::try_from` below
1507            )?
1508            .map(|Item { attrs, id, span, vis, kind, tokens }| {
1509                let kind = match ForeignItemKind::try_from(kind) {
1510                    Ok(kind) => kind,
1511                    Err(kind) => match kind {
1512                        ItemKind::Const(ConstItem { ident, ty, body, .. }) => {
1513                            let const_span = Some(span.with_hi(ident.span.lo()))
1514                                .filter(|span| span.can_be_used_for_suggestions());
1515                            self.dcx().emit_err(diagnostics::ExternItemCannotBeConst {
1516                                ident_span: ident.span,
1517                                const_span,
1518                            });
1519                            ForeignItemKind::Static(Box::new(StaticItem {
1520                                ident,
1521                                ty,
1522                                mutability: Mutability::Not,
1523                                expr: body,
1524                                safety: Safety::Default,
1525                                define_opaque: None,
1526                                eii_impls: ThinVec::default(),
1527                            }))
1528                        }
1529                        _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1530                    },
1531                };
1532                Some(Box::new(Item { attrs, id, span, vis, kind, tokens }))
1533            }))
1534    }
1535
1536    fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &'static str) -> Option<T> {
1537        // FIXME(#100717): needs variant for each `ItemKind` (instead of using `ItemKind::descr()`)
1538        let span = self.psess.source_map().guess_head_span(span);
1539        let descr = kind.descr();
1540        let help = match kind {
1541            ItemKind::DelegationMac(DelegationMac {
1542                suffixes: DelegationSuffixes::Glob(_),
1543                ..
1544            }) => false,
1545            _ => true,
1546        };
1547        self.dcx().emit_err(diagnostics::BadItemKind { span, descr, ctx, help });
1548        None
1549    }
1550
1551    fn is_use_closure(&self) -> bool {
1552        if self.token.is_keyword(kw::Use) {
1553            // Check if this could be a closure.
1554            self.look_ahead(1, |token| {
1555                // Move or Async here would be an error but still we're parsing a closure
1556                let dist =
1557                    if token.is_keyword(kw::Move) || token.is_keyword(kw::Async) { 2 } else { 1 };
1558
1559                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))
1560            })
1561        } else {
1562            false
1563        }
1564    }
1565
1566    pub(super) fn is_unsafe_foreign_mod(&self) -> bool {
1567        // Look for `unsafe`.
1568        if !self.token.is_keyword(kw::Unsafe) {
1569            return false;
1570        }
1571        // Look for `extern`.
1572        if !self.is_keyword_ahead(1, &[kw::Extern]) {
1573            return false;
1574        }
1575
1576        // Look for the optional ABI string literal.
1577        let n = if self.look_ahead(2, |t| t.can_begin_string_literal()) { 3 } else { 2 };
1578
1579        // Look for the `{`. Use `tree_look_ahead` because the ABI (if present)
1580        // might be a metavariable i.e. an invisible-delimited sequence, and
1581        // `tree_look_ahead` will consider that a single element when looking
1582        // ahead.
1583        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, _)))
1584            == Some(true)
1585    }
1586
1587    fn parse_global_static_front_matter(&mut self, case: Case) -> Option<Safety> {
1588        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) {
1589            // Check if this could be a closure.
1590            !self.look_ahead(1, |token| {
1591                if token.is_keyword_case(kw::Move, case) || token.is_keyword_case(kw::Use, case) {
1592                    return true;
1593                }
1594                #[allow(non_exhaustive_omitted_patterns)] match token.kind {
    token::Or | token::OrOr => true,
    _ => false,
}matches!(token.kind, token::Or | token::OrOr)
1595            })
1596        } else {
1597            // `$qual static`
1598            (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)
1599                || 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))
1600                && self.look_ahead(1, |t| t.is_keyword_case(kw::Static, case))
1601        };
1602
1603        if is_global_static {
1604            let safety = self.parse_safety(case);
1605            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);
1606            Some(safety)
1607        } else {
1608            None
1609        }
1610    }
1611
1612    /// Recover on `const mut` with `const` already eaten.
1613    fn recover_const_mut(&mut self, const_span: Span) {
1614        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)) {
1615            let span = self.prev_token.span;
1616            self.dcx()
1617                .emit_err(diagnostics::ConstGlobalCannotBeMutable { ident_span: span, const_span });
1618        } 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)) {
1619            let span = self.prev_token.span;
1620            self.dcx()
1621                .emit_err(diagnostics::ConstLetMutuallyExclusive { span: const_span.to(span) });
1622        }
1623    }
1624
1625    fn parse_const_block_item(&mut self) -> PResult<'a, ConstBlockItem> {
1626        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1627        let const_span = self.prev_token.span;
1628        self.psess.gated_spans.gate(sym::const_block_items, const_span);
1629        let block = self.parse_block()?;
1630        Ok(ConstBlockItem { id: DUMMY_NODE_ID, span: const_span.to(block.span), block })
1631    }
1632
1633    /// Parse a static item with the prefix `"static" "mut"?` already parsed and stored in
1634    /// `mutability`.
1635    ///
1636    /// ```ebnf
1637    /// Static = "static" "mut"? $ident ":" $ty (= $expr)? ";" ;
1638    /// ```
1639    fn parse_static_item(
1640        &mut self,
1641        safety: Safety,
1642        mutability: Mutability,
1643    ) -> PResult<'a, ItemKind> {
1644        let ident = self.parse_ident()?;
1645
1646        if self.token == TokenKind::Lt && self.may_recover() {
1647            let generics = self.parse_generics()?;
1648            self.dcx().emit_err(diagnostics::StaticWithGenerics { span: generics.span });
1649        }
1650
1651        // Parse the type of a static item. That is, the `":" $ty` fragment.
1652        // FIXME: This could maybe benefit from `.may_recover()`?
1653        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))) {
1654            (true, false) => self.parse_ty()?,
1655            // If there wasn't a `:` or the colon was followed by a `=` or `;`, recover a missing
1656            // type.
1657            (colon, _) => self.recover_missing_global_item_type(colon, Some(mutability)),
1658        };
1659
1660        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 };
1661
1662        self.expect_semi()?;
1663
1664        let item = StaticItem {
1665            ident,
1666            ty,
1667            safety,
1668            mutability,
1669            expr,
1670            define_opaque: None,
1671            eii_impls: ThinVec::default(),
1672        };
1673        Ok(ItemKind::Static(Box::new(item)))
1674    }
1675
1676    /// Parse a constant item with the prefix `"const"` already parsed.
1677    ///
1678    /// If `const_arg` is true, any expression assigned to the const will be parsed
1679    /// as a const_arg instead of a body expression.
1680    ///
1681    /// ```ebnf
1682    /// Const = "const" ($ident | "_") Generics ":" $ty (= $expr)? WhereClause ";" ;
1683    /// ```
1684    fn parse_const_item(
1685        &mut self,
1686        const_span: Span,
1687    ) -> PResult<'a, (Ident, Generics, Box<Ty>, Option<Box<Expr>>)> {
1688        let ident = self.parse_ident_or_underscore()?;
1689
1690        let mut generics = self.parse_generics()?;
1691
1692        // Check the span for emptiness instead of the list of parameters in order to correctly
1693        // recognize and subsequently flag empty parameter lists (`<>`) as unstable.
1694        if !generics.span.is_empty() {
1695            self.psess.gated_spans.gate(sym::generic_const_items, generics.span);
1696        }
1697
1698        // Parse the type of a constant item. That is, the `":" $ty` fragment.
1699        // FIXME: This could maybe benefit from `.may_recover()`?
1700        let ty = match (
1701            self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)),
1702            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)),
1703        ) {
1704            (true, false) => self.parse_ty()?,
1705            // If there wasn't a `:` or the colon was followed by a `=`, `;` or `where`, recover a missing type.
1706            (colon, _) => self.recover_missing_global_item_type(colon, None),
1707        };
1708
1709        // Proactively parse a where-clause to be able to provide a good error message in case we
1710        // encounter the item body following it.
1711        let before_where_clause =
1712            if self.may_recover() { self.parse_where_clause()? } else { WhereClause::default() };
1713
1714        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 };
1715
1716        let after_where_clause = self.parse_where_clause()?;
1717
1718        // Provide a nice error message if the user placed a where-clause before the item body.
1719        // Users may be tempted to write such code if they are still used to the deprecated
1720        // where-clause location on type aliases and associated types. See also #89122.
1721        if before_where_clause.has_where_token
1722            && let Some(rhs) = &rhs
1723        {
1724            self.dcx().emit_err(diagnostics::WhereClauseBeforeConstBody {
1725                span: before_where_clause.span,
1726                name: ident.span,
1727                body: rhs.span,
1728                sugg: if !after_where_clause.has_where_token {
1729                    self.psess.source_map().span_to_snippet(rhs.span).ok().map(|body_s| {
1730                        diagnostics::WhereClauseBeforeConstBodySugg {
1731                            left: before_where_clause.span.shrink_to_lo(),
1732                            snippet: body_s,
1733                            right: before_where_clause.span.shrink_to_hi().to(rhs.span),
1734                        }
1735                    })
1736                } else {
1737                    // FIXME(generic_const_items): Provide a structured suggestion to merge the first
1738                    // where-clause into the second one.
1739                    None
1740                },
1741            });
1742        }
1743
1744        // Merge the predicates of both where-clauses since either one can be relevant.
1745        // If we didn't parse a body (which is valid for associated consts in traits) and we were
1746        // allowed to recover, `before_where_clause` contains the predicates, otherwise they are
1747        // in `after_where_clause`. Further, both of them might contain predicates iff two
1748        // where-clauses were provided which is syntactically ill-formed but we want to recover from
1749        // it and treat them as one large where-clause.
1750        let mut predicates = before_where_clause.predicates;
1751        predicates.extend(after_where_clause.predicates);
1752        let where_clause = WhereClause {
1753            has_where_token: before_where_clause.has_where_token
1754                || after_where_clause.has_where_token,
1755            predicates,
1756            span: if after_where_clause.has_where_token {
1757                after_where_clause.span
1758            } else {
1759                before_where_clause.span
1760            },
1761        };
1762
1763        if where_clause.has_where_token {
1764            self.psess.gated_spans.gate(sym::generic_const_items, where_clause.span);
1765        }
1766
1767        generics.where_clause = where_clause;
1768
1769        if let Some(rhs) = self.try_recover_const_missing_semi(&rhs, const_span) {
1770            return Ok((ident, generics, ty, Some(rhs)));
1771        }
1772        self.expect_semi()?;
1773
1774        Ok((ident, generics, ty, rhs))
1775    }
1776
1777    /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1778    /// This means that the type is missing.
1779    fn recover_missing_global_item_type(
1780        &mut self,
1781        colon_present: bool,
1782        m: Option<Mutability>,
1783    ) -> Box<Ty> {
1784        // Construct the error and stash it away with the hope
1785        // that typeck will later enrich the error with a type.
1786        let kind = match m {
1787            Some(Mutability::Mut) => "static mut",
1788            Some(Mutability::Not) => "static",
1789            None => "const",
1790        };
1791
1792        let colon = match colon_present {
1793            true => "",
1794            false => ":",
1795        };
1796
1797        let span = self.prev_token.span.shrink_to_hi();
1798        let err = self.dcx().create_err(diagnostics::MissingConstType { span, colon, kind });
1799        err.stash(span, StashKey::ItemNoType);
1800
1801        // The user intended that the type be inferred,
1802        // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1803        Box::new(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID })
1804    }
1805
1806    /// Parses an enum declaration.
1807    fn parse_item_enum(&mut self) -> PResult<'a, ItemKind> {
1808        if self.token.is_keyword(kw::Struct) {
1809            let span = self.prev_token.span.to(self.token.span);
1810            let err = diagnostics::EnumStructMutuallyExclusive { span };
1811            if self.look_ahead(1, |t| t.is_ident()) {
1812                self.bump();
1813                self.dcx().emit_err(err);
1814            } else {
1815                return Err(self.dcx().create_err(err));
1816            }
1817        }
1818
1819        let prev_span = self.prev_token.span;
1820        let ident = self.parse_ident()?;
1821        let mut generics = self.parse_generics()?;
1822        generics.where_clause = self.parse_where_clause()?;
1823
1824        // Possibly recover `enum Foo;` instead of `enum Foo {}`
1825        let (variants, _) = if self.token == TokenKind::Semi {
1826            self.dcx().emit_err(diagnostics::UseEmptyBlockNotSemi { span: self.token.span });
1827            self.bump();
1828            (::thin_vec::ThinVec::new()thin_vec![], Trailing::No)
1829        } else {
1830            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| {
1831                p.parse_enum_variant(ident.span)
1832            })
1833            .map_err(|mut err| {
1834                err.span_label(ident.span, "while parsing this enum");
1835                // Try to recover `enum Foo { ident : Ty }`.
1836                if self.prev_token.is_non_reserved_ident() && self.token == token::Colon {
1837                    let snapshot = self.create_snapshot_for_diagnostic();
1838                    self.bump();
1839                    match self.parse_ty() {
1840                        Ok(_) => {
1841                            err.span_suggestion_verbose(
1842                                prev_span,
1843                                "perhaps you meant to use `struct` here",
1844                                "struct",
1845                                Applicability::MaybeIncorrect,
1846                            );
1847                        }
1848                        Err(e) => {
1849                            e.cancel();
1850                        }
1851                    }
1852                    self.restore_snapshot(snapshot);
1853                }
1854                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1855                self.bump(); // }
1856                err
1857            })?
1858        };
1859
1860        let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1861        Ok(ItemKind::Enum(ident, generics, enum_definition))
1862    }
1863
1864    fn parse_enum_variant(&mut self, span: Span) -> PResult<'a, Option<Variant>> {
1865        self.recover_vcs_conflict_marker();
1866        let variant_attrs = self.parse_outer_attributes()?;
1867        self.recover_vcs_conflict_marker();
1868        let help = "enum variants can be `Variant`, `Variant = <integer>`, \
1869                    `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`";
1870        self.collect_tokens(None, variant_attrs, ForceCollect::No, |this, variant_attrs| {
1871            let vlo = this.token.span;
1872
1873            let vis = this.parse_visibility(FollowedByType::No)?;
1874            if !this.recover_nested_adt_item(kw::Enum)? {
1875                return Ok((None, Trailing::No, UsePreAttrPos::No));
1876            }
1877            let ident = this.parse_field_ident("enum", vlo)?;
1878
1879            if this.token == token::Bang {
1880                if let Err(err) = this.unexpected() {
1881                    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();
1882                }
1883
1884                this.bump();
1885                this.parse_delim_args()?;
1886
1887                return Ok((None, Trailing::from(this.token == token::Comma), UsePreAttrPos::No));
1888            }
1889
1890            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)) {
1891                // Parse a struct variant.
1892                let (fields, recovered) =
1893                    match this.parse_record_struct_body("struct", ident.span, false) {
1894                        Ok((fields, recovered)) => (fields, recovered),
1895                        Err(mut err) => {
1896                            if this.token == token::Colon {
1897                                // We handle `enum` to `struct` suggestion in the caller.
1898                                return Err(err);
1899                            }
1900                            this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1901                            this.bump(); // }
1902                            err.span_label(span, "while parsing this enum");
1903                            err.help(help);
1904                            let guar = err.emit();
1905                            (::thin_vec::ThinVec::new()thin_vec![], Recovered::Yes(guar))
1906                        }
1907                    };
1908                VariantData::Struct { fields, recovered }
1909            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1910                let body = match this.parse_tuple_struct_body() {
1911                    Ok(body) => body,
1912                    Err(mut err) => {
1913                        if this.token == token::Colon {
1914                            // We handle `enum` to `struct` suggestion in the caller.
1915                            return Err(err);
1916                        }
1917                        this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
1918                        this.bump(); // )
1919                        err.span_label(span, "while parsing this enum");
1920                        err.help(help);
1921                        err.emit();
1922                        ::thin_vec::ThinVec::new()thin_vec![]
1923                    }
1924                };
1925                VariantData::Tuple(body, DUMMY_NODE_ID)
1926            } else {
1927                VariantData::Unit(DUMMY_NODE_ID)
1928            };
1929
1930            let disr_expr =
1931                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 };
1932
1933            let span = vlo.to(this.prev_token.span);
1934            if ident.name == kw::Underscore {
1935                this.psess.gated_spans.gate(sym::unnamed_enum_variants, span);
1936            }
1937            let vr = ast::Variant {
1938                ident,
1939                vis,
1940                id: DUMMY_NODE_ID,
1941                attrs: variant_attrs,
1942                data: struct_def,
1943                disr_expr,
1944                span,
1945                is_placeholder: false,
1946            };
1947
1948            Ok((Some(vr), Trailing::from(this.token == token::Comma), UsePreAttrPos::No))
1949        })
1950        .map_err(|mut err| {
1951            err.help(help);
1952            err
1953        })
1954    }
1955
1956    /// Parses `struct Foo { ... }`.
1957    fn parse_item_struct(&mut self) -> PResult<'a, ItemKind> {
1958        let ident = self.parse_ident()?;
1959
1960        let mut generics = self.parse_generics()?;
1961
1962        // There is a special case worth noting here, as reported in issue #17904.
1963        // If we are parsing a tuple struct it is the case that the where clause
1964        // should follow the field list. Like so:
1965        //
1966        // struct Foo<T>(T) where T: Copy;
1967        //
1968        // If we are parsing a normal record-style struct it is the case
1969        // that the where clause comes before the body, and after the generics.
1970        // So if we look ahead and see a brace or a where-clause we begin
1971        // parsing a record style struct.
1972        //
1973        // Otherwise if we look ahead and see a paren we parse a tuple-style
1974        // struct.
1975
1976        let vdata = if self.token.is_keyword(kw::Where) {
1977            let tuple_struct_body;
1978            (generics.where_clause, tuple_struct_body) =
1979                self.parse_struct_where_clause(ident, generics.span)?;
1980
1981            if let Some(body) = tuple_struct_body {
1982                // If we see a misplaced tuple struct body: `struct Foo<T> where T: Copy, (T);`
1983                let body = VariantData::Tuple(body, DUMMY_NODE_ID);
1984                self.expect_semi()?;
1985                body
1986            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1987                // If we see a: `struct Foo<T> where T: Copy;` style decl.
1988                VariantData::Unit(DUMMY_NODE_ID)
1989            } else {
1990                // If we see: `struct Foo<T> where T: Copy { ... }`
1991                let (fields, recovered) = self.parse_record_struct_body(
1992                    "struct",
1993                    ident.span,
1994                    generics.where_clause.has_where_token,
1995                )?;
1996                VariantData::Struct { fields, recovered }
1997            }
1998        // No `where` so: `struct Foo<T>;`
1999        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
2000            VariantData::Unit(DUMMY_NODE_ID)
2001        // Record-style struct definition
2002        } else if self.token == token::OpenBrace {
2003            let (fields, recovered) = self.parse_record_struct_body(
2004                "struct",
2005                ident.span,
2006                generics.where_clause.has_where_token,
2007            )?;
2008            VariantData::Struct { fields, recovered }
2009        // Tuple-style struct definition with optional where-clause.
2010        } else if self.token == token::OpenParen {
2011            let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
2012            generics.where_clause = self.parse_where_clause()?;
2013            self.expect_semi()?;
2014            body
2015        } else {
2016            let err = diagnostics::UnexpectedTokenAfterStructName::new(self.token.span, self.token);
2017            return Err(self.dcx().create_err(err));
2018        };
2019
2020        Ok(ItemKind::Struct(ident, generics, vdata))
2021    }
2022
2023    /// Parses `union Foo { ... }`.
2024    fn parse_item_union(&mut self) -> PResult<'a, ItemKind> {
2025        let ident = self.parse_ident()?;
2026
2027        let mut generics = self.parse_generics()?;
2028
2029        let vdata = if self.token.is_keyword(kw::Where) {
2030            generics.where_clause = self.parse_where_clause()?;
2031            let (fields, recovered) = self.parse_record_struct_body(
2032                "union",
2033                ident.span,
2034                generics.where_clause.has_where_token,
2035            )?;
2036            VariantData::Struct { fields, recovered }
2037        } else if self.token == token::OpenBrace {
2038            let (fields, recovered) = self.parse_record_struct_body(
2039                "union",
2040                ident.span,
2041                generics.where_clause.has_where_token,
2042            )?;
2043            VariantData::Struct { fields, recovered }
2044        } else {
2045            let token_str = super::token_descr(&self.token);
2046            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}");
2047            let mut err = self.dcx().struct_span_err(self.token.span, msg);
2048            err.span_label(self.token.span, "expected `where` or `{` after union name");
2049            return Err(err);
2050        };
2051
2052        Ok(ItemKind::Union(ident, generics, vdata))
2053    }
2054
2055    /// This function parses the fields of record structs:
2056    ///
2057    ///   - `struct S { ... }`
2058    ///   - `enum E { Variant { ... } }`
2059    pub(crate) fn parse_record_struct_body(
2060        &mut self,
2061        adt_ty: &str,
2062        ident_span: Span,
2063        parsed_where: bool,
2064    ) -> PResult<'a, (ThinVec<FieldDef>, Recovered)> {
2065        let mut fields = ThinVec::new();
2066        let mut recovered = Recovered::No;
2067        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2068            while self.token != token::CloseBrace {
2069                match self.parse_field_def(adt_ty, ident_span) {
2070                    Ok(field) => {
2071                        fields.push(field);
2072                    }
2073                    Err(mut err) => {
2074                        self.consume_block(
2075                            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace),
2076                            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace),
2077                            ConsumeClosingDelim::No,
2078                        );
2079                        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}"));
2080                        let guar = err.emit();
2081                        recovered = Recovered::Yes(guar);
2082                        break;
2083                    }
2084                }
2085            }
2086            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
2087        } else {
2088            let token_str = super::token_descr(&self.token);
2089            let where_str = if parsed_where { "" } else { "`where`, or " };
2090            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}");
2091            let mut err = self.dcx().struct_span_err(self.token.span, msg);
2092            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",));
2093            return Err(err);
2094        }
2095
2096        Ok((fields, recovered))
2097    }
2098
2099    fn parse_unsafe_field(&mut self) -> Safety {
2100        // not using parse_safety as that also accepts `safe`.
2101        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)) {
2102            let span = self.prev_token.span;
2103            self.psess.gated_spans.gate(sym::unsafe_fields, span);
2104            Safety::Unsafe(span)
2105        } else {
2106            Safety::Default
2107        }
2108    }
2109    /// This is the case where we find `struct Foo<T>(T) where T: Copy;`
2110    /// Unit like structs are handled in parse_item_struct function
2111    pub(super) fn parse_tuple_struct_body(&mut self) -> PResult<'a, ThinVec<FieldDef>> {
2112        let openparen_span = self.token.span;
2113        let mut encountered_colon = false;
2114        self.parse_paren_comma_seq(|p| {
2115            let attrs = p.parse_outer_attributes()?;
2116            p.collect_tokens(None, attrs, ForceCollect::No, |p, attrs| {
2117                let mut snapshot = None;
2118                if p.is_vcs_conflict_marker(&TokenKind::Shl, &TokenKind::Lt) {
2119                    // Account for `<<<<<<<` diff markers. We can't proactively error here because
2120                    // that can be a valid type start, so we snapshot and reparse only we've
2121                    // encountered another parse error.
2122                    snapshot = Some(p.create_snapshot_for_diagnostic());
2123                }
2124                let lo = p.token.span;
2125                let vis = match p.parse_visibility(FollowedByType::Yes) {
2126                    Ok(vis) => vis,
2127                    Err(err) => {
2128                        if let Some(ref mut snapshot) = snapshot {
2129                            snapshot.recover_vcs_conflict_marker();
2130                        }
2131                        return Err(err);
2132                    }
2133                };
2134                let mut_restriction = p.parse_mut_restriction()?;
2135                encountered_colon |=
2136                    p.token.is_ident() && p.look_ahead(1, |tok| tok == &token::Colon);
2137                // Unsafe fields are not supported in tuple structs, as doing so would result in a
2138                // parsing ambiguity for `struct X(unsafe fn())`.
2139                let ty = match p.parse_ty() {
2140                    Ok(ty) => ty,
2141                    Err(err) => {
2142                        if let Some(ref mut snapshot) = snapshot {
2143                            snapshot.recover_vcs_conflict_marker();
2144                        }
2145                        return Err(err);
2146                    }
2147                };
2148                let mut default = None;
2149                if p.token == token::Eq {
2150                    let mut snapshot = p.create_snapshot_for_diagnostic();
2151                    snapshot.bump();
2152                    match snapshot.parse_expr_anon_const() {
2153                        Ok(const_expr) => {
2154                            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2155                            p.psess.gated_spans.gate(sym::default_field_values, sp);
2156                            p.restore_snapshot(snapshot);
2157                            default = Some(const_expr);
2158                        }
2159                        Err(err) => {
2160                            err.cancel();
2161                        }
2162                    }
2163                }
2164
2165                Ok((
2166                    FieldDef {
2167                        span: lo.to(ty.span),
2168                        vis,
2169                        extras: Self::field_def_extras(Safety::Default, mut_restriction, default),
2170                        ident: None,
2171                        id: DUMMY_NODE_ID,
2172                        ty,
2173                        attrs,
2174                        is_placeholder: false,
2175                    },
2176                    Trailing::from(p.token == token::Comma),
2177                    UsePreAttrPos::No,
2178                ))
2179            })
2180        })
2181        .map(|(r, _)| r)
2182        .map_err(|mut error| {
2183            if self.token == token::Colon {
2184                error.subdiagnostic(UseDoubleColonSuggestion { colon: self.token.span });
2185            }
2186            if encountered_colon {
2187                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
2188                self.bump();
2189                error.subdiagnostic(UseRegularStructSuggestion {
2190                    open: openparen_span,
2191                    close: self.prev_token.span,
2192                    semicolon: if self.token == token::Semi { Some(self.token.span) } else { None },
2193                });
2194            }
2195            error
2196        })
2197    }
2198
2199    fn field_def_extras(
2200        safety: Safety,
2201        mut_restriction: MutRestriction,
2202        default: Option<AnonConst>,
2203    ) -> Option<Box<FieldDefExtras>> {
2204        match (safety, mut_restriction, default) {
2205            (
2206                Safety::Default,
2207                // We are throwing away the mut restriction span here.
2208                // see the span field comment for more info
2209                MutRestriction { kind: RestrictionKind::Unrestricted, span: _ },
2210                None,
2211            ) => None,
2212            (safety, mut_restriction, default) => {
2213                Some(Box::new(FieldDefExtras { safety, mut_restriction, default }))
2214            }
2215        }
2216    }
2217
2218    /// Parses an element of a struct declaration.
2219    fn parse_field_def(&mut self, adt_ty: &str, ident_span: Span) -> PResult<'a, FieldDef> {
2220        self.recover_vcs_conflict_marker();
2221        let attrs = self.parse_outer_attributes()?;
2222        self.recover_vcs_conflict_marker();
2223        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2224            let lo = this.token.span;
2225            let vis = this.parse_visibility(FollowedByType::No)?;
2226            let mut_restriction = this.parse_mut_restriction()?;
2227            let safety = this.parse_unsafe_field();
2228            this.parse_single_struct_field(
2229                adt_ty,
2230                lo,
2231                vis,
2232                mut_restriction,
2233                safety,
2234                attrs,
2235                ident_span,
2236            )
2237            .map(|field| (field, Trailing::No, UsePreAttrPos::No))
2238        })
2239    }
2240
2241    /// Parses a structure field declaration.
2242    fn parse_single_struct_field(
2243        &mut self,
2244        adt_ty: &str,
2245        lo: Span,
2246        vis: Visibility,
2247        mut_restriction: MutRestriction,
2248        safety: Safety,
2249        attrs: AttrVec,
2250        ident_span: Span,
2251    ) -> PResult<'a, FieldDef> {
2252        let a_var = self.parse_name_and_ty(adt_ty, lo, vis, mut_restriction, safety, attrs)?;
2253        match self.token.kind {
2254            token::Comma => {
2255                self.bump();
2256            }
2257            token::Semi => {
2258                self.bump();
2259                let sp = self.prev_token.span;
2260                let mut err =
2261                    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 `,`"));
2262                err.span_suggestion_short(
2263                    sp,
2264                    "replace `;` with `,`",
2265                    ",",
2266                    Applicability::MachineApplicable,
2267                );
2268                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}"));
2269                err.emit();
2270            }
2271            token::CloseBrace => {}
2272            token::DocComment(..) => {
2273                let previous_span = self.prev_token.span;
2274                let mut err = diagnostics::DocCommentDoesNotDocumentAnything {
2275                    span: self.token.span,
2276                    missing_comma: None,
2277                };
2278                self.bump(); // consume the doc comment
2279                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 {
2280                    self.dcx().emit_err(err);
2281                } else {
2282                    let sp = previous_span.shrink_to_hi();
2283                    err.missing_comma = Some(sp);
2284                    return Err(self.dcx().create_err(err));
2285                }
2286            }
2287            _ => {
2288                let sp = self.prev_token.span.shrink_to_hi();
2289                let msg =
2290                    ::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));
2291
2292                // Try to recover extra trailing angle brackets
2293                if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind
2294                    && let Some(last_segment) = segments.last()
2295                {
2296                    let guar = self.check_trailing_angle_brackets(
2297                        last_segment,
2298                        &[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)],
2299                    );
2300                    if let Some(_guar) = guar {
2301                        // Handle a case like `Vec<u8>>,` where we can continue parsing fields
2302                        // after the comma
2303                        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
2304
2305                        // `check_trailing_angle_brackets` already emitted a nicer error, as
2306                        // proven by the presence of `_guar`. We can continue parsing.
2307                        return Ok(a_var);
2308                    }
2309                }
2310
2311                let mut err = self.dcx().struct_span_err(sp, msg);
2312
2313                if self.token.is_ident()
2314                    || (self.token == TokenKind::Pound
2315                        && (self.look_ahead(1, |t| t == &token::OpenBracket)))
2316                {
2317                    // This is likely another field, TokenKind::Pound is used for `#[..]`
2318                    // attribute for next field. Emit the diagnostic and continue parsing.
2319                    err.span_suggestion(
2320                        sp,
2321                        "try adding a comma",
2322                        ",",
2323                        Applicability::MachineApplicable,
2324                    );
2325                    err.emit();
2326                } else {
2327                    return Err(err);
2328                }
2329            }
2330        }
2331        Ok(a_var)
2332    }
2333
2334    fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
2335        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)) {
2336            let sm = self.psess.source_map();
2337            let eq_typo = self.token == token::Eq && self.look_ahead(1, |t| t.is_path_start());
2338            let semi_typo = self.token == token::Semi
2339                && self.look_ahead(1, |t| {
2340                    t.is_path_start()
2341                    // We check that we are in a situation like `foo; bar` to avoid bad suggestions
2342                    // when there's no type and `;` was used instead of a comma.
2343                    && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
2344                        (Ok(l), Ok(r)) => l.line == r.line,
2345                        _ => true,
2346                    }
2347                });
2348            if eq_typo || semi_typo {
2349                self.bump();
2350                // Gracefully handle small typos.
2351                err.with_span_suggestion_short(
2352                    self.prev_token.span,
2353                    "field names and their types are separated with `:`",
2354                    ":",
2355                    Applicability::MachineApplicable,
2356                )
2357                .emit();
2358            } else {
2359                return Err(err);
2360            }
2361        }
2362        Ok(())
2363    }
2364
2365    /// Parses a structure field.
2366    fn parse_name_and_ty(
2367        &mut self,
2368        adt_ty: &str,
2369        lo: Span,
2370        vis: Visibility,
2371        mut_restriction: MutRestriction,
2372        safety: Safety,
2373        attrs: AttrVec,
2374    ) -> PResult<'a, FieldDef> {
2375        let name = self.parse_field_ident(adt_ty, lo)?;
2376        if self.token == token::Bang {
2377            if let Err(mut err) = self.unexpected() {
2378                // Encounter the macro invocation
2379                err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
2380                return Err(err);
2381            }
2382        }
2383        self.expect_field_ty_separator()?;
2384        let ty = self.parse_ty()?;
2385        if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
2386            return Err(self
2387                .dcx()
2388                .struct_span_err(self.token.span, "found single colon in a struct field type path")
2389                .with_span_suggestion_verbose(
2390                    self.token.span,
2391                    "write a path separator here",
2392                    "::",
2393                    Applicability::MaybeIncorrect,
2394                ));
2395        }
2396        let default = if self.token == token::Eq {
2397            self.bump();
2398            let const_expr = self.parse_expr_anon_const()?;
2399            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2400            self.psess.gated_spans.gate(sym::default_field_values, sp);
2401            Some(const_expr)
2402        } else {
2403            None
2404        };
2405        Ok(FieldDef {
2406            span: lo.to(self.prev_token.span),
2407            ident: Some(name),
2408            vis,
2409            extras: Self::field_def_extras(safety, mut_restriction, default),
2410            id: DUMMY_NODE_ID,
2411            ty,
2412            attrs,
2413            is_placeholder: false,
2414        })
2415    }
2416
2417    /// Parses a field identifier. Specialized version of `parse_ident_common`
2418    /// for better diagnostics and suggestions.
2419    fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
2420        let (ident, is_raw) = self.ident_or_err(true)?;
2421        if is_raw == IdentIsRaw::No
2422            && ident.is_reserved()
2423            && !(ident.name == kw::Underscore && adt_ty == "enum")
2424        {
2425            let snapshot = self.create_snapshot_for_diagnostic();
2426            let err = if self.check_fn_front_matter(false, Case::Sensitive) {
2427                let inherited_vis = Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited };
2428                // We use `parse_fn` to get a span for the function
2429                let fn_parse_mode =
2430                    FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
2431                match self.parse_fn(
2432                    &mut AttrVec::new(),
2433                    fn_parse_mode,
2434                    lo,
2435                    &inherited_vis,
2436                    Case::Insensitive,
2437                ) {
2438                    Ok(_) => self
2439                        .dcx()
2440                        .struct_span_err(
2441                            lo.to(self.prev_token.span),
2442                            ::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"),
2443                        )
2444                        .with_help(
2445                            "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
2446                        )
2447                        .with_help(
2448                            "see https://doc.rust-lang.org/book/ch05-03-method-syntax.html \
2449                             for more information",
2450                        ),
2451                    Err(err) => {
2452                        err.cancel();
2453                        self.restore_snapshot(snapshot);
2454                        self.expected_ident_found_err()
2455                    }
2456                }
2457            } 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)) {
2458                match self.parse_item_struct() {
2459                    Ok(item) => {
2460                        let ItemKind::Struct(ident, ..) = item else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2461                        self.dcx()
2462                            .struct_span_err(
2463                                lo.with_hi(ident.span.hi()),
2464                                ::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"),
2465                            )
2466                            .with_help(
2467                                "consider creating a new `struct` definition instead of nesting",
2468                            )
2469                    }
2470                    Err(err) => {
2471                        err.cancel();
2472                        self.restore_snapshot(snapshot);
2473                        self.expected_ident_found_err()
2474                    }
2475                }
2476            } else {
2477                let mut err = self.expected_ident_found_err();
2478                if self.eat_keyword_noexpect(kw::Let)
2479                    && let removal_span = self.prev_token.span.until(self.token.span)
2480                    && let Ok(ident) = self
2481                        .parse_ident_common(false)
2482                        // Cancel this error, we don't need it.
2483                        .map_err(|err| err.cancel())
2484                    && self.token == TokenKind::Colon
2485                {
2486                    err.span_suggestion_verbose(
2487                        removal_span,
2488                        "remove the `let` keyword",
2489                        String::new(),
2490                        Applicability::MachineApplicable,
2491                    );
2492                    err.note("the `let` keyword is not allowed in `struct` fields");
2493                    err.note(
2494                        "see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> \
2495                         for more information",
2496                    );
2497                    err.emit();
2498                    return Ok(ident);
2499                } else {
2500                    self.restore_snapshot(snapshot);
2501                }
2502                err
2503            };
2504            return Err(err);
2505        }
2506        self.bump();
2507        Ok(ident)
2508    }
2509
2510    /// Parses a declarative macro 2.0 definition.
2511    /// The `macro` keyword has already been parsed.
2512    /// ```ebnf
2513    /// MacBody = "{" TOKEN_STREAM "}" ;
2514    /// MacParams = "(" TOKEN_STREAM ")" ;
2515    /// DeclMac = "macro" Ident MacParams? MacBody ;
2516    /// ```
2517    fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemKind> {
2518        let ident = self.parse_ident()?;
2519        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)) {
2520            self.parse_delim_args()? // `MacBody`
2521        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
2522            let params = self.parse_token_tree(); // `MacParams`
2523            let pspan = params.span();
2524            if !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2525                self.unexpected()?;
2526            }
2527            let body = self.parse_token_tree(); // `MacBody`
2528            // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
2529            let bspan = body.span();
2530            let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
2531            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]);
2532            let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
2533            Box::new(DelimArgs { dspan, delim: Delimiter::Brace, tokens })
2534        } else {
2535            self.unexpected_any()?
2536        };
2537
2538        self.psess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
2539        Ok(ItemKind::MacroDef(
2540            ident,
2541            ast::MacroDef { body, macro_rules: false, eii_declaration: None },
2542        ))
2543    }
2544
2545    /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
2546    fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
2547        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)) {
2548            let macro_rules_span = self.token.span;
2549
2550            if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) {
2551                return IsMacroRulesItem::Yes { has_bang: true };
2552            } else if self.look_ahead(1, |t| t.is_ident()) {
2553                // macro_rules foo
2554                self.dcx().emit_err(diagnostics::MacroRulesMissingBang {
2555                    span: macro_rules_span,
2556                    hi: macro_rules_span.shrink_to_hi(),
2557                });
2558
2559                return IsMacroRulesItem::Yes { has_bang: false };
2560            }
2561        }
2562
2563        IsMacroRulesItem::No
2564    }
2565
2566    /// Parses a `macro_rules! foo { ... }` declarative macro.
2567    fn parse_item_macro_rules(
2568        &mut self,
2569        vis: &Visibility,
2570        has_bang: bool,
2571    ) -> PResult<'a, ItemKind> {
2572        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::MacroRules,
    token_type: crate::parser::token_type::TokenType::KwMacroRules,
}exp!(MacroRules))?; // `macro_rules`
2573
2574        if has_bang {
2575            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
2576        }
2577        let ident = self.parse_ident()?;
2578
2579        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
2580            // Handle macro_rules! foo!
2581            let span = self.prev_token.span;
2582            self.dcx().emit_err(diagnostics::MacroNameRemoveBang { span });
2583        }
2584
2585        let body = self.parse_delim_args()?;
2586        self.eat_semi_for_macro_if_needed(&body, None);
2587        self.complain_if_pub_macro(vis, true);
2588
2589        Ok(ItemKind::MacroDef(
2590            ident,
2591            ast::MacroDef { body, macro_rules: true, eii_declaration: None },
2592        ))
2593    }
2594
2595    /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
2596    /// If that's not the case, emit an error.
2597    fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
2598        if let VisibilityKind::Inherited = vis.kind {
2599            return;
2600        }
2601
2602        let vstr = pprust::vis_to_string(vis);
2603        let vstr = vstr.trim_end();
2604        if macro_rules {
2605            self.dcx().emit_err(diagnostics::MacroRulesVisibility { span: vis.span, vis: vstr });
2606        } else {
2607            self.dcx()
2608                .emit_err(diagnostics::MacroInvocationVisibility { span: vis.span, vis: vstr });
2609        }
2610    }
2611
2612    fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs, path: Option<&Path>) {
2613        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)) {
2614            self.report_invalid_macro_expansion_item(args, path);
2615        }
2616    }
2617
2618    fn report_invalid_macro_expansion_item(&self, args: &DelimArgs, path: Option<&Path>) {
2619        let span = args.dspan.entire();
2620        let mut err = self.dcx().struct_span_err(
2621            span,
2622            "macros that expand to items must be delimited with braces or followed by a semicolon",
2623        );
2624        // FIXME: This will make us not emit the help even for declarative
2625        // macros within the same crate (that we can fix), which is sad.
2626        if !span.from_expansion() {
2627            let DelimSpan { open, close } = args.dspan;
2628            // Check if this looks like `macro_rules!(name) { ... }`
2629            // a common mistake when trying to define a macro.
2630            if let Some(path) = path
2631                && path.segments.first().is_some_and(|seg| seg.ident.name == sym::macro_rules)
2632                && args.delim == Delimiter::Parenthesis
2633            {
2634                let replace =
2635                    if path.span.hi() + rustc_span::BytePos(1) < open.lo() { "" } else { " " };
2636                err.multipart_suggestion(
2637                    "to define a macro, remove the parentheses around the macro name",
2638                    ::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())],
2639                    Applicability::MachineApplicable,
2640                );
2641            } else {
2642                err.multipart_suggestion(
2643                    "change the delimiters to curly braces",
2644                    ::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())],
2645                    Applicability::MaybeIncorrect,
2646                );
2647                err.span_suggestion_verbose(
2648                    span.with_neighbor(self.token.span).shrink_to_hi(),
2649                    "add a semicolon",
2650                    ';',
2651                    Applicability::MaybeIncorrect,
2652                );
2653            }
2654        }
2655        err.emit();
2656    }
2657
2658    /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2659    /// it is, we try to parse the item and report error about nested types.
2660    fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2661        if (self.token.is_keyword(kw::Enum)
2662            || self.token.is_keyword(kw::Struct)
2663            || self.token.is_keyword(kw::Union))
2664            && self.look_ahead(1, |t| t.is_ident())
2665        {
2666            let kw_token = self.token;
2667            let kw_str = pprust::token_to_string(&kw_token);
2668            let item = self.parse_item(
2669                ForceCollect::No,
2670                AllowConstBlockItems::DoesNotMatter, // self.token != kw::Const
2671            )?;
2672            let mut item = item.unwrap().span;
2673            if self.token == token::Comma {
2674                item = item.to(self.token.span);
2675            }
2676            self.dcx().emit_err(diagnostics::NestedAdt {
2677                span: kw_token.span,
2678                item,
2679                kw_str,
2680                keyword: keyword.as_str(),
2681            });
2682            // We successfully parsed the item but we must inform the caller about nested problem.
2683            return Ok(false);
2684        }
2685        Ok(true)
2686    }
2687
2688    fn check_impl_frontmatter(&mut self, look_ahead: usize) -> bool {
2689        const ALL_QUALS: &[Symbol] = &[kw::Const, kw::Unsafe];
2690        // In contrast to the loop below, this call inserts `impl` into the
2691        // list of expected tokens shown in diagnostics.
2692        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)) {
2693            return true;
2694        }
2695        let mut i = 0;
2696        while i < ALL_QUALS.len() {
2697            let action = self.look_ahead(i + look_ahead, |token| {
2698                if token.is_keyword(kw::Impl) {
2699                    return Some(true);
2700                }
2701                if ALL_QUALS.iter().any(|&qual| token.is_keyword(qual)) {
2702                    // Ok, we found a legal keyword, keep looking for `impl`
2703                    return None;
2704                }
2705                Some(false)
2706            });
2707            if let Some(ret) = action {
2708                return ret;
2709            }
2710            i += 1;
2711        }
2712
2713        self.is_keyword_ahead(i, &[kw::Impl])
2714    }
2715
2716    /// Try to recover from over-parsing in const item when a semicolon is missing.
2717    ///
2718    /// This detects cases where we parsed too much because a semicolon was missing
2719    /// and the next line started an expression that the parser treated as a continuation
2720    /// (e.g., `foo() \n &bar` was parsed as `foo() & bar`).
2721    ///
2722    /// Returns a corrected expression if recovery is successful.
2723    fn try_recover_const_missing_semi(
2724        &mut self,
2725        rhs: &Option<Box<Expr>>,
2726        const_span: Span,
2727    ) -> Option<Box<Expr>> {
2728        if self.token == TokenKind::Semi {
2729            return None;
2730        }
2731        let Some(rhs) = rhs else {
2732            return None;
2733        };
2734        if !self.in_fn_body || !self.may_recover() || rhs.span.from_expansion() {
2735            return None;
2736        }
2737        if let Some((span, guar)) =
2738            self.missing_semi_from_binop("const", rhs, Some(const_span.shrink_to_lo()))
2739        {
2740            self.fn_body_missing_semi_guar = Some(guar);
2741            Some(self.mk_expr(span, ExprKind::Err(guar)))
2742        } else {
2743            None
2744        }
2745    }
2746}
2747enum IsMacroRulesItem {
2748    Yes { has_bang: bool },
2749    No,
2750}