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, InvisibleOrigin, 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_session::lint::builtin::VARARGS_WITHOUT_PATTERN;
14use rustc_span::edit_distance::edit_distance;
15use rustc_span::edition::Edition;
16use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, respan, sym};
17use thin_vec::{ThinVec, thin_vec};
18use tracing::debug;
19
20use super::diagnostics::{ConsumeClosingDelim, dummy_arg};
21use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
22use super::{
23    AllowConstBlockItems, AttrWrapper, ExpKeywordPair, ExpTokenPair, FollowedByType, ForceCollect,
24    Parser, PathStyle, Recovered, Trailing, UsePreAttrPos,
25};
26use crate::diagnostics::{
27    self, FnPointerCannotBeAsync, FnPointerCannotBeConst, MacroExpandsToAdtField,
28    UseDoubleColonSuggestion, UseRegularStructSuggestion,
29};
30use crate::exp;
31
32impl<'a> Parser<'a> {
33    /// Parses a source module as a crate. This is the main entry point for the parser.
34    pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
35        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))?;
36        Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
37    }
38
39    /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
40    fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemKind> {
41        let safety = self.parse_safety(Case::Sensitive);
42        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Mod,
    token_type: crate::parser::token_type::TokenType::KwMod,
}exp!(Mod))?;
43        let ident = self.parse_ident()?;
44        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)) {
45            ModKind::Unloaded
46        } else {
47            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))?;
48            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))?;
49            attrs.extend(inner_attrs);
50            ModKind::Loaded(items, Inline::Yes, inner_span)
51        };
52        Ok(ItemKind::Mod(safety, ident, mod_kind))
53    }
54
55    /// Parses the contents of a module (inner attributes followed by module items).
56    /// We exit once we hit `term` which can be either
57    /// - EOF (for files)
58    /// - `}` for mod items
59    pub fn parse_mod(
60        &mut self,
61        term: ExpTokenPair,
62    ) -> PResult<'a, (AttrVec, ThinVec<Box<Item>>, ModSpans)> {
63        let lo = self.token.span;
64        let attrs = self.parse_inner_attributes()?;
65
66        let post_attr_lo = self.token.span;
67        let mut items: ThinVec<Box<_>> = ThinVec::new();
68
69        // There shouldn't be any stray semicolons before or after items.
70        // `parse_item` consumes the appropriate semicolons so any leftover is an error.
71        loop {
72            while self.maybe_consume_incorrect_semicolon(items.last().map(|x| &**x)) {} // Eat all bad semicolons
73            let Some(item) = self.parse_item(ForceCollect::No, AllowConstBlockItems::Yes)? else {
74                break;
75            };
76            items.push(item);
77        }
78
79        if !self.eat(term) {
80            let token_str = super::token_descr(&self.token);
81            if !self.maybe_consume_incorrect_semicolon(items.last().map(|x| &**x)) {
82                let is_let = self.token.is_keyword(kw::Let);
83                let is_let_mut = is_let && self.look_ahead(1, |t| t.is_keyword(kw::Mut));
84                let let_has_ident = is_let && !is_let_mut && self.is_kw_followed_by_ident(kw::Let);
85
86                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected item, found {0}",
                token_str))
    })format!("expected item, found {token_str}");
