Skip to main content

rustc_parse/parser/
item.rs

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