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