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::errors::{
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(errors::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(errors::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(errors::DefaultNotFollowedByItem { span });
220            } else if let Defaultness::Final(span) = def {
221                this.dcx().emit_err(errors::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(errors::InappropriateDefault {
236                    span,
237                    article: kind.article(),
238                    descr: kind.descr(),
239                });
240            }
241            Defaultness::Final(span) => {
242                self.dcx().emit_err(errors::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Parsing a const block item that does not matter: {0:?}",
                                                    self.token.span) as &dyn 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, rhs_kind) = self.parse_const_item(false, const_span)?;
328            ItemKind::Const(Box::new(ConstItem {
329                defaultness: def_(),
330                ident,
331                generics,
332                ty,
333                rhs_kind,
334                define_opaque: None,
335            }))
336        } else if let Some(kind) = self.is_reuse_item() {
337            self.parse_item_delegation(attrs, def_(), kind)?
338        } 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)
339            || 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])
340        {
341            // MODULE ITEM
342            self.parse_item_mod(attrs)?
343        } 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) {
344            if let Const::Yes(const_span) = self.parse_constness(case) {
345                // TYPE CONST (mgca)
346                self.recover_const_mut(const_span);
347                self.recover_missing_kw_before_item()?;
348                let (ident, generics, ty, rhs_kind) = self.parse_const_item(true, const_span)?;
349                // Make sure this is only allowed if the feature gate is enabled.
350                // #![feature(mgca_type_const_syntax)]
351                self.psess.gated_spans.gate(sym::mgca_type_const_syntax, lo.to(const_span));
352                ItemKind::Const(Box::new(ConstItem {
353                    defaultness: def_(),
354                    ident,
355                    generics,
356                    ty,
357                    rhs_kind,
358                    define_opaque: None,
359                }))
360            } else {
361                // TYPE ITEM
362                self.parse_type_alias(def_())?
363            }
364        } 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) {
365            // ENUM ITEM
366            self.parse_item_enum()?
367        } 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) {
368            // STRUCT ITEM
369            self.parse_item_struct()?
370        } else if self.is_kw_followed_by_ident(kw::Union) {
371            // UNION ITEM
372            self.bump(); // `union`
373            self.parse_item_union()?
374        } else if self.is_builtin() {
375            // BUILTIN# ITEM
376            return self.parse_item_builtin();
377        } 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) {
378            // MACROS 2.0 ITEM
379            self.parse_item_decl_macro(lo)?
380        } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
381            // MACRO_RULES ITEM
382            self.parse_item_macro_rules(vis, has_bang)?
383        } else if self.isnt_macro_invocation()
384            && (self.token.is_ident_named(sym::import)
385                || self.token.is_ident_named(sym::using)
386                || self.token.is_ident_named(sym::include)
387                || self.token.is_ident_named(sym::require))
388        {
389            return self.recover_import_as_use();
390        } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
391            self.recover_missing_kw_before_item()?;
392            return Ok(None);
393        } else if self.isnt_macro_invocation() && case == Case::Sensitive {
394            _ = def_;
395
396            // Recover wrong cased keywords
397            return self.parse_item_kind(
398                attrs,
399                macros_allowed,
400                allow_const_block_items,
401                lo,
402                vis,
403                def,
404                fn_parse_mode,
405                Case::Insensitive,
406            );
407        } else if macros_allowed && self.check_path() {
408            if self.isnt_macro_invocation() {
409                self.recover_missing_kw_before_item()?;
410            }
411            // MACRO INVOCATION ITEM
412            ItemKind::MacCall(Box::new(self.parse_item_macro(vis)?))
413        } else {
414            return Ok(None);
415        };
416        Ok(Some(info))
417    }
418
419    fn recover_import_as_use(&mut self) -> PResult<'a, Option<ItemKind>> {
420        let span = self.token.span;
421        let token_name = super::token_descr(&self.token);
422        let snapshot = self.create_snapshot_for_diagnostic();
423        self.bump();
424        match self.parse_use_item() {
425            Ok(u) => {
426                self.dcx().emit_err(errors::RecoverImportAsUse { span, token_name });
427                Ok(Some(u))
428            }
429            Err(e) => {
430                e.cancel();
431                self.restore_snapshot(snapshot);
432                Ok(None)
433            }
434        }
435    }
436
437    fn parse_use_item(&mut self) -> PResult<'a, ItemKind> {
438        let tree = self.parse_use_tree()?;
439        if let Err(mut e) = self.expect_semi() {
440            match tree.kind {
441                UseTreeKind::Glob(_) => {
442                    e.note("the wildcard token must be last on the path");
443                }
444                UseTreeKind::Nested { .. } => {
445                    e.note("glob-like brace syntax must be last on the path");
446                }
447                _ => (),
448            }
449            return Err(e);
450        }
451        Ok(ItemKind::Use(tree))
452    }
453
454    /// When parsing a statement, would the start of a path be an item?
455    pub(super) fn is_path_start_item(&mut self) -> bool {
456        self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
457        || self.is_reuse_item().is_some() // yes: `reuse impl Trait for Struct { self.0 }`, yes: `reuse some_path::foo;`
458        || self.check_trait_front_matter() // no: `auto::b`, yes: `auto trait X { .. }`
459        || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
460        || #[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`
461    }
462
463    fn is_reuse_item(&mut self) -> Option<ReuseKind> {
464        if !self.token.is_keyword(kw::Reuse) {
465            return None;
466        }
467
468        // no: `reuse ::path` for compatibility reasons with macro invocations
469        if self.look_ahead(1, |t| t.is_path_start() && *t != token::PathSep) {
470            Some(ReuseKind::Path)
471        } else if self.check_impl_frontmatter(1) {
472            Some(ReuseKind::Impl)
473        } else {
474            None
475        }
476    }
477
478    /// Are we sure this could not possibly be a macro invocation?
479    fn isnt_macro_invocation(&mut self) -> bool {
480        self.check_ident() && self.look_ahead(1, |t| *t != token::Bang && *t != token::PathSep)
481    }
482
483    /// Recover on encountering a struct, enum, or method definition where the user
484    /// forgot to add the `struct`, `enum`, or `fn` keyword
485    fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
486        let is_pub = self.prev_token.is_keyword(kw::Pub);
487        let is_const = self.prev_token.is_keyword(kw::Const);
488        let ident_span = self.token.span;
489        let span = if is_pub { self.prev_token.span.to(ident_span) } else { ident_span };
490        let insert_span = ident_span.shrink_to_lo();
491
492        let ident = if self.token.is_ident()
493            && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen))
494            && self.look_ahead(1, |t| {
495                #[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)
496            }) {
497            self.parse_ident_common(true).unwrap()
498        } else {
499            return Ok(());
500        };
501
502        let mut found_generics = false;
503        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Lt,
    token_type: crate::parser::token_type::TokenType::Lt,
}exp!(Lt)) {
504            found_generics = true;
505            self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)]);
506            self.bump(); // `>`
507        }
508
509        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)) {
510            // possible struct or enum definition where `struct` or `enum` was forgotten
511            if self.look_ahead(1, |t| *t == token::CloseBrace) {
512                // `S {}` could be unit enum or struct
513                Some(errors::MissingKeywordForItemDefinition::EnumOrStruct { span })
514            } else if self.look_ahead(2, |t| *t == token::Colon)
515                || self.look_ahead(3, |t| *t == token::Colon)
516            {
517                // `S { f:` or `S { pub f:`
518                Some(errors::MissingKeywordForItemDefinition::Struct { span, insert_span, ident })
519            } else {
520                Some(errors::MissingKeywordForItemDefinition::Enum { span, insert_span, ident })
521            }
522        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
523            // possible function or tuple struct definition where `fn` or `struct` was forgotten
524            self.bump(); // `(`
525            let is_method = self.recover_self_param();
526
527            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);
528
529            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)) {
530                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)]);
531                self.bump(); // `{`
532                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);
533                if is_method {
534                    errors::MissingKeywordForItemDefinition::Method { span, insert_span, ident }
535                } else {
536                    errors::MissingKeywordForItemDefinition::Function { span, insert_span, ident }
537                }
538            } 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)) {
539                errors::MissingKeywordForItemDefinition::Struct { span, insert_span, ident }
540            } else {
541                errors::MissingKeywordForItemDefinition::Ambiguous {
542                    span,
543                    subdiag: if found_generics {
544                        None
545                    } else if let Ok(snippet) = self.span_to_snippet(ident_span) {
546                        Some(errors::AmbiguousMissingKwForItemSub::SuggestMacro {
547                            span: ident_span,
548                            snippet,
549                        })
550                    } else {
551                        Some(errors::AmbiguousMissingKwForItemSub::HelpMacro)
552                    },
553                }
554            };
555            Some(err)
556        } else if found_generics {
557            Some(errors::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: None })
558        } else {
559            None
560        };
561
562        if let Some(err) = err { Err(self.dcx().create_err(err)) } else { Ok(()) }
563    }
564
565    fn parse_item_builtin(&mut self) -> PResult<'a, Option<ItemKind>> {
566        // To be expanded
567        Ok(None)
568    }
569
570    /// Parses an item macro, e.g., `item!();`.
571    fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
572        let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
573        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
574        match self.parse_delim_args() {
575            // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
576            Ok(args) => {
577                self.eat_semi_for_macro_if_needed(&args, Some(&path));
578                self.complain_if_pub_macro(vis, false);
579                Ok(MacCall { path, args })
580            }
581
582            Err(mut err) => {
583                // Maybe the user misspelled `macro_rules` (issue #91227)
584                if self.token.is_ident()
585                    && let [segment] = path.segments.as_slice()
586                    && edit_distance("macro_rules", &segment.ident.to_string(), 2).is_some()
587                {
588                    err.span_suggestion(
589                        path.span,
590                        "perhaps you meant to define a macro",
591                        "macro_rules",
592                        Applicability::MachineApplicable,
593                    );
594                }
595                Err(err)
596            }
597        }
598    }
599
600    /// Recover if we parsed attributes and expected an item but there was none.
601    fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
602        let ([start @ end] | [start, .., end]) = attrs else {
603            return Ok(());
604        };
605        let msg = if end.is_doc_comment() {
606            "expected item after doc comment"
607        } else {
608            "expected item after attributes"
609        };
610        let mut err = self.dcx().struct_span_err(end.span, msg);
611        if end.is_doc_comment() {
612            err.span_label(end.span, "this doc comment doesn't document anything");
613        } else if self.token == TokenKind::Semi {
614            err.span_suggestion_verbose(
615                self.token.span,
616                "consider removing this semicolon",
617                "",
618                Applicability::MaybeIncorrect,
619            );
620        }
621        if let [.., penultimate, _] = attrs {
622            err.span_label(start.span.to(penultimate.span), "other attributes here");
623        }
624        Err(err)
625    }
626
627    fn is_async_fn(&self) -> bool {
628        self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
629    }
630
631    fn parse_polarity(&mut self) -> ast::ImplPolarity {
632        // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
633        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()) {
634            self.psess.gated_spans.gate(sym::negative_impls, self.token.span);
635            self.bump(); // `!`
636            ast::ImplPolarity::Negative(self.prev_token.span)
637        } else {
638            ast::ImplPolarity::Positive
639        }
640    }
641
642    /// Parses an implementation item.
643    ///
644    /// ```ignore (illustrative)
645    /// impl<'a, T> TYPE { /* impl items */ }
646    /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
647    /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
648    /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
649    /// ```
650    ///
651    /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
652    /// ```ebnf
653    /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
654    /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
655    /// ```
656    fn parse_item_impl(
657        &mut self,
658        attrs: &mut AttrVec,
659        defaultness: Defaultness,
660        is_reuse: bool,
661    ) -> PResult<'a, ItemKind> {
662        let constness = self.parse_constness(Case::Sensitive);
663        let safety = self.parse_safety(Case::Sensitive);
664        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Impl,
    token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl))?;
