rustc_parse/parser/
item.rs

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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy