Skip to main content

rustc_parse/parser/
item.rs

1use std::fmt::Write;
2use std::mem;
3
4use ast::token::IdentIsRaw;
5use rustc_ast as ast;
6use rustc_ast::ast::*;
7use rustc_ast::token::{self, Delimiter, InvisibleOrigin, MetaVarKind, TokenKind};
8use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
9use rustc_ast::util::case::Case;
10use rustc_ast_pretty::pprust;
11use rustc_errors::codes::*;
12use rustc_errors::{Applicability, PResult, StashKey, msg, struct_span_code_err};
13use rustc_session::lint::builtin::VARARGS_WITHOUT_PATTERN;
14use rustc_span::edit_distance::edit_distance;
15use rustc_span::edition::Edition;
16use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, kw, 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, const_span)?;
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, const_span)?;
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        const_span: Span,
1562    ) -> PResult<'a, (Ident, Generics, Box<Ty>, ConstItemRhsKind)> {
1563        let ident = self.parse_ident_or_underscore()?;
1564
1565        let mut generics = self.parse_generics()?;
1566
1567        // Check the span for emptiness instead of the list of parameters in order to correctly
1568        // recognize and subsequently flag empty parameter lists (`<>`) as unstable.
1569        if !generics.span.is_empty() {
1570            self.psess.gated_spans.gate(sym::generic_const_items, generics.span);
1571        }
1572
1573        // Parse the type of a constant item. That is, the `":" $ty` fragment.
1574        // FIXME: This could maybe benefit from `.may_recover()`?
1575        let ty = match (
1576            self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)),
1577            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)),
1578        ) {
1579            (true, false) => self.parse_ty()?,
1580            // If there wasn't a `:` or the colon was followed by a `=`, `;` or `where`, recover a missing type.
1581            (colon, _) => self.recover_missing_global_item_type(colon, None),
1582        };
1583
1584        // Proactively parse a where-clause to be able to provide a good error message in case we
1585        // encounter the item body following it.
1586        let before_where_clause =
1587            if self.may_recover() { self.parse_where_clause()? } else { WhereClause::default() };
1588
1589        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) {
1590            (true, true) => ConstItemRhsKind::TypeConst {
1591                rhs: Some(self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct)?),
1592            },
1593            (true, false) => ConstItemRhsKind::Body { rhs: Some(self.parse_expr()?) },
1594            (false, true) => ConstItemRhsKind::TypeConst { rhs: None },
1595            (false, false) => ConstItemRhsKind::Body { rhs: None },
1596        };
1597
1598        let after_where_clause = self.parse_where_clause()?;
1599
1600        // Provide a nice error message if the user placed a where-clause before the item body.
1601        // Users may be tempted to write such code if they are still used to the deprecated
1602        // where-clause location on type aliases and associated types. See also #89122.
1603        if before_where_clause.has_where_token
1604            && let Some(rhs_span) = rhs.span()
1605        {
1606            self.dcx().emit_err(errors::WhereClauseBeforeConstBody {
1607                span: before_where_clause.span,
1608                name: ident.span,
1609                body: rhs_span,
1610                sugg: if !after_where_clause.has_where_token {
1611                    self.psess.source_map().span_to_snippet(rhs_span).ok().map(|body_s| {
1612                        errors::WhereClauseBeforeConstBodySugg {
1613                            left: before_where_clause.span.shrink_to_lo(),
1614                            snippet: body_s,
1615                            right: before_where_clause.span.shrink_to_hi().to(rhs_span),
1616                        }
1617                    })
1618                } else {
1619                    // FIXME(generic_const_items): Provide a structured suggestion to merge the first
1620                    // where-clause into the second one.
1621                    None
1622                },
1623            });
1624        }
1625
1626        // Merge the predicates of both where-clauses since either one can be relevant.
1627        // If we didn't parse a body (which is valid for associated consts in traits) and we were
1628        // allowed to recover, `before_where_clause` contains the predicates, otherwise they are
1629        // in `after_where_clause`. Further, both of them might contain predicates iff two
1630        // where-clauses were provided which is syntactically ill-formed but we want to recover from
1631        // it and treat them as one large where-clause.
1632        let mut predicates = before_where_clause.predicates;
1633        predicates.extend(after_where_clause.predicates);
1634        let where_clause = WhereClause {
1635            has_where_token: before_where_clause.has_where_token
1636                || after_where_clause.has_where_token,
1637            predicates,
1638            span: if after_where_clause.has_where_token {
1639                after_where_clause.span
1640            } else {
1641                before_where_clause.span
1642            },
1643        };
1644
1645        if where_clause.has_where_token {
1646            self.psess.gated_spans.gate(sym::generic_const_items, where_clause.span);
1647        }
1648
1649        generics.where_clause = where_clause;
1650
1651        if let Some(rhs) = self.try_recover_const_missing_semi(&rhs, const_span) {
1652            return Ok((ident, generics, ty, ConstItemRhsKind::Body { rhs: Some(rhs) }));
1653        }
1654        self.expect_semi()?;
1655
1656        Ok((ident, generics, ty, rhs))
1657    }
1658
1659    /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1660    /// This means that the type is missing.
1661    fn recover_missing_global_item_type(
1662        &mut self,
1663        colon_present: bool,
1664        m: Option<Mutability>,
1665    ) -> Box<Ty> {
1666        // Construct the error and stash it away with the hope
1667        // that typeck will later enrich the error with a type.
1668        let kind = match m {
1669            Some(Mutability::Mut) => "static mut",
1670            Some(Mutability::Not) => "static",
1671            None => "const",
1672        };
1673
1674        let colon = match colon_present {
1675            true => "",
1676            false => ":",
1677        };
1678
1679        let span = self.prev_token.span.shrink_to_hi();
1680        let err = self.dcx().create_err(errors::MissingConstType { span, colon, kind });
1681        err.stash(span, StashKey::ItemNoType);
1682
1683        // The user intended that the type be inferred,
1684        // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1685        Box::new(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1686    }
1687
1688    /// Parses an enum declaration.
1689    fn parse_item_enum(&mut self) -> PResult<'a, ItemKind> {
1690        if self.token.is_keyword(kw::Struct) {
1691            let span = self.prev_token.span.to(self.token.span);
1692            let err = errors::EnumStructMutuallyExclusive { span };
1693            if self.look_ahead(1, |t| t.is_ident()) {
1694                self.bump();
1695                self.dcx().emit_err(err);
1696            } else {
1697                return Err(self.dcx().create_err(err));
1698            }
1699        }
1700
1701        let prev_span = self.prev_token.span;
1702        let ident = self.parse_ident()?;
1703        let mut generics = self.parse_generics()?;
1704        generics.where_clause = self.parse_where_clause()?;
1705
1706        // Possibly recover `enum Foo;` instead of `enum Foo {}`
1707        let (variants, _) = if self.token == TokenKind::Semi {
1708            self.dcx().emit_err(errors::UseEmptyBlockNotSemi { span: self.token.span });
1709            self.bump();
1710            (::thin_vec::ThinVec::new()thin_vec![], Trailing::No)
1711        } else {
1712            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| {
1713                p.parse_enum_variant(ident.span)
1714            })
1715            .map_err(|mut err| {
1716                err.span_label(ident.span, "while parsing this enum");
1717                // Try to recover `enum Foo { ident : Ty }`.
1718                if self.prev_token.is_non_reserved_ident() && self.token == token::Colon {
1719                    let snapshot = self.create_snapshot_for_diagnostic();
1720                    self.bump();
1721                    match self.parse_ty() {
1722                        Ok(_) => {
1723                            err.span_suggestion_verbose(
1724                                prev_span,
1725                                "perhaps you meant to use `struct` here",
1726                                "struct",
1727                                Applicability::MaybeIncorrect,
1728                            );
1729                        }
1730                        Err(e) => {
1731                            e.cancel();
1732                        }
1733                    }
1734                    self.restore_snapshot(snapshot);
1735                }
1736                self.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1737                self.bump(); // }
1738                err
1739            })?
1740        };
1741
1742        let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1743        Ok(ItemKind::Enum(ident, generics, enum_definition))
1744    }
1745
1746    fn parse_enum_variant(&mut self, span: Span) -> PResult<'a, Option<Variant>> {
1747        self.recover_vcs_conflict_marker();
1748        let variant_attrs = self.parse_outer_attributes()?;
1749        self.recover_vcs_conflict_marker();
1750        let help = "enum variants can be `Variant`, `Variant = <integer>`, \
1751                    `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`";
1752        self.collect_tokens(None, variant_attrs, ForceCollect::No, |this, variant_attrs| {
1753            let vlo = this.token.span;
1754
1755            let vis = this.parse_visibility(FollowedByType::No)?;
1756            if !this.recover_nested_adt_item(kw::Enum)? {
1757                return Ok((None, Trailing::No, UsePreAttrPos::No));
1758            }
1759            let ident = this.parse_field_ident("enum", vlo)?;
1760
1761            if this.token == token::Bang {
1762                if let Err(err) = this.unexpected() {
1763                    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();
1764                }
1765
1766                this.bump();
1767                this.parse_delim_args()?;
1768
1769                return Ok((None, Trailing::from(this.token == token::Comma), UsePreAttrPos::No));
1770            }
1771
1772            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)) {
1773                // Parse a struct variant.
1774                let (fields, recovered) =
1775                    match this.parse_record_struct_body("struct", ident.span, false) {
1776                        Ok((fields, recovered)) => (fields, recovered),
1777                        Err(mut err) => {
1778                            if this.token == token::Colon {
1779                                // We handle `enum` to `struct` suggestion in the caller.
1780                                return Err(err);
1781                            }
1782                            this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]);
1783                            this.bump(); // }
1784                            err.span_label(span, "while parsing this enum");
1785                            err.help(help);
1786                            let guar = err.emit();
1787                            (::thin_vec::ThinVec::new()thin_vec![], Recovered::Yes(guar))
1788                        }
1789                    };
1790                VariantData::Struct { fields, recovered }
1791            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1792                let body = match this.parse_tuple_struct_body() {
1793                    Ok(body) => body,
1794                    Err(mut err) => {
1795                        if this.token == token::Colon {
1796                            // We handle `enum` to `struct` suggestion in the caller.
1797                            return Err(err);
1798                        }
1799                        this.eat_to_tokens(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]);
1800                        this.bump(); // )
1801                        err.span_label(span, "while parsing this enum");
1802                        err.help(help);
1803                        err.emit();
1804                        ::thin_vec::ThinVec::new()thin_vec![]
1805                    }
1806                };
1807                VariantData::Tuple(body, DUMMY_NODE_ID)
1808            } else {
1809                VariantData::Unit(DUMMY_NODE_ID)
1810            };
1811
1812            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)) {
1813                Some(this.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst)?)
1814            } else {
1815                None
1816            };
1817
1818            let vr = ast::Variant {
1819                ident,
1820                vis,
1821                id: DUMMY_NODE_ID,
1822                attrs: variant_attrs,
1823                data: struct_def,
1824                disr_expr,
1825                span: vlo.to(this.prev_token.span),
1826                is_placeholder: false,
1827            };
1828
1829            Ok((Some(vr), Trailing::from(this.token == token::Comma), UsePreAttrPos::No))
1830        })
1831        .map_err(|mut err| {
1832            err.help(help);
1833            err
1834        })
1835    }
1836
1837    /// Parses `struct Foo { ... }`.
1838    fn parse_item_struct(&mut self) -> PResult<'a, ItemKind> {
1839        let ident = self.parse_ident()?;
1840
1841        let mut generics = self.parse_generics()?;
1842
1843        // There is a special case worth noting here, as reported in issue #17904.
1844        // If we are parsing a tuple struct it is the case that the where clause
1845        // should follow the field list. Like so:
1846        //
1847        // struct Foo<T>(T) where T: Copy;
1848        //
1849        // If we are parsing a normal record-style struct it is the case
1850        // that the where clause comes before the body, and after the generics.
1851        // So if we look ahead and see a brace or a where-clause we begin
1852        // parsing a record style struct.
1853        //
1854        // Otherwise if we look ahead and see a paren we parse a tuple-style
1855        // struct.
1856
1857        let vdata = if self.token.is_keyword(kw::Where) {
1858            let tuple_struct_body;
1859            (generics.where_clause, tuple_struct_body) =
1860                self.parse_struct_where_clause(ident, generics.span)?;
1861
1862            if let Some(body) = tuple_struct_body {
1863                // If we see a misplaced tuple struct body: `struct Foo<T> where T: Copy, (T);`
1864                let body = VariantData::Tuple(body, DUMMY_NODE_ID);
1865                self.expect_semi()?;
1866                body
1867            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1868                // If we see a: `struct Foo<T> where T: Copy;` style decl.
1869                VariantData::Unit(DUMMY_NODE_ID)
1870            } else {
1871                // If we see: `struct Foo<T> where T: Copy { ... }`
1872                let (fields, recovered) = self.parse_record_struct_body(
1873                    "struct",
1874                    ident.span,
1875                    generics.where_clause.has_where_token,
1876                )?;
1877                VariantData::Struct { fields, recovered }
1878            }
1879        // No `where` so: `struct Foo<T>;`
1880        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1881            VariantData::Unit(DUMMY_NODE_ID)
1882        // Record-style struct definition
1883        } else if self.token == token::OpenBrace {
1884            let (fields, recovered) = self.parse_record_struct_body(
1885                "struct",
1886                ident.span,
1887                generics.where_clause.has_where_token,
1888            )?;
1889            VariantData::Struct { fields, recovered }
1890        // Tuple-style struct definition with optional where-clause.
1891        } else if self.token == token::OpenParen {
1892            let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1893            generics.where_clause = self.parse_where_clause()?;
1894            self.expect_semi()?;
1895            body
1896        } else {
1897            let err = errors::UnexpectedTokenAfterStructName::new(self.token.span, self.token);
1898            return Err(self.dcx().create_err(err));
1899        };
1900
1901        Ok(ItemKind::Struct(ident, generics, vdata))
1902    }
1903
1904    /// Parses `union Foo { ... }`.
1905    fn parse_item_union(&mut self) -> PResult<'a, ItemKind> {
1906        let ident = self.parse_ident()?;
1907
1908        let mut generics = self.parse_generics()?;
1909
1910        let vdata = if self.token.is_keyword(kw::Where) {
1911            generics.where_clause = self.parse_where_clause()?;
1912            let (fields, recovered) = self.parse_record_struct_body(
1913                "union",
1914                ident.span,
1915                generics.where_clause.has_where_token,
1916            )?;
1917            VariantData::Struct { fields, recovered }
1918        } else if self.token == token::OpenBrace {
1919            let (fields, recovered) = self.parse_record_struct_body(
1920                "union",
1921                ident.span,
1922                generics.where_clause.has_where_token,
1923            )?;
1924            VariantData::Struct { fields, recovered }
1925        } else {
1926            let token_str = super::token_descr(&self.token);
1927            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}");
1928            let mut err = self.dcx().struct_span_err(self.token.span, msg);
1929            err.span_label(self.token.span, "expected `where` or `{` after union name");
1930            return Err(err);
1931        };
1932
1933        Ok(ItemKind::Union(ident, generics, vdata))
1934    }
1935
1936    /// This function parses the fields of record structs:
1937    ///
1938    ///   - `struct S { ... }`
1939    ///   - `enum E { Variant { ... } }`
1940    pub(crate) fn parse_record_struct_body(
1941        &mut self,
1942        adt_ty: &str,
1943        ident_span: Span,
1944        parsed_where: bool,
1945    ) -> PResult<'a, (ThinVec<FieldDef>, Recovered)> {
1946        let mut fields = ThinVec::new();
1947        let mut recovered = Recovered::No;
1948        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
1949            while self.token != token::CloseBrace {
1950                match self.parse_field_def(adt_ty, ident_span) {
1951                    Ok(field) => {
1952                        fields.push(field);
1953                    }
1954                    Err(mut err) => {
1955                        self.consume_block(
1956                            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace),
1957                            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace),
1958                            ConsumeClosingDelim::No,
1959                        );
1960                        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}"));
1961                        let guar = err.emit();
1962                        recovered = Recovered::Yes(guar);
1963                        break;
1964                    }
1965                }
1966            }
1967            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
1968        } else {
1969            let token_str = super::token_descr(&self.token);
1970            let where_str = if parsed_where { "" } else { "`where`, or " };
1971            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}");
1972            let mut err = self.dcx().struct_span_err(self.token.span, msg);
1973            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",));
1974            return Err(err);
1975        }
1976
1977        Ok((fields, recovered))
1978    }
1979
1980    fn parse_unsafe_field(&mut self) -> Safety {
1981        // not using parse_safety as that also accepts `safe`.
1982        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)) {
1983            let span = self.prev_token.span;
1984            self.psess.gated_spans.gate(sym::unsafe_fields, span);
1985            Safety::Unsafe(span)
1986        } else {
1987            Safety::Default
1988        }
1989    }
1990
1991    pub(super) fn parse_tuple_struct_body(&mut self) -> PResult<'a, ThinVec<FieldDef>> {
1992        // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1993        // Unit like structs are handled in parse_item_struct function
1994        self.parse_paren_comma_seq(|p| {
1995            let attrs = p.parse_outer_attributes()?;
1996            p.collect_tokens(None, attrs, ForceCollect::No, |p, attrs| {
1997                let mut snapshot = None;
1998                if p.is_vcs_conflict_marker(&TokenKind::Shl, &TokenKind::Lt) {
1999                    // Account for `<<<<<<<` diff markers. We can't proactively error here because
2000                    // that can be a valid type start, so we snapshot and reparse only we've
2001                    // encountered another parse error.
2002                    snapshot = Some(p.create_snapshot_for_diagnostic());
2003                }
2004                let lo = p.token.span;
2005                let vis = match p.parse_visibility(FollowedByType::Yes) {
2006                    Ok(vis) => vis,
2007                    Err(err) => {
2008                        if let Some(ref mut snapshot) = snapshot {
2009                            snapshot.recover_vcs_conflict_marker();
2010                        }
2011                        return Err(err);
2012                    }
2013                };
2014                // Unsafe fields are not supported in tuple structs, as doing so would result in a
2015                // parsing ambiguity for `struct X(unsafe fn())`.
2016                let ty = match p.parse_ty() {
2017                    Ok(ty) => ty,
2018                    Err(err) => {
2019                        if let Some(ref mut snapshot) = snapshot {
2020                            snapshot.recover_vcs_conflict_marker();
2021                        }
2022                        return Err(err);
2023                    }
2024                };
2025                let mut default = None;
2026                if p.token == token::Eq {
2027                    let mut snapshot = p.create_snapshot_for_diagnostic();
2028                    snapshot.bump();
2029                    match snapshot.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst) {
2030                        Ok(const_expr) => {
2031                            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2032                            p.psess.gated_spans.gate(sym::default_field_values, sp);
2033                            p.restore_snapshot(snapshot);
2034                            default = Some(const_expr);
2035                        }
2036                        Err(err) => {
2037                            err.cancel();
2038                        }
2039                    }
2040                }
2041
2042                Ok((
2043                    FieldDef {
2044                        span: lo.to(ty.span),
2045                        vis,
2046                        safety: Safety::Default,
2047                        ident: None,
2048                        id: DUMMY_NODE_ID,
2049                        ty,
2050                        default,
2051                        attrs,
2052                        is_placeholder: false,
2053                    },
2054                    Trailing::from(p.token == token::Comma),
2055                    UsePreAttrPos::No,
2056                ))
2057            })
2058        })
2059        .map(|(r, _)| r)
2060    }
2061
2062    /// Parses an element of a struct declaration.
2063    fn parse_field_def(&mut self, adt_ty: &str, ident_span: Span) -> PResult<'a, FieldDef> {
2064        self.recover_vcs_conflict_marker();
2065        let attrs = self.parse_outer_attributes()?;
2066        self.recover_vcs_conflict_marker();
2067        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2068            let lo = this.token.span;
2069            let vis = this.parse_visibility(FollowedByType::No)?;
2070            let safety = this.parse_unsafe_field();
2071            this.parse_single_struct_field(adt_ty, lo, vis, safety, attrs, ident_span)
2072                .map(|field| (field, Trailing::No, UsePreAttrPos::No))
2073        })
2074    }
2075
2076    /// Parses a structure field declaration.
2077    fn parse_single_struct_field(
2078        &mut self,
2079        adt_ty: &str,
2080        lo: Span,
2081        vis: Visibility,
2082        safety: Safety,
2083        attrs: AttrVec,
2084        ident_span: Span,
2085    ) -> PResult<'a, FieldDef> {
2086        let a_var = self.parse_name_and_ty(adt_ty, lo, vis, safety, attrs)?;
2087        match self.token.kind {
2088            token::Comma => {
2089                self.bump();
2090            }
2091            token::Semi => {
2092                self.bump();
2093                let sp = self.prev_token.span;
2094                let mut err =
2095                    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 `,`"));
2096                err.span_suggestion_short(
2097                    sp,
2098                    "replace `;` with `,`",
2099                    ",",
2100                    Applicability::MachineApplicable,
2101                );
2102                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}"));
2103                err.emit();
2104            }
2105            token::CloseBrace => {}
2106            token::DocComment(..) => {
2107                let previous_span = self.prev_token.span;
2108                let mut err = errors::DocCommentDoesNotDocumentAnything {
2109                    span: self.token.span,
2110                    missing_comma: None,
2111                };
2112                self.bump(); // consume the doc comment
2113                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 {
2114                    self.dcx().emit_err(err);
2115                } else {
2116                    let sp = previous_span.shrink_to_hi();
2117                    err.missing_comma = Some(sp);
2118                    return Err(self.dcx().create_err(err));
2119                }
2120            }
2121            _ => {
2122                let sp = self.prev_token.span.shrink_to_hi();
2123                let msg =
2124                    ::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));
2125
2126                // Try to recover extra trailing angle brackets
2127                if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind
2128                    && let Some(last_segment) = segments.last()
2129                {
2130                    let guar = self.check_trailing_angle_brackets(
2131                        last_segment,
2132                        &[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)],
2133                    );
2134                    if let Some(_guar) = guar {
2135                        // Handle a case like `Vec<u8>>,` where we can continue parsing fields
2136                        // after the comma
2137                        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
2138
2139                        // `check_trailing_angle_brackets` already emitted a nicer error, as
2140                        // proven by the presence of `_guar`. We can continue parsing.
2141                        return Ok(a_var);
2142                    }
2143                }
2144
2145                let mut err = self.dcx().struct_span_err(sp, msg);
2146
2147                if self.token.is_ident()
2148                    || (self.token == TokenKind::Pound
2149                        && (self.look_ahead(1, |t| t == &token::OpenBracket)))
2150                {
2151                    // This is likely another field, TokenKind::Pound is used for `#[..]`
2152                    // attribute for next field. Emit the diagnostic and continue parsing.
2153                    err.span_suggestion(
2154                        sp,
2155                        "try adding a comma",
2156                        ",",
2157                        Applicability::MachineApplicable,
2158                    );
2159                    err.emit();
2160                } else {
2161                    return Err(err);
2162                }
2163            }
2164        }
2165        Ok(a_var)
2166    }
2167
2168    fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
2169        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)) {
2170            let sm = self.psess.source_map();
2171            let eq_typo = self.token == token::Eq && self.look_ahead(1, |t| t.is_path_start());
2172            let semi_typo = self.token == token::Semi
2173                && self.look_ahead(1, |t| {
2174                    t.is_path_start()
2175                    // We check that we are in a situation like `foo; bar` to avoid bad suggestions
2176                    // when there's no type and `;` was used instead of a comma.
2177                    && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
2178                        (Ok(l), Ok(r)) => l.line == r.line,
2179                        _ => true,
2180                    }
2181                });
2182            if eq_typo || semi_typo {
2183                self.bump();
2184                // Gracefully handle small typos.
2185                err.with_span_suggestion_short(
2186                    self.prev_token.span,
2187                    "field names and their types are separated with `:`",
2188                    ":",
2189                    Applicability::MachineApplicable,
2190                )
2191                .emit();
2192            } else {
2193                return Err(err);
2194            }
2195        }
2196        Ok(())
2197    }
2198
2199    /// Parses a structure field.
2200    fn parse_name_and_ty(
2201        &mut self,
2202        adt_ty: &str,
2203        lo: Span,
2204        vis: Visibility,
2205        safety: Safety,
2206        attrs: AttrVec,
2207    ) -> PResult<'a, FieldDef> {
2208        let name = self.parse_field_ident(adt_ty, lo)?;
2209        if self.token == token::Bang {
2210            if let Err(mut err) = self.unexpected() {
2211                // Encounter the macro invocation
2212                err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
2213                return Err(err);
2214            }
2215        }
2216        self.expect_field_ty_separator()?;
2217        let ty = self.parse_ty()?;
2218        if self.token == token::Colon && self.look_ahead(1, |&t| t != token::Colon) {
2219            self.dcx()
2220                .struct_span_err(self.token.span, "found single colon in a struct field type path")
2221                .with_span_suggestion_verbose(
2222                    self.token.span,
2223                    "write a path separator here",
2224                    "::",
2225                    Applicability::MaybeIncorrect,
2226                )
2227                .emit();
2228        }
2229        let default = if self.token == token::Eq {
2230            self.bump();
2231            let const_expr = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::AnonConst)?;
2232            let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
2233            self.psess.gated_spans.gate(sym::default_field_values, sp);
2234            Some(const_expr)
2235        } else {
2236            None
2237        };
2238        Ok(FieldDef {
2239            span: lo.to(self.prev_token.span),
2240            ident: Some(name),
2241            vis,
2242            safety,
2243            id: DUMMY_NODE_ID,
2244            ty,
2245            default,
2246            attrs,
2247            is_placeholder: false,
2248        })
2249    }
2250
2251    /// Parses a field identifier. Specialized version of `parse_ident_common`
2252    /// for better diagnostics and suggestions.
2253    fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
2254        let (ident, is_raw) = self.ident_or_err(true)?;
2255        if is_raw == IdentIsRaw::No && ident.is_reserved() {
2256            let snapshot = self.create_snapshot_for_diagnostic();
2257            let err = if self.check_fn_front_matter(false, Case::Sensitive) {
2258                let inherited_vis =
2259                    Visibility { span: DUMMY_SP, kind: VisibilityKind::Inherited, tokens: None };
2260                // We use `parse_fn` to get a span for the function
2261                let fn_parse_mode =
2262                    FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true };
2263                match self.parse_fn(
2264                    &mut AttrVec::new(),
2265                    fn_parse_mode,
2266                    lo,
2267                    &inherited_vis,
2268                    Case::Insensitive,
2269                ) {
2270                    Ok(_) => {
2271                        self.dcx().struct_span_err(
2272                            lo.to(self.prev_token.span),
2273                            ::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"),
2274                        )
2275                        .with_help(
2276                            "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
2277                        )
2278                        .with_help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information")
2279                    }
2280                    Err(err) => {
2281                        err.cancel();
2282                        self.restore_snapshot(snapshot);
2283                        self.expected_ident_found_err()
2284                    }
2285                }
2286            } 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)) {
2287                match self.parse_item_struct() {
2288                    Ok(item) => {
2289                        let ItemKind::Struct(ident, ..) = item else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2290                        self.dcx()
2291                            .struct_span_err(
2292                                lo.with_hi(ident.span.hi()),
2293                                ::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"),
2294                            )
2295                            .with_help(
2296                                "consider creating a new `struct` definition instead of nesting",
2297                            )
2298                    }
2299                    Err(err) => {
2300                        err.cancel();
2301                        self.restore_snapshot(snapshot);
2302                        self.expected_ident_found_err()
2303                    }
2304                }
2305            } else {
2306                let mut err = self.expected_ident_found_err();
2307                if self.eat_keyword_noexpect(kw::Let)
2308                    && let removal_span = self.prev_token.span.until(self.token.span)
2309                    && let Ok(ident) = self
2310                        .parse_ident_common(false)
2311                        // Cancel this error, we don't need it.
2312                        .map_err(|err| err.cancel())
2313                    && self.token == TokenKind::Colon
2314                {
2315                    err.span_suggestion(
2316                        removal_span,
2317                        "remove this `let` keyword",
2318                        String::new(),
2319                        Applicability::MachineApplicable,
2320                    );
2321                    err.note("the `let` keyword is not allowed in `struct` fields");
2322                    err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
2323                    err.emit();
2324                    return Ok(ident);
2325                } else {
2326                    self.restore_snapshot(snapshot);
2327                }
2328                err
2329            };
2330            return Err(err);
2331        }
2332        self.bump();
2333        Ok(ident)
2334    }
2335
2336    /// Parses a declarative macro 2.0 definition.
2337    /// The `macro` keyword has already been parsed.
2338    /// ```ebnf
2339    /// MacBody = "{" TOKEN_STREAM "}" ;
2340    /// MacParams = "(" TOKEN_STREAM ")" ;
2341    /// DeclMac = "macro" Ident MacParams? MacBody ;
2342    /// ```
2343    fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemKind> {
2344        let ident = self.parse_ident()?;
2345        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)) {
2346            self.parse_delim_args()? // `MacBody`
2347        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
2348            let params = self.parse_token_tree(); // `MacParams`
2349            let pspan = params.span();
2350            if !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2351                self.unexpected()?;
2352            }
2353            let body = self.parse_token_tree(); // `MacBody`
2354            // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
2355            let bspan = body.span();
2356            let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
2357            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]);
2358            let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
2359            Box::new(DelimArgs { dspan, delim: Delimiter::Brace, tokens })
2360        } else {
2361            self.unexpected_any()?
2362        };
2363
2364        self.psess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
2365        Ok(ItemKind::MacroDef(
2366            ident,
2367            ast::MacroDef { body, macro_rules: false, eii_declaration: None },
2368        ))
2369    }
2370
2371    /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
2372    fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
2373        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)) {
2374            let macro_rules_span = self.token.span;
2375
2376            if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) {
2377                return IsMacroRulesItem::Yes { has_bang: true };
2378            } else if self.look_ahead(1, |t| t.is_ident()) {
2379                // macro_rules foo
2380                self.dcx().emit_err(errors::MacroRulesMissingBang {
2381                    span: macro_rules_span,
2382                    hi: macro_rules_span.shrink_to_hi(),
2383                });
2384
2385                return IsMacroRulesItem::Yes { has_bang: false };
2386            }
2387        }
2388
2389        IsMacroRulesItem::No
2390    }
2391
2392    /// Parses a `macro_rules! foo { ... }` declarative macro.
2393    fn parse_item_macro_rules(
2394        &mut self,
2395        vis: &Visibility,
2396        has_bang: bool,
2397    ) -> PResult<'a, ItemKind> {
2398        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`
2399
2400        if has_bang {
2401            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang))?; // `!`
2402        }
2403        let ident = self.parse_ident()?;
2404
2405        if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
2406            // Handle macro_rules! foo!
2407            let span = self.prev_token.span;
2408            self.dcx().emit_err(errors::MacroNameRemoveBang { span });
2409        }
2410
2411        let body = self.parse_delim_args()?;
2412        self.eat_semi_for_macro_if_needed(&body, None);
2413        self.complain_if_pub_macro(vis, true);
2414
2415        Ok(ItemKind::MacroDef(
2416            ident,
2417            ast::MacroDef { body, macro_rules: true, eii_declaration: None },
2418        ))
2419    }
2420
2421    /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
2422    /// If that's not the case, emit an error.
2423    fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
2424        if let VisibilityKind::Inherited = vis.kind {
2425            return;
2426        }
2427
2428        let vstr = pprust::vis_to_string(vis);
2429        let vstr = vstr.trim_end();
2430        if macro_rules {
2431            self.dcx().emit_err(errors::MacroRulesVisibility { span: vis.span, vis: vstr });
2432        } else {
2433            self.dcx().emit_err(errors::MacroInvocationVisibility { span: vis.span, vis: vstr });
2434        }
2435    }
2436
2437    fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs, path: Option<&Path>) {
2438        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)) {
2439            self.report_invalid_macro_expansion_item(args, path);
2440        }
2441    }
2442
2443    fn report_invalid_macro_expansion_item(&self, args: &DelimArgs, path: Option<&Path>) {
2444        let span = args.dspan.entire();
2445        let mut err = self.dcx().struct_span_err(
2446            span,
2447            "macros that expand to items must be delimited with braces or followed by a semicolon",
2448        );
2449        // FIXME: This will make us not emit the help even for declarative
2450        // macros within the same crate (that we can fix), which is sad.
2451        if !span.from_expansion() {
2452            let DelimSpan { open, close } = args.dspan;
2453            // Check if this looks like `macro_rules!(name) { ... }`
2454            // a common mistake when trying to define a macro.
2455            if let Some(path) = path
2456                && path.segments.first().is_some_and(|seg| seg.ident.name == sym::macro_rules)
2457                && args.delim == Delimiter::Parenthesis
2458            {
2459                let replace =
2460                    if path.span.hi() + rustc_span::BytePos(1) < open.lo() { "" } else { " " };
2461                err.multipart_suggestion(
2462                    "to define a macro, remove the parentheses around the macro name",
2463                    ::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())],
2464                    Applicability::MachineApplicable,
2465                );
2466            } else {
2467                err.multipart_suggestion(
2468                    "change the delimiters to curly braces",
2469                    ::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())],
2470                    Applicability::MaybeIncorrect,
2471                );
2472                err.span_suggestion(
2473                    span.with_neighbor(self.token.span).shrink_to_hi(),
2474                    "add a semicolon",
2475                    ';',
2476                    Applicability::MaybeIncorrect,
2477                );
2478            }
2479        }
2480        err.emit();
2481    }
2482
2483    /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2484    /// it is, we try to parse the item and report error about nested types.
2485    fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2486        if (self.token.is_keyword(kw::Enum)
2487            || self.token.is_keyword(kw::Struct)
2488            || self.token.is_keyword(kw::Union))
2489            && self.look_ahead(1, |t| t.is_ident())
2490        {
2491            let kw_token = self.token;
2492            let kw_str = pprust::token_to_string(&kw_token);
2493            let item = self.parse_item(
2494                ForceCollect::No,
2495                AllowConstBlockItems::DoesNotMatter, // self.token != kw::Const
2496            )?;
2497            let mut item = item.unwrap().span;
2498            if self.token == token::Comma {
2499                item = item.to(self.token.span);
2500            }
2501            self.dcx().emit_err(errors::NestedAdt {
2502                span: kw_token.span,
2503                item,
2504                kw_str,
2505                keyword: keyword.as_str(),
2506            });
2507            // We successfully parsed the item but we must inform the caller about nested problem.
2508            return Ok(false);
2509        }
2510        Ok(true)
2511    }
2512}
2513
2514/// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2515///
2516/// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2517///
2518/// This function pointer accepts an edition, because in edition 2015, trait declarations
2519/// were allowed to omit parameter names. In 2018, they became required. It also accepts an
2520/// `IsDotDotDot` parameter, as `extern` function declarations and function pointer types are
2521/// allowed to omit the name of the `...` but regular function items are not.
2522type ReqName = fn(Edition, IsDotDotDot) -> bool;
2523
2524#[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)]
2525pub(crate) enum IsDotDotDot {
2526    Yes,
2527    No,
2528}
2529
2530/// Parsing configuration for functions.
2531///
2532/// The syntax of function items is slightly different within trait definitions,
2533/// impl blocks, and modules. It is still parsed using the same code, just with
2534/// different flags set, so that even when the input is wrong and produces a parse
2535/// error, it still gets into the AST and the rest of the parser and
2536/// type checker can run.
2537#[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)]
2538pub(crate) struct FnParseMode {
2539    /// A function pointer that decides if, per-parameter `p`, `p` must have a
2540    /// pattern or just a type. This field affects parsing of the parameters list.
2541    ///
2542    /// ```text
2543    /// fn foo(alef: A) -> X { X::new() }
2544    ///        -----^^ affects parsing this part of the function signature
2545    ///        |
2546    ///        if req_name returns false, then this name is optional
2547    ///
2548    /// fn bar(A) -> X;
2549    ///        ^
2550    ///        |
2551    ///        if req_name returns true, this is an error
2552    /// ```
2553    ///
2554    /// Calling this function pointer should only return false if:
2555    ///
2556    ///   * The item is being parsed inside of a trait definition.
2557    ///     Within an impl block or a module, it should always evaluate
2558    ///     to true.
2559    ///   * The span is from Edition 2015. In particular, you can get a
2560    ///     2015 span inside a 2021 crate using macros.
2561    ///
2562    /// Or if `IsDotDotDot::Yes`, this function will also return `false` if the item being parsed
2563    /// is inside an `extern` block.
2564    pub(super) req_name: ReqName,
2565    /// The context in which this function is parsed, used for diagnostics.
2566    /// This indicates the fn is a free function or method and so on.
2567    pub(super) context: FnContext,
2568    /// If this flag is set to `true`, then plain, semicolon-terminated function
2569    /// prototypes are not allowed here.
2570    ///
2571    /// ```text
2572    /// fn foo(alef: A) -> X { X::new() }
2573    ///                      ^^^^^^^^^^^^
2574    ///                      |
2575    ///                      this is always allowed
2576    ///
2577    /// fn bar(alef: A, bet: B) -> X;
2578    ///                             ^
2579    ///                             |
2580    ///                             if req_body is set to true, this is an error
2581    /// ```
2582    ///
2583    /// This field should only be set to false if the item is inside of a trait
2584    /// definition or extern block. Within an impl block or a module, it should
2585    /// always be set to true.
2586    pub(super) req_body: bool,
2587}
2588
2589/// The context in which a function is parsed.
2590/// FIXME(estebank, xizheyin): Use more variants.
2591#[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 {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
2592pub(crate) enum FnContext {
2593    /// Free context.
2594    Free,
2595    /// A Trait context.
2596    Trait,
2597    /// An Impl block.
2598    Impl,
2599}
2600
2601/// Parsing of functions and methods.
2602impl<'a> Parser<'a> {
2603    /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2604    fn parse_fn(
2605        &mut self,
2606        attrs: &mut AttrVec,
2607        fn_parse_mode: FnParseMode,
2608        sig_lo: Span,
2609        vis: &Visibility,
2610        case: Case,
2611    ) -> PResult<'a, (Ident, FnSig, Generics, Option<Box<FnContract>>, Option<Box<Block>>)> {
2612        let fn_span = self.token.span;
2613        let header = self.parse_fn_front_matter(vis, case, FrontMatterParsingMode::Function)?; // `const ... fn`
2614        let ident = self.parse_ident()?; // `foo`
2615        let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2616        let decl = match self.parse_fn_decl(&fn_parse_mode, AllowPlus::Yes, RecoverReturnSign::Yes)
2617        {
2618            Ok(decl) => decl,
2619            Err(old_err) => {
2620                // If we see `for Ty ...` then user probably meant `impl` item.
2621                if self.token.is_keyword(kw::For) {
2622                    old_err.cancel();
2623                    return Err(self.dcx().create_err(errors::FnTypoWithImpl { fn_span }));
2624                } else {
2625                    return Err(old_err);
2626                }
2627            }
2628        };
2629
2630        // Store the end of function parameters to give better diagnostics
2631        // inside `parse_fn_body()`.
2632        let fn_params_end = self.prev_token.span.shrink_to_hi();
2633
2634        let contract = self.parse_contract()?;
2635
2636        generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2637
2638        // `fn_params_end` is needed only when it's followed by a where clause.
2639        let fn_params_end =
2640            if generics.where_clause.has_where_token { Some(fn_params_end) } else { None };
2641
2642        let mut sig_hi = self.prev_token.span;
2643        // Either `;` or `{ ... }`.
2644        let body =
2645            self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body, fn_params_end)?;
2646        let fn_sig_span = sig_lo.to(sig_hi);
2647        Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, contract, body))
2648    }
2649
2650    /// Provide diagnostics when function body is not found
2651    fn error_fn_body_not_found(
2652        &mut self,
2653        ident_span: Span,
2654        req_body: bool,
2655        fn_params_end: Option<Span>,
2656    ) -> PResult<'a, ErrorGuaranteed> {
2657        let expected: &[_] =
2658            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)] };
2659        match self.expected_one_of_not_found(&[], expected) {
2660            Ok(error_guaranteed) => Ok(error_guaranteed),
2661            Err(mut err) => {
2662                if self.token == token::CloseBrace {
2663                    // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2664                    // the AST for typechecking.
2665                    err.span_label(ident_span, "while parsing this `fn`");
2666                    Ok(err.emit())
2667                } else if self.token == token::RArrow
2668                    && let Some(fn_params_end) = fn_params_end
2669                {
2670                    // Instead of a function body, the parser has encountered a right arrow
2671                    // preceded by a where clause.
2672
2673                    // Find whether token behind the right arrow is a function trait and
2674                    // store its span.
2675                    let fn_trait_span =
2676                        [sym::FnOnce, sym::FnMut, sym::Fn].into_iter().find_map(|symbol| {
2677                            if self.prev_token.is_ident_named(symbol) {
2678                                Some(self.prev_token.span)
2679                            } else {
2680                                None
2681                            }
2682                        });
2683
2684                    // Parse the return type (along with the right arrow) and store its span.
2685                    // If there's a parse error, cancel it and return the existing error
2686                    // as we are primarily concerned with the
2687                    // expected-function-body-but-found-something-else error here.
2688                    let arrow_span = self.token.span;
2689                    let ty_span = match self.parse_ret_ty(
2690                        AllowPlus::Yes,
2691                        RecoverQPath::Yes,
2692                        RecoverReturnSign::Yes,
2693                    ) {
2694                        Ok(ty_span) => ty_span.span().shrink_to_hi(),
2695                        Err(parse_error) => {
2696                            parse_error.cancel();
2697                            return Err(err);
2698                        }
2699                    };
2700                    let ret_ty_span = arrow_span.to(ty_span);
2701
2702                    if let Some(fn_trait_span) = fn_trait_span {
2703                        // Typo'd Fn* trait bounds such as
2704                        // fn foo<F>() where F: FnOnce -> () {}
2705                        err.subdiagnostic(errors::FnTraitMissingParen { span: fn_trait_span });
2706                    } else if let Ok(snippet) = self.psess.source_map().span_to_snippet(ret_ty_span)
2707                    {
2708                        // If token behind right arrow is not a Fn* trait, the programmer
2709                        // probably misplaced the return type after the where clause like
2710                        // `fn foo<T>() where T: Default -> u8 {}`
2711                        err.primary_message(
2712                            "return type should be specified after the function parameters",
2713                        );
2714                        err.subdiagnostic(errors::MisplacedReturnType {
2715                            fn_params_end,
2716                            snippet,
2717                            ret_ty_span,
2718                        });
2719                    }
2720                    Err(err)
2721                } else {
2722                    Err(err)
2723                }
2724            }
2725        }
2726    }
2727
2728    /// Parse the "body" of a function.
2729    /// This can either be `;` when there's no body,
2730    /// or e.g. a block when the function is a provided one.
2731    fn parse_fn_body(
2732        &mut self,
2733        attrs: &mut AttrVec,
2734        ident: &Ident,
2735        sig_hi: &mut Span,
2736        req_body: bool,
2737        fn_params_end: Option<Span>,
2738    ) -> PResult<'a, Option<Box<Block>>> {
2739        let has_semi = if req_body {
2740            self.token == TokenKind::Semi
2741        } else {
2742            // Only include `;` in list of expected tokens if body is not required
2743            self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi))
2744        };
2745        let (inner_attrs, body) = if has_semi {
2746            // Include the trailing semicolon in the span of the signature
2747            self.expect_semi()?;
2748            *sig_hi = self.prev_token.span;
2749            (AttrVec::new(), None)
2750        } 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() {
2751            let prev_in_fn_body = self.in_fn_body;
2752            self.in_fn_body = true;
2753            let res = self.parse_block_common(self.token.span, BlockCheckMode::Default, None).map(
2754                |(attrs, mut body)| {
2755                    if let Some(guar) = self.fn_body_missing_semi_guar.take() {
2756                        body.stmts.push(self.mk_stmt(
2757                            body.span,
2758                            StmtKind::Expr(self.mk_expr(body.span, ExprKind::Err(guar))),
2759                        ));
2760                    }
2761                    (attrs, Some(body))
2762                },
2763            );
2764            self.in_fn_body = prev_in_fn_body;
2765            res?
2766        } else if self.token == token::Eq {
2767            // Recover `fn foo() = $expr;`.
2768            self.bump(); // `=`
2769            let eq_sp = self.prev_token.span;
2770            let _ = self.parse_expr()?;
2771            self.expect_semi()?; // `;`
2772            let span = eq_sp.to(self.prev_token.span);
2773            let guar = self.dcx().emit_err(errors::FunctionBodyEqualsExpr {
2774                span,
2775                sugg: errors::FunctionBodyEqualsExprSugg { eq: eq_sp, semi: self.prev_token.span },
2776            });
2777            (AttrVec::new(), Some(self.mk_block_err(span, guar)))
2778        } else {
2779            self.error_fn_body_not_found(ident.span, req_body, fn_params_end)?;
2780            (AttrVec::new(), None)
2781        };
2782        attrs.extend(inner_attrs);
2783        Ok(body)
2784    }
2785
2786    fn check_impl_frontmatter(&mut self, look_ahead: usize) -> bool {
2787        const ALL_QUALS: &[Symbol] = &[kw::Const, kw::Unsafe];
2788        // In contrast to the loop below, this call inserts `impl` into the
2789        // list of expected tokens shown in diagnostics.
2790        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)) {
2791            return true;
2792        }
2793        let mut i = 0;
2794        while i < ALL_QUALS.len() {
2795            let action = self.look_ahead(i + look_ahead, |token| {
2796                if token.is_keyword(kw::Impl) {
2797                    return Some(true);
2798                }
2799                if ALL_QUALS.iter().any(|&qual| token.is_keyword(qual)) {
2800                    // Ok, we found a legal keyword, keep looking for `impl`
2801                    return None;
2802                }
2803                Some(false)
2804            });
2805            if let Some(ret) = action {
2806                return ret;
2807            }
2808            i += 1;
2809        }
2810
2811        self.is_keyword_ahead(i, &[kw::Impl])
2812    }
2813
2814    /// Is the current token the start of an `FnHeader` / not a valid parse?
2815    ///
2816    /// `check_pub` adds additional `pub` to the checks in case users place it
2817    /// wrongly, can be used to ensure `pub` never comes after `default`.
2818    pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2819        const ALL_QUALS: &[ExpKeywordPair] = &[
2820            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Pub,
    token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub),
2821            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen),
2822            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const),
2823            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async),
2824            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe),
2825            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Safe,
    token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe),
2826            crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern),
2827        ];
2828
2829        // We use an over-approximation here.
2830        // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2831        // `pub` is added in case users got confused with the ordering like `async pub fn`,
2832        // only if it wasn't preceded by `default` as `default pub` is invalid.
2833        let quals: &[_] = if check_pub {
2834            ALL_QUALS
2835        } else {
2836            &[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)]
2837        };
2838        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`.
2839            // `$qual fn` or `$qual $qual`:
2840            || quals.iter().any(|&exp| self.check_keyword_case(exp, case))
2841                && self.look_ahead(1, |t| {
2842                    // `$qual fn`, e.g. `const fn` or `async fn`.
2843                    t.is_keyword_case(kw::Fn, case)
2844                    // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2845                    || (
2846                        (
2847                            t.is_non_raw_ident_where(|i|
2848                                quals.iter().any(|exp| exp.kw == i.name)
2849                                    // Rule out 2015 `const async: T = val`.
2850                                    && i.is_reserved()
2851                            )
2852                            || case == Case::Insensitive
2853                                && t.is_non_raw_ident_where(|i| quals.iter().any(|exp| {
2854                                    exp.kw.as_str() == i.name.as_str().to_lowercase()
2855                                }))
2856                        )
2857                        // Rule out `unsafe extern {`.
2858                        && !self.is_unsafe_foreign_mod()
2859                        // Rule out `async gen {` and `async gen move {`
2860                        && !self.is_async_gen_block()
2861                        // Rule out `const unsafe auto` and `const unsafe trait`.
2862                        && !self.is_keyword_ahead(2, &[kw::Auto, kw::Trait])
2863                    )
2864                })
2865            // `extern ABI fn`
2866            || 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)
2867                // Use `tree_look_ahead` because `ABI` might be a metavariable,
2868                // i.e. an invisible-delimited sequence, and `tree_look_ahead`
2869                // will consider that a single element when looking ahead.
2870                && self.look_ahead(1, |t| t.can_begin_string_literal())
2871                && (self.tree_look_ahead(2, |tt| {
2872                    match tt {
2873                        TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case),
2874                        TokenTree::Delimited(..) => false,
2875                    }
2876                }) == Some(true) ||
2877                    // This branch is only for better diagnostics; `pub`, `unsafe`, etc. are not
2878                    // allowed here.
2879                    (self.may_recover()
2880                        && self.tree_look_ahead(2, |tt| {
2881                            match tt {
2882                                TokenTree::Token(t, _) =>
2883                                    ALL_QUALS.iter().any(|exp| {
2884                                        t.is_keyword(exp.kw)
2885                                    }),
2886                                TokenTree::Delimited(..) => false,
2887                            }
2888                        }) == Some(true)
2889                        && self.tree_look_ahead(3, |tt| {
2890                            match tt {
2891                                TokenTree::Token(t, _) => t.is_keyword_case(kw::Fn, case),
2892                                TokenTree::Delimited(..) => false,
2893                            }
2894                        }) == Some(true)
2895                    )
2896                )
2897    }
2898
2899    /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2900    /// up to and including the `fn` keyword. The formal grammar is:
2901    ///
2902    /// ```text
2903    /// Extern = "extern" StringLit? ;
2904    /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2905    /// FnFrontMatter = FnQual "fn" ;
2906    /// ```
2907    ///
2908    /// `vis` represents the visibility that was already parsed, if any. Use
2909    /// `Visibility::Inherited` when no visibility is known.
2910    ///
2911    /// If `parsing_mode` is `FrontMatterParsingMode::FunctionPtrType`, we error on `const` and `async` qualifiers,
2912    /// which are not allowed in function pointer types.
2913    pub(super) fn parse_fn_front_matter(
2914        &mut self,
2915        orig_vis: &Visibility,
2916        case: Case,
2917        parsing_mode: FrontMatterParsingMode,
2918    ) -> PResult<'a, FnHeader> {
2919        let sp_start = self.token.span;
2920        let constness = self.parse_constness(case);
2921        if parsing_mode == FrontMatterParsingMode::FunctionPtrType
2922            && let Const::Yes(const_span) = constness
2923        {
2924            self.dcx().emit_err(FnPointerCannotBeConst {
2925                span: const_span,
2926                suggestion: const_span.until(self.token.span),
2927            });
2928        }
2929
2930        let async_start_sp = self.token.span;
2931        let coroutine_kind = self.parse_coroutine_kind(case);
2932        if parsing_mode == FrontMatterParsingMode::FunctionPtrType
2933            && let Some(ast::CoroutineKind::Async { span: async_span, .. }) = coroutine_kind
2934        {
2935            self.dcx().emit_err(FnPointerCannotBeAsync {
2936                span: async_span,
2937                suggestion: async_span.until(self.token.span),
2938            });
2939        }
2940        // FIXME(gen_blocks): emit a similar error for `gen fn()`
2941
2942        let unsafe_start_sp = self.token.span;
2943        let safety = self.parse_safety(case);
2944
2945        let ext_start_sp = self.token.span;
2946        let ext = self.parse_extern(case);
2947
2948        if let Some(CoroutineKind::Async { span, .. }) = coroutine_kind {
2949            if span.is_rust_2015() {
2950                self.dcx().emit_err(errors::AsyncFnIn2015 {
2951                    span,
2952                    help: errors::HelpUseLatestEdition::new(),
2953                });
2954            }
2955        }
2956
2957        match coroutine_kind {
2958            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
2959                self.psess.gated_spans.gate(sym::gen_blocks, span);
2960            }
2961            Some(CoroutineKind::Async { .. }) | None => {}
2962        }
2963
2964        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) {
2965            // It is possible for `expect_one_of` to recover given the contents of
2966            // `self.expected_token_types`, therefore, do not use `self.unexpected()` which doesn't
2967            // account for this.
2968            match self.expect_one_of(&[], &[]) {
2969                Ok(Recovered::Yes(_)) => {}
2970                Ok(Recovered::No) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2971                Err(mut err) => {
2972                    // Qualifier keywords ordering check
2973                    enum WrongKw {
2974                        Duplicated(Span),
2975                        Misplaced(Span),
2976                        /// `MisplacedDisallowedQualifier` is only used instead of `Misplaced`,
2977                        /// when the misplaced keyword is disallowed by the current `FrontMatterParsingMode`.
2978                        /// In this case, we avoid generating the suggestion to swap around the keywords,
2979                        /// as we already generated a suggestion to remove the keyword earlier.
2980                        MisplacedDisallowedQualifier,
2981                    }
2982
2983                    // We may be able to recover
2984                    let mut recover_constness = constness;
2985                    let mut recover_coroutine_kind = coroutine_kind;
2986                    let mut recover_safety = safety;
2987                    // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2988                    // that the keyword is already present and the second instance should be removed.
2989                    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)) {
2990                        match constness {
2991                            Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2992                            Const::No => {
2993                                recover_constness = Const::Yes(self.token.span);
2994                                match parsing_mode {
2995                                    FrontMatterParsingMode::Function => {
2996                                        Some(WrongKw::Misplaced(async_start_sp))
2997                                    }
2998                                    FrontMatterParsingMode::FunctionPtrType => {
2999                                        self.dcx().emit_err(FnPointerCannotBeConst {
3000                                            span: self.token.span,
3001                                            suggestion: self
3002                                                .token
3003                                                .span
3004                                                .with_lo(self.prev_token.span.hi()),
3005                                        });
3006                                        Some(WrongKw::MisplacedDisallowedQualifier)
3007                                    }
3008                                }
3009                            }
3010                        }
3011                    } 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)) {
3012                        match coroutine_kind {
3013                            Some(CoroutineKind::Async { span, .. }) => {
3014                                Some(WrongKw::Duplicated(span))
3015                            }
3016                            Some(CoroutineKind::AsyncGen { span, .. }) => {
3017                                Some(WrongKw::Duplicated(span))
3018                            }
3019                            Some(CoroutineKind::Gen { .. }) => {
3020                                recover_coroutine_kind = Some(CoroutineKind::AsyncGen {
3021                                    span: self.token.span,
3022                                    closure_id: DUMMY_NODE_ID,
3023                                    return_impl_trait_id: DUMMY_NODE_ID,
3024                                });
3025                                // FIXME(gen_blocks): This span is wrong, didn't want to think about it.
3026                                Some(WrongKw::Misplaced(unsafe_start_sp))
3027                            }
3028                            None => {
3029                                recover_coroutine_kind = Some(CoroutineKind::Async {
3030                                    span: self.token.span,
3031                                    closure_id: DUMMY_NODE_ID,
3032                                    return_impl_trait_id: DUMMY_NODE_ID,
3033                                });
3034                                match parsing_mode {
3035                                    FrontMatterParsingMode::Function => {
3036                                        Some(WrongKw::Misplaced(async_start_sp))
3037                                    }
3038                                    FrontMatterParsingMode::FunctionPtrType => {
3039                                        self.dcx().emit_err(FnPointerCannotBeAsync {
3040                                            span: self.token.span,
3041                                            suggestion: self
3042                                                .token
3043                                                .span
3044                                                .with_lo(self.prev_token.span.hi()),
3045                                        });
3046                                        Some(WrongKw::MisplacedDisallowedQualifier)
3047                                    }
3048                                }
3049                            }
3050                        }
3051                    } 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)) {
3052                        match safety {
3053                            Safety::Unsafe(sp) => Some(WrongKw::Duplicated(sp)),
3054                            Safety::Safe(sp) => {
3055                                recover_safety = Safety::Unsafe(self.token.span);
3056                                Some(WrongKw::Misplaced(sp))
3057                            }
3058                            Safety::Default => {
3059                                recover_safety = Safety::Unsafe(self.token.span);
3060                                Some(WrongKw::Misplaced(ext_start_sp))
3061                            }
3062                        }
3063                    } 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)) {
3064                        match safety {
3065                            Safety::Safe(sp) => Some(WrongKw::Duplicated(sp)),
3066                            Safety::Unsafe(sp) => {
3067                                recover_safety = Safety::Safe(self.token.span);
3068                                Some(WrongKw::Misplaced(sp))
3069                            }
3070                            Safety::Default => {
3071                                recover_safety = Safety::Safe(self.token.span);
3072                                Some(WrongKw::Misplaced(ext_start_sp))
3073                            }
3074                        }
3075                    } else {
3076                        None
3077                    };
3078
3079                    // The keyword is already present, suggest removal of the second instance
3080                    if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
3081                        let original_kw = self
3082                            .span_to_snippet(original_sp)
3083                            .expect("Span extracted directly from keyword should always work");
3084
3085                        err.span_suggestion(
3086                            self.token_uninterpolated_span(),
3087                            ::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"),
3088                            "",
3089                            Applicability::MachineApplicable,
3090                        )
3091                        .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"));
3092                    }
3093                    // The keyword has not been seen yet, suggest correct placement in the function front matter
3094                    else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
3095                        let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
3096                        if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
3097                            let misplaced_qual_sp = self.token_uninterpolated_span();
3098                            let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
3099
3100                            err.span_suggestion(
3101                                    correct_pos_sp.to(misplaced_qual_sp),
3102                                    ::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}`"),
3103                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", misplaced_qual,
                current_qual))
    })format!("{misplaced_qual} {current_qual}"),
3104                                    Applicability::MachineApplicable,
3105                                ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
3106                        }
3107                    }
3108                    // Recover incorrect visibility order such as `async pub`
3109                    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)) {
3110                        let sp = sp_start.to(self.prev_token.span);
3111                        if let Ok(snippet) = self.span_to_snippet(sp) {
3112                            let current_vis = match self.parse_visibility(FollowedByType::No) {
3113                                Ok(v) => v,
3114                                Err(d) => {
3115                                    d.cancel();
3116                                    return Err(err);
3117                                }
3118                            };
3119                            let vs = pprust::vis_to_string(&current_vis);
3120                            let vs = vs.trim_end();
3121
3122                            // There was no explicit visibility
3123                            if #[allow(non_exhaustive_omitted_patterns)] match orig_vis.kind {
    VisibilityKind::Inherited => true,
    _ => false,
}matches!(orig_vis.kind, VisibilityKind::Inherited) {
3124                                err.span_suggestion(
3125                                    sp_start.to(self.prev_token.span),
3126                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("visibility `{0}` must come before `{1}`",
                vs, snippet))
    })format!("visibility `{vs}` must come before `{snippet}`"),
3127                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", vs, snippet))
    })format!("{vs} {snippet}"),
3128                                    Applicability::MachineApplicable,
3129                                );
3130                            }
3131                            // There was an explicit visibility
3132                            else {
3133                                err.span_suggestion(
3134                                    current_vis.span,
3135                                    "there is already a visibility modifier, remove one",
3136                                    "",
3137                                    Applicability::MachineApplicable,
3138                                )
3139                                .span_note(orig_vis.span, "explicit visibility first seen here");
3140                            }
3141                        }
3142                    }
3143
3144                    // FIXME(gen_blocks): add keyword recovery logic for genness
3145
3146                    if let Some(wrong_kw) = wrong_kw
3147                        && self.may_recover()
3148                        && self.look_ahead(1, |tok| tok.is_keyword_case(kw::Fn, case))
3149                    {
3150                        // Advance past the misplaced keyword and `fn`
3151                        self.bump();
3152                        self.bump();
3153                        // When we recover from a `MisplacedDisallowedQualifier`, we already emitted an error for the disallowed qualifier
3154                        // So we don't emit another error that the qualifier is unexpected.
3155                        if #[allow(non_exhaustive_omitted_patterns)] match wrong_kw {
    WrongKw::MisplacedDisallowedQualifier => true,
    _ => false,
}matches!(wrong_kw, WrongKw::MisplacedDisallowedQualifier) {
3156                            err.cancel();
3157                        } else {
3158                            err.emit();
3159                        }
3160                        return Ok(FnHeader {
3161                            constness: recover_constness,
3162                            safety: recover_safety,
3163                            coroutine_kind: recover_coroutine_kind,
3164                            ext,
3165                        });
3166                    }
3167
3168                    return Err(err);
3169                }
3170            }
3171        }
3172
3173        Ok(FnHeader { constness, safety, coroutine_kind, ext })
3174    }
3175
3176    /// Parses the parameter list and result type of a function declaration.
3177    pub(super) fn parse_fn_decl(
3178        &mut self,
3179        fn_parse_mode: &FnParseMode,
3180        ret_allow_plus: AllowPlus,
3181        recover_return_sign: RecoverReturnSign,
3182    ) -> PResult<'a, Box<FnDecl>> {
3183        Ok(Box::new(FnDecl {
3184            inputs: self.parse_fn_params(fn_parse_mode)?,
3185            output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
3186        }))
3187    }
3188
3189    /// Parses the parameter list of a function, including the `(` and `)` delimiters.
3190    pub(super) fn parse_fn_params(
3191        &mut self,
3192        fn_parse_mode: &FnParseMode,
3193    ) -> PResult<'a, ThinVec<Param>> {
3194        let mut first_param = true;
3195        // Parse the arguments, starting out with `self` being allowed...
3196        if self.token != TokenKind::OpenParen
3197        // might be typo'd trait impl, handled elsewhere
3198        && !self.token.is_keyword(kw::For)
3199        {
3200            // recover from missing argument list, e.g. `fn main -> () {}`
3201            self.dcx()
3202                .emit_err(errors::MissingFnParams { span: self.prev_token.span.shrink_to_hi() });
3203            return Ok(ThinVec::new());
3204        }
3205
3206        let (mut params, _) = self.parse_paren_comma_seq(|p| {
3207            p.recover_vcs_conflict_marker();
3208            let snapshot = p.create_snapshot_for_diagnostic();
3209            let param = p.parse_param_general(fn_parse_mode, first_param, true).or_else(|e| {
3210                let guar = e.emit();
3211                // When parsing a param failed, we should check to make the span of the param
3212                // not contain '(' before it.
3213                // For example when parsing `*mut Self` in function `fn oof(*mut Self)`.
3214                let lo = if let TokenKind::OpenParen = p.prev_token.kind {
3215                    p.prev_token.span.shrink_to_hi()
3216                } else {
3217                    p.prev_token.span
3218                };
3219                p.restore_snapshot(snapshot);
3220                // Skip every token until next possible arg or end.
3221                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)]);
3222                // Create a placeholder argument for proper arg count (issue #34264).
3223                Ok(dummy_arg(Ident::new(sym::dummy, lo.to(p.prev_token.span)), guar))
3224            });
3225            // ...now that we've parsed the first argument, `self` is no longer allowed.
3226            first_param = false;
3227            param
3228        })?;
3229        // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
3230        self.deduplicate_recovered_params_names(&mut params);
3231        Ok(params)
3232    }
3233
3234    /// Parses a single function parameter.
3235    ///
3236    /// - `self` is syntactically allowed when `first_param` holds.
3237    /// - `recover_arg_parse` is used to recover from a failed argument parse.
3238    pub(super) fn parse_param_general(
3239        &mut self,
3240        fn_parse_mode: &FnParseMode,
3241        first_param: bool,
3242        recover_arg_parse: bool,
3243    ) -> PResult<'a, Param> {
3244        let lo = self.token.span;
3245        let attrs = self.parse_outer_attributes()?;
3246        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3247            // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
3248            if let Some(mut param) = this.parse_self_param()? {
3249                param.attrs = attrs;
3250                let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
3251                return Ok((res?, Trailing::No, UsePreAttrPos::No));
3252            }
3253
3254            let is_dot_dot_dot = if this.token.kind == token::DotDotDot {
3255                IsDotDotDot::Yes
3256            } else {
3257                IsDotDotDot::No
3258            };
3259            let is_name_required = (fn_parse_mode.req_name)(
3260                this.token.span.with_neighbor(this.prev_token.span).edition(),
3261                is_dot_dot_dot,
3262            );
3263            let is_name_required = if is_name_required && is_dot_dot_dot == IsDotDotDot::Yes {
3264                this.psess.buffer_lint(
3265                    VARARGS_WITHOUT_PATTERN,
3266                    this.token.span,
3267                    ast::CRATE_NODE_ID,
3268                    errors::VarargsWithoutPattern { span: this.token.span },
3269                );
3270                false
3271            } else {
3272                is_name_required
3273            };
3274            let (pat, ty) = if is_name_required || this.is_named_param() {
3275                {
    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:3275",
                        "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(3275u32),
                        ::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);
3276                let (pat, colon) = this.parse_fn_param_pat_colon()?;
3277                if !colon {
3278                    let mut err = this.unexpected().unwrap_err();
3279                    return if let Some(ident) = this.parameter_without_type(
3280                        &mut err,
3281                        pat,
3282                        is_name_required,
3283                        first_param,
3284                        fn_parse_mode,
3285                    ) {
3286                        let guar = err.emit();
3287                        Ok((dummy_arg(ident, guar), Trailing::No, UsePreAttrPos::No))
3288                    } else {
3289                        Err(err)
3290                    };
3291                }
3292
3293                this.eat_incorrect_doc_comment_for_param_type();
3294                (pat, this.parse_ty_for_param()?)
3295            } else {
3296                {
    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:3296",
                        "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(3296u32),
                        ::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");
3297                let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
3298                this.eat_incorrect_doc_comment_for_param_type();
3299                let mut ty = this.parse_ty_for_param();
3300
3301                if let Ok(t) = &ty {
3302                    // Check for trailing angle brackets
3303                    if let TyKind::Path(_, Path { segments, .. }) = &t.kind
3304                        && let Some(segment) = segments.last()
3305                        && let Some(guar) =
3306                            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)])
3307                    {
3308                        return Ok((
3309                            dummy_arg(segment.ident, guar),
3310                            Trailing::No,
3311                            UsePreAttrPos::No,
3312                        ));
3313                    }
3314
3315                    if this.token != token::Comma && this.token != token::CloseParen {
3316                        // This wasn't actually a type, but a pattern looking like a type,
3317                        // so we are going to rollback and re-parse for recovery.
3318                        ty = this.unexpected_any();
3319                    }
3320                }
3321                match ty {
3322                    Ok(ty) => {
3323                        let pat = this.mk_pat(ty.span, PatKind::Missing);
3324                        (Box::new(pat), ty)
3325                    }
3326                    // If this is a C-variadic argument and we hit an error, return the error.
3327                    Err(err) if this.token == token::DotDotDot => return Err(err),
3328                    Err(err) if this.unmatched_angle_bracket_count > 0 => return Err(err),
3329                    Err(err) if recover_arg_parse => {
3330                        // Recover from attempting to parse the argument as a type without pattern.
3331                        err.cancel();
3332                        this.restore_snapshot(parser_snapshot_before_ty);
3333                        this.recover_arg_parse()?
3334                    }
3335                    Err(err) => return Err(err),
3336                }
3337            };
3338
3339            let span = lo.to(this.prev_token.span);
3340
3341            Ok((
3342                Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
3343                Trailing::No,
3344                UsePreAttrPos::No,
3345            ))
3346        })
3347    }
3348
3349    /// Returns the parsed optional self parameter and whether a self shortcut was used.
3350    fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
3351        // Extract an identifier *after* having confirmed that the token is one.
3352        let expect_self_ident = |this: &mut Self| match this.token.ident() {
3353            Some((ident, IdentIsRaw::No)) => {
3354                this.bump();
3355                ident
3356            }
3357            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3358        };
3359        // is lifetime `n` tokens ahead?
3360        let is_lifetime = |this: &Self, n| this.look_ahead(n, |t| t.is_lifetime());
3361        // Is `self` `n` tokens ahead?
3362        let is_isolated_self = |this: &Self, n| {
3363            this.is_keyword_ahead(n, &[kw::SelfLower])
3364                && this.look_ahead(n + 1, |t| t != &token::PathSep)
3365        };
3366        // Is `pin const self` `n` tokens ahead?
3367        let is_isolated_pin_const_self = |this: &Self, n| {
3368            this.look_ahead(n, |token| token.is_ident_named(sym::pin))
3369                && this.is_keyword_ahead(n + 1, &[kw::Const])
3370                && is_isolated_self(this, n + 2)
3371        };
3372        // Is `mut self` `n` tokens ahead?
3373        let is_isolated_mut_self =
3374            |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
3375        // Is `pin mut self` `n` tokens ahead?
3376        let is_isolated_pin_mut_self = |this: &Self, n| {
3377            this.look_ahead(n, |token| token.is_ident_named(sym::pin))
3378                && is_isolated_mut_self(this, n + 1)
3379        };
3380        // Parse `self` or `self: TYPE`. We already know the current token is `self`.
3381        let parse_self_possibly_typed = |this: &mut Self, m| {
3382            let eself_ident = expect_self_ident(this);
3383            let eself_hi = this.prev_token.span;
3384            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)) {
3385                SelfKind::Explicit(this.parse_ty()?, m)
3386            } else {
3387                SelfKind::Value(m)
3388            };
3389            Ok((eself, eself_ident, eself_hi))
3390        };
3391        let expect_self_ident_not_typed =
3392            |this: &mut Self, modifier: &SelfKind, modifier_span: Span| {
3393                let eself_ident = expect_self_ident(this);
3394
3395                // Recover `: Type` after a qualified self
3396                if this.may_recover() && this.eat_noexpect(&token::Colon) {
3397                    let snap = this.create_snapshot_for_diagnostic();
3398                    match this.parse_ty() {
3399                        Ok(ty) => {
3400                            this.dcx().emit_err(errors::IncorrectTypeOnSelf {
3401                                span: ty.span,
3402                                move_self_modifier: errors::MoveSelfModifier {
3403                                    removal_span: modifier_span,
3404                                    insertion_span: ty.span.shrink_to_lo(),
3405                                    modifier: modifier.to_ref_suggestion(),
3406                                },
3407                            });
3408                        }
3409                        Err(diag) => {
3410                            diag.cancel();
3411                            this.restore_snapshot(snap);
3412                        }
3413                    }
3414                }
3415                eself_ident
3416            };
3417        // Recover for the grammar `*self`, `*const self`, and `*mut self`.
3418        let recover_self_ptr = |this: &mut Self| {
3419            this.dcx().emit_err(errors::SelfArgumentPointer { span: this.token.span });
3420
3421            Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
3422        };
3423
3424        // Parse optional `self` parameter of a method.
3425        // Only a limited set of initial token sequences is considered `self` parameters; anything
3426        // else is parsed as a normal function parameter list, so some lookahead is required.
3427        let eself_lo = self.token.span;
3428        let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
3429            token::And => {
3430                let has_lifetime = is_lifetime(self, 1);
3431                let skip_lifetime_count = has_lifetime as usize;
3432                let eself = if is_isolated_self(self, skip_lifetime_count + 1) {
3433                    // `&{'lt} self`
3434                    self.bump(); // &
3435                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3436                    SelfKind::Region(lifetime, Mutability::Not)
3437                } else if is_isolated_mut_self(self, skip_lifetime_count + 1) {
3438                    // `&{'lt} mut self`
3439                    self.bump(); // &
3440                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3441                    self.bump(); // mut
3442                    SelfKind::Region(lifetime, Mutability::Mut)
3443                } else if is_isolated_pin_const_self(self, skip_lifetime_count + 1) {
3444                    // `&{'lt} pin const self`
3445                    self.bump(); // &
3446                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3447                    self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
3448                    self.bump(); // pin
3449                    self.bump(); // const
3450                    SelfKind::Pinned(lifetime, Mutability::Not)
3451                } else if is_isolated_pin_mut_self(self, skip_lifetime_count + 1) {
3452                    // `&{'lt} pin mut self`
3453                    self.bump(); // &
3454                    let lifetime = has_lifetime.then(|| self.expect_lifetime());
3455                    self.psess.gated_spans.gate(sym::pin_ergonomics, self.token.span);
3456                    self.bump(); // pin
3457                    self.bump(); // mut
3458                    SelfKind::Pinned(lifetime, Mutability::Mut)
3459                } else {
3460                    // `&not_self`
3461                    return Ok(None);
3462                };
3463                let hi = self.token.span;
3464                let self_ident = expect_self_ident_not_typed(self, &eself, eself_lo.until(hi));
3465                (eself, self_ident, hi)
3466            }
3467            // `*self`
3468            token::Star if is_isolated_self(self, 1) => {
3469                self.bump();
3470                recover_self_ptr(self)?
3471            }
3472            // `*mut self` and `*const self`
3473            token::Star
3474                if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
3475            {
3476                self.bump();
3477                self.bump();
3478                recover_self_ptr(self)?
3479            }
3480            // `self` and `self: TYPE`
3481            token::Ident(..) if is_isolated_self(self, 0) => {
3482                parse_self_possibly_typed(self, Mutability::Not)?
3483            }
3484            // `mut self` and `mut self: TYPE`
3485            token::Ident(..) if is_isolated_mut_self(self, 0) => {
3486                self.bump();
3487                parse_self_possibly_typed(self, Mutability::Mut)?
3488            }
3489            _ => return Ok(None),
3490        };
3491
3492        let eself = source_map::respan(eself_lo.to(eself_hi), eself);
3493        Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
3494    }
3495
3496    fn is_named_param(&self) -> bool {
3497        let offset = match &self.token.kind {
3498            token::OpenInvisible(origin) => match origin {
3499                InvisibleOrigin::MetaVar(MetaVarKind::Pat(_)) => {
3500                    return self.check_noexpect_past_close_delim(&token::Colon);
3501                }
3502                _ => 0,
3503            },
3504            token::And | token::AndAnd => 1,
3505            _ if self.token.is_keyword(kw::Mut) => 1,
3506            _ => 0,
3507        };
3508
3509        self.look_ahead(offset, |t| t.is_ident())
3510            && self.look_ahead(offset + 1, |t| t == &token::Colon)
3511    }
3512
3513    fn recover_self_param(&mut self) -> bool {
3514        #[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!(
3515            self.parse_outer_attributes()
3516                .and_then(|_| self.parse_self_param())
3517                .map_err(|e| e.cancel()),
3518            Ok(Some(_))
3519        )
3520    }
3521
3522    /// Try to recover from over-parsing in const item when a semicolon is missing.
3523    ///
3524    /// This detects cases where we parsed too much because a semicolon was missing
3525    /// and the next line started an expression that the parser treated as a continuation
3526    /// (e.g., `foo() \n &bar` was parsed as `foo() & bar`).
3527    ///
3528    /// Returns a corrected expression if recovery is successful.
3529    fn try_recover_const_missing_semi(
3530        &mut self,
3531        rhs: &ConstItemRhsKind,
3532        const_span: Span,
3533    ) -> Option<Box<Expr>> {
3534        if self.token == TokenKind::Semi {
3535            return None;
3536        }
3537        let ConstItemRhsKind::Body { rhs: Some(rhs) } = rhs else {
3538            return None;
3539        };
3540        if !self.in_fn_body || !self.may_recover() || rhs.span.from_expansion() {
3541            return None;
3542        }
3543        if let Some((span, guar)) =
3544            self.missing_semi_from_binop("const", rhs, Some(const_span.shrink_to_lo()))
3545        {
3546            self.fn_body_missing_semi_guar = Some(guar);
3547            Some(self.mk_expr(span, ExprKind::Err(guar)))
3548        } else {
3549            None
3550        }
3551    }
3552}
3553
3554enum IsMacroRulesItem {
3555    Yes { has_bang: bool },
3556    No,
3557}
3558
3559#[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 {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
3560pub(super) enum FrontMatterParsingMode {
3561    /// Parse the front matter of a function declaration
3562    Function,
3563    /// Parse the front matter of a function pointet type.
3564    /// For function pointer types, the `const` and `async` keywords are not permitted.
3565    FunctionPtrType,
3566}