87                let mut err = self.dcx().struct_span_err(self.token.span, msg);
88
89                let label = if is_let {
90                    "`let` cannot be used for global variables"
91                } else {
92                    "expected item"
93                };
94                err.span_label(self.token.span, label);
95
96                if is_let {
97                    if is_let_mut {
98                        err.help("consider using `static` and a `Mutex` instead of `let mut`");
99                    } else if let_has_ident {
100                        err.span_suggestion_short(
101                            self.token.span,
102                            "consider using `static` or `const` instead of `let`",
103                            "static",
104                            Applicability::MaybeIncorrect,
105                        );
106                    } else {
107                        err.help("consider using `static` or `const` instead of `let`");
108                    }
109                }
110                err.note("for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>");
111                return Err(err);
112            }
113        }
114
115        let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
116        let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
117        Ok((attrs, items, mod_spans))
118    }
119}
120
121enum ReuseKind {
122    Path,
123    Impl,
124}
125
126impl<'a> Parser<'a> {
127    pub fn parse_item(
128        &mut self,
129        force_collect: ForceCollect,
130        allow_const_block_items: AllowConstBlockItems,
131    ) -> PResult<'a, Option<Box<Item>>> {
132        let fn_parse_mode =
133            FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
134        self.parse_item_(fn_parse_mode, force_collect, allow_const_block_items)
135            .map(|i| i.map(Box::new))
136    }
137
138    fn parse_item_(
139        &mut self,
140        fn_parse_mode: FnParseMode,
141        force_collect: ForceCollect,
142        const_block_items_allowed: AllowConstBlockItems,
143    ) -> PResult<'a, Option<Item>> {
144        self.recover_vcs_conflict_marker();
145        let attrs = self.parse_outer_attributes()?;
146        self.recover_vcs_conflict_marker();
147        self.parse_item_common(
148            attrs,
149            true,
150            false,
151            fn_parse_mode,
152            force_collect,
153            const_block_items_allowed,
154        )
155    }
156
157    pub(super) fn parse_item_common(
158        &mut self,
159        attrs: AttrWrapper,
160        mac_allowed: bool,
161        attrs_allowed: bool,
162        fn_parse_mode: FnParseMode,
163        force_collect: ForceCollect,
164        allow_const_block_items: AllowConstBlockItems,
165    ) -> PResult<'a, Option<Item>> {
166        if let Some(item) = self.eat_metavar_seq(MetaVarKind::Item, |this| {
167            this.parse_item(ForceCollect::Yes, allow_const_block_items)
168        }) {
169            let mut item = item.expect("an actual item");
170            attrs.prepend_to_nt_inner(&mut item.attrs);
171            return Ok(Some(*item));
172        }
173
174        self.collect_tokens(None, attrs, force_collect, |this, mut attrs| {
175            let lo = this.token.span;
176            let vis = this.parse_visibility(FollowedByType::No)?;
177            let mut def = this.parse_defaultness();
178            let kind = this.parse_item_kind(
179                &mut attrs,
180                mac_allowed,
181                allow_const_block_items,
182                lo,
183                &vis,
184                &mut def,
185                fn_parse_mode,
186                Case::Sensitive,
187            )?;
188            if let Some(kind) = kind {
189                this.error_on_unconsumed_default(def, &kind);
190                let span = lo.to(this.prev_token.span);
191                let id = DUMMY_NODE_ID;
192                let item = Item { attrs, id, kind, vis, span, tokens: None };
193                return Ok((Some(item), Trailing::No, UsePreAttrPos::No));
194            }
195
196            // At this point, we have failed to parse an item.
197            if !#[allow(non_exhaustive_omitted_patterns)] match vis.kind {
    VisibilityKind::Inherited => true,
    _ => false,
}matches!(vis.kind, VisibilityKind::Inherited) {
198                let vis_str = pprust::vis_to_string(&vis).trim_end().to_string();
199                let mut err = this.dcx().create_err(diagnostics::VisibilityNotFollowedByItem {
200                    span: vis.span,
201                    vis: vis_str,
202                });
203                if let Some((ident, _)) = this.token.ident()
204                    && !ident.is_used_keyword()
205                    && let Some((similar_kw, is_incorrect_case)) = ident
206                        .name
207                        .find_similar(&rustc_span::symbol::used_keywords(|| ident.span.edition()))
208                {
209                    err.subdiagnostic(diagnostics::MisspelledKw {
210                        similar_kw: similar_kw.to_string(),
211                        span: ident.span,
212                        is_incorrect_case,
213                    });
214                }
215                err.emit();
216            }
217
218            if let Defaultness::Default(span) = def {
219                this.dcx().emit_err(diagnostics::DefaultNotFollowedByItem { span });
220            } else if let Defaultness::Final(span) = def {
221                this.dcx().emit_err(diagnostics::FinalNotFollowedByItem { span });
222            }
223
224            if !attrs_allowed {
225                this.recover_attrs_no_item(&attrs)?;
226            }
227            Ok((None, Trailing::No, UsePreAttrPos::No))
228        })
229    }
230
231    /// Error in-case `default`/`final` was parsed in an in-appropriate context.
232    fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
233        match def {
234            Defaultness::Default(span) => {
235                self.dcx().emit_err(diagnostics::InappropriateDefault {
236                    span,
237                    article: kind.article(),
238                    descr: kind.descr(),
239                });
240            }
241            Defaultness::Final(span) => {
242                self.dcx().emit_err(diagnostics::InappropriateFinal {
243                    span,
244                    article: kind.article(),
245                    descr: kind.descr(),
246                });
247            }
248            Defaultness::Implicit => (),
249        }
250    }
251
252    /// Parses one of the items allowed by the flags.
253    fn parse_item_kind(
254        &mut self,
255        attrs: &mut AttrVec,
256        macros_allowed: bool,
257        allow_const_block_items: AllowConstBlockItems,
258        lo: Span,
259        vis: &Visibility,
260        def: &mut Defaultness,
261        fn_parse_mode: FnParseMode,
262        case: Case,
263    ) -> PResult<'a, Option<ItemKind>> {
264        let check_pub = def == &Defaultness::Implicit;
265        let mut def_ = || mem::replace(def, Defaultness::Implicit);
266
267        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) {
268            self.parse_use_item()?
269        } else if self.check_fn_front_matter(check_pub, case) {
270            // FUNCTION ITEM
271            let defaultness = def_();
272            if let Defaultness::Default(span) = defaultness {
273                // Default functions should only require feature `min_specialization`. We remove the
274                // `specialization` tag again as such spans *require* feature `specialization` to be
275                // enabled. In a later stage, we make `specialization` imply `min_specialization`.
276                self.psess.gated_spans.gate(sym::min_specialization, span);
277                self.psess.gated_spans.ungate_last(sym::specialization, span);
278            }
279            let (ident, sig, generics, contract, body) =
280                self.parse_fn(attrs, fn_parse_mode, lo, vis, case)?;
281            ItemKind::Fn(Box::new(Fn {
282                defaultness,
283                ident,
284                sig,
285                generics,
286                contract,
287                body,
288                define_opaque: None,
289                eii_impls: ThinVec::new(),
290            }))
291        } 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) {
292            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) {
293                // EXTERN CRATE
294                self.parse_item_extern_crate()?
295            } else {
296                // EXTERN BLOCK
297                self.parse_item_foreign_mod(attrs, Safety::Default)?
298            }
299        } else if self.is_unsafe_foreign_mod() {
300            // EXTERN BLOCK
301            let safety = self.parse_safety(Case::Sensitive);
302            self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern))?;
303            self.parse_item_foreign_mod(attrs, safety)?
304        } else if let Some(safety) = self.parse_global_static_front_matter(case) {
305            // STATIC ITEM
306            let mutability = self.parse_mutability();
307            self.parse_static_item(safety, mutability)?
308        } 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() {
309            // TRAIT ITEM
310            self.parse_item_trait(attrs, lo)?
311        } else if self.check_impl_frontmatter(0) {
312            // IMPL ITEM
313            self.parse_item_impl(attrs, def_(), false)?
314        } else if let AllowConstBlockItems::Yes | AllowConstBlockItems::DoesNotMatter =
315            allow_const_block_items
316            && self.check_inline_const(0)
317        {
318            // CONST BLOCK ITEM
319            if let AllowConstBlockItems::DoesNotMatter = allow_const_block_items {
320                {
    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:320",
                        "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(320u32),
                        ::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);
321            };
322            ItemKind::ConstBlock(self.parse_const_block_item()?)
323        } else if let Const::Yes(const_span) = self.parse_constness(case) {
324            // CONST ITEM
325            self.recover_const_mut(const_span);
326            self.recover_missing_kw_before_item()?;
327            let (ident, generics, ty, body) = self.parse_const_item(const_span)?;
328            ItemKind::Const(Box::new(ConstItem {
329                defaultness: def_(),
330                ident,
331                generics,
332                ty,
333                body,
334                kind: ConstItemKind::Body,
335                define_opaque: None,
336            }))
337        } else if let Some(kind) = self.is_reuse_item() {
338            self.parse_item_delegation(attrs, def_(), kind)?
339        } else if self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Mod,
    token_type: crate::parser::token_type::TokenType::KwMod,
}exp!(Mod), case)
340            || self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe), case) && self.is_keyword_ahead(1, &[kw::Mod])
341        {
342            // MODULE ITEM
343            self.parse_item_mod(attrs)?
344        } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Type,
    token_type: crate::parser::token_type::TokenType::KwType,
}exp!(Type), case) {
345            if let Const::Yes(const_span) = self.parse_constness(case) {
346                // TYPE CONST (mgca)
347                self.recover_const_mut(const_span);
348                self.recover_missing_kw_before_item()?;
349                let (ident, generics, ty, body) = self.parse_const_item(const_span)?;
350                // Make sure this is only allowed if the feature gate is enabled.
351                // #![feature(mgca_type_const_syntax)]
352                self.psess.gated_spans.gate(sym::mgca_type_const_syntax, lo.to(const_span));
353                ItemKind::Const(Box::new(ConstItem {
354                    defaultness: def_(),
355                    ident,
356                    generics,
357                    ty,
358                    body,
359                    kind: ConstItemKind::TypeConst,
360                    define_opaque: None,
361                }))
362            } else {
363                // TYPE ITEM
364                self.parse_type_alias(def_())?
365            }
366        } 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) {
367            // ENUM ITEM
368            self.parse_item_enum()?
369        } 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) {
370            // STRUCT ITEM
371            self.parse_item_struct()?
372        } else if self.is_kw_followed_by_ident(kw::Union) {
373            // UNION ITEM
374            self.bump(); // `union`
375            self.parse_item_union()?
376        } else if self.is_builtin() {
377            // BUILTIN# ITEM
378            return self.parse_item_builtin();
379        } 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) {
380            // MACROS 2.0 ITEM
381            self.parse_item_decl_macro(lo)?
382        } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
383            // MACRO_RULES ITEM
384            self.parse_item_macro_rules(vis, has_bang)?
385        } else if self.isnt_macro_invocation()
386            && (self.token.is_ident_named(sym::import)
387                || self.token.is_ident_named(sym::using)
388                || self.token.is_ident_named(sym::include)
389                || self.token.is_ident_named(sym::require))
390        {
391            return self.recover_import_as_use();
392        } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
393            self.recover_missing_kw_before_item()?;
394            return Ok(None);
395        } else if self.isnt_macro_invocation() && case == Case::Sensitive {
396            _ = def_;
397
398            // Recover wrong cased keywords
399            return self.parse_item_kind(
400                attrs,
401                macros_allowed,
402                allow_const_block_items,
403                lo,
404                vis,
405                def,
406                fn_parse_mode,
407                Case::Insensitive,
408            );
409        } else if macros_allowed && self.check_path() {
410            if self.isnt_macro_invocation() {
411                self.recover_missing_kw_before_item()?;
412            }
413            // MACRO INVOCATION ITEM
414            ItemKind::MacCall(Box::new(self.parse_item_macro(vis)?))
415        } else {
416            return Ok(None);
417        };
418        Ok(Some(info))
419    }
420
421    fn recover_import_as_use(&mut self) -> PResult<'a, Option<ItemKind>> {
422        let span = self.token.span;
423        let token_name = super::token_descr(&self.token);
424        let snapshot = self.create_snapshot_for_diagnostic();
425        self.bump();
426        match self.parse_use_item() {
427            Ok(u) => {
428                self.dcx().emit_err(diagnostics::RecoverImportAsUse { span, token_name });
429                Ok(Some(u))
430            }
431            Err(e) => {
432                e.cancel();
433                self.restore_snapshot(snapshot);
434                Ok(None)
435            }
436        }
437    }
438
439    fn parse_use_item(&mut self) -> PResult<'a, ItemKind> {
440        let tree = self.parse_use_tree()?;
441        if let Err(mut e) = self.expect_semi() {
442            match tree.kind {
443                UseTreeKind::Glob(_) => {
444                    e.note("the wildcard token must be last on the path");
445                }
446                UseTreeKind::Nested { .. } => {
447                    e.note("glob-like brace syntax must be last on the path");
448                }
449                _ => (),
450            }
451            return Err(e);
452        }
453        Ok(ItemKind::Use(tree))
454    }
455
456    /// When parsing a statement, would the start of a path be an item?
457    pub(super) fn is_path_start_item(&mut self) -> bool {
458        self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
459        || self.is_reuse_item().is_some() // yes: `reuse impl Trait for Struct { self.0 }`, yes: `reuse some_path::foo;`
460        || self.check_trait_front_matter() // no: `auto::b`, yes: `auto trait X { .. }`
461        || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
462        || #[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`
463    }
464
465    fn is_reuse_item(&mut self) -> Option<ReuseKind> {
466        if !self.token.is_keyword(kw::Reuse) {
467            return None;
468        }
469
470        // no: `reuse ::path` for compatibility reasons with macro invocations
471        if self.look_ahead(1, |t| t.is_path_start() && *t != token::PathSep) {
472            Some(ReuseKind::Path)
473        } else if self.check_impl_frontmatter(1) {
474            Some(ReuseKind::Impl)
475        } else {
476            None
477        }
478    }
479
480    /// Are we sure this could not possibly be a macro invocation?
481    fn isnt_macro_invocation(&mut self) -> bool {
482        self.check_ident() && self.look_ahead(1, |t| *t != token::Bang && *t != token::PathSep)
483    }
484
485    /// Recover on encountering a struct, enum, or method definition where the user
486    /// forgot to add the `struct`, `enum`, or `fn` keyword
487    fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
488        let is_pub = self.prev_token.is_keyword(kw::Pub);
489        let is_const = self.prev_token.is_keyword(kw::Const);
490        let ident_span = self.token.span;
491        let span = if is_pub { self.prev_token.span.to(ident_span) } else { ident_span };
492        let insert_span = ident_span.shrink_to_lo();
493
494        let ident = if self.token.is_ident()
495            && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen))
496            && self.look_ahead(1, |t| {
497                #[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)
498            }) {
499            self.parse_ident_common(true).unwrap()
500        } else {
501            return Ok(());
502        };
503
504        let mut found_generics = false;
505        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Lt,
    token_type: crate::parser::token_type::TokenType::Lt,
}exp!(Lt)) {
506            found_generics = true;
507            self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)]);
508            self.bump(); // `>`
509        }
510
511        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)) {
512            // possible struct or enum definition where `struct` or `enum` was forgotten
513            if self.look_ahead(1, |t| *t == token::CloseBrace) {
514                // `S {}` could be unit enum or struct
515                Some(diagnostics::MissingKeywordForItemDefinition::EnumOrStruct { span })
516            } else if self.look_ahead(2, |t| *t == token::Colon)
517                || self.look_ahead(3, |t| *t == token::Colon)
518            {
519                // `S { f:` or `S { pub f:`
520                Some(diagnostics::MissingKeywordForItemDefinition::Struct {
521                    span,
522                    insert_span,
523                    ident,
524                })
525            } else {
526                Some(diagnostics::MissingKeywordForItemDefinition::Enum {
527                    span,
528                    insert_span,
529                    ident,
530                })
531            }
532        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
533            // possible function or tuple struct definition where `fn` or `struct` was forgotten
534            self.bump(); // `(`
535            let is_method = self.recover_self_param();
536
537            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);
538
539            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)) {
540                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)]);
541                self.bump(); // `{`
542                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);
543                if is_method {
544                    diagnostics::MissingKeywordForItemDefinition::Method {
545                        span,
546                        insert_span,
547                        ident,
548                    }
549                } else {
550                    diagnostics::MissingKeywordForItemDefinition::Function {
551                        span,
552                        insert_span,
553                        ident,
554                    }
555                }
556            } 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)) {
557                diagnostics::MissingKeywordForItemDefinition::Struct { span, insert_span, ident }
558            } else {
559                diagnostics::MissingKeywordForItemDefinition::Ambiguous {
560                    span,
561                    subdiag: if found_generics {
562                        None
563                    } else if let Ok(snippet) = self.span_to_snippet(ident_span) {
564                        Some(diagnostics::AmbiguousMissingKwForItemSub::SuggestMacro {
565                            span: ident_span,
566                            snippet,
567                        })
568                    } else {
569                        Some(diagnostics::AmbiguousMissingKwForItemSub::HelpMacro)
570                    },
571                }
572            };
573            Some(err)
574        } else if found_generics {
575            Some(diagnostics::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: None })
576        } else {
577            None
578        };
579
580        if let Some(err) = err { Err(self.dcx().create_err(err)) } else { Ok(()) }
581    }
582
583    fn parse_item_builtin(&mut self) -> PResult<'a, Option<ItemKind>> {
584        // To be expanded
585        Ok(None)
586    }
587
588    /// Parses an item macro, e.g., `item!();`.
589    fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
590        let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
591        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
592        match self.parse_delim_args() {
593            // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
594            Ok(args) => {
595                self.eat_semi_for_macro_if_needed(&args, Some(&path));
596                self.complain_if_pub_macro(vis, false);
597                Ok(MacCall { path, args })
598            }
599
600            Err(mut err) => {
601                // Maybe the user misspelled `macro_rules` (issue #91227)
602                if self.token.is_ident()
603                    && let [segment] = path.segments.as_slice()
604                    && edit_distance("macro_rules", &segment.ident.to_string(), 2).is_some()
605                {
606                    err.span_suggestion(
607                        path.span,
608                        "perhaps you meant to define a macro",
609                        "macro_rules",
610                        Applicability::MachineApplicable,
611                    );
612                }
613                Err(err)
614            }
615        }
616    }
617
618    /// Recover if we parsed attributes and expected an item but there was none.
619    fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
620        let ([start @ end] | [start, .., end]) = attrs else {
621            return Ok(());
622        };
623        let msg = if end.is_doc_comment() {
624            "expected item after doc comment"
625        } else {
626            "expected item after attributes"
627        };
628        let mut err = self.dcx().struct_span_err(end.span, msg);
629        if end.is_doc_comment() {
630            err.span_label(end.span, "this doc comment doesn't document anything");
631        } else if self.token == TokenKind::Semi {
632            err.span_suggestion_verbose(
633                self.token.span,
634                "consider removing this semicolon",
635                "",
636                Applicability::MaybeIncorrect,
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    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                        mut_restriction,
2170                        safety: Safety::Default,
2171                        ident: None,
2172                        id: DUMMY_NODE_ID,
2173                        ty,
2174                        default,
2175                        attrs,
2176                        is_placeholder: false,
2177                    },
2178                    Trailing::from(p.token == token::Comma),
2179                    UsePreAttrPos::No,
2180                ))
2181            })
2182        })
2183        .map(|(r, _)| r)
2184        .map_err(|mut error| {
2185            if self.token == token::Colon {
2186                error.subdiagnostic(UseDoubleColonSuggestion { colon: self.token.span });
2187            }
2188            if encountered_colon {
2189                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
2190                self.bump();
2191                error.subdiagnostic(UseRegularStructSuggestion {
2192                    open: openparen_span,
2193                    close: self.prev_token.span,
2194                    semicolon: if self.token == token::Semi { Some(self.token.span) } else { None },
2195                });
2196            }
2197            error
2198        })
2199    }
2200
2201    /// Parses an element of a struct declaration.
2202    fn parse_field_def(&mut self, adt_ty: &str, ident_span: Span) -> PResult<'a, FieldDef> {
2203        self.recover_vcs_conflict_marker();
2204        let attrs = self.parse_outer_attributes()?;
2205        self.recover_vcs_conflict_marker();
2206        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2207            let lo = this.token.span;
2208            let vis = this.parse_visibility(FollowedByType::No)?;
2209            let mut_restriction = this.parse_mut_restriction()?;
2210            let safety = this.parse_unsafe_field();
2211            this.parse_single_struct_field(
2212                adt_ty,
2213                lo,
2214                vis,
2215                mut_restriction,
2216                safety,
2217                attrs,
2218                ident_span,
2219            )
2220            .map(|field| (field, Trailing::No, UsePreAttrPos::No))
2221        })
2222    }
2223
2224    /// Parses a structure field declaration.
2225    fn parse_single_struct_field(
2226        &mut self,
2227        adt_ty: &str,
2228        lo: Span,
2229        vis: Visibility,
2230        mut_restriction: MutRestriction,
2231        safety: Safety,
2232        attrs: AttrVec,
2233        ident_span: Span,
2234    ) -> PResult<'a, FieldDef> {
2235        let a_var = self.parse_name_and_ty(adt_ty, lo, vis, mut_restriction, safety, attrs)?;
2236        match self.token.kind {
2237            token::Comma => {
2238                self.bump();
2239            }
2240            token::Semi => {
2241                self.bump();
2242                let sp = self.prev_token.span;
2243                let mut err =
2244                    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 `,`"));
2245                err.span_suggestion_short(
2246                    sp,
2247                    "replace `;` with `,`",
2248                    ",",
2249                    Applicability::MachineApplicable,
2250                );
2251                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}"));
2252                err.emit();
2253            }
2254            token::CloseBrace => {}
2255            token::DocComment(..) => {
2256                let previous_span = self.prev_token.span;
2257                let mut err = diagnostics::DocCommentDoesNotDocumentAnything {
2258                    span: self.token.span,
2259                    missing_comma: None,
2260                };
2261                self.bump(); // consume the doc comment
2262                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 {
2263                    self.dcx().emit_err(err);
2264                } else {
2265                    let sp = previous_span.shrink_to_hi();
2266                    err.missing_comma = Some(sp);
2267                    return Err(self.dcx().create_err(err));
2268                }
2269            }
2270            _ => {
2271                let sp = self.prev_token.span.shrink_to_hi();
2272                let msg =
2273                    ::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));
2274
2275                // Try to recover extra trailing angle brackets
2276                if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind
2277                    && let Some(last_segment) = segments.last()
2278                {
2279                    let guar = self.check_trailing_angle_brackets(
2280                        last_segment,
2281                        &[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)],
2282                    );
2283                    if let Some(_guar) = guar {
2284                        // Handle a case like `Vec<u8>>,` where we can continue parsing fields
2285                        // after the comma
2286                        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
2287
2288                        // `check_trailing_angle_brackets` already emitted a nicer error, as
2289                        // proven by the presence of `_guar`. We can continue parsing.
2290                        return Ok(a_var);
2291                    }
2292                }
2293
2294                let mut err = self.dcx().struct_span_err(sp, msg);
2295
2296                if self.token.is_ident()
2297                    || (self.token == TokenKind::Pound
2298                        && (self.look_ahead(1, |t| t == &token::OpenBracket)))
2299                {
2300                    // This is likely another field, TokenKind::Pound is used for `#[..]`
2301                    // attribute for next field. Emit the diagnostic and continue parsing.
2302                    err.span_suggestion(
2303                        sp,
2304                        "try adding a comma",
2305                        ",",
2306                        Applicability::MachineApplicable,
2307                    );
2308                    err.emit();
2309                } else {
2310                    return Err(err);
2311                }
2312            }
2313        }
2314        Ok(a_var)
2315    }
2316
2317    fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
2318        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)) {
2319            let sm = self.psess.source_map();
2320            let eq_typo = self.token == token::Eq && self.look_ahead(1, |t| t.is_path_start());
2321            let semi_typo = self.token == token::Semi
2322                && self.look_ahead(1, |t| {
2323                    t.is_path_start()
2324                    // We check that we are in a situation like `foo; bar` to avoid bad suggestions
2325                    // when there's no type and `;` was used instead of a comma.
2326                    && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
2327                        (Ok(l), Ok(r)) => l.line == r.line,
2328                        _ => true,
2329                    }
2330                });
2331            if eq_typo || semi_typo {
2332                self.bump();
2333                // Gracefully handle small typos.
2334                err.with_span_suggestion_short(
2335                    self.prev_token.span,
2336                    "field names and their types are separated with `:`",
2337                    ":",
2338                    Applicability::MachineApplicable,
2339                )
2340                .emit();
2341            } else {
2342                return Err(err);
2343            }
2344        }
2345        Ok(())
2346    }
2347
2348    /// Parses a structure field.
2349    fn parse_name_and_ty(
2350        &mut self,
2351        adt_ty: &str,
2352        lo: Span,
2353        vis: Visibility,
2354        mut_restriction: MutRestriction,
2355        safety: Safety,
2356        attrs: AttrVec,
2357    ) -> PResult<'a, FieldDef> {
2358        let name = self.parse_field_ident(adt_ty, lo)?;
2359        if self.token == token::Bang {
2360            if let Err(mut err) = self.unexpected() {
2361                // Encounter the macro invocation
2362                err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
2363                return Err(err);
2364            }
2365        }
2366        self.expect_field_ty_separator()?;
2367        let ty = self.parse_ty()?;
2368        if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
2369            self.dcx()
2370                .struct_span_err(self.token.span, "found single colon in a struct field type path")
2371                .with_span_suggestion_verbose(
2372                    self.token.span,
2373                    "write a path separator here",
2374                    "::",
2375                    Applicability::MaybeIncorrect,
2376                )
2377                .emit();
2378        }
2379        let default = if self.token == token::Eq {
2380            self.bump();
2381            let const_expr = self.parse_expr_anon_const()?;
2382            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2383            self.psess.gated_spans.gate(sym::default_field_values, sp);
2384            Some(const_expr)
2385        } else {
2386            None
2387        };
2388        Ok(FieldDef {
2389            span: lo.to(self.prev_token.span),
2390            ident: Some(name),
2391            vis,
2392            safety,
2393            mut_restriction,
2394            id: DUMMY_NODE_ID,
2395            ty,
2396            default,
2397            attrs,
2398            is_placeholder: false,
2399        })
2400    }
2401
2402    /// Parses a field identifier. Specialized version of `parse_ident_common`
2403    /// for better diagnostics and suggestions.
2404    fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
2405        let (ident, is_raw) = self.ident_or_err(true)?;
2406        if is_raw == IdentIsRaw::No
2407            && ident.is_reserved()
2408            && !(ident.name == kw::Underscore && adt_ty == "enum")
2409        {
2410            let snapshot = self.create_snapshot_for_diagnostic();
2411            let err = if self.check_fn_front_matter(false, Case::Sensitive) {
2412                let inherited_vis = Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited };
2413                // We use `parse_fn` to get a span for the function
2414                let fn_parse_mode =
2415                    FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
2416                match self.parse_fn(
2417                    &mut AttrVec::new(),
2418                    fn_parse_mode,
2419                    lo,
2420                    &inherited_vis,
2421                    Case::Insensitive,
2422                ) {
2423                    Ok(_) => {
2424                        self.dcx().struct_span_err(
2425                            lo.to(self.prev_token.span),
2426                            ::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"),
2427                        )
2428                        .with_help(
2429                            "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
2430                        )
2431                        .with_help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information")
2432                    }
2433                    Err(err) => {
2434                        err.cancel();
2435                        self.restore_snapshot(snapshot);
2436                        self.expected_ident_found_err()
2437                    }
2438                }
2439            } 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)) {
2440                match self.parse_item_struct() {
2441                    Ok(item) => {
2442                        let ItemKind::Struct(ident, ..) = item else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2443                        self.dcx()
2444                            .struct_span_err(
2445                                lo.with_hi(ident.span.hi()),
2446                                ::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"),
2447                            )
2448                            .with_help(
2449                                "consider creating a new `struct` definition instead of nesting",
2450                            )
2451                    }
2452                    Err(err) => {
2453                        err.cancel();
2454                        self.restore_snapshot(snapshot);
2455                        self.expected_ident_found_err()
2456                    }
2457                }
2458            } else {
2459                let mut err = self.expected_ident_found_err();
2460                if self.eat_keyword_noexpect(kw::Let)
2461                    && let removal_span = self.prev_token.span.until(self.token.span)
2462                    && let Ok(ident) = self
2463                        .parse_ident_common(false)
2464                        // Cancel this error, we don't need it.
2465                        .map_err(|err| err.cancel())
2466                    && self.token == TokenKind::Colon
2467                {
2468                    err.span_suggestion(
2469                        removal_span,
2470                        "remove this `let` keyword",
2471                        String::new(),
2472                        Applicability::MachineApplicable,
2473                    );
2474                    err.note("the `let` keyword is not allowed in `struct` fields");
2475                    err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
2476                    err.emit();
2477                    return Ok(ident);
2478                } else {
2479                    self.restore_snapshot(snapshot);
2480                }
2481                err
2482            };
2483            return Err(err);
2484        }
2485        self.bump();
2486        Ok(ident)
2487    }
2488
2489    /// Parses a declarative macro 2.0 definition.
2490    /// The `macro` keyword has already been parsed.
2491    /// ```ebnf
2492    /// MacBody = "{" TOKEN_STREAM "}" ;
2493    /// MacParams = "(" TOKEN_STREAM ")" ;
2494    /// DeclMac = "macro" Ident MacParams? MacBody ;
2495    /// ```
2496    fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemKind> {
2497        let ident = self.parse_ident()?;
2498        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)) {
2499            self.parse_delim_args()? // `MacBody`
2500        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
2501            let params = self.parse_token_tree(); // `MacParams`
2502            let pspan = params.span();
2503            if !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2504                self.unexpected()?;
2505            }
2506            let body = self.parse_token_tree(); // `MacBody`
2507            // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
2508            let bspan = body.span();
2509            let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
2510            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]);
2511            let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
2512            Box::new(DelimArgs { dspan, delim: Delimiter::Brace, tokens })
2513        } else {
2514            self.unexpected_any()?
2515        };
2516
2517        self.psess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
2518        Ok(ItemKind::MacroDef(
2519            ident,
2520            ast::MacroDef { body, macro_rules: false, eii_declaration: None },
2521        ))
2522    }
2523
2524    /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
2525    fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
2526        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)) {
2527            let macro_rules_span = self.token.span;
2528
2529            if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) {
2530                return IsMacroRulesItem::Yes { has_bang: true };
2531            } else if self.look_ahead(1, |t| t.is_ident()) {
2532                // macro_rules foo
2533                self.dcx().emit_err(diagnostics::MacroRulesMissingBang {
2534                    span: macro_rules_span,
2535                    hi: macro_rules_span.shrink_to_hi(),
2536                });
2537
2538                return IsMacroRulesItem::Yes { has_bang: false };
2539            }
2540        }
2541
2542        IsMacroRulesItem::No
2543    }
2544
2545    /// Parses a `macro_rules! foo { ... }` declarative macro.
2546    fn parse_item_macro_rules(
2547        &mut self,
2548        vis: &Visibility,
2549        has_bang: bool,
2550    ) -> PResult<'a, ItemKind> {
2551        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`
2552
2553        if has_bang {
2554            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
2555        }
2556        let ident = self.parse_ident()?;
2557
2558        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
2559            // Handle macro_rules! foo!
2560            let span = self.prev_token.span;
2561            self.dcx().emit_err(diagnostics::MacroNameRemoveBang { span });
2562        }
2563
2564        let body = self.parse_delim_args()?;
2565        self.eat_semi_for_macro_if_needed(&body, None);
2566        self.complain_if_pub_macro(vis, true);
2567
2568        Ok(ItemKind::MacroDef(
2569            ident,
2570            ast::MacroDef { body, macro_rules: true, eii_declaration: None },
2571        ))
2572    }
2573
2574    /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
2575    /// If that's not the case, emit an error.
2576    fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
2577        if let VisibilityKind::Inherited = vis.kind {
2578            return;
2579        }
2580
2581        let vstr = pprust::vis_to_string(vis);
2582        let vstr = vstr.trim_end();
2583        if macro_rules {
2584            self.dcx().emit_err(diagnostics::MacroRulesVisibility { span: vis.span, vis: vstr });
2585        } else {
2586            self.dcx()
2587                .emit_err(diagnostics::MacroInvocationVisibility { span: vis.span, vis: vstr });
2588        }
2589    }
2590
2591    fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs, path: Option<&Path>) {
2592        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)) {
2593            self.report_invalid_macro_expansion_item(args, path);
2594        }
2595    }
2596
2597    fn report_invalid_macro_expansion_item(&self, args: &DelimArgs, path: Option<&Path>) {
2598        let span = args.dspan.entire();
2599        let mut err = self.dcx().struct_span_err(
2600            span,
2601            "macros that expand to items must be delimited with braces or followed by a semicolon",
2602        );
2603        // FIXME: This will make us not emit the help even for declarative
2604        // macros within the same crate (that we can fix), which is sad.
2605        if !span.from_expansion() {
2606            let DelimSpan { open, close } = args.dspan;
2607            // Check if this looks like `macro_rules!(name) { ... }`
2608            // a common mistake when trying to define a macro.
2609            if let Some(path) = path
2610                && path.segments.first().is_some_and(|seg| seg.ident.name == sym::macro_rules)
2611                && args.delim == Delimiter::Parenthesis
2612            {
2613                let replace =
2614                    if path.span.hi() + rustc_span::BytePos(1) < open.lo() { "" } else { " " };
2615                err.multipart_suggestion(
2616                    "to define a macro, remove the parentheses around the macro name",
2617                    ::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())],
2618                    Applicability::MachineApplicable,
2619                );
2620            } else {
2621                err.multipart_suggestion(
2622                    "change the delimiters to curly braces",
2623                    ::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())],
2624                    Applicability::MaybeIncorrect,
2625                );
2626                err.span_suggestion(
2627                    span.with_neighbor(self.token.span).shrink_to_hi(),
2628                    "add a semicolon",
2629                    ';',
2630                    Applicability::MaybeIncorrect,
2631                );
2632            }
2633        }
2634        err.emit();
2635    }
2636
2637    /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2638    /// it is, we try to parse the item and report error about nested types.
2639    fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2640        if (self.token.is_keyword(kw::Enum)
2641            || self.token.is_keyword(kw::Struct)
2642            || self.token.is_keyword(kw::Union))
2643            && self.look_ahead(1, |t| t.is_ident())
2644        {
2645            let kw_token = self.token;
2646            let kw_str = pprust::token_to_string(&kw_token);
2647            let item = self.parse_item(
2648                ForceCollect::No,
2649                AllowConstBlockItems::DoesNotMatter, // self.token != kw::Const
2650            )?;
2651            let mut item = item.unwrap().span;
2652            if self.token == token::Comma {
2653                item = item.to(self.token.span);
2654            }
2655            self.dcx().emit_err(diagnostics::NestedAdt {
2656                span: kw_token.span,
2657                item,
2658                kw_str,
2659                keyword: keyword.as_str(),
2660            });
2661            // We successfully parsed the item but we must inform the caller about nested problem.
2662            return Ok(false);
2663        }
2664        Ok(true)
2665    }
2666}
2667
2668/// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2669///
2670/// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2671///
2672/// This function pointer accepts an edition, because in edition 2015, trait declarations
2673/// were allowed to omit parameter names. In 2018, they became required. It also accepts an
2674/// `IsDotDotDot` parameter, as `extern` function declarations and function pointer types are
2675/// allowed to omit the name of the `...` but regular function items are not.
2676type ReqName = fn(Edition, IsDotDotDot) -> bool;
2677
2678#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsDotDotDot { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsDotDotDot {
    #[inline]
    fn clone(&self) -> IsDotDotDot { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for IsDotDotDot {
    #[inline]
    fn eq(&self, other: &IsDotDotDot) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
2679pub(crate) enum IsDotDotDot {
2680    Yes,
2681    No,
2682}
2683
2684/// Parsing configuration for functions.
2685///
2686/// The syntax of function items is slightly different within trait definitions,
2687/// impl blocks, and modules. It is still parsed using the same code, just with
2688/// different flags set, so that even when the input is wrong and produces a parse
2689/// error, it still gets into the AST and the rest of the parser and
2690/// type checker can run.
2691#[derive(#[automatically_derived]
impl ::core::clone::Clone for FnParseMode {
    #[inline]
    fn clone(&self) -> FnParseMode {
        let _: ::core::clone::AssertParamIsClone<ReqName>;
        let _: ::core::clone::AssertParamIsClone<FnContext>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FnParseMode { }Copy)]
2692pub(crate) struct FnParseMode {
2693    /// A function pointer that decides if, per-parameter `p`, `p` must have a
2694    /// pattern or just a type. This field affects parsing of the parameters list.
2695    ///
2696    /// ```text
2697    /// fn foo(alef: A) -> X { X::new() }
2698    ///        -----^^ affects parsing this part of the function signature
2699    ///        |
2700    ///        if req_name returns false, then this name is optional
2701    ///
2702    /// fn bar(A) -> X;
2703    ///        ^
2704    ///        |
2705    ///        if req_name returns true, this is an error
2706    /// ```
2707    ///
2708    /// Calling this function pointer should only return false if:
2709    ///
2710    ///   * The item is being parsed inside of a trait definition.
2711    ///     Within an impl block or a module, it should always evaluate
2712    ///     to true.
2713    ///   * The span is from Edition 2015. In particular, you can get a
2714    ///     2015 span inside a 2021 crate using macros.
2715    ///
2716    /// Or if `IsDotDotDot::Yes`, this function will also return `false` if the item being parsed
2717    /// is inside an `extern` block.
2718    pub(super) req_name: ReqName,
2719    /// The context in which this function is parsed, used for diagnostics.
2720    /// This indicates the fn is a free function or method and so on.
2721    pub(super) context: FnContext,
2722    /// If this flag is set to `true`, then plain, semicolon-terminated function
2723    /// prototypes are not allowed here.
2724    ///
2725    /// ```text
2726    /// fn foo(alef: A) -> X { X::new() }
2727    ///                      ^^^^^^^^^^^^
2728    ///                      |
2729    ///                      this is always allowed
2730    ///
2731    /// fn bar(alef: A, bet: B) -> X;
2732    ///                             ^
2733    ///                             |
2734    ///                             if req_body is set to true, this is an error
2735    /// ```
2736    ///
2737    /// This field should only be set to false if the item is inside of a trait
2738    /// definition or extern block. Within an impl block or a module, it should
2739    /// always be set to true.
2740    pub(super) req_body: bool,
2741}
2742
2743/// The context in which a function is parsed.
2744/// FIXME(estebank, xizheyin): Use more variants.
2745#[derive(#[automatically_derived]
impl ::core::clone::Clone for FnContext {
    #[inline]
    fn clone(&self) -> FnContext { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FnContext { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for FnContext {
    #[inline]
    fn eq(&self, other: &FnContext) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for FnContext {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
2746pub(crate) enum FnContext {
2747    /// Free context.
2748    Free,
2749    /// A Trait context.
2750    Trait,
2751    /// An Impl block.
2752    Impl,
2753}
2754
2755/// Parsing of functions and methods.
2756impl<'a> Parser<'a> {
2757    /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2758    fn parse_fn(
2759        &mut self,
2760        attrs: &mut AttrVec,
2761        fn_parse_mode: FnParseMode,
2762        sig_lo: Span,
2763        vis: &Visibility,
2764        case: Case,
2765    ) -> PResult<'a, (Ident, FnSig, Generics, Option<Box<FnContract>>, Option<Box<Block>>)> {
2766        let fn_span = self.token.span;
2767        let header = self.parse_fn_front_matter(vis, case, FrontMatterParsingMode::Function)?; // `const ... fn`
2768        let ident = self.parse_ident()?; // `foo`
2769        let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2770        let decl = match self.parse_fn_decl(&fn_parse_mode, AllowPlus::Yes, RecoverReturnSign::Yes)
2771        {
2772            Ok(decl) => decl,
2773            Err(old_err) => {
2774                // If we see `for Ty ...` then user probably meant `impl` item.
2775                if self.token.is_keyword(kw::For) {
2776                    old_err.cancel();
2777                    return Err(self.dcx().create_err(diagnostics::FnTypoWithImpl { fn_span }));
2778                } else {
2779                    return Err(old_err);
2780                }
2781            }
2782        };
2783
2784        // Store the end of function parameters to give better diagnostics
2785        // inside `parse_fn_body()`.
2786        let fn_params_end = self.prev_token.span.shrink_to_hi();
2787
2788        let contract = self.parse_contract()?;
2789
2790        generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2791
2792        // `fn_params_end` is needed only when it's followed by a where clause.
2793        let fn_params_end =
2794            if generics.where_clause.has_where_token { Some(fn_params_end) } else { None };
2795
2796        let mut sig_hi = self.prev_token.span;
2797        // Either `;` or `{ ... }`.
2798        let body =
2799            self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body, fn_params_end)?;
2800        let fn_sig_span = sig_lo.to(sig_hi);
2801        Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, contract, body))
2802    }
2803
2804    /// Provide diagnostics when function body is not found
2805    fn error_fn_body_not_found(
2806        &mut self,
2807        ident_span: Span,
2808        req_body: bool,
2809        fn_params_end: Option<Span>,
2810    ) -> PResult<'a, ErrorGuaranteed> {
2811        let expected: &[_] =
2812            if req_body { &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)] } else { &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)] };
2813        match self.expected_one_of_not_found(&[], expected) {
2814            Ok(error_guaranteed) => Ok(error_guaranteed),
2815            Err(mut err) => {
2816                if self.token == token::CloseBrace {
2817                    // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2818                    // the AST for typechecking.
2819                    err.span_label(ident_span, "while parsing this `fn`");
2820                    Ok(err.emit())
2821                } else if self.token == token::RArrow
2822                    && let Some(fn_params_end) = fn_params_end
2823                {
2824                    // Instead of a function body, the parser has encountered a right arrow
2825                    // preceded by a where clause.
2826
2827                    // Find whether token behind the right arrow is a function trait and
2828                    // store its span.
2829                    let fn_trait_span =
2830                        [sym::FnOnce, sym::FnMut, sym::Fn].into_iter().find_map(|symbol| {
2831                            if self.prev_token.is_ident_named(symbol) {
2832                                Some(self.prev_token.span)
2833                            } else {
2834                                None
2835                            }
2836                        });
2837
2838                    // Parse the return type (along with the right arrow) and store its span.
2839                    // If there's a parse error, cancel it and return the existing error
2840                    // as we are primarily concerned with the
2841                    // expected-function-body-but-found-something-else error here.
2842                    let arrow_span = self.token.span;
2843                    let ty_span = match self.parse_ret_ty(
2844                        AllowPlus::Yes,
2845                        RecoverQPath::Yes,
2846                        RecoverReturnSign::Yes,
2847                    ) {
2848                        Ok(ty_span) => ty_span.span().shrink_to_hi(),
2849                        Err(parse_error) => {
2850                            parse_error.cancel();
2851                            return Err(err);
2852                        }
2853                    };
2854                    let ret_ty_span = arrow_span.to(ty_span);
2855
2856                    if let Some(fn_trait_span) = fn_trait_span {
2857                        // Typo'd Fn* trait bounds such as
2858                        // fn foo<F>() where F: FnOnce -> () {}
2859                        err.subdiagnostic(diagnostics::FnTraitMissingParen { span: fn_trait_span });
2860                    } else if let Ok(snippet) = self.psess.source_map().span_to_snippet(ret_ty_span)
2861                    {
2862                        // If token behind right arrow is not a Fn* trait, the programmer
2863                        // probably misplaced the return type after the where clause like
2864                        // `fn foo<T>() where T: Default -> u8 {}`
2865                        err.primary_message(
2866                            "return type should be specified after the function parameters",
2867                        );
2868                        err.subdiagnostic(diagnostics::MisplacedReturnType {
2869                            fn_params_end,
2870                            snippet,
2871                            ret_ty_span,
2872                        });
2873                    }
2874                    Err(err)
2875                } else {
2876                    Err(err)
2877                }
2878            }
2879        }
2880    }
2881
2882    /// Parse the "body" of a function.
2883    /// This can either be `;` when there's no body,
2884    /// or e.g. a block when the function is a provided one.
2885    fn parse_fn_body(
2886        &mut self,
2887        attrs: &mut AttrVec,
2888        ident: &Ident,
2889        sig_hi: &mut Span,
2890        req_body: bool,
2891        fn_params_end: Option<Span>,
2892    ) -> PResult<'a, Option<Box<Block>>> {
2893        let has_semi = if req_body {
2894            self.token == TokenKind::Semi
2895        } else {
2896            // Only include `;` in list of expected tokens if body is not required
2897            self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))
2898        };
2899        let (inner_attrs, body) = if has_semi {
2900            // Include the trailing semicolon in the span of the signature
2901            self.expect_semi()?;
2902            *sig_hi = self.prev_token.span;
2903            (AttrVec::new(), None)
2904        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) || self.token.is_metavar_block() {
2905            let prev_in_fn_body = self.in_fn_body;
2906            self.in_fn_body = true;
2907            let res = self.parse_block_common(self.token.span, BlockCheckMode::Default, None).map(
2908                |(attrs, mut body)| {
2909                    if let Some(guar) = self.fn_body_missing_semi_guar.take() {
2910                        body.stmts.push(self.mk_stmt(
2911                            body.span,
2912                            StmtKind::Expr(self.mk_expr(body.span, ExprKind::Err(guar))),
2913                        ));
2914                    }
2915                    (attrs, Some(body))
2916                },
2917            );
2918            self.in_fn_body = prev_in_fn_body;
2919            res?
2920        } else if self.token == token::Eq {
2921            // Recover `fn foo() = $expr;`.
2922            self.bump(); // `=`
2923            let eq_sp = self.prev_token.span;
2924            let _ = self.parse_expr()?;
2925            self.expect_semi()?; // `;`
2926            let span = eq_sp.to(self.prev_token.span);
2927            let guar = self.dcx().emit_err(diagnostics::FunctionBodyEqualsExpr {
2928                span,
2929                sugg: diagnostics::FunctionBodyEqualsExprSugg {
2930                    eq: eq_sp,
2931                    semi: self.prev_token.span,
2932                },
2933            });
2934            (AttrVec::new(), Some(self.mk_block_err(span, guar)))
2935        } else {
2936            self.error_fn_body_not_found(ident.span, req_body, fn_params_end)?;
2937            (AttrVec::new(), None)
2938        };
2939        attrs.extend(inner_attrs);
2940        Ok(body)
2941    }
2942
2943    fn check_impl_frontmatter(&mut self, look_ahead: usize) -> bool {
2944        const ALL_QUALS: &[Symbol] = &[kw::Const, kw::Unsafe];
2945        // In contrast to the loop below, this call inserts `impl` into the
2946        // list of expected tokens shown in diagnostics.
2947        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)) {
2948            return true;
2949        }
2950        let mut i = 0;
2951        while i < ALL_QUALS.len() {
2952            let action = self.look_ahead(i + look_ahead, |token| {
2953                if token.is_keyword(kw::Impl) {
2954                    return Some(true);
2955                }
2956                if ALL_QUALS.iter().any(|&qual| token.is_keyword(qual)) {
2957                    // Ok, we found a legal keyword, keep looking for `impl`
2958                    return None;
2959                }
2960                Some(false)
2961            });
2962            if let Some(ret) = action {
2963                return ret;
2964            }
2965            i += 1;
2966        }
2967
2968        self.is_keyword_ahead(i, &[kw::Impl])
2969    }
2970
2971    /// Is the current token the start of an `FnHeader` / not a valid parse?
2972    ///
2973    /// `check_pub` adds additional `pub` to the checks in case users place it
2974    /// wrongly, can be used to ensure `pub` never comes after `default`.
2975    pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2976        const ALL_QUALS: &[ExpKeywordPair] = &[
2977            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Pub,
    token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub),
2978            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen),
2979            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const),
2980            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async),
2981            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe),
2982            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Safe,
    token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe),
2983            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern),
2984        ];
2985
2986        // We use an over-approximation here.
2987        // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2988        // `pub` is added in case users got confused with the ordering like `async pub fn`,
2989        // only if it wasn't preceded by `default` as `default pub` is invalid.
2990        let quals: &[_] = if check_pub {
2991            ALL_QUALS
2992        } else {
2993            &[crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen), crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const), crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async), crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe), crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Safe,
    token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe), crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern)]
2994        };
2995        self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Fn,
    token_type: crate::parser::token_type::TokenType::KwFn,
}exp!(Fn), case) // Definitely an `fn`.
2996            // `$qual fn` or `$qual $qual`:
2997            || quals.iter().any(|&exp| self.check_keyword_case(exp, case))
2998                && self.look_ahead(1, |t| {
2999                    // `$qual fn`, e.g. `const fn` or `async fn`.
3000                    t.is_keyword_case(kw::Fn, case)
3001                    // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
3002                    || (
3003                        (
3004                            t.is_non_raw_ident_where(|i|
3005                                quals.iter().any(|exp| exp.kw == i.name)
3006                                    // Rule out 2015 `const async: T = val`.
3007                                    && i.is_reserved()
3008                            )
3009                            || case == Case::Insensitive
3010                                && t.is_non_raw_ident_where(|i| quals.iter().any(|exp| {
3011                                    exp.kw.as_str() == i.name.as_str().to_lowercase()
3012                                }))
3013                        )
3014                        // Rule out `unsafe extern {`.
3015                        && !self.is_unsafe_foreign_mod()
3016                        // Rule out `async gen {` and `async gen move {`
3017                        && !self.is_async_gen_block()
3018                        // Rule out `const unsafe auto` and `const unsafe trait` and `const unsafe impl`
3019                        && !self.is_keyword_ahead(2, &[kw::Auto, kw::Trait, kw::Impl])
3020                    )
3021                })
3022            // `extern ABI fn`
3023            || self.check_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern), case)
3024                // Use `tree_look_ahead` because `ABI` might be a metavariable,
3025                // i.e. an invisible-delimited sequence, and `tree_look_ahead`
3026                // will consider that a single element when looking ahead.
3027                && self.look_ahead(1, |t| t.can_begin_string_literal())
3028                && (self.tree_look_ahead(2, |tt| {
3029                    match tt {
3030                        TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case),
3031                        TokenTree::Delimited(..) => false,
3032                    }
3033                }) == Some(true) ||
3034                    // This branch is only for better diagnostics; `pub`, `unsafe`, etc. are not
3035                    // allowed here.
3036                    (self.may_recover()
3037                        && self.tree_look_ahead(2, |tt| {
3038                            match tt {
3039                                TokenTree::Token(t, _) =>
3040                                    ALL_QUALS.iter().any(|exp| {
3041                                        t.is_keyword(exp.kw)
3042                                    }),
3043                                TokenTree::Delimited(..) => false,
3044                            }
3045                        }) == Some(true)
3046                        && self.tree_look_ahead(3, |tt| {
3047                            match tt {
3048                                TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case),
3049                                TokenTree::Delimited(..) => false,
3050                            }
3051                        }) == Some(true)
3052                    )
3053                )
3054    }
3055
3056    /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
3057    /// up to and including the `fn` keyword. The formal grammar is:
3058    ///
3059    /// ```text
3060    /// Extern = "extern" StringLit? ;
3061    /// FnQual = "const"? "async"? "unsafe"? Extern? ;
3062    /// FnFrontMatter = FnQual "fn" ;
3063    /// ```
3064    ///
3065    /// `vis` represents the visibility that was already parsed, if any. Use
3066    /// `Visibility::Inherited` when no visibility is known.
3067    ///
3068    /// If `parsing_mode` is `FrontMatterParsingMode::FunctionPtrType`, we error on `const` and `async` qualifiers,
3069    /// which are not allowed in function pointer types.
3070    pub(super) fn parse_fn_front_matter(
3071        &mut self,
3072        orig_vis: &Visibility,
3073        case: Case,
3074        parsing_mode: FrontMatterParsingMode,
3075    ) -> PResult<'a, FnHeader> {
3076        let sp_start = self.token.span;
3077        let constness = self.parse_constness(case);
3078        if parsing_mode == FrontMatterParsingMode::FunctionPtrType
3079            && let Const::Yes(const_span) = constness
3080        {
3081            self.dcx().emit_err(FnPointerCannotBeConst {
3082                span: const_span,
3083                suggestion: const_span.until(self.token.span),
3084            });
3085        }
3086
3087        let async_start_sp = self.token.span;
3088        let coroutine_kind = self.parse_coroutine_kind(case);
3089        if parsing_mode == FrontMatterParsingMode::FunctionPtrType
3090            && let Some(ast::CoroutineKind::Async { span: async_span, .. }) = coroutine_kind
3091        {
3092            self.dcx().emit_err(FnPointerCannotBeAsync {
3093                span: async_span,
3094                suggestion: async_span.until(self.token.span),
3095            });
3096        }
3097        // FIXME(gen_blocks): emit a similar error for `gen fn()`
3098
3099        let unsafe_start_sp = self.token.span;
3100        let safety = self.parse_safety(case);
3101
3102        let ext_start_sp = self.token.span;
3103        let ext = self.parse_extern(case);
3104
3105        if let Some(CoroutineKind::Async { span, .. }) = coroutine_kind {
3106            if span.is_rust_2015() {
3107                self.dcx().emit_err(diagnostics::AsyncFnIn2015 {
3108                    span,
3109                    help: diagnostics::HelpUseLatestEdition::new(),
3110                });
3111            }
3112        }
3113
3114        match coroutine_kind {
3115            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
3116                self.psess.gated_spans.gate(sym::gen_blocks, span);
3117            }
3118            Some(CoroutineKind::Async { .. }) | None => {}
3119        }
3120
3121        if !self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Fn,
    token_type: crate::parser::token_type::TokenType::KwFn,
}exp!(Fn), case) {
3122            // It is possible for `expect_one_of` to recover given the contents of
3123            // `self.expected_token_types`, therefore, do not use `self.unexpected()` which doesn't
3124            // account for this.
3125            match self.expect_one_of(&[], &[]) {
3126                Ok(Recovered::Yes(_)) => {}
3127                Ok(Recovered::No) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3128                Err(mut err) => {
3129                    // Qualifier keywords ordering check
3130                    enum WrongKw {
3131                        Duplicated(Span),
3132                        Misplaced(Span),
3133                        /// `MisplacedDisallowedQualifier` is only used instead of `Misplaced`,
3134                        /// when the misplaced keyword is disallowed by the current `FrontMatterParsingMode`.
3135                        /// In this case, we avoid generating the suggestion to swap around the keywords,
3136                        /// as we already generated a suggestion to remove the keyword earlier.
3137                        MisplacedDisallowedQualifier,
3138                    }
3139
3140                    // We may be able to recover
3141                    let mut recover_constness = constness;
3142                    let mut recover_coroutine_kind = coroutine_kind;
3143                    let mut recover_safety = safety;
3144                    // This will allow the machine fix to directly place the keyword in the correct place or to indicate
3145                    // that the keyword is already present and the second instance should be removed.
3146                    let wrong_kw = if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)) {
3147                        match constness {
3148                            Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
3149                            Const::No => {
3150                                recover_constness = Const::Yes(self.token.span);
3151                                match parsing_mode {
3152                                    FrontMatterParsingMode::Function => {
3153                                        Some(WrongKw::Misplaced(async_start_sp))
3154                                    }
3155                                    FrontMatterParsingMode::FunctionPtrType => {
3156                                        self.dcx().emit_err(FnPointerCannotBeConst {
3157                                            span: self.token.span,
3158                                            suggestion: self
3159                                                .token
3160                                                .span
3161                                                .with_lo(self.prev_token.span.hi()),
3162                                        });
3163                                        Some(WrongKw::MisplacedDisallowedQualifier)
3164                                    }
3165                                }
3166                            }
3167                        }
3168                    } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async)) {
3169                        match coroutine_kind {
3170                            Some(CoroutineKind::Async { span, .. }) => {
3171                                Some(WrongKw::Duplicated(span))
3172                            }
3173                            Some(CoroutineKind::AsyncGen { span, .. }) => {
3174                                Some(WrongKw::Duplicated(span))
3175                            }
3176                            Some(CoroutineKind::Gen { .. }) => {
3177                                recover_coroutine_kind = Some(CoroutineKind::AsyncGen {
3178                                    span: self.token.span,
3179                                    closure_id: DUMMY_NODE_ID,
3180                                    return_impl_trait_id: DUMMY_NODE_ID,
3181                                });
3182                                // FIXME(gen_blocks): This span is wrong, didn't want to think about it.
3183                                Some(WrongKw::Misplaced(unsafe_start_sp))
3184                            }
3185                            None => {
3186                                recover_coroutine_kind = Some(CoroutineKind::Async {
3187                                    span: self.token.span,
3188                                    closure_id: DUMMY_NODE_ID,
3189                                    return_impl_trait_id: DUMMY_NODE_ID,
3190                                });
3191                                match parsing_mode {
3192                                    FrontMatterParsingMode::Function => {
3193                                        Some(WrongKw::Misplaced(async_start_sp))
3194                                    }
3195                                    FrontMatterParsingMode::FunctionPtrType => {
3196                                        self.dcx().emit_err(FnPointerCannotBeAsync {
3197                                            span: self.token.span,
3198                                            suggestion: self
3199                                                .token
3200                                                .span
3201                                                .with_lo(self.prev_token.span.hi()),
3202                                        });
3203                                        Some(WrongKw::MisplacedDisallowedQualifier)
3204                                    }
3205                                }
3206                            }
3207                        }
3208                    } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe)) {
3209                        match safety {
3210                            Safety::Unsafe(sp) => Some(WrongKw::Duplicated(sp)),
3211                            Safety::Safe(sp) => {
3212                                recover_safety = Safety::Unsafe(self.token.span);
3213                                Some(WrongKw::Misplaced(sp))
3214                            }
3215                            Safety::Default => {
3216                                recover_safety = Safety::Unsafe(self.token.span);
3217                                Some(WrongKw::Misplaced(ext_start_sp))
3218                            }
3219                        }
3220                    } else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Safe,
    token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe)) {
3221                        match safety {
3222                            Safety::Safe(sp) => Some(WrongKw::Duplicated(sp)),
3223                            Safety::Unsafe(sp) => {
3224                                recover_safety = Safety::Safe(self.token.span);
3225                                Some(WrongKw::Misplaced(sp))
3226                            }
3227                            Safety::Default => {
3228                                recover_safety = Safety::Safe(self.token.span);
3229                                Some(WrongKw::Misplaced(ext_start_sp))
3230                            }
3231                        }
3232                    } else {
3233                        None
3234                    };
3235
3236                    // The keyword is already present, suggest removal of the second instance
3237                    if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
3238                        let original_kw = self
3239                            .span_to_snippet(original_sp)
3240                            .expect("Span extracted directly from keyword should always work");
3241
3242                        err.span_suggestion(
3243                            self.token_uninterpolated_span(),
3244                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` already used earlier, remove this one",
                original_kw))
    })format!("`{original_kw}` already used earlier, remove this one"),
3245                            "",
3246                            Applicability::MachineApplicable,
3247                        )
3248                        .span_note(original_sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` first seen here",
                original_kw))
    })format!("`{original_kw}` first seen here"));
3249                    }
3250                    // The keyword has not been seen yet, suggest correct placement in the function front matter
3251                    else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
3252                        let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
3253                        if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
3254                            let misplaced_qual_sp = self.token_uninterpolated_span();
3255                            let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
3256
3257                            err.span_suggestion(
3258                                    correct_pos_sp.to(misplaced_qual_sp),
3259                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` must come before `{1}`",
                misplaced_qual, current_qual))
    })format!("`{misplaced_qual}` must come before `{current_qual}`"),
3260                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", misplaced_qual,
                current_qual))
    })format!("{misplaced_qual} {current_qual}"),
3261                                    Applicability::MachineApplicable,
3262                                ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
3263                        }
3264                    }
3265                    // Recover incorrect visibility order such as `async pub`
3266                    else if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Pub,
    token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub)) {
3267                        let sp = sp_start.to(self.prev_token.span);
3268                        if let Ok(snippet) = self.span_to_snippet(sp) {
3269                            let current_vis = match self.parse_visibility(FollowedByType::No) {
3270                                Ok(v) => v,
3271                                Err(d) => {
3272                                    d.cancel();
3273                                    return Err(err);
3274                                }
3275                            };
3276                            let vs = pprust::vis_to_string(&current_vis);
3277                            let vs = vs.trim_end();
3278
3279                            // There was no explicit visibility
3280                            if #[allow(non_exhaustive_omitted_patterns)] match orig_vis.kind {
    VisibilityKind::Inherited => true,
    _ => false,
}matches!(orig_vis.kind, VisibilityKind::Inherited) {
3281                                err.span_suggestion(
3282                                    sp_start.to(self.prev_token.span),
3283                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("visibility `{0}` must come before `{1}`",
                vs, snippet))
    })format!("visibility `{vs}` must come before `{snippet}`"),
3284                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", vs, snippet))
    })format!("{vs} {snippet}"),
3285                                    Applicability::MachineApplicable,
3286                                );
3287                            }
3288                            // There was an explicit visibility
3289                            else {
3290                                err.span_suggestion(
3291                                    current_vis.span,
3292                                    "there is already a visibility modifier, remove one",
3293                                    "",
3294                                    Applicability::MachineApplicable,
3295                                )
3296                                .span_note(orig_vis.span, "explicit visibility first seen here");
3297                            }
3298                        }
3299                    }
3300
3301                    // FIXME(gen_blocks): add keyword recovery logic for genness
3302
3303                    if let Some(wrong_kw) = wrong_kw
3304                        && self.may_recover()
3305                        && self.look_ahead(1, |tok| tok.is_keyword_case(kw::Fn, case))
3306                    {
3307                        // Advance past the misplaced keyword and `fn`
3308                        self.bump();
3309                        self.bump();
3310                        // When we recover from a `MisplacedDisallowedQualifier`, we already emitted an error for the disallowed qualifier
3311                        // So we don't emit another error that the qualifier is unexpected.
3312                        if #[allow(non_exhaustive_omitted_patterns)] match wrong_kw {
    WrongKw::MisplacedDisallowedQualifier => true,
    _ => false,
}matches!(wrong_kw, WrongKw::MisplacedDisallowedQualifier) {
3313                            err.cancel();
3314                        } else {
3315                            err.emit();
3316                        }
3317                        return Ok(FnHeader {
3318                            constness: recover_constness,
3319                            safety: recover_safety,
3320                            coroutine_kind: recover_coroutine_kind,
3321                            ext,
3322                        });
3323                    }
3324
3325                    return Err(err);
3326                }
3327            }
3328        }
3329
3330        Ok(FnHeader { constness, safety, coroutine_kind, ext })
3331    }
3332
3333    /// Parses the parameter list and result type of a function declaration.
3334    pub(super) fn parse_fn_decl(
3335        &mut self,
3336        fn_parse_mode: &FnParseMode,
3337        ret_allow_plus: AllowPlus,
3338        recover_return_sign: RecoverReturnSign,
3339    ) -> PResult<'a, Box<FnDecl>> {
3340        Ok(Box::new(FnDecl {
3341            inputs: self.parse_fn_params(fn_parse_mode)?,
3342            output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
3343        }))
3344    }
3345
3346    /// Parses the parameter list of a function, including the `(` and `)` delimiters.
3347    pub(super) fn parse_fn_params(
3348        &mut self,
3349        fn_parse_mode: &FnParseMode,
3350    ) -> PResult<'a, ThinVec<Param>> {
3351        let mut first_param = true;
3352        // Parse the arguments, starting out with `self` being allowed...
3353        if self.token != TokenKind::OpenParen
3354        // might be typo'd trait impl, handled elsewhere
3355        && !self.token.is_keyword(kw::For)
3356        {
3357            // recover from missing argument list, e.g. `fn main -> () {}`
3358            self.dcx().emit_err(diagnostics::MissingFnParams {
3359                span: self.prev_token.span.shrink_to_hi(),
3360            });
3361            return Ok(ThinVec::new());
3362        }
3363
3364        let (mut params, _) = self.parse_paren_comma_seq(|p| {
3365            p.recover_vcs_conflict_marker();
3366            let snapshot = p.create_snapshot_for_diagnostic();
3367            let param = p.parse_param_general(fn_parse_mode, first_param, true).or_else(|e| {
3368                let guar = e.emit();
3369                // When parsing a param failed, we should check to make the span of the param
3370                // not contain '(' before it.
3371                // For example when parsing `*mut Self` in function `fn oof(*mut Self)`.
3372                let lo = if let TokenKind::OpenParen = p.prev_token.kind {
3373                    p.prev_token.span.shrink_to_hi()
3374                } else {
3375                    p.prev_token.span
3376                };
3377                p.restore_snapshot(snapshot);
3378                // Skip every token until next possible arg or end.
3379                p.eat_to_tokens(&[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::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
3380                // Create a placeholder argument for proper arg count (issue #34264).
3381                Ok(dummy_arg(Ident::new(sym::dummy, lo.to(p.prev_token.span)), guar))
3382            });
3383            // ...now that we've parsed the first argument, `self` is no longer allowed.
3384            first_param = false;
3385            param
3386        })?;
3387        // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
3388        self.deduplicate_recovered_params_names(&mut params);
3389        Ok(params)
3390    }
3391
3392    /// Parses a single function parameter.
3393    ///
3394    /// - `self` is syntactically allowed when `first_param` holds.
3395    /// - `recover_arg_parse` is used to recover from a failed argument parse.
3396    pub(super) fn parse_param_general(
3397        &mut self,
3398        fn_parse_mode: &FnParseMode,
3399        first_param: bool,
3400        recover_arg_parse: bool,
3401    ) -> PResult<'a, Param> {
3402        let lo = self.token.span;
3403        let attrs = self.parse_outer_attributes()?;
3404        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3405            // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
3406            if let Some(mut param) = this.parse_self_param()? {
3407                param.attrs = attrs;
3408                let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
3409                return Ok((res?, Trailing::No, UsePreAttrPos::No));
3410            }
3411
3412            let is_dot_dot_dot = if this.token.kind == token::DotDotDot {
3413                IsDotDotDot::Yes
3414            } else {
3415                IsDotDotDot::No
3416            };
3417            let is_name_required = (fn_parse_mode.req_name)(
3418                this.token.span.with_neighbor(this.prev_token.span).edition(),
3419                is_dot_dot_dot,
3420            );
3421            let is_name_required = if is_name_required && is_dot_dot_dot == IsDotDotDot::Yes {
3422                this.psess.buffer_lint(
3423                    VARARGS_WITHOUT_PATTERN,
3424                    this.token.span,
3425                    ast::CRATE_NODE_ID,
3426                    diagnostics::VarargsWithoutPattern { span: this.token.span },
3427                );
3428                false
3429            } else {
3430                is_name_required
3431            };
3432            let (pat, ty) = if is_name_required || this.is_named_param() {
3433                {
    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:3433",
                        "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(3433u32),
                        ::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!("parse_param_general parse_pat (is_name_required:{0})",
                                                    is_name_required) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
3434                let (pat, colon) = this.parse_fn_param_pat_colon()?;
3435                if !colon {
3436                    let mut err = this.unexpected().unwrap_err();
3437                    let pat_span = pat.span;
3438                    return if let Some(ident) = this.parameter_without_type(
3439                        &mut err,
3440                        pat,
3441                        is_name_required,
3442                        first_param,
3443                        fn_parse_mode,
3444                    ) {
3445                        let guar = err.emit();
3446                        let mut arg = dummy_arg(ident, guar);
3447                        arg.span = pat_span;
3448                        Ok((arg, Trailing::No, UsePreAttrPos::No))
3449                    } else {
3450                        Err(err)
3451                    };
3452                }
3453
3454                this.eat_incorrect_doc_comment_for_param_type();
3455                (pat, this.parse_ty_for_param()?)
3456            } else {
3457                {
    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:3457",
                        "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(3457u32),
                        ::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!("parse_param_general ident_to_pat")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("parse_param_general ident_to_pat");
3458                let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
3459                this.eat_incorrect_doc_comment_for_param_type();
3460                let mut ty = this.parse_ty_for_param();
3461
3462                if let Ok(t) = &ty {
3463                    // Check for trailing angle brackets
3464                    if let TyKind::Path(_, Path { segments, .. }) = &t.kind
3465                        && let Some(segment) = segments.last()
3466                        && let Some(guar) =
3467                            this.check_trailing_angle_brackets(segment, &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)])
3468                    {
3469                        return Ok((
3470                            dummy_arg(segment.ident, guar),
3471                            Trailing::No,
3472                            UsePreAttrPos::No,
3473                        ));
3474                    }
3475
3476                    if this.token != token::Comma && this.token != token::CloseParen {
3477                        // This wasn't actually a type, but a pattern looking like a type,
3478                        // so we are going to rollback and re-parse for recovery.
3479                        ty = this.unexpected_any();
3480                    }
3481                }
3482                match ty {
3483                    Ok(ty) => {
3484                        let pat = this.mk_pat(ty.span, PatKind::Missing);
3485                        (Box::new(pat), ty)
3486                    }
3487                    // If this is a C-variadic argument and we hit an error, return the error.
3488                    Err(err) if this.token == token::DotDotDot => return Err(err),
3489                    Err(err) if this.unmatched_angle_bracket_count > 0 => return Err(err),
3490                    Err(err) if recover_arg_parse => {
3491                        // Recover from attempting to parse the argument as a type without pattern.
3492                        err.cancel();
3493                        this.restore_snapshot(parser_snapshot_before_ty);
3494                        this.recover_arg_parse()?
3495                    }
3496                    Err(err) => return Err(err),
3497                }
3498            };
3499
3500            let span = lo.to(this.prev_token.span);
3501
3502            Ok((
3503                Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
3504                Trailing::No,
3505                UsePreAttrPos::No,
3506            ))
3507        })
3508    }
3509
3510    /// Returns the parsed optional self parameter and whether a self shortcut was used.
3511    fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
3512        // Extract an identifier *after* having confirmed that the token is one.
3513        let expect_self_ident = |this: &mut Self| match this.token.ident() {
3514            Some((ident, IdentIsRaw::No)) => {
3515                this.bump();
3516                ident
3517            }
3518            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3519        };
3520        // is lifetime `n` tokens ahead?
3521        let is_lifetime = |this: &Self, n| this.look_ahead(n, |t| t.is_lifetime());
3522        // Is `self` `n` tokens ahead?
3523        let is_isolated_self = |this: &Self, n| {
3524            this.is_keyword_ahead(n, &[kw::SelfLower])
3525                && this.look_ahead(n + 1, |t| t != &token::PathSep)
3526        };
3527        // Is `pin const self` `n` tokens ahead?
3528        let is_isolated_pin_const_self = |this: &Self, n| {
3529            this.look_ahead(n, |token| token.is_ident_named(sym::pin))
3530                && this.is_keyword_ahead(n + 1, &[kw::Const])
3531                && is_isolated_self(this, n + 2)
3532        };
3533        // Is `mut self` `n` tokens ahead?
3534        let is_isolated_mut_self =
3535            |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
3536        // Is `pin mut self` `n` tokens ahead?
3537        let is_isolated_pin_mut_self = |this: &Self, n| {
3538            this.look_ahead(n, |token| token.is_ident_named(sym::pin))
3539                && is_isolated_mut_self(this, n + 1)
3540        };
3541        // Parse `self` or `self: TYPE`. We already know the current token is `self`.
3542        let parse_self_possibly_typed = |this: &mut Self, m| {
3543            let eself_ident = expect_self_ident(this);
3544            let eself_hi = this.prev_token.span;
3545            let eself = if this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) {
3546                SelfKind::Explicit(this.parse_ty()?, m)
3547            } else {
3548                SelfKind::Value(m)
3549            };
3550            Ok((eself, eself_ident, eself_hi))
3551        };
3552        let expect_self_ident_not_typed =
3553            |this: &mut Self, modifier: &SelfKind, modifier_span: Span| {
3554                let eself_ident = expect_self_ident(this);
3555
3556                // Recover `: Type` after a qualified self
3557                if this.may_recover() && this.eat_noexpect(&token::Colon) {
3558                    let snap = this.create_snapshot_for_diagnostic();
3559                    match this.parse_ty() {
3560                        Ok(ty) => {
3561                            this.dcx().emit_err(diagnostics::IncorrectTypeOnSelf {
3562                                span: ty.span,
3563                                move_self_modifier: diagnostics::MoveSelfModifier {
3564                                    removal_span: modifier_span,
3565                                    insertion_span: ty.span.shrink_to_lo(),
3566                                    modifier: modifier.to_ref_suggestion(),
3567                                },
3568                            });
3569                        }
3570                        Err(diag) => {
3571                            diag.cancel();
3572                            this.restore_snapshot(snap);
3573                        }
3574                    }
3575                }
3576                eself_ident
3577            };
3578        // Recover for the grammar `*self`, `*const self`, and `*mut self`.
3579        let recover_self_ptr = |this: &mut Self| {
3580            this.dcx().emit_err(diagnostics::SelfArgumentPointer { span: this.token.span });
3581
3582            Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
3583        };
3584
3585        // Parse optional `self` parameter of a method.
3586        // Only a limited set of initial token sequences is considered `self` parameters; anything
3587        // else is parsed as a normal function parameter list, so some lookahead is required.
3588        let eself_lo = self.token.span;
3589        let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
3590            token::And => {
3591                let has_lifetime = is_lifetime(self, 1);
3592                let skip_lifetime_count = has_lifetime as usize;
3593                let eself = if is_isolated_self(self, skip_lifetime_count + 1) {
3594                    // `&{'lt} self`
3595                    self.bump(); // &
3596                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3597                    SelfKind::Region(lifetime, Mutability::Not)
3598                } else if is_isolated_mut_self(self, skip_lifetime_count + 1) {
3599                    // `&{'lt} mut self`
3600                    self.bump(); // &
3601                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3602                    self.bump(); // mut
3603                    SelfKind::Region(lifetime, Mutability::Mut)
3604                } else if is_isolated_pin_const_self(self, skip_lifetime_count + 1) {
3605                    // `&{'lt} pin const self`
3606                    self.bump(); // &
3607                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3608                    self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
3609                    self.bump(); // pin
3610                    self.bump(); // const
3611                    SelfKind::Pinned(lifetime, Mutability::Not)
3612                } else if is_isolated_pin_mut_self(self, skip_lifetime_count + 1) {
3613                    // `&{'lt} pin mut self`
3614                    self.bump(); // &
3615                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3616                    self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
3617                    self.bump(); // pin
3618                    self.bump(); // mut
3619                    SelfKind::Pinned(lifetime, Mutability::Mut)
3620                } else {
3621                    // `&not_self`
3622                    return Ok(None);
3623                };
3624                let hi = self.token.span;
3625                let self_ident = expect_self_ident_not_typed(self, &eself, eself_lo.until(hi));
3626                (eself, self_ident, hi)
3627            }
3628            // `*self`
3629            token::Star if is_isolated_self(self, 1) => {
3630                self.bump();
3631                recover_self_ptr(self)?
3632            }
3633            // `*mut self` and `*const self`
3634            token::Star
3635                if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
3636            {
3637                self.bump();
3638                self.bump();
3639                recover_self_ptr(self)?
3640            }
3641            // `self` and `self: TYPE`
3642            token::Ident(..) if is_isolated_self(self, 0) => {
3643                parse_self_possibly_typed(self, Mutability::Not)?
3644            }
3645            // `mut self` and `mut self: TYPE`
3646            token::Ident(..) if is_isolated_mut_self(self, 0) => {
3647                self.bump();
3648                parse_self_possibly_typed(self, Mutability::Mut)?
3649            }
3650            _ => return Ok(None),
3651        };
3652
3653        let eself = respan(eself_lo.to(eself_hi), eself);
3654        Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
3655    }
3656
3657    fn is_named_param(&self) -> bool {
3658        let offset = match &self.token.kind {
3659            token::OpenInvisible(origin) => match origin {
3660                InvisibleOrigin::MetaVar(MetaVarKind::Pat(_)) => {
3661                    return self.check_noexpect_past_close_delim(&token::Colon);
3662                }
3663                _ => 0,
3664            },
3665            token::And | token::AndAnd => 1,
3666            _ if self.token.is_keyword(kw::Mut) => 1,
3667            _ => 0,
3668        };
3669
3670        self.look_ahead(offset, |t| t.is_ident())
3671            && self.look_ahead(offset + 1, |t| t == &token::Colon)
3672    }
3673
3674    fn recover_self_param(&mut self) -> bool {
3675        #[allow(non_exhaustive_omitted_patterns)] match self.parse_outer_attributes().and_then(|_|
                self.parse_self_param()).map_err(|e| e.cancel()) {
    Ok(Some(_)) => true,
    _ => false,
}matches!(
3676            self.parse_outer_attributes()
3677                .and_then(|_| self.parse_self_param())
3678                .map_err(|e| e.cancel()),
3679            Ok(Some(_))
3680        )
3681    }
3682
3683    /// Try to recover from over-parsing in const item when a semicolon is missing.
3684    ///
3685    /// This detects cases where we parsed too much because a semicolon was missing
3686    /// and the next line started an expression that the parser treated as a continuation
3687    /// (e.g., `foo() \n &bar` was parsed as `foo() & bar`).
3688    ///
3689    /// Returns a corrected expression if recovery is successful.
3690    fn try_recover_const_missing_semi(
3691        &mut self,
3692        rhs: &Option<Box<Expr>>,
3693        const_span: Span,
3694    ) -> Option<Box<Expr>> {
3695        if self.token == TokenKind::Semi {
3696            return None;
3697        }
3698        let Some(rhs) = rhs else {
3699            return None;
3700        };
3701        if !self.in_fn_body || !self.may_recover() || rhs.span.from_expansion() {
3702            return None;
3703        }
3704        if let Some((span, guar)) =
3705            self.missing_semi_from_binop("const", rhs, Some(const_span.shrink_to_lo()))
3706        {
3707            self.fn_body_missing_semi_guar = Some(guar);
3708            Some(self.mk_expr(span, ExprKind::Err(guar)))
3709        } else {
3710            None
3711        }
3712    }
3713}
3714
3715enum IsMacroRulesItem {
3716    Yes { has_bang: bool },
3717    No,
3718}
3719
3720#[derive(#[automatically_derived]
impl ::core::marker::Copy for FrontMatterParsingMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FrontMatterParsingMode {
    #[inline]
    fn clone(&self) -> FrontMatterParsingMode { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for FrontMatterParsingMode {
    #[inline]
    fn eq(&self, other: &FrontMatterParsingMode) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for FrontMatterParsingMode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
3721pub(super) enum FrontMatterParsingMode {
3722    /// Parse the front matter of a function declaration
3723    Function,
3724    /// Parse the front matter of a function pointet type.
3725    /// For function pointer types, the `const` and `async` keywords are not permitted.
3726    FunctionPtrType,
3727}