rustc_parse/parser/
item.rs

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