665
666        // First, parse generic parameters if necessary.
667        let mut generics = if self.choose_generics_over_qpath(0) {
668            self.parse_generics()?
669        } else {
670            let mut generics = Generics::default();
671            // impl A for B {}
672            //    /\ this is where `generics.span` should point when there are no type params.
673            generics.span = self.prev_token.span.shrink_to_hi();
674            generics
675        };
676
677        if let Const::Yes(span) = constness {
678            self.psess.gated_spans.gate(sym::const_trait_impl, span);
679        }
680
681        // Parse stray `impl async Trait`
682        if (self.token_uninterpolated_span().at_least_rust_2018()
683            && self.token.is_keyword(kw::Async))
684            || self.is_kw_followed_by_ident(kw::Async)
685        {
686            self.bump();
687            self.dcx().emit_err(errors::AsyncImpl { span: self.prev_token.span });
688        }
689
690        let polarity = self.parse_polarity();
691
692        // Parse both types and traits as a type, then reinterpret if necessary.
693        let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
694        {
695            let span = self.prev_token.span.between(self.token.span);
696            return Err(self.dcx().create_err(errors::MissingTraitInTraitImpl {
697                span,
698                for_span: span.to(self.token.span),
699            }));
700        } else {
701            self.parse_ty_with_generics_recovery(&generics)?
702        };
703
704        // If `for` is missing we try to recover.
705        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));
706        let missing_for_span = self.prev_token.span.between(self.token.span);
707
708        let ty_second = if self.token == token::DotDot {
709            // We need to report this error after `cfg` expansion for compatibility reasons
710            self.bump(); // `..`, do not add it to expected tokens
711
712            // AST validation later detects this `TyKind::Dummy` and emits an
713            // error. (#121072 will hopefully remove all this special handling
714            // of the obsolete `impl Trait for ..` and then this can go away.)
715            Some(self.mk_ty(self.prev_token.span, TyKind::Dummy))
716        } else if has_for || self.token.can_begin_type() {
717            Some(self.parse_ty()?)
718        } else {
719            None
720        };
721
722        generics.where_clause = self.parse_where_clause()?;
723
724        let impl_items = if is_reuse {
725            Default::default()
726        } else {
727            self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?
728        };
729
730        let (of_trait, self_ty) = match ty_second {
731            Some(ty_second) => {
732                // impl Trait for Type
733                if !has_for {
734                    self.dcx().emit_err(errors::MissingForInTraitImpl { span: missing_for_span });
735                }
736
737                let ty_first = *ty_first;
738                let path = match ty_first.kind {
739                    // This notably includes paths passed through `ty` macro fragments (#46438).
740                    TyKind::Path(None, path) => path,
741                    other => {
742                        if let TyKind::ImplTrait(_, bounds) = other
743                            && let [bound] = bounds.as_slice()
744                            && let GenericBound::Trait(poly_trait_ref) = bound
745                        {
746                            // Suggest removing extra `impl` keyword:
747                            // `impl<T: Default> impl Default for Wrapper<T>`
748                            //                   ^^^^^
749                            let extra_impl_kw = ty_first.span.until(bound.span());
750                            self.dcx().emit_err(errors::ExtraImplKeywordInTraitImpl {
751                                extra_impl_kw,
752                                impl_trait_span: ty_first.span,
753                            });
754                            poly_trait_ref.trait_ref.path.clone()
755                        } else {
756                            return Err(self.dcx().create_err(
757                                errors::ExpectedTraitInTraitImplFoundType { span: ty_first.span },
758                            ));
759                        }
760                    }
761                };
762                let trait_ref = TraitRef { path, ref_id: ty_first.id };
763
764                let of_trait =
765                    Some(Box::new(TraitImplHeader { defaultness, safety, polarity, trait_ref }));
766                (of_trait, ty_second)
767            }
768            None => {
769                let self_ty = ty_first;
770                let error = |modifier, modifier_name, modifier_span| {
771                    self.dcx().create_err(errors::TraitImplModifierInInherentImpl {
772                        span: self_ty.span,
773                        modifier,
774                        modifier_name,
775                        modifier_span,
776                        self_ty: self_ty.span,
777                    })
778                };
779
780                if let Safety::Unsafe(span) = safety {
781                    error("unsafe", "unsafe", span).with_code(E0197).emit();
782                }
783                if let ImplPolarity::Negative(span) = polarity {
784                    error("!", "negative", span).emit();
785                }
786                if let Defaultness::Default(def_span) = defaultness {
787                    error("default", "default", def_span).emit();
788                }
789                if let Const::Yes(span) = constness {
790                    self.psess.gated_spans.gate(sym::const_trait_impl, span);
791                }
792                (None, self_ty)
793            }
794        };
795
796        Ok(ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, constness }))
797    }
798
799    fn parse_item_delegation(
800        &mut self,
801        attrs: &mut AttrVec,
802        defaultness: Defaultness,
803        kind: ReuseKind,
804    ) -> PResult<'a, ItemKind> {
805        let span = self.token.span;
806        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Reuse,
    token_type: crate::parser::token_type::TokenType::KwReuse,
}exp!(Reuse))?;
807
808        let item_kind = match kind {
809            ReuseKind::Path => self.parse_path_like_delegation(),
810            ReuseKind::Impl => self.parse_impl_delegation(span, attrs, defaultness),
811        }?;
812
813        self.psess.gated_spans.gate(sym::fn_delegation, span.to(self.prev_token.span));
814
815        Ok(item_kind)
816    }
817
818    fn parse_delegation_body(&mut self) -> PResult<'a, Option<Box<Block>>> {
819        Ok(if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
820            Some(self.parse_block()?)
821        } else {
822            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))?;
823            None
824        })
825    }
826
827    fn parse_impl_delegation(
828        &mut self,
829        span: Span,
830        attrs: &mut AttrVec,
831        defaultness: Defaultness,
832    ) -> PResult<'a, ItemKind> {
833        let mut impl_item = self.parse_item_impl(attrs, defaultness, true)?;
834        let ItemKind::Impl(Impl { items, of_trait, .. }) = &mut impl_item else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
835
836        let until_expr_span = span.to(self.prev_token.span);
837
838        let Some(of_trait) = of_trait else {
839            return Err(self
840                .dcx()
841                .create_err(errors::ImplReuseInherentImpl { span: until_expr_span }));
842        };
843
844        let body = self.parse_delegation_body()?;
845        let whole_reuse_span = span.to(self.prev_token.span);
846
847        items.push(Box::new(AssocItem {
848            id: DUMMY_NODE_ID,
849            attrs: Default::default(),
850            span: whole_reuse_span,
851            tokens: None,
852            vis: Visibility {
853                kind: VisibilityKind::Inherited,
854                span: whole_reuse_span,
855                tokens: None,
856            },
857            kind: AssocItemKind::DelegationMac(Box::new(DelegationMac {
858                qself: None,
859                prefix: of_trait.trait_ref.path.clone(),
860                suffixes: DelegationSuffixes::Glob(whole_reuse_span),
861                body,
862            })),
863        }));
864
865        Ok(impl_item)
866    }
867
868    fn parse_path_like_delegation(&mut self) -> PResult<'a, ItemKind> {
869        let (qself, path) = if self.eat_lt() {
870            let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
871            (Some(qself), path)
872        } else {
873            (None, self.parse_path(PathStyle::Expr)?)
874        };
875
876        let rename = |this: &mut Self| {
877            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 })
878        };
879
880        Ok(if self.eat_path_sep() {
881            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)) {
882                DelegationSuffixes::Glob(self.prev_token.span)
883            } else {
884                let parse_suffix = |p: &mut Self| Ok((p.parse_path_segment_ident()?, rename(p)?));
885                DelegationSuffixes::List(
886                    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,
887                )
888            };
889
890            ItemKind::DelegationMac(Box::new(DelegationMac {
891                qself,
892                prefix: path,
893                suffixes,
894                body: self.parse_delegation_body()?,
895            }))
896        } else {
897            let rename = rename(self)?;
898            let ident = rename.unwrap_or_else(|| path.segments.last().unwrap().ident);
899
900            ItemKind::Delegation(Box::new(Delegation {
901                id: DUMMY_NODE_ID,
902                qself,
903                path,
904                ident,
905                rename,
906                body: self.parse_delegation_body()?,
907                source: DelegationSource::Single,
908            }))
909        })
910    }
911
912    fn parse_item_list<T>(
913        &mut self,
914        attrs: &mut AttrVec,
915        mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
916    ) -> PResult<'a, ThinVec<T>> {
917        let open_brace_span = self.token.span;
918
919        // Recover `impl Ty;` instead of `impl Ty {}`
920        if self.token == TokenKind::Semi {
921            self.dcx().emit_err(errors::UseEmptyBlockNotSemi { span: self.token.span });
922            self.bump();
923            return Ok(ThinVec::new());
924        }
925
926        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))?;
927        attrs.extend(self.parse_inner_attributes()?);
928
929        let mut items = ThinVec::new();
930        while !self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
931            if self.recover_doc_comment_before_brace() {
932                continue;
933            }
934            self.recover_vcs_conflict_marker();
935            match parse_item(self) {
936                Ok(None) => {
937                    let mut is_unnecessary_semicolon = !items.is_empty()
938                        // When the close delim is `)` in a case like the following, `token.kind`
939                        // is expected to be `token::CloseParen`, but the actual `token.kind` is
940                        // `token::CloseBrace`. This is because the `token.kind` of the close delim
941                        // is treated as the same as that of the open delim in
942                        // `TokenTreesReader::parse_token_tree`, even if the delimiters of them are
943                        // different. Therefore, `token.kind` should not be compared here.
944                        //
945                        // issue-60075.rs
946                        // ```
947                        // trait T {
948                        //     fn qux() -> Option<usize> {
949                        //         let _ = if true {
950                        //         });
951                        //          ^ this close delim
952                        //         Some(4)
953                        //     }
954                        // ```
955                        && self
956                            .span_to_snippet(self.prev_token.span)
957                            .is_ok_and(|snippet| snippet == "}")
958                        && self.token == token::Semi;
959                    let mut semicolon_span = self.token.span;
960                    if !is_unnecessary_semicolon {
961                        // #105369, Detect spurious `;` before assoc fn body
962                        is_unnecessary_semicolon =
963                            self.token == token::OpenBrace && self.prev_token == token::Semi;
964                        semicolon_span = self.prev_token.span;
965                    }
966                    // We have to bail or we'll potentially never make progress.
967                    let non_item_span = self.token.span;
968                    let is_let = self.token.is_keyword(kw::Let);
969
970                    let mut err =
971                        self.dcx().struct_span_err(non_item_span, "non-item in item list");
972                    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);
973                    if is_let {
974                        err.span_suggestion_verbose(
975                            non_item_span,
976                            "consider using `const` instead of `let` for associated const",
977                            "const",
978                            Applicability::MachineApplicable,
979                        );
980                    } else {
981                        err.span_label(open_brace_span, "item list starts here")
982                            .span_label(non_item_span, "non-item starts here")
983                            .span_label(self.prev_token.span, "item list ends here");
984                    }
985                    if is_unnecessary_semicolon {
986                        err.span_suggestion(
987                            semicolon_span,
988                            "consider removing this semicolon",
989                            "",
990                            Applicability::MaybeIncorrect,
991                        );
992                    }
993                    err.emit();
994                    break;
995                }
996                Ok(Some(item)) => items.extend(item),
997                Err(err) => {
998                    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);
999                    err.with_span_label(
1000                        open_brace_span,
1001                        "while parsing this item list starting here",
1002                    )
1003                    .with_span_label(self.prev_token.span, "the item list ends here")
1004                    .emit();
1005                    break;
1006                }
1007            }
1008        }
1009        Ok(items)
1010    }
1011
1012    /// Recover on a doc comment before `}`.
1013    fn recover_doc_comment_before_brace(&mut self) -> bool {
1014        if let token::DocComment(..) = self.token.kind {
1015            if self.look_ahead(1, |tok| tok == &token::CloseBrace) {
1016                // FIXME: merge with `DocCommentDoesNotDocumentAnything` (E0585)
1017                {
    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!(
1018                    self.dcx(),
1019                    self.token.span,
1020                    E0584,
1021                    "found a documentation comment that doesn't document anything",
1022                )
1023                .with_span_label(self.token.span, "this doc comment doesn't document anything")
1024                .with_help(
1025                    "doc comments must come before what they document, if a comment was \
1026                    intended use `//`",
1027                )
1028                .emit();
1029                self.bump();
1030                return true;
1031            }
1032        }
1033        false
1034    }
1035
1036    /// Parses defaultness (i.e., `default` or nothing).
1037    fn parse_defaultness(&mut self) -> Defaultness {
1038        // We are interested in `default` followed by another identifier.
1039        // However, we must avoid keywords that occur as binary operators.
1040        // Currently, the only applicable keyword is `as` (`default as Ty`).
1041        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))
1042            && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
1043        {
1044            self.psess.gated_spans.gate(sym::specialization, self.token.span);
1045            self.bump(); // `default`
1046            Defaultness::Default(self.prev_token_uninterpolated_span())
1047        } 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)) {
1048            self.psess.gated_spans.gate(sym::final_associated_functions, self.prev_token.span);
1049            Defaultness::Final(self.prev_token_uninterpolated_span())
1050        } else {
1051            Defaultness::Implicit
1052        }
1053    }
1054
1055    /// Is this an `[impl(in? path)]? const? unsafe? auto? trait` item?
1056    fn check_trait_front_matter(&mut self) -> bool {
1057        const SUFFIXES: &[&[Symbol]] = &[
1058            &[kw::Trait],
1059            &[kw::Auto, kw::Trait],
1060            &[kw::Unsafe, kw::Trait],
1061            &[kw::Unsafe, kw::Auto, kw::Trait],
1062            &[kw::Const, kw::Trait],
1063            &[kw::Const, kw::Auto, kw::Trait],
1064            &[kw::Const, kw::Unsafe, kw::Trait],
1065            &[kw::Const, kw::Unsafe, kw::Auto, kw::Trait],
1066        ];
1067        // `impl(`
1068        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) {
1069            // `impl(in` unambiguously introduces an `impl` restriction
1070            if self.is_keyword_ahead(2, &[kw::In]) {
1071                return true;
1072            }
1073            // `impl(crate | self | super)` + SUFFIX
1074            if self.is_keyword_ahead(2, &[kw::Crate, kw::SelfLower, kw::Super])
1075                && self.look_ahead(3, |t| t == &token::CloseParen)
1076                && SUFFIXES.iter().any(|suffix| {
1077                    suffix.iter().enumerate().all(|(i, kw)| self.is_keyword_ahead(i + 4, &[*kw]))
1078                })
1079            {
1080                return true;
1081            }
1082            // Recover cases like `impl(path::to::module)` + SUFFIX to suggest inserting `in`.
1083            SUFFIXES.iter().any(|suffix| {
1084                suffix.iter().enumerate().all(|(i, kw)| {
1085                    self.tree_look_ahead(i + 2, |t| {
1086                        if let TokenTree::Token(token, _) = t {
1087                            token.is_keyword(*kw)
1088                        } else {
1089                            false
1090                        }
1091                    })
1092                    .unwrap_or(false)
1093                })
1094            })
1095        } else {
1096            SUFFIXES.iter().any(|suffix| {
1097                suffix.iter().enumerate().all(|(i, kw)| {
1098                    // We use `check_keyword` for the first token to include it in the expected tokens.
1099                    if i == 0 {
1100                        match *kw {
1101                            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)),
1102                            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)),
1103                            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)),
1104                            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)),
1105                            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1106                        }
1107                    } else {
1108                        self.is_keyword_ahead(i, &[*kw])
1109                    }
1110                })
1111            })
1112        }
1113    }
1114
1115    /// Parses `[impl(in? path)]? const? unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
1116    fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemKind> {
1117        let impl_restriction = self.parse_impl_restriction()?;
1118        let constness = self.parse_constness(Case::Sensitive);
1119        if let Const::Yes(span) = constness {
1120            self.psess.gated_spans.gate(sym::const_trait_impl, span);
1121        }
1122        let safety = self.parse_safety(Case::Sensitive);
1123        // Parse optional `auto` prefix.
1124        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)) {
1125            self.psess.gated_spans.gate(sym::auto_traits, self.prev_token.span);
1126            IsAuto::Yes
1127        } else {
1128            IsAuto::No
1129        };
1130
1131        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Trait,
    token_type: crate::parser::token_type::TokenType::KwTrait,
}exp!(Trait))?;
1132        let ident = self.parse_ident()?;
1133        let mut generics = self.parse_generics()?;
1134
1135        // Parse optional colon and supertrait bounds.
1136        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));
1137        let span_at_colon = self.prev_token.span;
1138        let bounds = if had_colon { self.parse_generic_bounds()? } else { Vec::new() };
1139
1140        let span_before_eq = self.prev_token.span;
1141        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1142            // It's a trait alias.
1143            if had_colon {
1144                let span = span_at_colon.to(span_before_eq);
1145                self.dcx().emit_err(errors::BoundsNotAllowedOnTraitAliases { span });
1146            }
1147
1148            let bounds = self.parse_generic_bounds()?;
1149            generics.where_clause = self.parse_where_clause()?;
1150            self.expect_semi()?;
1151
1152            let whole_span = lo.to(self.prev_token.span);
1153            if is_auto == IsAuto::Yes {
1154                self.dcx().emit_err(errors::TraitAliasCannotBeAuto { span: whole_span });
1155            }
1156            if let Safety::Unsafe(_) = safety {
1157                self.dcx().emit_err(errors::TraitAliasCannotBeUnsafe { span: whole_span });
1158            }
1159            if let RestrictionKind::Restricted { .. } = impl_restriction.kind {
1160                self.dcx().emit_err(errors::TraitAliasCannotBeImplRestricted { span: whole_span });
1161            }
1162
1163            self.psess.gated_spans.gate(sym::trait_alias, whole_span);
1164
1165            Ok(ItemKind::TraitAlias(Box::new(TraitAlias { constness, ident, generics, bounds })))
1166        } else {
1167            // It's a normal trait.
1168            generics.where_clause = self.parse_where_clause()?;
1169            let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
1170            Ok(ItemKind::Trait(Box::new(Trait {
1171                impl_restriction,
1172                constness,
1173                is_auto,
1174                safety,
1175                ident,
1176                generics,
1177                bounds,
1178                items,
1179            })))
1180        }
1181    }
1182
1183    pub fn parse_impl_item(
1184        &mut self,
1185        force_collect: ForceCollect,
1186    ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1187        let fn_parse_mode =
1188            FnParseMode { req_name: |_, _| true, context: FnContext::Impl, req_body: true };
1189        self.parse_assoc_item(fn_parse_mode, force_collect)
1190    }
1191
1192    pub fn parse_trait_item(
1193        &mut self,
1194        force_collect: ForceCollect,
1195    ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1196        let fn_parse_mode = FnParseMode {
1197            req_name: |edition, _| edition >= Edition::Edition2018,
1198            context: FnContext::Trait,
1199            req_body: false,
1200        };
1201        self.parse_assoc_item(fn_parse_mode, force_collect)
1202    }
1203
1204    /// Parses associated items.
1205    fn parse_assoc_item(
1206        &mut self,
1207        fn_parse_mode: FnParseMode,
1208        force_collect: ForceCollect,
1209    ) -> PResult<'a, Option<Option<Box<AssocItem>>>> {
1210        Ok(self
1211            .parse_item_(
1212                fn_parse_mode,
1213                force_collect,
1214                AllowConstBlockItems::DoesNotMatter, // due to `AssocItemKind::try_from` below
1215            )?
1216            .map(|Item { attrs, id, span, vis, kind, tokens }| {
1217                let kind = match AssocItemKind::try_from(kind) {
1218                    Ok(kind) => kind,
1219                    Err(kind) => match kind {
1220                        ItemKind::Static(StaticItem {
1221                            ident,
1222                            ty,
1223                            safety: _,
1224                            mutability: _,
1225                            expr,
1226                            define_opaque,
1227                            eii_impls: _,
1228                        }) => {
1229                            self.dcx().emit_err(errors::AssociatedStaticItemNotAllowed { span });
1230                            AssocItemKind::Const(Box::new(ConstItem {
1231                                defaultness: Defaultness::Implicit,
1232                                ident,
1233                                generics: Generics::default(),
1234                                ty,
1235                                rhs_kind: ConstItemRhsKind::Body { rhs: expr },
1236                                define_opaque,
1237                            }))
1238                        }
1239                        _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
1240                    },
1241                };
1242                Some(Box::new(Item { attrs, id, span, vis, kind, tokens }))
1243            }))
1244    }
1245
1246    /// Parses a `type` alias with the following grammar:
1247    /// ```ebnf
1248    /// TypeAlias = "type" Ident Generics (":" GenericBounds)? WhereClause ("=" Ty)? WhereClause ";" ;
1249    /// ```
1250    /// The `"type"` has already been eaten.
1251    fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemKind> {
1252        let ident = self.parse_ident()?;
1253        let mut generics = self.parse_generics()?;
1254
1255        // Parse optional colon and param bounds.
1256        let bounds = 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 { Vec::new() };
1257        generics.where_clause = self.parse_where_clause()?;
1258
1259        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 };
1260
1261        let after_where_clause = self.parse_where_clause()?;
1262
1263        self.expect_semi()?;
1264
1265        Ok(ItemKind::TyAlias(Box::new(TyAlias {
1266            defaultness,
1267            ident,
1268            generics,
1269            after_where_clause,
1270            bounds,
1271            ty,
1272        })))
1273    }
1274
1275    /// Parses a `UseTree`.
1276    ///
1277    /// ```text
1278    /// USE_TREE = [`::`] `*` |
1279    ///            [`::`] `{` USE_TREE_LIST `}` |
1280    ///            PATH `::` `*` |
1281    ///            PATH `::` `{` USE_TREE_LIST `}` |
1282    ///            PATH [`as` IDENT]
1283    /// ```
1284    fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
1285        let lo = self.token.span;
1286
1287        let mut prefix =
1288            ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None };
1289        let kind =
1290            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() {
1291                // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
1292                let mod_sep_ctxt = self.token.span.ctxt();
1293                if self.eat_path_sep() {
1294                    prefix
1295                        .segments
1296                        .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1297                }
1298
1299                self.parse_use_tree_glob_or_nested()?
1300            } else {
1301                // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
1302                prefix = self.parse_path(PathStyle::Mod)?;
1303
1304                if self.eat_path_sep() {
1305                    self.parse_use_tree_glob_or_nested()?
1306                } else {
1307                    // Recover from using a colon as path separator.
1308                    while self.eat_noexpect(&token::Colon) {
1309                        self.dcx()
1310                            .emit_err(errors::SingleColonImportPath { span: self.prev_token.span });
1311
1312                        // We parse the rest of the path and append it to the original prefix.
1313                        self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1314                        prefix.span = lo.to(self.prev_token.span);
1315                    }
1316
1317                    UseTreeKind::Simple(self.parse_rename()?)
1318                }
1319            };
1320
1321        Ok(UseTree { prefix, kind })
1322    }
1323
1324    /// Parses `*` or `{...}`.
1325    fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1326        Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Star,
    token_type: crate::parser::token_type::TokenType::Star,
}exp!(Star)) {
1327            UseTreeKind::Glob(self.prev_token.span)
1328        } else {
1329            let lo = self.token.span;
1330            UseTreeKind::Nested {
1331                items: self.parse_use_tree_list()?,
1332                span: lo.to(self.prev_token.span),
1333            }
1334        })
1335    }
1336
1337    /// Parses a `UseTreeKind::Nested(list)`.
1338    ///
1339    /// ```text
1340    /// USE_TREE_LIST = ∅ | (USE_TREE `,`)* USE_TREE [`,`]
1341    /// ```
1342    fn parse_use_tree_list(&mut self) -> PResult<'a, ThinVec<(UseTree, ast::NodeId)>> {
1343        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| {
1344            p.recover_vcs_conflict_marker();
1345            Ok((p.parse_use_tree()?, DUMMY_NODE_ID))
1346        })
1347        .map(|(r, _)| r)
1348    }
1349
1350    fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1351        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)) {
1352            self.parse_ident_or_underscore().map(Some)
1353        } else {
1354            Ok(None)
1355        }
1356    }
1357
1358    fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1359        match self.token.ident() {
1360            Some((ident @ Ident { name: kw::Underscore, .. }, IdentIsRaw::No)) => {
1361                self.bump();
1362                Ok(ident)
1363            }
1364            _ => self.parse_ident(),
1365        }
1366    }
1367
1368    /// Parses `extern crate` links.
1369    ///
1370    /// # Examples
1371    ///
1372    /// ```ignore (illustrative)
1373    /// extern crate foo;
1374    /// extern crate bar as foo;
1375    /// ```
1376    fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemKind> {
1377        // Accept `extern crate name-like-this` for better diagnostics
1378        let orig_ident = self.parse_crate_name_with_dashes()?;
1379        let (orig_name, item_ident) = if let Some(rename) = self.parse_rename()? {
1380            (Some(orig_ident.name), rename)
1381        } else {
1382            (None, orig_ident)
1383        };
1384        self.expect_semi()?;
1385        Ok(ItemKind::ExternCrate(orig_name, item_ident))
1386    }
1387
1388    fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1389        let ident = if self.token.is_keyword(kw::SelfLower) {
1390            self.parse_path_segment_ident()
1391        } else {
1392            self.parse_ident()
1393        }?;
1394
1395        let dash = crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Minus,
    token_type: crate::parser::token_type::TokenType::Minus,
}exp!(Minus);
1396        if self.token != dash.tok {
1397            return Ok(ident);
1398        }
1399
1400        // Accept `extern crate name-like-this` for better diagnostics.
1401        let mut dashes = ::alloc::vec::Vec::new()vec![];
1402        let mut idents = ::alloc::vec::Vec::new()vec![];
1403        while self.eat(dash) {
1404            dashes.push(self.prev_token.span);
1405            idents.push(self.parse_ident()?);
1406        }
1407
1408        let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1409        let mut fixed_name = ident.name.to_string();
1410        for part in idents {
1411            fixed_name.write_fmt(format_args!("_{0}", part.name))write!(fixed_name, "_{}", part.name).unwrap();
1412        }
1413
1414        self.dcx().emit_err(errors::ExternCrateNameWithDashes {
1415            span: fixed_name_sp,
1416            sugg: errors::ExternCrateNameWithDashesSugg { dashes },
1417        });
1418
1419        Ok(Ident::from_str_and_span(&fixed_name, fixed_name_sp))
1420    }
1421
1422    /// Parses `extern` for foreign ABIs modules.
1423    ///
1424    /// `extern` is expected to have been consumed before calling this method.
1425    ///
1426    /// # Examples
1427    ///
1428    /// ```ignore (only-for-syntax-highlight)
1429    /// extern "C" {}
1430    /// extern {}
1431    /// ```
1432    fn parse_item_foreign_mod(
1433        &mut self,
1434        attrs: &mut AttrVec,
1435        mut safety: Safety,
1436    ) -> PResult<'a, ItemKind> {
1437        let extern_span = self.prev_token_uninterpolated_span();
1438        let abi = self.parse_abi(); // ABI?
1439        // FIXME: This recovery should be tested better.
1440        if safety == Safety::Default
1441            && self.token.is_keyword(kw::Unsafe)
1442            && self.look_ahead(1, |t| *t == token::OpenBrace)
1443        {
1444            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();
1445            safety = Safety::Unsafe(self.token.span);
1446            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));
1447        }
1448        Ok(ItemKind::ForeignMod(ast::ForeignMod {
1449            extern_span,
1450            safety,
1451            abi,
1452            items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1453        }))
1454    }
1455
1456    /// Parses a foreign item (one in an `extern { ... }` block).
1457    pub fn parse_foreign_item(
1458        &mut self,
1459        force_collect: ForceCollect,
1460    ) -> PResult<'a, Option<Option<Box<ForeignItem>>>> {
1461        let fn_parse_mode = FnParseMode {
1462            req_name: |_, is_dot_dot_dot| is_dot_dot_dot == IsDotDotDot::No,
1463            context: FnContext::Free,
1464            req_body: false,
1465        };
1466        Ok(self
1467            .parse_item_(
1468                fn_parse_mode,
1469                force_collect,
1470                AllowConstBlockItems::DoesNotMatter, // due to `ForeignItemKind::try_from` below
1471            )?
1472            .map(|Item { attrs, id, span, vis, kind, tokens }| {
1473                let kind = match ForeignItemKind::try_from(kind) {
1474                    Ok(kind) => kind,
1475                    Err(kind) => match kind {
1476                        ItemKind::Const(ConstItem { ident, ty, rhs_kind, .. }) => {
1477                            let const_span = Some(span.with_hi(ident.span.lo()))
1478                                .filter(|span| span.can_be_used_for_suggestions());
1479                            self.dcx().emit_err(errors::ExternItemCannotBeConst {
1480                                ident_span: ident.span,
1481                                const_span,
1482                            });
1483                            ForeignItemKind::Static(Box::new(StaticItem {
1484                                ident,
1485                                ty,
1486                                mutability: Mutability::Not,
1487                                expr: match rhs_kind {
1488                                    ConstItemRhsKind::Body { rhs } => rhs,
1489                                    ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
1490                                        Some(anon.value)
1491                                    }
1492                                    ConstItemRhsKind::TypeConst { rhs: None } => None,
1493                                },
1494                                safety: Safety::Default,
1495                                define_opaque: None,
1496                                eii_impls: ThinVec::default(),
1497                            }))
1498                        }
1499                        _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1500                    },
1501                };
1502                Some(Box::new(Item { attrs, id, span, vis, kind, tokens }))
1503            }))
1504    }
1505
1506    fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &'static str) -> Option<T> {
1507        // FIXME(#100717): needs variant for each `ItemKind` (instead of using `ItemKind::descr()`)
1508        let span = self.psess.source_map().guess_head_span(span);
1509        let descr = kind.descr();
1510        let help = match kind {
1511            ItemKind::DelegationMac(DelegationMac {
1512                suffixes: DelegationSuffixes::Glob(_),
1513                ..
1514            }) => false,
1515            _ => true,
1516        };
1517        self.dcx().emit_err(errors::BadItemKind { span, descr, ctx, help });
1518        None
1519    }
1520
1521    fn is_use_closure(&self) -> bool {
1522        if self.token.is_keyword(kw::Use) {
1523            // Check if this could be a closure.
1524            self.look_ahead(1, |token| {
1525                // Move or Async here would be an error but still we're parsing a closure
1526                let dist =
1527                    if token.is_keyword(kw::Move) || token.is_keyword(kw::Async) { 2 } else { 1 };
1528
1529                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))
1530            })
1531        } else {
1532            false
1533        }
1534    }
1535
1536    fn is_unsafe_foreign_mod(&self) -> bool {
1537        // Look for `unsafe`.
1538        if !self.token.is_keyword(kw::Unsafe) {
1539            return false;
1540        }
1541        // Look for `extern`.
1542        if !self.is_keyword_ahead(1, &[kw::Extern]) {
1543            return false;
1544        }
1545
1546        // Look for the optional ABI string literal.
1547        let n = if self.look_ahead(2, |t| t.can_begin_string_literal()) { 3 } else { 2 };
1548
1549        // Look for the `{`. Use `tree_look_ahead` because the ABI (if present)
1550        // might be a metavariable i.e. an invisible-delimited sequence, and
1551        // `tree_look_ahead` will consider that a single element when looking
1552        // ahead.
1553        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, _)))
1554            == Some(true)
1555    }
1556
1557    fn parse_global_static_front_matter(&mut self, case: Case) -> Option<Safety> {
1558        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) {
1559            // Check if this could be a closure.
1560            !self.look_ahead(1, |token| {
1561                if token.is_keyword_case(kw::Move, case) || token.is_keyword_case(kw::Use, case) {
1562                    return true;
1563                }
1564                #[allow(non_exhaustive_omitted_patterns)] match token.kind {
    token::Or | token::OrOr => true,
    _ => false,
}matches!(token.kind, token::Or | token::OrOr)
1565            })
1566        } else {
1567            // `$qual static`
1568            (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)
1569                || 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))
1570                && self.look_ahead(1, |t| t.is_keyword_case(kw::Static, case))
1571        };
1572
1573        if is_global_static {
1574            let safety = self.parse_safety(case);
1575            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);
1576            Some(safety)
1577        } else {
1578            None
1579        }
1580    }
1581
1582    /// Recover on `const mut` with `const` already eaten.
1583    fn recover_const_mut(&mut self, const_span: Span) {
1584        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)) {
1585            let span = self.prev_token.span;
1586            self.dcx()
1587                .emit_err(errors::ConstGlobalCannotBeMutable { ident_span: span, const_span });
1588        } 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)) {
1589            let span = self.prev_token.span;
1590            self.dcx().emit_err(errors::ConstLetMutuallyExclusive { span: const_span.to(span) });
1591        }
1592    }
1593
1594    fn parse_const_block_item(&mut self) -> PResult<'a, ConstBlockItem> {
1595        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1596        let const_span = self.prev_token.span;
1597        self.psess.gated_spans.gate(sym::const_block_items, const_span);
1598        let block = self.parse_block()?;
1599        Ok(ConstBlockItem { id: DUMMY_NODE_ID, span: const_span.to(block.span), block })
1600    }
1601
1602    /// Parse a static item with the prefix `"static" "mut"?` already parsed and stored in
1603    /// `mutability`.
1604    ///
1605    /// ```ebnf
1606    /// Static = "static" "mut"? $ident ":" $ty (= $expr)? ";" ;
1607    /// ```
1608    fn parse_static_item(
1609        &mut self,
1610        safety: Safety,
1611        mutability: Mutability,
1612    ) -> PResult<'a, ItemKind> {
1613        let ident = self.parse_ident()?;
1614
1615        if self.token == TokenKind::Lt && self.may_recover() {
1616            let generics = self.parse_generics()?;
1617            self.dcx().emit_err(errors::StaticWithGenerics { span: generics.span });
1618        }
1619
1620        // Parse the type of a static item. That is, the `":" $ty` fragment.
1621        // FIXME: This could maybe benefit from `.may_recover()`?
1622        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))) {
1623            (true, false) => self.parse_ty()?,
1624            // If there wasn't a `:` or the colon was followed by a `=` or `;`, recover a missing
1625            // type.
1626            (colon, _) => self.recover_missing_global_item_type(colon, Some(mutability)),
1627        };
1628
1629        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 };
1630
1631        self.expect_semi()?;
1632
1633        let item = StaticItem {
1634            ident,
1635            ty,
1636            safety,
1637            mutability,
1638            expr,
1639            define_opaque: None,
1640            eii_impls: ThinVec::default(),
1641        };
1642        Ok(ItemKind::Static(Box::new(item)))
1643    }
1644
1645    /// Parse a constant item with the prefix `"const"` already parsed.
1646    ///
1647    /// If `const_arg` is true, any expression assigned to the const will be parsed
1648    /// as a const_arg instead of a body expression.
1649    ///
1650    /// ```ebnf
1651    /// Const = "const" ($ident | "_") Generics ":" $ty (= $expr)? WhereClause ";" ;
1652    /// ```
1653    fn parse_const_item(
1654        &mut self,
1655        const_arg: bool,
1656        const_span: Span,
1657    ) -> PResult<'a, (Ident, Generics, Box<Ty>, ConstItemRhsKind)> {
1658        let ident = self.parse_ident_or_underscore()?;
1659
1660        let mut generics = self.parse_generics()?;
1661
1662        // Check the span for emptiness instead of the list of parameters in order to correctly
1663        // recognize and subsequently flag empty parameter lists (`<>`) as unstable.
1664        if !generics.span.is_empty() {
1665            self.psess.gated_spans.gate(sym::generic_const_items, generics.span);
1666        }
1667
1668        // Parse the type of a constant item. That is, the `":" $ty` fragment.
1669        // FIXME: This could maybe benefit from `.may_recover()`?
1670        let ty = match (
1671            self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)),
1672            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)),
1673        ) {
1674            (true, false) => self.parse_ty()?,
1675            // If there wasn't a `:` or the colon was followed by a `=`, `;` or `where`, recover a missing type.
1676            (colon, _) => self.recover_missing_global_item_type(colon, None),
1677        };
1678
1679        // Proactively parse a where-clause to be able to provide a good error message in case we
1680        // encounter the item body following it.
1681        let before_where_clause =
1682            if self.may_recover() { self.parse_where_clause()? } else { WhereClause::default() };
1683
1684        let rhs = match (self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)), const_arg) {
1685            (true, true) => ConstItemRhsKind::TypeConst {
1686                rhs: Some(self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct)?),
1687            },
1688            (true, false) => ConstItemRhsKind::Body { rhs: Some(self.parse_expr()?) },
1689            (false, true) => ConstItemRhsKind::TypeConst { rhs: None },
1690            (false, false) => ConstItemRhsKind::Body { rhs: None },
1691        };
1692
1693        let after_where_clause = self.parse_where_clause()?;
1694
1695        // Provide a nice error message if the user placed a where-clause before the item body.
1696        // Users may be tempted to write such code if they are still used to the deprecated
1697        // where-clause location on type aliases and associated types. See also #89122.
1698        if before_where_clause.has_where_token
1699            && let Some(rhs_span) = rhs.span()
1700        {
1701            self.dcx().emit_err(errors::WhereClauseBeforeConstBody {
1702                span: before_where_clause.span,
1703                name: ident.span,
1704                body: rhs_span,
1705                sugg: if !after_where_clause.has_where_token {
1706                    self.psess.source_map().span_to_snippet(rhs_span).ok().map(|body_s| {
1707                        errors::WhereClauseBeforeConstBodySugg {
1708                            left: before_where_clause.span.shrink_to_lo(),
1709                            snippet: body_s,
1710                            right: before_where_clause.span.shrink_to_hi().to(rhs_span),
1711                        }
1712                    })
1713                } else {
1714                    // FIXME(generic_const_items): Provide a structured suggestion to merge the first
1715                    // where-clause into the second one.
1716                    None
1717                },
1718            });
1719        }
1720
1721        // Merge the predicates of both where-clauses since either one can be relevant.
1722        // If we didn't parse a body (which is valid for associated consts in traits) and we were
1723        // allowed to recover, `before_where_clause` contains the predicates, otherwise they are
1724        // in `after_where_clause`. Further, both of them might contain predicates iff two
1725        // where-clauses were provided which is syntactically ill-formed but we want to recover from
1726        // it and treat them as one large where-clause.
1727        let mut predicates = before_where_clause.predicates;
1728        predicates.extend(after_where_clause.predicates);
1729        let where_clause = WhereClause {
1730            has_where_token: before_where_clause.has_where_token
1731                || after_where_clause.has_where_token,
1732            predicates,
1733            span: if after_where_clause.has_where_token {
1734                after_where_clause.span
1735            } else {
1736                before_where_clause.span
1737            },
1738        };
1739
1740        if where_clause.has_where_token {
1741            self.psess.gated_spans.gate(sym::generic_const_items, where_clause.span);
1742        }
1743
1744        generics.where_clause = where_clause;
1745
1746        if let Some(rhs) = self.try_recover_const_missing_semi(&rhs, const_span) {
1747            return Ok((ident, generics, ty, ConstItemRhsKind::Body { rhs: Some(rhs) }));
1748        }
1749        self.expect_semi()?;
1750
1751        Ok((ident, generics, ty, rhs))
1752    }
1753
1754    /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1755    /// This means that the type is missing.
1756    fn recover_missing_global_item_type(
1757        &mut self,
1758        colon_present: bool,
1759        m: Option<Mutability>,
1760    ) -> Box<Ty> {
1761        // Construct the error and stash it away with the hope
1762        // that typeck will later enrich the error with a type.
1763        let kind = match m {
1764            Some(Mutability::Mut) => "static mut",
1765            Some(Mutability::Not) => "static",
1766            None => "const",
1767        };
1768
1769        let colon = match colon_present {
1770            true => "",
1771            false => ":",
1772        };
1773
1774        let span = self.prev_token.span.shrink_to_hi();
1775        let err = self.dcx().create_err(errors::MissingConstType { span, colon, kind });
1776        err.stash(span, StashKey::ItemNoType);
1777
1778        // The user intended that the type be inferred,
1779        // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1780        Box::new(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1781    }
1782
1783    /// Parses an enum declaration.
1784    fn parse_item_enum(&mut self) -> PResult<'a, ItemKind> {
1785        if self.token.is_keyword(kw::Struct) {
1786            let span = self.prev_token.span.to(self.token.span);
1787            let err = errors::EnumStructMutuallyExclusive { span };
1788            if self.look_ahead(1, |t| t.is_ident()) {
1789                self.bump();
1790                self.dcx().emit_err(err);
1791            } else {
1792                return Err(self.dcx().create_err(err));
1793            }
1794        }
1795
1796        let prev_span = self.prev_token.span;
1797        let ident = self.parse_ident()?;
1798        let mut generics = self.parse_generics()?;
1799        generics.where_clause = self.parse_where_clause()?;
1800
1801        // Possibly recover `enum Foo;` instead of `enum Foo {}`
1802        let (variants, _) = if self.token == TokenKind::Semi {
1803            self.dcx().emit_err(errors::UseEmptyBlockNotSemi { span: self.token.span });
1804            self.bump();
1805            (::thin_vec::ThinVec::new()thin_vec![], Trailing::No)
1806        } else {
1807            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| {
1808                p.parse_enum_variant(ident.span)
1809            })
1810            .map_err(|mut err| {
1811                err.span_label(ident.span, "while parsing this enum");
1812                // Try to recover `enum Foo { ident : Ty }`.
1813                if self.prev_token.is_non_reserved_ident() && self.token == token::Colon {
1814                    let snapshot = self.create_snapshot_for_diagnostic();
1815                    self.bump();
1816                    match self.parse_ty() {
1817                        Ok(_) => {
1818                            err.span_suggestion_verbose(
1819                                prev_span,
1820                                "perhaps you meant to use `struct` here",
1821                                "struct",
1822                                Applicability::MaybeIncorrect,
1823                            );
1824                        }
1825                        Err(e) => {
1826                            e.cancel();
1827                        }
1828                    }
1829                    self.restore_snapshot(snapshot);
1830                }
1831                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1832                self.bump(); // }
1833                err
1834            })?
1835        };
1836
1837        let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1838        Ok(ItemKind::Enum(ident, generics, enum_definition))
1839    }
1840
1841    fn parse_enum_variant(&mut self, span: Span) -> PResult<'a, Option<Variant>> {
1842        self.recover_vcs_conflict_marker();
1843        let variant_attrs = self.parse_outer_attributes()?;
1844        self.recover_vcs_conflict_marker();
1845        let help = "enum variants can be `Variant`, `Variant = <integer>`, \
1846                    `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`";
1847        self.collect_tokens(None, variant_attrs, ForceCollect::No, |this, variant_attrs| {
1848            let vlo = this.token.span;
1849
1850            let vis = this.parse_visibility(FollowedByType::No)?;
1851            if !this.recover_nested_adt_item(kw::Enum)? {
1852                return Ok((None, Trailing::No, UsePreAttrPos::No));
1853            }
1854            let ident = this.parse_field_ident("enum", vlo)?;
1855
1856            if this.token == token::Bang {
1857                if let Err(err) = this.unexpected() {
1858                    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();
1859                }
1860
1861                this.bump();
1862                this.parse_delim_args()?;
1863
1864                return Ok((None, Trailing::from(this.token == token::Comma), UsePreAttrPos::No));
1865            }
1866
1867            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)) {
1868                // Parse a struct variant.
1869                let (fields, recovered) =
1870                    match this.parse_record_struct_body("struct", ident.span, false) {
1871                        Ok((fields, recovered)) => (fields, recovered),
1872                        Err(mut err) => {
1873                            if this.token == token::Colon {
1874                                // We handle `enum` to `struct` suggestion in the caller.
1875                                return Err(err);
1876                            }
1877                            this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1878                            this.bump(); // }
1879                            err.span_label(span, "while parsing this enum");
1880                            err.help(help);
1881                            let guar = err.emit();
1882                            (::thin_vec::ThinVec::new()thin_vec![], Recovered::Yes(guar))
1883                        }
1884                    };
1885                VariantData::Struct { fields, recovered }
1886            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1887                let body = match this.parse_tuple_struct_body() {
1888                    Ok(body) => body,
1889                    Err(mut err) => {
1890                        if this.token == token::Colon {
1891                            // We handle `enum` to `struct` suggestion in the caller.
1892                            return Err(err);
1893                        }
1894                        this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
1895                        this.bump(); // )
1896                        err.span_label(span, "while parsing this enum");
1897                        err.help(help);
1898                        err.emit();
1899                        ::thin_vec::ThinVec::new()thin_vec![]
1900                    }
1901                };
1902                VariantData::Tuple(body, DUMMY_NODE_ID)
1903            } else {
1904                VariantData::Unit(DUMMY_NODE_ID)
1905            };
1906
1907            let disr_expr = if this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1908                Some(this.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst)?)
1909            } else {
1910                None
1911            };
1912
1913            let span = vlo.to(this.prev_token.span);
1914            if ident.name == kw::Underscore {
1915                this.psess.gated_spans.gate(sym::unnamed_enum_variants, span);
1916            }
1917            let vr = ast::Variant {
1918                ident,
1919                vis,
1920                id: DUMMY_NODE_ID,
1921                attrs: variant_attrs,
1922                data: struct_def,
1923                disr_expr,
1924                span,
1925                is_placeholder: false,
1926            };
1927
1928            Ok((Some(vr), Trailing::from(this.token == token::Comma), UsePreAttrPos::No))
1929        })
1930        .map_err(|mut err| {
1931            err.help(help);
1932            err
1933        })
1934    }
1935
1936    /// Parses `struct Foo { ... }`.
1937    fn parse_item_struct(&mut self) -> PResult<'a, ItemKind> {
1938        let ident = self.parse_ident()?;
1939
1940        let mut generics = self.parse_generics()?;
1941
1942        // There is a special case worth noting here, as reported in issue #17904.
1943        // If we are parsing a tuple struct it is the case that the where clause
1944        // should follow the field list. Like so:
1945        //
1946        // struct Foo<T>(T) where T: Copy;
1947        //
1948        // If we are parsing a normal record-style struct it is the case
1949        // that the where clause comes before the body, and after the generics.
1950        // So if we look ahead and see a brace or a where-clause we begin
1951        // parsing a record style struct.
1952        //
1953        // Otherwise if we look ahead and see a paren we parse a tuple-style
1954        // struct.
1955
1956        let vdata = if self.token.is_keyword(kw::Where) {
1957            let tuple_struct_body;
1958            (generics.where_clause, tuple_struct_body) =
1959                self.parse_struct_where_clause(ident, generics.span)?;
1960
1961            if let Some(body) = tuple_struct_body {
1962                // If we see a misplaced tuple struct body: `struct Foo<T> where T: Copy, (T);`
1963                let body = VariantData::Tuple(body, DUMMY_NODE_ID);
1964                self.expect_semi()?;
1965                body
1966            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1967                // If we see a: `struct Foo<T> where T: Copy;` style decl.
1968                VariantData::Unit(DUMMY_NODE_ID)
1969            } else {
1970                // If we see: `struct Foo<T> where T: Copy { ... }`
1971                let (fields, recovered) = self.parse_record_struct_body(
1972                    "struct",
1973                    ident.span,
1974                    generics.where_clause.has_where_token,
1975                )?;
1976                VariantData::Struct { fields, recovered }
1977            }
1978        // No `where` so: `struct Foo<T>;`
1979        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1980            VariantData::Unit(DUMMY_NODE_ID)
1981        // Record-style struct definition
1982        } else if self.token == token::OpenBrace {
1983            let (fields, recovered) = self.parse_record_struct_body(
1984                "struct",
1985                ident.span,
1986                generics.where_clause.has_where_token,
1987            )?;
1988            VariantData::Struct { fields, recovered }
1989        // Tuple-style struct definition with optional where-clause.
1990        } else if self.token == token::OpenParen {
1991            let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1992            generics.where_clause = self.parse_where_clause()?;
1993            self.expect_semi()?;
1994            body
1995        } else {
1996            let err = errors::UnexpectedTokenAfterStructName::new(self.token.span, self.token);
1997            return Err(self.dcx().create_err(err));
1998        };
1999
2000        Ok(ItemKind::Struct(ident, generics, vdata))
2001    }
2002
2003    /// Parses `union Foo { ... }`.
2004    fn parse_item_union(&mut self) -> PResult<'a, ItemKind> {
2005        let ident = self.parse_ident()?;
2006
2007        let mut generics = self.parse_generics()?;
2008
2009        let vdata = if self.token.is_keyword(kw::Where) {
2010            generics.where_clause = self.parse_where_clause()?;
2011            let (fields, recovered) = self.parse_record_struct_body(
2012                "union",
2013                ident.span,
2014                generics.where_clause.has_where_token,
2015            )?;
2016            VariantData::Struct { fields, recovered }
2017        } else if self.token == token::OpenBrace {
2018            let (fields, recovered) = self.parse_record_struct_body(
2019                "union",
2020                ident.span,
2021                generics.where_clause.has_where_token,
2022            )?;
2023            VariantData::Struct { fields, recovered }
2024        } else {
2025            let token_str = super::token_descr(&self.token);
2026            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}");
2027            let mut err = self.dcx().struct_span_err(self.token.span, msg);
2028            err.span_label(self.token.span, "expected `where` or `{` after union name");
2029            return Err(err);
2030        };
2031
2032        Ok(ItemKind::Union(ident, generics, vdata))
2033    }
2034
2035    /// This function parses the fields of record structs:
2036    ///
2037    ///   - `struct S { ... }`
2038    ///   - `enum E { Variant { ... } }`
2039    pub(crate) fn parse_record_struct_body(
2040        &mut self,
2041        adt_ty: &str,
2042        ident_span: Span,
2043        parsed_where: bool,
2044    ) -> PResult<'a, (ThinVec<FieldDef>, Recovered)> {
2045        let mut fields = ThinVec::new();
2046        let mut recovered = Recovered::No;
2047        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2048            while self.token != token::CloseBrace {
2049                match self.parse_field_def(adt_ty, ident_span) {
2050                    Ok(field) => {
2051                        fields.push(field);
2052                    }
2053                    Err(mut err) => {
2054                        self.consume_block(
2055                            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace),
2056                            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace),
2057                            ConsumeClosingDelim::No,
2058                        );
2059                        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}"));
2060                        let guar = err.emit();
2061                        recovered = Recovered::Yes(guar);
2062                        break;
2063                    }
2064                }
2065            }
2066            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
2067        } else {
2068            let token_str = super::token_descr(&self.token);
2069            let where_str = if parsed_where { "" } else { "`where`, or " };
2070            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}");
2071            let mut err = self.dcx().struct_span_err(self.token.span, msg);
2072            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",));
2073            return Err(err);
2074        }
2075
2076        Ok((fields, recovered))
2077    }
2078
2079    fn parse_unsafe_field(&mut self) -> Safety {
2080        // not using parse_safety as that also accepts `safe`.
2081        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)) {
2082            let span = self.prev_token.span;
2083            self.psess.gated_spans.gate(sym::unsafe_fields, span);
2084            Safety::Unsafe(span)
2085        } else {
2086            Safety::Default
2087        }
2088    }
2089    /// This is the case where we find `struct Foo<T>(T) where T: Copy;`
2090    /// Unit like structs are handled in parse_item_struct function
2091    pub(super) fn parse_tuple_struct_body(&mut self) -> PResult<'a, ThinVec<FieldDef>> {
2092        let openparen_span = self.token.span;
2093        let mut encountered_colon = false;
2094        self.parse_paren_comma_seq(|p| {
2095            let attrs = p.parse_outer_attributes()?;
2096            p.collect_tokens(None, attrs, ForceCollect::No, |p, attrs| {
2097                let mut snapshot = None;
2098                if p.is_vcs_conflict_marker(&TokenKind::Shl, &TokenKind::Lt) {
2099                    // Account for `<<<<<<<` diff markers. We can't proactively error here because
2100                    // that can be a valid type start, so we snapshot and reparse only we've
2101                    // encountered another parse error.
2102                    snapshot = Some(p.create_snapshot_for_diagnostic());
2103                }
2104                let lo = p.token.span;
2105                let vis = match p.parse_visibility(FollowedByType::Yes) {
2106                    Ok(vis) => vis,
2107                    Err(err) => {
2108                        if let Some(ref mut snapshot) = snapshot {
2109                            snapshot.recover_vcs_conflict_marker();
2110                        }
2111                        return Err(err);
2112                    }
2113                };
2114                let mut_restriction = p.parse_mut_restriction()?;
2115                encountered_colon |=
2116                    p.token.is_ident() && p.look_ahead(1, |tok| tok == &token::Colon);
2117                // Unsafe fields are not supported in tuple structs, as doing so would result in a
2118                // parsing ambiguity for `struct X(unsafe fn())`.
2119                let ty = match p.parse_ty() {
2120                    Ok(ty) => ty,
2121                    Err(err) => {
2122                        if let Some(ref mut snapshot) = snapshot {
2123                            snapshot.recover_vcs_conflict_marker();
2124                        }
2125                        return Err(err);
2126                    }
2127                };
2128                let mut default = None;
2129                if p.token == token::Eq {
2130                    let mut snapshot = p.create_snapshot_for_diagnostic();
2131                    snapshot.bump();
2132                    match snapshot.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst) {
2133                        Ok(const_expr) => {
2134                            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2135                            p.psess.gated_spans.gate(sym::default_field_values, sp);
2136                            p.restore_snapshot(snapshot);
2137                            default = Some(const_expr);
2138                        }
2139                        Err(err) => {
2140                            err.cancel();
2141                        }
2142                    }
2143                }
2144
2145                Ok((
2146                    FieldDef {
2147                        span: lo.to(ty.span),
2148                        vis,
2149                        mut_restriction,
2150                        safety: Safety::Default,
2151                        ident: None,
2152                        id: DUMMY_NODE_ID,
2153                        ty,
2154                        default,
2155                        attrs,
2156                        is_placeholder: false,
2157                    },
2158                    Trailing::from(p.token == token::Comma),
2159                    UsePreAttrPos::No,
2160                ))
2161            })
2162        })
2163        .map(|(r, _)| r)
2164        .map_err(|mut error| {
2165            if self.token == token::Colon {
2166                error.subdiagnostic(UseDoubleColonSuggestion { colon: self.token.span });
2167            }
2168            if encountered_colon {
2169                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
2170                self.bump();
2171                error.subdiagnostic(UseRegularStructSuggestion {
2172                    open: openparen_span,
2173                    close: self.prev_token.span,
2174                    semicolon: if self.token == token::Semi { Some(self.token.span) } else { None },
2175                });
2176            }
2177            error
2178        })
2179    }
2180
2181    /// Parses an element of a struct declaration.
2182    fn parse_field_def(&mut self, adt_ty: &str, ident_span: Span) -> PResult<'a, FieldDef> {
2183        self.recover_vcs_conflict_marker();
2184        let attrs = self.parse_outer_attributes()?;
2185        self.recover_vcs_conflict_marker();
2186        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2187            let lo = this.token.span;
2188            let vis = this.parse_visibility(FollowedByType::No)?;
2189            let mut_restriction = this.parse_mut_restriction()?;
2190            let safety = this.parse_unsafe_field();
2191            this.parse_single_struct_field(
2192                adt_ty,
2193                lo,
2194                vis,
2195                mut_restriction,
2196                safety,
2197                attrs,
2198                ident_span,
2199            )
2200            .map(|field| (field, Trailing::No, UsePreAttrPos::No))
2201        })
2202    }
2203
2204    /// Parses a structure field declaration.
2205    fn parse_single_struct_field(
2206        &mut self,
2207        adt_ty: &str,
2208        lo: Span,
2209        vis: Visibility,
2210        mut_restriction: MutRestriction,
2211        safety: Safety,
2212        attrs: AttrVec,
2213        ident_span: Span,
2214    ) -> PResult<'a, FieldDef> {
2215        let a_var = self.parse_name_and_ty(adt_ty, lo, vis, mut_restriction, safety, attrs)?;
2216        match self.token.kind {
2217            token::Comma => {
2218                self.bump();
2219            }
2220            token::Semi => {
2221                self.bump();
2222                let sp = self.prev_token.span;
2223                let mut err =
2224                    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 `,`"));
2225                err.span_suggestion_short(
2226                    sp,
2227                    "replace `;` with `,`",
2228                    ",",
2229                    Applicability::MachineApplicable,
2230                );
2231                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}"));
2232                err.emit();
2233            }
2234            token::CloseBrace => {}
2235            token::DocComment(..) => {
2236                let previous_span = self.prev_token.span;
2237                let mut err = errors::DocCommentDoesNotDocumentAnything {
2238                    span: self.token.span,
2239                    missing_comma: None,
2240                };
2241                self.bump(); // consume the doc comment
2242                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 {
2243                    self.dcx().emit_err(err);
2244                } else {
2245                    let sp = previous_span.shrink_to_hi();
2246                    err.missing_comma = Some(sp);
2247                    return Err(self.dcx().create_err(err));
2248                }
2249            }
2250            _ => {
2251                let sp = self.prev_token.span.shrink_to_hi();
2252                let msg =
2253                    ::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));
2254
2255                // Try to recover extra trailing angle brackets
2256                if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind
2257                    && let Some(last_segment) = segments.last()
2258                {
2259                    let guar = self.check_trailing_angle_brackets(
2260                        last_segment,
2261                        &[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)],
2262                    );
2263                    if let Some(_guar) = guar {
2264                        // Handle a case like `Vec<u8>>,` where we can continue parsing fields
2265                        // after the comma
2266                        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
2267
2268                        // `check_trailing_angle_brackets` already emitted a nicer error, as
2269                        // proven by the presence of `_guar`. We can continue parsing.
2270                        return Ok(a_var);
2271                    }
2272                }
2273
2274                let mut err = self.dcx().struct_span_err(sp, msg);
2275
2276                if self.token.is_ident()
2277                    || (self.token == TokenKind::Pound
2278                        && (self.look_ahead(1, |t| t == &token::OpenBracket)))
2279                {
2280                    // This is likely another field, TokenKind::Pound is used for `#[..]`
2281                    // attribute for next field. Emit the diagnostic and continue parsing.
2282                    err.span_suggestion(
2283                        sp,
2284                        "try adding a comma",
2285                        ",",
2286                        Applicability::MachineApplicable,
2287                    );
2288                    err.emit();
2289                } else {
2290                    return Err(err);
2291                }
2292            }
2293        }
2294        Ok(a_var)
2295    }
2296
2297    fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
2298        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)) {
2299            let sm = self.psess.source_map();
2300            let eq_typo = self.token == token::Eq && self.look_ahead(1, |t| t.is_path_start());
2301            let semi_typo = self.token == token::Semi
2302                && self.look_ahead(1, |t| {
2303                    t.is_path_start()
2304                    // We check that we are in a situation like `foo; bar` to avoid bad suggestions
2305                    // when there's no type and `;` was used instead of a comma.
2306                    && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
2307                        (Ok(l), Ok(r)) => l.line == r.line,
2308                        _ => true,
2309                    }
2310                });
2311            if eq_typo || semi_typo {
2312                self.bump();
2313                // Gracefully handle small typos.
2314                err.with_span_suggestion_short(
2315                    self.prev_token.span,
2316                    "field names and their types are separated with `:`",
2317                    ":",
2318                    Applicability::MachineApplicable,
2319                )
2320                .emit();
2321            } else {
2322                return Err(err);
2323            }
2324        }
2325        Ok(())
2326    }
2327
2328    /// Parses a structure field.
2329    fn parse_name_and_ty(
2330        &mut self,
2331        adt_ty: &str,
2332        lo: Span,
2333        vis: Visibility,
2334        mut_restriction: MutRestriction,
2335        safety: Safety,
2336        attrs: AttrVec,
2337    ) -> PResult<'a, FieldDef> {
2338        let name = self.parse_field_ident(adt_ty, lo)?;
2339        if self.token == token::Bang {
2340            if let Err(mut err) = self.unexpected() {
2341                // Encounter the macro invocation
2342                err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
2343                return Err(err);
2344            }
2345        }
2346        self.expect_field_ty_separator()?;
2347        let ty = self.parse_ty()?;
2348        if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
2349            self.dcx()
2350                .struct_span_err(self.token.span, "found single colon in a struct field type path")
2351                .with_span_suggestion_verbose(
2352                    self.token.span,
2353                    "write a path separator here",
2354                    "::",
2355                    Applicability::MaybeIncorrect,
2356                )
2357                .emit();
2358        }
2359        let default = if self.token == token::Eq {
2360            self.bump();
2361            let const_expr = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst)?;
2362            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2363            self.psess.gated_spans.gate(sym::default_field_values, sp);
2364            Some(const_expr)
2365        } else {
2366            None
2367        };
2368        Ok(FieldDef {
2369            span: lo.to(self.prev_token.span),
2370            ident: Some(name),
2371            vis,
2372            safety,
2373            mut_restriction,
2374            id: DUMMY_NODE_ID,
2375            ty,
2376            default,
2377            attrs,
2378            is_placeholder: false,
2379        })
2380    }
2381
2382    /// Parses a field identifier. Specialized version of `parse_ident_common`
2383    /// for better diagnostics and suggestions.
2384    fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
2385        let (ident, is_raw) = self.ident_or_err(true)?;
2386        if is_raw == IdentIsRaw::No
2387            && ident.is_reserved()
2388            && !(ident.name == kw::Underscore && adt_ty == "enum")
2389        {
2390            let snapshot = self.create_snapshot_for_diagnostic();
2391            let err = if self.check_fn_front_matter(false, Case::Sensitive) {
2392                let inherited_vis =
2393                    Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited, tokens: None };
2394                // We use `parse_fn` to get a span for the function
2395                let fn_parse_mode =
2396                    FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
2397                match self.parse_fn(
2398                    &mut AttrVec::new(),
2399                    fn_parse_mode,
2400                    lo,
2401                    &inherited_vis,
2402                    Case::Insensitive,
2403                ) {
2404                    Ok(_) => {
2405                        self.dcx().struct_span_err(
2406                            lo.to(self.prev_token.span),
2407                            ::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"),
2408                        )
2409                        .with_help(
2410                            "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
2411                        )
2412                        .with_help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information")
2413                    }
2414                    Err(err) => {
2415                        err.cancel();
2416                        self.restore_snapshot(snapshot);
2417                        self.expected_ident_found_err()
2418                    }
2419                }
2420            } 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)) {
2421                match self.parse_item_struct() {
2422                    Ok(item) => {
2423                        let ItemKind::Struct(ident, ..) = item else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2424                        self.dcx()
2425                            .struct_span_err(
2426                                lo.with_hi(ident.span.hi()),
2427                                ::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"),
2428                            )
2429                            .with_help(
2430                                "consider creating a new `struct` definition instead of nesting",
2431                            )
2432                    }
2433                    Err(err) => {
2434                        err.cancel();
2435                        self.restore_snapshot(snapshot);
2436                        self.expected_ident_found_err()
2437                    }
2438                }
2439            } else {
2440                let mut err = self.expected_ident_found_err();
2441                if self.eat_keyword_noexpect(kw::Let)
2442                    && let removal_span = self.prev_token.span.until(self.token.span)
2443                    && let Ok(ident) = self
2444                        .parse_ident_common(false)
2445                        // Cancel this error, we don't need it.
2446                        .map_err(|err| err.cancel())
2447                    && self.token == TokenKind::Colon
2448                {
2449                    err.span_suggestion(
2450                        removal_span,
2451                        "remove this `let` keyword",
2452                        String::new(),
2453                        Applicability::MachineApplicable,
2454                    );
2455                    err.note("the `let` keyword is not allowed in `struct` fields");
2456                    err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
2457                    err.emit();
2458                    return Ok(ident);
2459                } else {
2460                    self.restore_snapshot(snapshot);
2461                }
2462                err
2463            };
2464            return Err(err);
2465        }
2466        self.bump();
2467        Ok(ident)
2468    }
2469
2470    /// Parses a declarative macro 2.0 definition.
2471    /// The `macro` keyword has already been parsed.
2472    /// ```ebnf
2473    /// MacBody = "{" TOKEN_STREAM "}" ;
2474    /// MacParams = "(" TOKEN_STREAM ")" ;
2475    /// DeclMac = "macro" Ident MacParams? MacBody ;
2476    /// ```
2477    fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemKind> {
2478        let ident = self.parse_ident()?;
2479        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)) {
2480            self.parse_delim_args()? // `MacBody`
2481        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
2482            let params = self.parse_token_tree(); // `MacParams`
2483            let pspan = params.span();
2484            if !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2485                self.unexpected()?;
2486            }
2487            let body = self.parse_token_tree(); // `MacBody`
2488            // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
2489            let bspan = body.span();
2490            let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
2491            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]);
2492            let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
2493            Box::new(DelimArgs { dspan, delim: Delimiter::Brace, tokens })
2494        } else {
2495            self.unexpected_any()?
2496        };
2497
2498        self.psess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
2499        Ok(ItemKind::MacroDef(
2500            ident,
2501            ast::MacroDef { body, macro_rules: false, eii_declaration: None },
2502        ))
2503    }
2504
2505    /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
2506    fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
2507        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)) {
2508            let macro_rules_span = self.token.span;
2509
2510            if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) {
2511                return IsMacroRulesItem::Yes { has_bang: true };
2512            } else if self.look_ahead(1, |t| t.is_ident()) {
2513                // macro_rules foo
2514                self.dcx().emit_err(errors::MacroRulesMissingBang {
2515                    span: macro_rules_span,
2516                    hi: macro_rules_span.shrink_to_hi(),
2517                });
2518
2519                return IsMacroRulesItem::Yes { has_bang: false };
2520            }
2521        }
2522
2523        IsMacroRulesItem::No
2524    }
2525
2526    /// Parses a `macro_rules! foo { ... }` declarative macro.
2527    fn parse_item_macro_rules(
2528        &mut self,
2529        vis: &Visibility,
2530        has_bang: bool,
2531    ) -> PResult<'a, ItemKind> {
2532        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`
2533
2534        if has_bang {
2535            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
2536        }
2537        let ident = self.parse_ident()?;
2538
2539        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
2540            // Handle macro_rules! foo!
2541            let span = self.prev_token.span;
2542            self.dcx().emit_err(errors::MacroNameRemoveBang { span });
2543        }
2544
2545        let body = self.parse_delim_args()?;
2546        self.eat_semi_for_macro_if_needed(&body, None);
2547        self.complain_if_pub_macro(vis, true);
2548
2549        Ok(ItemKind::MacroDef(
2550            ident,
2551            ast::MacroDef { body, macro_rules: true, eii_declaration: None },
2552        ))
2553    }
2554
2555    /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
2556    /// If that's not the case, emit an error.
2557    fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
2558        if let VisibilityKind::Inherited = vis.kind {
2559            return;
2560        }
2561
2562        let vstr = pprust::vis_to_string(vis);
2563        let vstr = vstr.trim_end();
2564        if macro_rules {
2565            self.dcx().emit_err(errors::MacroRulesVisibility { span: vis.span, vis: vstr });
2566        } else {
2567            self.dcx().emit_err(errors::MacroInvocationVisibility { span: vis.span, vis: vstr });
2568        }
2569    }
2570
2571    fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs, path: Option<&Path>) {
2572        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)) {
2573            self.report_invalid_macro_expansion_item(args, path);
2574        }
2575    }
2576
2577    fn report_invalid_macro_expansion_item(&self, args: &DelimArgs, path: Option<&Path>) {
2578        let span = args.dspan.entire();
2579        let mut err = self.dcx().struct_span_err(
2580            span,
2581            "macros that expand to items must be delimited with braces or followed by a semicolon",
2582        );
2583        // FIXME: This will make us not emit the help even for declarative
2584        // macros within the same crate (that we can fix), which is sad.
2585        if !span.from_expansion() {
2586            let DelimSpan { open, close } = args.dspan;
2587            // Check if this looks like `macro_rules!(name) { ... }`
2588            // a common mistake when trying to define a macro.
2589            if let Some(path) = path
2590                && path.segments.first().is_some_and(|seg| seg.ident.name == sym::macro_rules)
2591                && args.delim == Delimiter::Parenthesis
2592            {
2593                let replace =
2594                    if path.span.hi() + rustc_span::BytePos(1) < open.lo() { "" } else { " " };
2595                err.multipart_suggestion(
2596                    "to define a macro, remove the parentheses around the macro name",
2597                    ::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())],
2598                    Applicability::MachineApplicable,
2599                );
2600            } else {
2601                err.multipart_suggestion(
2602                    "change the delimiters to curly braces",
2603                    ::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())],
2604                    Applicability::MaybeIncorrect,
2605                );
2606                err.span_suggestion(
2607                    span.with_neighbor(self.token.span).shrink_to_hi(),
2608                    "add a semicolon",
2609                    ';',
2610                    Applicability::MaybeIncorrect,
2611                );
2612            }
2613        }
2614        err.emit();
2615    }
2616
2617    /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2618    /// it is, we try to parse the item and report error about nested types.
2619    fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2620        if (self.token.is_keyword(kw::Enum)
2621            || self.token.is_keyword(kw::Struct)
2622            || self.token.is_keyword(kw::Union))
2623            && self.look_ahead(1, |t| t.is_ident())
2624        {
2625            let kw_token = self.token;
2626            let kw_str = pprust::token_to_string(&kw_token);
2627            let item = self.parse_item(
2628                ForceCollect::No,
2629                AllowConstBlockItems::DoesNotMatter, // self.token != kw::Const
2630            )?;
2631            let mut item = item.unwrap().span;
2632            if self.token == token::Comma {
2633                item = item.to(self.token.span);
2634            }
2635            self.dcx().emit_err(errors::NestedAdt {
2636                span: kw_token.span,
2637                item,
2638                kw_str,
2639                keyword: keyword.as_str(),
2640            });
2641            // We successfully parsed the item but we must inform the caller about nested problem.
2642            return Ok(false);
2643        }
2644        Ok(true)
2645    }
2646}
2647
2648/// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2649///
2650/// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2651///
2652/// This function pointer accepts an edition, because in edition 2015, trait declarations
2653/// were allowed to omit parameter names. In 2018, they became required. It also accepts an
2654/// `IsDotDotDot` parameter, as `extern` function declarations and function pointer types are
2655/// allowed to omit the name of the `...` but regular function items are not.
2656type ReqName = fn(Edition, IsDotDotDot) -> bool;
2657
2658#[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)]
2659pub(crate) enum IsDotDotDot {
2660    Yes,
2661    No,
2662}
2663
2664/// Parsing configuration for functions.
2665///
2666/// The syntax of function items is slightly different within trait definitions,
2667/// impl blocks, and modules. It is still parsed using the same code, just with
2668/// different flags set, so that even when the input is wrong and produces a parse
2669/// error, it still gets into the AST and the rest of the parser and
2670/// type checker can run.
2671#[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)]
2672pub(crate) struct FnParseMode {
2673    /// A function pointer that decides if, per-parameter `p`, `p` must have a
2674    /// pattern or just a type. This field affects parsing of the parameters list.
2675    ///
2676    /// ```text
2677    /// fn foo(alef: A) -> X { X::new() }
2678    ///        -----^^ affects parsing this part of the function signature
2679    ///        |
2680    ///        if req_name returns false, then this name is optional
2681    ///
2682    /// fn bar(A) -> X;
2683    ///        ^
2684    ///        |
2685    ///        if req_name returns true, this is an error
2686    /// ```
2687    ///
2688    /// Calling this function pointer should only return false if:
2689    ///
2690    ///   * The item is being parsed inside of a trait definition.
2691    ///     Within an impl block or a module, it should always evaluate
2692    ///     to true.
2693    ///   * The span is from Edition 2015. In particular, you can get a
2694    ///     2015 span inside a 2021 crate using macros.
2695    ///
2696    /// Or if `IsDotDotDot::Yes`, this function will also return `false` if the item being parsed
2697    /// is inside an `extern` block.
2698    pub(super) req_name: ReqName,
2699    /// The context in which this function is parsed, used for diagnostics.
2700    /// This indicates the fn is a free function or method and so on.
2701    pub(super) context: FnContext,
2702    /// If this flag is set to `true`, then plain, semicolon-terminated function
2703    /// prototypes are not allowed here.
2704    ///
2705    /// ```text
2706    /// fn foo(alef: A) -> X { X::new() }
2707    ///                      ^^^^^^^^^^^^
2708    ///                      |
2709    ///                      this is always allowed
2710    ///
2711    /// fn bar(alef: A, bet: B) -> X;
2712    ///                             ^
2713    ///                             |
2714    ///                             if req_body is set to true, this is an error
2715    /// ```
2716    ///
2717    /// This field should only be set to false if the item is inside of a trait
2718    /// definition or extern block. Within an impl block or a module, it should
2719    /// always be set to true.
2720    pub(super) req_body: bool,
2721}
2722
2723/// The context in which a function is parsed.
2724/// FIXME(estebank, xizheyin): Use more variants.
2725#[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)]
2726pub(crate) enum FnContext {
2727    /// Free context.
2728    Free,
2729    /// A Trait context.
2730    Trait,
2731    /// An Impl block.
2732    Impl,
2733}
2734
2735/// Parsing of functions and methods.
2736impl<'a> Parser<'a> {
2737    /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2738    fn parse_fn(
2739        &mut self,
2740        attrs: &mut AttrVec,
2741        fn_parse_mode: FnParseMode,
2742        sig_lo: Span,
2743        vis: &Visibility,
2744        case: Case,
2745    ) -> PResult<'a, (Ident, FnSig, Generics, Option<Box<FnContract>>, Option<Box<Block>>)> {
2746        let fn_span = self.token.span;
2747        let header = self.parse_fn_front_matter(vis, case, FrontMatterParsingMode::Function)?; // `const ... fn`
2748        let ident = self.parse_ident()?; // `foo`
2749        let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2750        let decl = match self.parse_fn_decl(&fn_parse_mode, AllowPlus::Yes, RecoverReturnSign::Yes)
2751        {
2752            Ok(decl) => decl,
2753            Err(old_err) => {
2754                // If we see `for Ty ...` then user probably meant `impl` item.
2755                if self.token.is_keyword(kw::For) {
2756                    old_err.cancel();
2757                    return Err(self.dcx().create_err(errors::FnTypoWithImpl { fn_span }));
2758                } else {
2759                    return Err(old_err);
2760                }
2761            }
2762        };
2763
2764        // Store the end of function parameters to give better diagnostics
2765        // inside `parse_fn_body()`.
2766        let fn_params_end = self.prev_token.span.shrink_to_hi();
2767
2768        let contract = self.parse_contract()?;
2769
2770        generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2771
2772        // `fn_params_end` is needed only when it's followed by a where clause.
2773        let fn_params_end =
2774            if generics.where_clause.has_where_token { Some(fn_params_end) } else { None };
2775
2776        let mut sig_hi = self.prev_token.span;
2777        // Either `;` or `{ ... }`.
2778        let body =
2779            self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body, fn_params_end)?;
2780        let fn_sig_span = sig_lo.to(sig_hi);
2781        Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, contract, body))
2782    }
2783
2784    /// Provide diagnostics when function body is not found
2785    fn error_fn_body_not_found(
2786        &mut self,
2787        ident_span: Span,
2788        req_body: bool,
2789        fn_params_end: Option<Span>,
2790    ) -> PResult<'a, ErrorGuaranteed> {
2791        let expected: &[_] =
2792            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)] };
2793        match self.expected_one_of_not_found(&[], expected) {
2794            Ok(error_guaranteed) => Ok(error_guaranteed),
2795            Err(mut err) => {
2796                if self.token == token::CloseBrace {
2797                    // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2798                    // the AST for typechecking.
2799                    err.span_label(ident_span, "while parsing this `fn`");
2800                    Ok(err.emit())
2801                } else if self.token == token::RArrow
2802                    && let Some(fn_params_end) = fn_params_end
2803                {
2804                    // Instead of a function body, the parser has encountered a right arrow
2805                    // preceded by a where clause.
2806
2807                    // Find whether token behind the right arrow is a function trait and
2808                    // store its span.
2809                    let fn_trait_span =
2810                        [sym::FnOnce, sym::FnMut, sym::Fn].into_iter().find_map(|symbol| {
2811                            if self.prev_token.is_ident_named(symbol) {
2812                                Some(self.prev_token.span)
2813                            } else {
2814                                None
2815                            }
2816                        });
2817
2818                    // Parse the return type (along with the right arrow) and store its span.
2819                    // If there's a parse error, cancel it and return the existing error
2820                    // as we are primarily concerned with the
2821                    // expected-function-body-but-found-something-else error here.
2822                    let arrow_span = self.token.span;
2823                    let ty_span = match self.parse_ret_ty(
2824                        AllowPlus::Yes,
2825                        RecoverQPath::Yes,
2826                        RecoverReturnSign::Yes,
2827                    ) {
2828                        Ok(ty_span) => ty_span.span().shrink_to_hi(),
2829                        Err(parse_error) => {
2830                            parse_error.cancel();
2831                            return Err(err);
2832                        }
2833                    };
2834                    let ret_ty_span = arrow_span.to(ty_span);
2835
2836                    if let Some(fn_trait_span) = fn_trait_span {
2837                        // Typo'd Fn* trait bounds such as
2838                        // fn foo<F>() where F: FnOnce -> () {}
2839                        err.subdiagnostic(errors::FnTraitMissingParen { span: fn_trait_span });
2840                    } else if let Ok(snippet) = self.psess.source_map().span_to_snippet(ret_ty_span)
2841                    {
2842                        // If token behind right arrow is not a Fn* trait, the programmer
2843                        // probably misplaced the return type after the where clause like
2844                        // `fn foo<T>() where T: Default -> u8 {}`
2845                        err.primary_message(
2846                            "return type should be specified after the function parameters",
2847                        );
2848                        err.subdiagnostic(errors::MisplacedReturnType {
2849                            fn_params_end,
2850                            snippet,
2851                            ret_ty_span,
2852                        });
2853                    }
2854                    Err(err)
2855                } else {
2856                    Err(err)
2857                }
2858            }
2859        }
2860    }
2861
2862    /// Parse the "body" of a function.
2863    /// This can either be `;` when there's no body,
2864    /// or e.g. a block when the function is a provided one.
2865    fn parse_fn_body(
2866        &mut self,
2867        attrs: &mut AttrVec,
2868        ident: &Ident,
2869        sig_hi: &mut Span,
2870        req_body: bool,
2871        fn_params_end: Option<Span>,
2872    ) -> PResult<'a, Option<Box<Block>>> {
2873        let has_semi = if req_body {
2874            self.token == TokenKind::Semi
2875        } else {
2876            // Only include `;` in list of expected tokens if body is not required
2877            self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))
2878        };
2879        let (inner_attrs, body) = if has_semi {
2880            // Include the trailing semicolon in the span of the signature
2881            self.expect_semi()?;
2882            *sig_hi = self.prev_token.span;
2883            (AttrVec::new(), None)
2884        } 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() {
2885            let prev_in_fn_body = self.in_fn_body;
2886            self.in_fn_body = true;
2887            let res = self.parse_block_common(self.token.span, BlockCheckMode::Default, None).map(
2888                |(attrs, mut body)| {
2889                    if let Some(guar) = self.fn_body_missing_semi_guar.take() {
2890                        body.stmts.push(self.mk_stmt(
2891                            body.span,
2892                            StmtKind::Expr(self.mk_expr(body.span, ExprKind::Err(guar))),
2893                        ));
2894                    }
2895                    (attrs, Some(body))
2896                },
2897            );
2898            self.in_fn_body = prev_in_fn_body;
2899            res?
2900        } else if self.token == token::Eq {
2901            // Recover `fn foo() = $expr;`.
2902            self.bump(); // `=`
2903            let eq_sp = self.prev_token.span;
2904            let _ = self.parse_expr()?;
2905            self.expect_semi()?; // `;`
2906            let span = eq_sp.to(self.prev_token.span);
2907            let guar = self.dcx().emit_err(errors::FunctionBodyEqualsExpr {
2908                span,
2909                sugg: errors::FunctionBodyEqualsExprSugg { eq: eq_sp, semi: self.prev_token.span },
2910            });
2911            (AttrVec::new(), Some(self.mk_block_err(span, guar)))
2912        } else {
2913            self.error_fn_body_not_found(ident.span, req_body, fn_params_end)?;
2914            (AttrVec::new(), None)
2915        };
2916        attrs.extend(inner_attrs);
2917        Ok(body)
2918    }
2919
2920    fn check_impl_frontmatter(&mut self, look_ahead: usize) -> bool {
2921        const ALL_QUALS: &[Symbol] = &[kw::Const, kw::Unsafe];
2922        // In contrast to the loop below, this call inserts `impl` into the
2923        // list of expected tokens shown in diagnostics.
2924        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)) {
2925            return true;
2926        }
2927        let mut i = 0;
2928        while i < ALL_QUALS.len() {
2929            let action = self.look_ahead(i + look_ahead, |token| {
2930                if token.is_keyword(kw::Impl) {
2931                    return Some(true);
2932                }
2933                if ALL_QUALS.iter().any(|&qual| token.is_keyword(qual)) {
2934                    // Ok, we found a legal keyword, keep looking for `impl`
2935                    return None;
2936                }
2937                Some(false)
2938            });
2939            if let Some(ret) = action {
2940                return ret;
2941            }
2942            i += 1;
2943        }
2944
2945        self.is_keyword_ahead(i, &[kw::Impl])
2946    }
2947
2948    /// Is the current token the start of an `FnHeader` / not a valid parse?
2949    ///
2950    /// `check_pub` adds additional `pub` to the checks in case users place it
2951    /// wrongly, can be used to ensure `pub` never comes after `default`.
2952    pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2953        const ALL_QUALS: &[ExpKeywordPair] = &[
2954            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Pub,
    token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub),
2955            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen),
2956            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const),
2957            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async),
2958            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe),
2959            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Safe,
    token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe),
2960            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern),
2961        ];
2962
2963        // We use an over-approximation here.
2964        // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2965        // `pub` is added in case users got confused with the ordering like `async pub fn`,
2966        // only if it wasn't preceded by `default` as `default pub` is invalid.
2967        let quals: &[_] = if check_pub {
2968            ALL_QUALS
2969        } else {
2970            &[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)]
2971        };
2972        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`.
2973            // `$qual fn` or `$qual $qual`:
2974            || quals.iter().any(|&exp| self.check_keyword_case(exp, case))
2975                && self.look_ahead(1, |t| {
2976                    // `$qual fn`, e.g. `const fn` or `async fn`.
2977                    t.is_keyword_case(kw::Fn, case)
2978                    // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2979                    || (
2980                        (
2981                            t.is_non_raw_ident_where(|i|
2982                                quals.iter().any(|exp| exp.kw == i.name)
2983                                    // Rule out 2015 `const async: T = val`.
2984                                    && i.is_reserved()
2985                            )
2986                            || case == Case::Insensitive
2987                                && t.is_non_raw_ident_where(|i| quals.iter().any(|exp| {
2988                                    exp.kw.as_str() == i.name.as_str().to_lowercase()
2989                                }))
2990                        )
2991                        // Rule out `unsafe extern {`.
2992                        && !self.is_unsafe_foreign_mod()
2993                        // Rule out `async gen {` and `async gen move {`
2994                        && !self.is_async_gen_block()
2995                        // Rule out `const unsafe auto` and `const unsafe trait` and `const unsafe impl`
2996                        && !self.is_keyword_ahead(2, &[kw::Auto, kw::Trait, kw::Impl])
2997                    )
2998                })
2999            // `extern ABI fn`
3000            || 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)
3001                // Use `tree_look_ahead` because `ABI` might be a metavariable,
3002                // i.e. an invisible-delimited sequence, and `tree_look_ahead`
3003                // will consider that a single element when looking ahead.
3004                && self.look_ahead(1, |t| t.can_begin_string_literal())
3005                && (self.tree_look_ahead(2, |tt| {
3006                    match tt {
3007                        TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case),
3008                        TokenTree::Delimited(..) => false,
3009                    }
3010                }) == Some(true) ||
3011                    // This branch is only for better diagnostics; `pub`, `unsafe`, etc. are not
3012                    // allowed here.
3013                    (self.may_recover()
3014                        && self.tree_look_ahead(2, |tt| {
3015                            match tt {
3016                                TokenTree::Token(t, _) =>
3017                                    ALL_QUALS.iter().any(|exp| {
3018                                        t.is_keyword(exp.kw)
3019                                    }),
3020                                TokenTree::Delimited(..) => false,
3021                            }
3022                        }) == Some(true)
3023                        && self.tree_look_ahead(3, |tt| {
3024                            match tt {
3025                                TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case),
3026                                TokenTree::Delimited(..) => false,
3027                            }
3028                        }) == Some(true)
3029                    )
3030                )
3031    }
3032
3033    /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
3034    /// up to and including the `fn` keyword. The formal grammar is:
3035    ///
3036    /// ```text
3037    /// Extern = "extern" StringLit? ;
3038    /// FnQual = "const"? "async"? "unsafe"? Extern? ;
3039    /// FnFrontMatter = FnQual "fn" ;
3040    /// ```
3041    ///
3042    /// `vis` represents the visibility that was already parsed, if any. Use
3043    /// `Visibility::Inherited` when no visibility is known.
3044    ///
3045    /// If `parsing_mode` is `FrontMatterParsingMode::FunctionPtrType`, we error on `const` and `async` qualifiers,
3046    /// which are not allowed in function pointer types.
3047    pub(super) fn parse_fn_front_matter(
3048        &mut self,
3049        orig_vis: &Visibility,
3050        case: Case,
3051        parsing_mode: FrontMatterParsingMode,
3052    ) -> PResult<'a, FnHeader> {
3053        let sp_start = self.token.span;
3054        let constness = self.parse_constness(case);
3055        if parsing_mode == FrontMatterParsingMode::FunctionPtrType
3056            && let Const::Yes(const_span) = constness
3057        {
3058            self.dcx().emit_err(FnPointerCannotBeConst {
3059                span: const_span,
3060                suggestion: const_span.until(self.token.span),
3061            });
3062        }
3063
3064        let async_start_sp = self.token.span;
3065        let coroutine_kind = self.parse_coroutine_kind(case);
3066        if parsing_mode == FrontMatterParsingMode::FunctionPtrType
3067            && let Some(ast::CoroutineKind::Async { span: async_span, .. }) = coroutine_kind
3068        {
3069            self.dcx().emit_err(FnPointerCannotBeAsync {
3070                span: async_span,
3071                suggestion: async_span.until(self.token.span),
3072            });
3073        }
3074        // FIXME(gen_blocks): emit a similar error for `gen fn()`
3075
3076        let unsafe_start_sp = self.token.span;
3077        let safety = self.parse_safety(case);
3078
3079        let ext_start_sp = self.token.span;
3080        let ext = self.parse_extern(case);
3081
3082        if let Some(CoroutineKind::Async { span, .. }) = coroutine_kind {
3083            if span.is_rust_2015() {
3084                self.dcx().emit_err(errors::AsyncFnIn2015 {
3085                    span,
3086                    help: errors::HelpUseLatestEdition::new(),
3087                });
3088            }
3089        }
3090
3091        match coroutine_kind {
3092            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
3093                self.psess.gated_spans.gate(sym::gen_blocks, span);
3094            }
3095            Some(CoroutineKind::Async { .. }) | None => {}
3096        }
3097
3098        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) {
3099            // It is possible for `expect_one_of` to recover given the contents of
3100            // `self.expected_token_types`, therefore, do not use `self.unexpected()` which doesn't
3101            // account for this.
3102            match self.expect_one_of(&[], &[]) {
3103                Ok(Recovered::Yes(_)) => {}
3104                Ok(Recovered::No) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3105                Err(mut err) => {
3106                    // Qualifier keywords ordering check
3107                    enum WrongKw {
3108                        Duplicated(Span),
3109                        Misplaced(Span),
3110                        /// `MisplacedDisallowedQualifier` is only used instead of `Misplaced`,
3111                        /// when the misplaced keyword is disallowed by the current `FrontMatterParsingMode`.
3112                        /// In this case, we avoid generating the suggestion to swap around the keywords,
3113                        /// as we already generated a suggestion to remove the keyword earlier.
3114                        MisplacedDisallowedQualifier,
3115                    }
3116
3117                    // We may be able to recover
3118                    let mut recover_constness = constness;
3119                    let mut recover_coroutine_kind = coroutine_kind;
3120                    let mut recover_safety = safety;
3121                    // This will allow the machine fix to directly place the keyword in the correct place or to indicate
3122                    // that the keyword is already present and the second instance should be removed.
3123                    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)) {
3124                        match constness {
3125                            Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
3126                            Const::No => {
3127                                recover_constness = Const::Yes(self.token.span);
3128                                match parsing_mode {
3129                                    FrontMatterParsingMode::Function => {
3130                                        Some(WrongKw::Misplaced(async_start_sp))
3131                                    }
3132                                    FrontMatterParsingMode::FunctionPtrType => {
3133                                        self.dcx().emit_err(FnPointerCannotBeConst {
3134                                            span: self.token.span,
3135                                            suggestion: self
3136                                                .token
3137                                                .span
3138                                                .with_lo(self.prev_token.span.hi()),
3139                                        });
3140                                        Some(WrongKw::MisplacedDisallowedQualifier)
3141                                    }
3142                                }
3143                            }
3144                        }
3145                    } 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)) {
3146                        match coroutine_kind {
3147                            Some(CoroutineKind::Async { span, .. }) => {
3148                                Some(WrongKw::Duplicated(span))
3149                            }
3150                            Some(CoroutineKind::AsyncGen { span, .. }) => {
3151                                Some(WrongKw::Duplicated(span))
3152                            }
3153                            Some(CoroutineKind::Gen { .. }) => {
3154                                recover_coroutine_kind = Some(CoroutineKind::AsyncGen {
3155                                    span: self.token.span,
3156                                    closure_id: DUMMY_NODE_ID,
3157                                    return_impl_trait_id: DUMMY_NODE_ID,
3158                                });
3159                                // FIXME(gen_blocks): This span is wrong, didn't want to think about it.
3160                                Some(WrongKw::Misplaced(unsafe_start_sp))
3161                            }
3162                            None => {
3163                                recover_coroutine_kind = Some(CoroutineKind::Async {
3164                                    span: self.token.span,
3165                                    closure_id: DUMMY_NODE_ID,
3166                                    return_impl_trait_id: DUMMY_NODE_ID,
3167                                });
3168                                match parsing_mode {
3169                                    FrontMatterParsingMode::Function => {
3170                                        Some(WrongKw::Misplaced(async_start_sp))
3171                                    }
3172                                    FrontMatterParsingMode::FunctionPtrType => {
3173                                        self.dcx().emit_err(FnPointerCannotBeAsync {
3174                                            span: self.token.span,
3175                                            suggestion: self
3176                                                .token
3177                                                .span
3178                                                .with_lo(self.prev_token.span.hi()),
3179                                        });
3180                                        Some(WrongKw::MisplacedDisallowedQualifier)
3181                                    }
3182                                }
3183                            }
3184                        }
3185                    } 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)) {
3186                        match safety {
3187                            Safety::Unsafe(sp) => Some(WrongKw::Duplicated(sp)),
3188                            Safety::Safe(sp) => {
3189                                recover_safety = Safety::Unsafe(self.token.span);
3190                                Some(WrongKw::Misplaced(sp))
3191                            }
3192                            Safety::Default => {
3193                                recover_safety = Safety::Unsafe(self.token.span);
3194                                Some(WrongKw::Misplaced(ext_start_sp))
3195                            }
3196                        }
3197                    } 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)) {
3198                        match safety {
3199                            Safety::Safe(sp) => Some(WrongKw::Duplicated(sp)),
3200                            Safety::Unsafe(sp) => {
3201                                recover_safety = Safety::Safe(self.token.span);
3202                                Some(WrongKw::Misplaced(sp))
3203                            }
3204                            Safety::Default => {
3205                                recover_safety = Safety::Safe(self.token.span);
3206                                Some(WrongKw::Misplaced(ext_start_sp))
3207                            }
3208                        }
3209                    } else {
3210                        None
3211                    };
3212
3213                    // The keyword is already present, suggest removal of the second instance
3214                    if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
3215                        let original_kw = self
3216                            .span_to_snippet(original_sp)
3217                            .expect("Span extracted directly from keyword should always work");
3218
3219                        err.span_suggestion(
3220                            self.token_uninterpolated_span(),
3221                            ::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"),
3222                            "",
3223                            Applicability::MachineApplicable,
3224                        )
3225                        .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"));
3226                    }
3227                    // The keyword has not been seen yet, suggest correct placement in the function front matter
3228                    else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
3229                        let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
3230                        if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
3231                            let misplaced_qual_sp = self.token_uninterpolated_span();
3232                            let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
3233
3234                            err.span_suggestion(
3235                                    correct_pos_sp.to(misplaced_qual_sp),
3236                                    ::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}`"),
3237                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", misplaced_qual,
                current_qual))
    })format!("{misplaced_qual} {current_qual}"),
3238                                    Applicability::MachineApplicable,
3239                                ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
3240                        }
3241                    }
3242                    // Recover incorrect visibility order such as `async pub`
3243                    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)) {
3244                        let sp = sp_start.to(self.prev_token.span);
3245                        if let Ok(snippet) = self.span_to_snippet(sp) {
3246                            let current_vis = match self.parse_visibility(FollowedByType::No) {
3247                                Ok(v) => v,
3248                                Err(d) => {
3249                                    d.cancel();
3250                                    return Err(err);
3251                                }
3252                            };
3253                            let vs = pprust::vis_to_string(&current_vis);
3254                            let vs = vs.trim_end();
3255
3256                            // There was no explicit visibility
3257                            if #[allow(non_exhaustive_omitted_patterns)] match orig_vis.kind {
    VisibilityKind::Inherited => true,
    _ => false,
}matches!(orig_vis.kind, VisibilityKind::Inherited) {
3258                                err.span_suggestion(
3259                                    sp_start.to(self.prev_token.span),
3260                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("visibility `{0}` must come before `{1}`",
                vs, snippet))
    })format!("visibility `{vs}` must come before `{snippet}`"),
3261                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", vs, snippet))
    })format!("{vs} {snippet}"),
3262                                    Applicability::MachineApplicable,
3263                                );
3264                            }
3265                            // There was an explicit visibility
3266                            else {
3267                                err.span_suggestion(
3268                                    current_vis.span,
3269                                    "there is already a visibility modifier, remove one",
3270                                    "",
3271                                    Applicability::MachineApplicable,
3272                                )
3273                                .span_note(orig_vis.span, "explicit visibility first seen here");
3274                            }
3275                        }
3276                    }
3277
3278                    // FIXME(gen_blocks): add keyword recovery logic for genness
3279
3280                    if let Some(wrong_kw) = wrong_kw
3281                        && self.may_recover()
3282                        && self.look_ahead(1, |tok| tok.is_keyword_case(kw::Fn, case))
3283                    {
3284                        // Advance past the misplaced keyword and `fn`
3285                        self.bump();
3286                        self.bump();
3287                        // When we recover from a `MisplacedDisallowedQualifier`, we already emitted an error for the disallowed qualifier
3288                        // So we don't emit another error that the qualifier is unexpected.
3289                        if #[allow(non_exhaustive_omitted_patterns)] match wrong_kw {
    WrongKw::MisplacedDisallowedQualifier => true,
    _ => false,
}matches!(wrong_kw, WrongKw::MisplacedDisallowedQualifier) {
3290                            err.cancel();
3291                        } else {
3292                            err.emit();
3293                        }
3294                        return Ok(FnHeader {
3295                            constness: recover_constness,
3296                            safety: recover_safety,
3297                            coroutine_kind: recover_coroutine_kind,
3298                            ext,
3299                        });
3300                    }
3301
3302                    return Err(err);
3303                }
3304            }
3305        }
3306
3307        Ok(FnHeader { constness, safety, coroutine_kind, ext })
3308    }
3309
3310    /// Parses the parameter list and result type of a function declaration.
3311    pub(super) fn parse_fn_decl(
3312        &mut self,
3313        fn_parse_mode: &FnParseMode,
3314        ret_allow_plus: AllowPlus,
3315        recover_return_sign: RecoverReturnSign,
3316    ) -> PResult<'a, Box<FnDecl>> {
3317        Ok(Box::new(FnDecl {
3318            inputs: self.parse_fn_params(fn_parse_mode)?,
3319            output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
3320        }))
3321    }
3322
3323    /// Parses the parameter list of a function, including the `(` and `)` delimiters.
3324    pub(super) fn parse_fn_params(
3325        &mut self,
3326        fn_parse_mode: &FnParseMode,
3327    ) -> PResult<'a, ThinVec<Param>> {
3328        let mut first_param = true;
3329        // Parse the arguments, starting out with `self` being allowed...
3330        if self.token != TokenKind::OpenParen
3331        // might be typo'd trait impl, handled elsewhere
3332        && !self.token.is_keyword(kw::For)
3333        {
3334            // recover from missing argument list, e.g. `fn main -> () {}`
3335            self.dcx()
3336                .emit_err(errors::MissingFnParams { span: self.prev_token.span.shrink_to_hi() });
3337            return Ok(ThinVec::new());
3338        }
3339
3340        let (mut params, _) = self.parse_paren_comma_seq(|p| {
3341            p.recover_vcs_conflict_marker();
3342            let snapshot = p.create_snapshot_for_diagnostic();
3343            let param = p.parse_param_general(fn_parse_mode, first_param, true).or_else(|e| {
3344                let guar = e.emit();
3345                // When parsing a param failed, we should check to make the span of the param
3346                // not contain '(' before it.
3347                // For example when parsing `*mut Self` in function `fn oof(*mut Self)`.
3348                let lo = if let TokenKind::OpenParen = p.prev_token.kind {
3349                    p.prev_token.span.shrink_to_hi()
3350                } else {
3351                    p.prev_token.span
3352                };
3353                p.restore_snapshot(snapshot);
3354                // Skip every token until next possible arg or end.
3355                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)]);
3356                // Create a placeholder argument for proper arg count (issue #34264).
3357                Ok(dummy_arg(Ident::new(sym::dummy, lo.to(p.prev_token.span)), guar))
3358            });
3359            // ...now that we've parsed the first argument, `self` is no longer allowed.
3360            first_param = false;
3361            param
3362        })?;
3363        // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
3364        self.deduplicate_recovered_params_names(&mut params);
3365        Ok(params)
3366    }
3367
3368    /// Parses a single function parameter.
3369    ///
3370    /// - `self` is syntactically allowed when `first_param` holds.
3371    /// - `recover_arg_parse` is used to recover from a failed argument parse.
3372    pub(super) fn parse_param_general(
3373        &mut self,
3374        fn_parse_mode: &FnParseMode,
3375        first_param: bool,
3376        recover_arg_parse: bool,
3377    ) -> PResult<'a, Param> {
3378        let lo = self.token.span;
3379        let attrs = self.parse_outer_attributes()?;
3380        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3381            // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
3382            if let Some(mut param) = this.parse_self_param()? {
3383                param.attrs = attrs;
3384                let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
3385                return Ok((res?, Trailing::No, UsePreAttrPos::No));
3386            }
3387
3388            let is_dot_dot_dot = if this.token.kind == token::DotDotDot {
3389                IsDotDotDot::Yes
3390            } else {
3391                IsDotDotDot::No
3392            };
3393            let is_name_required = (fn_parse_mode.req_name)(
3394                this.token.span.with_neighbor(this.prev_token.span).edition(),
3395                is_dot_dot_dot,
3396            );
3397            let is_name_required = if is_name_required && is_dot_dot_dot == IsDotDotDot::Yes {
3398                this.psess.buffer_lint(
3399                    VARARGS_WITHOUT_PATTERN,
3400                    this.token.span,
3401                    ast::CRATE_NODE_ID,
3402                    errors::VarargsWithoutPattern { span: this.token.span },
3403                );
3404                false
3405            } else {
3406                is_name_required
3407            };
3408            let (pat, ty) = if is_name_required || this.is_named_param() {
3409                {
    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:3409",
                        "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(3409u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("parse_param_general parse_pat (is_name_required:{0})",
                                                    is_name_required) as &dyn Value))])
            });
    } else { ; }
};debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
3410                let (pat, colon) = this.parse_fn_param_pat_colon()?;
3411                if !colon {
3412                    let mut err = this.unexpected().unwrap_err();
3413                    return if let Some(ident) = this.parameter_without_type(
3414                        &mut err,
3415                        pat,
3416                        is_name_required,
3417                        first_param,
3418                        fn_parse_mode,
3419                    ) {
3420                        let guar = err.emit();
3421                        Ok((dummy_arg(ident, guar), Trailing::No, UsePreAttrPos::No))
3422                    } else {
3423                        Err(err)
3424                    };
3425                }
3426
3427                this.eat_incorrect_doc_comment_for_param_type();
3428                (pat, this.parse_ty_for_param()?)
3429            } else {
3430                {
    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:3430",
                        "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(3430u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("parse_param_general ident_to_pat")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("parse_param_general ident_to_pat");
3431                let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
3432                this.eat_incorrect_doc_comment_for_param_type();
3433                let mut ty = this.parse_ty_for_param();
3434
3435                if let Ok(t) = &ty {
3436                    // Check for trailing angle brackets
3437                    if let TyKind::Path(_, Path { segments, .. }) = &t.kind
3438                        && let Some(segment) = segments.last()
3439                        && let Some(guar) =
3440                            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)])
3441                    {
3442                        return Ok((
3443                            dummy_arg(segment.ident, guar),
3444                            Trailing::No,
3445                            UsePreAttrPos::No,
3446                        ));
3447                    }
3448
3449                    if this.token != token::Comma && this.token != token::CloseParen {
3450                        // This wasn't actually a type, but a pattern looking like a type,
3451                        // so we are going to rollback and re-parse for recovery.
3452                        ty = this.unexpected_any();
3453                    }
3454                }
3455                match ty {
3456                    Ok(ty) => {
3457                        let pat = this.mk_pat(ty.span, PatKind::Missing);
3458                        (Box::new(pat), ty)
3459                    }
3460                    // If this is a C-variadic argument and we hit an error, return the error.
3461                    Err(err) if this.token == token::DotDotDot => return Err(err),
3462                    Err(err) if this.unmatched_angle_bracket_count > 0 => return Err(err),
3463                    Err(err) if recover_arg_parse => {
3464                        // Recover from attempting to parse the argument as a type without pattern.
3465                        err.cancel();
3466                        this.restore_snapshot(parser_snapshot_before_ty);
3467                        this.recover_arg_parse()?
3468                    }
3469                    Err(err) => return Err(err),
3470                }
3471            };
3472
3473            let span = lo.to(this.prev_token.span);
3474
3475            Ok((
3476                Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
3477                Trailing::No,
3478                UsePreAttrPos::No,
3479            ))
3480        })
3481    }
3482
3483    /// Returns the parsed optional self parameter and whether a self shortcut was used.
3484    fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
3485        // Extract an identifier *after* having confirmed that the token is one.
3486        let expect_self_ident = |this: &mut Self| match this.token.ident() {
3487            Some((ident, IdentIsRaw::No)) => {
3488                this.bump();
3489                ident
3490            }
3491            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3492        };
3493        // is lifetime `n` tokens ahead?
3494        let is_lifetime = |this: &Self, n| this.look_ahead(n, |t| t.is_lifetime());
3495        // Is `self` `n` tokens ahead?
3496        let is_isolated_self = |this: &Self, n| {
3497            this.is_keyword_ahead(n, &[kw::SelfLower])
3498                && this.look_ahead(n + 1, |t| t != &token::PathSep)
3499        };
3500        // Is `pin const self` `n` tokens ahead?
3501        let is_isolated_pin_const_self = |this: &Self, n| {
3502            this.look_ahead(n, |token| token.is_ident_named(sym::pin))
3503                && this.is_keyword_ahead(n + 1, &[kw::Const])
3504                && is_isolated_self(this, n + 2)
3505        };
3506        // Is `mut self` `n` tokens ahead?
3507        let is_isolated_mut_self =
3508            |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
3509        // Is `pin mut self` `n` tokens ahead?
3510        let is_isolated_pin_mut_self = |this: &Self, n| {
3511            this.look_ahead(n, |token| token.is_ident_named(sym::pin))
3512                && is_isolated_mut_self(this, n + 1)
3513        };
3514        // Parse `self` or `self: TYPE`. We already know the current token is `self`.
3515        let parse_self_possibly_typed = |this: &mut Self, m| {
3516            let eself_ident = expect_self_ident(this);
3517            let eself_hi = this.prev_token.span;
3518            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)) {
3519                SelfKind::Explicit(this.parse_ty()?, m)
3520            } else {
3521                SelfKind::Value(m)
3522            };
3523            Ok((eself, eself_ident, eself_hi))
3524        };
3525        let expect_self_ident_not_typed =
3526            |this: &mut Self, modifier: &SelfKind, modifier_span: Span| {
3527                let eself_ident = expect_self_ident(this);
3528
3529                // Recover `: Type` after a qualified self
3530                if this.may_recover() && this.eat_noexpect(&token::Colon) {
3531                    let snap = this.create_snapshot_for_diagnostic();
3532                    match this.parse_ty() {
3533                        Ok(ty) => {
3534                            this.dcx().emit_err(errors::IncorrectTypeOnSelf {
3535                                span: ty.span,
3536                                move_self_modifier: errors::MoveSelfModifier {
3537                                    removal_span: modifier_span,
3538                                    insertion_span: ty.span.shrink_to_lo(),
3539                                    modifier: modifier.to_ref_suggestion(),
3540                                },
3541                            });
3542                        }
3543                        Err(diag) => {
3544                            diag.cancel();
3545                            this.restore_snapshot(snap);
3546                        }
3547                    }
3548                }
3549                eself_ident
3550            };
3551        // Recover for the grammar `*self`, `*const self`, and `*mut self`.
3552        let recover_self_ptr = |this: &mut Self| {
3553            this.dcx().emit_err(errors::SelfArgumentPointer { span: this.token.span });
3554
3555            Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
3556        };
3557
3558        // Parse optional `self` parameter of a method.
3559        // Only a limited set of initial token sequences is considered `self` parameters; anything
3560        // else is parsed as a normal function parameter list, so some lookahead is required.
3561        let eself_lo = self.token.span;
3562        let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
3563            token::And => {
3564                let has_lifetime = is_lifetime(self, 1);
3565                let skip_lifetime_count = has_lifetime as usize;
3566                let eself = if is_isolated_self(self, skip_lifetime_count + 1) {
3567                    // `&{'lt} self`
3568                    self.bump(); // &
3569                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3570                    SelfKind::Region(lifetime, Mutability::Not)
3571                } else if is_isolated_mut_self(self, skip_lifetime_count + 1) {
3572                    // `&{'lt} mut self`
3573                    self.bump(); // &
3574                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3575                    self.bump(); // mut
3576                    SelfKind::Region(lifetime, Mutability::Mut)
3577                } else if is_isolated_pin_const_self(self, skip_lifetime_count + 1) {
3578                    // `&{'lt} pin const self`
3579                    self.bump(); // &
3580                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3581                    self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
3582                    self.bump(); // pin
3583                    self.bump(); // const
3584                    SelfKind::Pinned(lifetime, Mutability::Not)
3585                } else if is_isolated_pin_mut_self(self, skip_lifetime_count + 1) {
3586                    // `&{'lt} pin mut self`
3587                    self.bump(); // &
3588                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3589                    self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
3590                    self.bump(); // pin
3591                    self.bump(); // mut
3592                    SelfKind::Pinned(lifetime, Mutability::Mut)
3593                } else {
3594                    // `&not_self`
3595                    return Ok(None);
3596                };
3597                let hi = self.token.span;
3598                let self_ident = expect_self_ident_not_typed(self, &eself, eself_lo.until(hi));
3599                (eself, self_ident, hi)
3600            }
3601            // `*self`
3602            token::Star if is_isolated_self(self, 1) => {
3603                self.bump();
3604                recover_self_ptr(self)?
3605            }
3606            // `*mut self` and `*const self`
3607            token::Star
3608                if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
3609            {
3610                self.bump();
3611                self.bump();
3612                recover_self_ptr(self)?
3613            }
3614            // `self` and `self: TYPE`
3615            token::Ident(..) if is_isolated_self(self, 0) => {
3616                parse_self_possibly_typed(self, Mutability::Not)?
3617            }
3618            // `mut self` and `mut self: TYPE`
3619            token::Ident(..) if is_isolated_mut_self(self, 0) => {
3620                self.bump();
3621                parse_self_possibly_typed(self, Mutability::Mut)?
3622            }
3623            _ => return Ok(None),
3624        };
3625
3626        let eself = respan(eself_lo.to(eself_hi), eself);
3627        Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
3628    }
3629
3630    fn is_named_param(&self) -> bool {
3631        let offset = match &self.token.kind {
3632            token::OpenInvisible(origin) => match origin {
3633                InvisibleOrigin::MetaVar(MetaVarKind::Pat(_)) => {
3634                    return self.check_noexpect_past_close_delim(&token::Colon);
3635                }
3636                _ => 0,
3637            },
3638            token::And | token::AndAnd => 1,
3639            _ if self.token.is_keyword(kw::Mut) => 1,
3640            _ => 0,
3641        };
3642
3643        self.look_ahead(offset, |t| t.is_ident())
3644            && self.look_ahead(offset + 1, |t| t == &token::Colon)
3645    }
3646
3647    fn recover_self_param(&mut self) -> bool {
3648        #[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!(
3649            self.parse_outer_attributes()
3650                .and_then(|_| self.parse_self_param())
3651                .map_err(|e| e.cancel()),
3652            Ok(Some(_))
3653        )
3654    }
3655
3656    /// Try to recover from over-parsing in const item when a semicolon is missing.
3657    ///
3658    /// This detects cases where we parsed too much because a semicolon was missing
3659    /// and the next line started an expression that the parser treated as a continuation
3660    /// (e.g., `foo() \n &bar` was parsed as `foo() & bar`).
3661    ///
3662    /// Returns a corrected expression if recovery is successful.
3663    fn try_recover_const_missing_semi(
3664        &mut self,
3665        rhs: &ConstItemRhsKind,
3666        const_span: Span,
3667    ) -> Option<Box<Expr>> {
3668        if self.token == TokenKind::Semi {
3669            return None;
3670        }
3671        let ConstItemRhsKind::Body { rhs: Some(rhs) } = rhs else {
3672            return None;
3673        };
3674        if !self.in_fn_body || !self.may_recover() || rhs.span.from_expansion() {
3675            return None;
3676        }
3677        if let Some((span, guar)) =
3678            self.missing_semi_from_binop("const", rhs, Some(const_span.shrink_to_lo()))
3679        {
3680            self.fn_body_missing_semi_guar = Some(guar);
3681            Some(self.mk_expr(span, ExprKind::Err(guar)))
3682        } else {
3683            None
3684        }
3685    }
3686}
3687
3688enum IsMacroRulesItem {
3689    Yes { has_bang: bool },
3690    No,
3691}
3692
3693#[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)]
3694pub(super) enum FrontMatterParsingMode {
3695    /// Parse the front matter of a function declaration
3696    Function,
3697    /// Parse the front matter of a function pointet type.
3698    /// For function pointer types, the `const` and `async` keywords are not permitted.
3699    FunctionPtrType,
3700}