rustc_parse/parser/
item.rs

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